1 ;; -*- mode: common-lisp; package: puri -*-
3 ;; For general URI information see RFC2396.
5 ;; copyright (c) 1999-2002 Franz Inc, Berkeley, CA - All rights reserved.
6 ;; copyright (c) 2002-2005 Franz Inc, Oakland, CA - All rights reserved.
7 ;; copyright (c) 2003-2010 Kevin Rosenberg
9 ;; This code is free software; you can redistribute it and/or
10 ;; modify it under the terms of the version 2.1 of
11 ;; the GNU Lesser General Public License as published by
12 ;; the Free Software Foundation, as clarified by the
13 ;; preamble found here:
14 ;; http://opensource.franz.com/preamble.html
16 ;; Versions ported from Franz's opensource release
17 ;; uri.cl,v 2.3.6.4.2.1 2001/08/09 17:42:39 layer
18 ;; uri.cl,v 2.9.84.1 2005/08/11 18:38:52 layer
20 ;; This code is distributed in the hope that it will be useful,
21 ;; but without any warranty; without even the implied warranty of
22 ;; merchantability or fitness for a particular purpose. See the GNU
23 ;; Lesser General Public License for more details.
29 #-allegro (:nicknames #:net.uri)
31 #:uri ; the type and a function
35 #:uri-scheme ; and slots
41 #:uri-authority ; pseudo-slot accessor
44 #:urn-nid ; pseudo-slot accessor
45 #:urn-nss ; pseudo-slot accessor
55 #:make-uri-space ; interning...
62 #:uri-parse-error ;; Added by KMR
67 (eval-when (:compile-toplevel) (declaim (optimize (speed 3))))
71 (defun parse-body (forms &optional env)
72 "Parses a body, returns (VALUES docstring declarations forms)"
73 (declare (ignore env))
74 ;; fixme -- need to add parsing of multiple declarations
75 (let (docstring declarations)
76 (when (stringp (car forms))
77 (setq docstring (car forms))
78 (setq forms (cdr forms)))
79 (when (and (listp (car forms))
80 (symbolp (caar forms))
81 (string-equal (symbol-name '#:declare)
82 (symbol-name (caar forms))))
83 (setq declarations (car forms))
84 (setq forms (cdr forms)))
85 (values docstring declarations forms)))
88 (defun shrink-vector (str size)
90 (excl::.primcall 'sys::shrink-svector str size)
92 (setq str (sb-kernel:shrink-vector str size))
94 (lisp::shrink-vector str size)
96 (system::shrink-vector$vector str size)
98 (common-lisp::shrink-vector str size)
99 #-(or allegro cmu lispworks sbcl scl)
100 (setq str (subseq str 0 size))
104 ;; KMR: Added new condition to handle cross-implementation variances
105 ;; in the parse-error condition many implementations define
107 (define-condition uri-parse-error (parse-error)
108 ((fmt-control :initarg :fmt-control :accessor fmt-control)
109 (fmt-arguments :initarg :fmt-arguments :accessor fmt-arguments ))
110 (:report (lambda (c stream)
111 (format stream "Parse error:")
112 (apply #'format stream (fmt-control c) (fmt-arguments c)))))
114 (defun .parse-error (fmt &rest args)
115 (error 'uri-parse-error :fmt-control fmt :fmt-arguments args))
118 (defun internal-reader-error (stream fmt &rest args)
119 (apply #'format stream fmt args))
121 #-allegro (defvar *current-case-mode* :case-insensitive-upper)
122 #+allegro (eval-when (:compile-toplevel :load-toplevel :execute)
123 (import '(excl:*current-case-mode*
124 excl:delimited-string-to-list
126 excl::internal-reader-error
130 (defmethod position-char (char (string string) start max)
131 (declare (optimize (speed 3) (safety 0) (space 0))
132 (fixnum start max) (string string))
133 (do* ((i start (1+ i)))
136 (when (char= char (char string i)) (return i))))
139 (defun delimited-string-to-list (string &optional (separator #\space)
141 (declare (optimize (speed 3) (safety 0) (space 0)
142 (compilation-speed 0))
144 (type character separator))
145 (do* ((len (length string))
148 (end (position-char separator string pos len)
149 (position-char separator string pos len)))
152 (push (subseq string pos) output)
153 (when (and (plusp len) (not skip-terminal))
156 (declare (type fixnum pos len)
157 (type (or null fixnum) end))
158 (push (subseq string pos end) output)
159 (setq pos (1+ end))))
162 (eval-when (:compile-toplevel :load-toplevel :execute)
163 (defvar if*-keyword-list '("then" "thenret" "else" "elseif"))
165 (defmacro if* (&rest args)
166 (do ((xx (reverse args) (cdr xx))
173 (cond ((eq state :compl)
175 (t (error "if*: illegal form ~s" args))))
176 (cond ((and (symbolp (car xx))
177 (member (symbol-name (car xx))
179 :test #'string-equal))
180 (setq lookat (symbol-name (car xx)))))
182 (cond ((eq state :init)
183 (cond (lookat (cond ((string-equal lookat "thenret")
187 "if*: bad keyword ~a" lookat))))
190 (push (car xx) col))))
193 (cond ((string-equal lookat "else")
196 "if*: multiples elses")))
199 (push `(t ,@col) totalcol))
200 ((string-equal lookat "then")
202 (t (error "if*: bad keyword ~s"
204 (t (push (car xx) col))))
208 "if*: keyword ~s at the wrong place " (car xx)))
209 (t (setq state :compl)
210 (push `(,(car xx) ,@col) totalcol))))
212 (cond ((not (string-equal lookat "elseif"))
213 (error "if*: missing elseif clause ")))
214 (setq state :init))))))
220 (scheme :initarg :scheme :initform nil :accessor uri-scheme)
221 (host :initarg :host :initform nil :accessor uri-host)
222 (port :initarg :port :initform nil :accessor uri-port)
223 (path :initarg :path :initform nil :accessor uri-path)
224 (query :initarg :query :initform nil :accessor uri-query)
225 (fragment :initarg :fragment :initform nil :accessor uri-fragment)
226 (plist :initarg :plist :initform nil :accessor uri-plist)
230 ;; used to prevent unnessary work, looking for chars to escape and
232 :initarg :escaped :initform nil :accessor uri-escaped)
234 ;; the cached printable representation of the URI. It *might* be
235 ;; different than the original string, though, because the user might
236 ;; have escaped non-reserved chars--they won't be escaped when the URI
238 :initarg :string :initform nil :accessor uri-string)
240 ;; the cached parsed representation of the URI path.
241 :initarg :parsed-path
243 :accessor .uri-parsed-path)
245 :initarg :parsed-host
247 :accessor .uri-parsed-host)
249 ;; cached sxhash, so we don't have to compute it more than once.
250 :initarg :hashcode :initform nil :accessor uri-hashcode)))
252 (defmethod initialize-instance :after ((uri puri:uri) &key &allow-other-keys)
253 (let ((parsed-path (puri:uri-parsed-path uri))
254 (parsed-host (puri:uri-parsed-host uri)))
256 (setf (puri:uri-parsed-path uri)
259 (setf (puri:uri-parsed-host uri)
263 ((nid :initarg :nid :initform nil :accessor urn-nid)
264 (nss :initarg :nss :initform nil :accessor urn-nss)))
266 (eval-when (:compile-toplevel :execute)
267 (defmacro clear-caching-on-slot-change (name)
268 `(defmethod (setf ,name) :around (new-value (self uri))
269 (declare (ignore new-value))
270 (prog1 (call-next-method)
271 (setf (uri-string self) nil)
272 ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
273 ,@(when (eq name 'uri-host) `((setf (.uri-parsed-host self) nil)))
274 (setf (uri-hashcode self) nil))))
277 (clear-caching-on-slot-change uri-scheme)
278 (clear-caching-on-slot-change uri-port)
279 (clear-caching-on-slot-change uri-path)
280 (clear-caching-on-slot-change uri-query)
281 (clear-caching-on-slot-change uri-fragment)
284 (defmethod make-load-form ((self uri) &optional env)
285 (declare (ignore env))
286 `(make-instance ',(class-name (class-of self))
287 :scheme ,(uri-scheme self)
288 :host ,(uri-host self)
289 :parsed-host ',(.uri-parsed-host self)
290 :port ,(uri-port self)
291 :path ',(uri-path self)
292 :query ,(uri-query self)
293 :fragment ,(uri-fragment self)
294 :plist ',(uri-plist self)
295 :string ,(uri-string self)
296 :parsed-path ',(.uri-parsed-path self)))
298 (defmethod uri-p ((thing uri)) t)
299 (defmethod uri-p ((thing t)) nil)
303 (scheme (when uri (uri-scheme uri)))
304 (host (when uri (uri-host uri)))
306 (when uri (copy-seq (.uri-parsed-host uri))))
307 (port (when uri (uri-port uri)))
308 (path (when uri (uri-path uri)))
310 (when uri (copy-list (.uri-parsed-path uri))))
311 (query (when uri (uri-query uri)))
312 (fragment (when uri (uri-fragment uri)))
313 (plist (when uri (copy-list (uri-plist uri))))
314 (class (when uri (class-of uri)))
315 &aux (escaped (when uri (uri-escaped uri))))
317 then (setf (uri-scheme place) scheme)
318 (setf (uri-host place) host)
319 (setf (.uri-parsed-host place) parsed-host)
320 (setf (uri-port place) port)
321 (setf (uri-path place) path)
322 (setf (.uri-parsed-path place) parsed-path)
323 (setf (uri-query place) query)
324 (setf (uri-fragment place) fragment)
325 (setf (uri-plist place) plist)
326 (setf (uri-escaped place) escaped)
327 (setf (uri-string place) nil)
328 (setf (uri-hashcode place) nil)
330 elseif (eq 'uri class)
331 then ;; allow the compiler to optimize the call to make-instance:
333 :scheme scheme :host host :port port :path path
334 :parsed-path parsed-path :parsed-host parsed-host
335 :query query :fragment fragment :plist plist
336 :escaped escaped :string nil :hashcode nil)
337 else (make-instance class
338 :scheme scheme :host host :port port :path path
339 :parsed-path parsed-path :parsed-host parsed-host
340 :query query :fragment fragment :plist plist
341 :escaped escaped :string nil :hashcode nil)))
343 (defmethod uri-parsed-path ((uri uri))
345 (when (null (.uri-parsed-path uri))
346 (setf (.uri-parsed-path uri)
347 (parse-path (uri-path uri) (uri-escaped uri))))
348 (.uri-parsed-path uri)))
350 (defmethod (setf uri-parsed-path) (path-list (uri uri))
351 (assert (and (consp path-list)
352 (or (member (car path-list) '(:absolute :relative)
354 (setf (uri-path uri) (render-parsed-path path-list t))
355 (setf (.uri-parsed-path uri) path-list)
358 (defmethod uri-parsed-host ((uri uri))
360 (when (null (.uri-parsed-host uri))
361 (setf (.uri-parsed-host uri)
362 (to-unicode (uri-host uri))))
363 (.uri-parsed-host uri)))
365 (defmethod (setf uri-parsed-host) (host (uri uri))
366 (setf (uri-host uri) (to-ascii host))
367 (setf (.uri-parsed-host uri) (to-unicode host)))
369 (defun uri-authority (uri)
371 (let ((*print-pretty* nil))
372 (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
375 (if* (equalp "urn" (uri-scheme uri))
377 else (error "URI is not a URN: ~s." uri)))
380 (if* (equalp "urn" (uri-scheme uri))
382 else (error "URI is not a URN: ~s." uri)))
384 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
387 (defparameter *excluded-characters*
389 ;; exclude control characters
390 (loop for i from 0 to #x1f
391 collect (code-char i))
392 '(;; `delims' (except #\%, because it's handled specially):
393 #\< #\> #\" #\space #\#
394 #\Rubout ;; (code-char #x7f)
396 #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
397 "Excluded charcters from RFC2369 (http://www.ietf.org/rfc/rfc2396.txt 2.4.3)")
399 (defun reserved-char-vector (chars &key except)
400 (do* ((a (make-array 128 :element-type 'bit :initial-element 0))
401 (chars chars (cdr chars))
402 (c (car chars) (car chars)))
404 (if* (and except (member c except :test #'char=))
406 else (setf (sbit a (char-int c)) 1))))
408 (defparameter *reserved-characters*
409 (reserved-char-vector
410 (append *excluded-characters*
411 '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
412 (defparameter *reserved-authority-characters*
413 (reserved-char-vector
414 (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
415 (defparameter *reserved-path-characters*
416 (reserved-char-vector
417 (append *excluded-characters*
419 ;;;;The rfc says this should be here, but it doesn't make sense.
423 (defparameter *reserved-fragment-characters*
424 (reserved-char-vector (remove #\# *excluded-characters*)))
426 (eval-when (:compile-toplevel :execute)
427 (defun gen-char-range-list (start end)
429 (endcode (1+ (char-int end)))
430 (chcode (char-int start)
434 ;; - has to be first, otherwise it signifies a range!
436 then (setq res (nreverse res))
439 else (nreverse res)))
440 (if* (= #.(char-int #\-) chcode)
442 else (push (code-char chcode) res))))
445 (defparameter *valid-nid-characters*
446 (reserved-char-vector
447 '#.(nconc (gen-char-range-list #\a #\z)
448 (gen-char-range-list #\A #\Z)
449 (gen-char-range-list #\0 #\9)
451 (defparameter *reserved-nss-characters*
452 (reserved-char-vector
453 (append *excluded-characters* '(#\& #\~ #\/ #\?))))
455 (defparameter *illegal-characters*
456 (reserved-char-vector (remove #\# *excluded-characters*)))
457 (defparameter *strict-illegal-query-characters*
458 (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
459 (defparameter *illegal-query-characters*
460 (reserved-char-vector
461 *excluded-characters* :except '(#\^ #\| #\#)))
464 (defun parse-uri (thing &key (class 'uri) &aux escape)
465 (when (uri-p thing) (return-from parse-uri thing))
467 (setq escape (escape-p thing))
468 (multiple-value-bind (scheme host port path query fragment)
469 (parse-uri-string thing)
473 (case *current-case-mode*
474 ((:case-insensitive-upper :case-sensitive-upper)
476 ((:case-insensitive-lower :case-sensitive-lower)
478 (decode-escaped-encoding scheme escape))
479 (find-package :keyword))))
481 (when (and scheme (eq :urn scheme))
482 (return-from parse-uri
483 (make-instance 'urn :scheme scheme :nid host :nss (to-ascii path))))
485 (when host (setq host (to-ascii (decode-escaped-encoding host escape))))
487 (setq port (read-from-string port))
488 (when (not (numberp port)) (error "port is not a number: ~s." port))
489 (when (not (plusp port))
490 (error "port is not a positive integer: ~d." port))
491 (when (eql port (case scheme
497 (when (or (string= "" path)
498 (and ;; we canonicalize away a reference to just /:
500 (member scheme '(:http :https :ftp) :test #'eq)
505 (decode-escaped-encoding path escape *reserved-path-characters*)))
506 (when query (setq query (decode-escaped-encoding query escape)))
509 (decode-escaped-encoding fragment escape
510 *reserved-fragment-characters*)))
512 then ;; allow the compiler to optimize the make-instance call:
521 else ;; do it the slow way:
531 (defmethod uri ((thing uri))
534 (defmethod uri ((thing string))
537 (defmethod uri ((thing t))
538 (error "Cannot coerce ~s to a uri." thing))
540 (defvar *strict-parse* t)
542 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
543 (declare (optimize (speed 3)))
544 ;; Speed is important, so use a specialized state machine instead of
545 ;; regular expressions for parsing the URI string. The regexp we are
554 (end (length string))
559 (path-components '())
562 ;; namespace identifier, for urn parsing only:
564 (declare (fixnum state start end))
565 (flet ((read-token (kind &optional legal-chars)
569 else (let ((sindex start)
572 (declare (fixnum sindex))
575 (when (>= start end) (return nil))
576 (setq c (char string start))
577 (let ((ci (char-int c)))
579 then (if* (and (eq :colon kind) (eq c #\:))
581 elseif (= 0 (sbit legal-chars ci))
584 URI ~s contains illegal character ~s at position ~d."
586 elseif (and (< ci 128)
588 (= 1 (sbit illegal-chars ci)))
589 then (.parse-error "~
590 URI ~s contains illegal character ~s at position ~d."
594 (#\? (return :question))
595 (#\# (return :hash))))
596 (:query (case c (#\# (return :hash))))
599 (#\: (return :colon))
600 (#\? (return :question))
602 (#\/ (return :slash)))))
604 (if* (> start sindex)
605 then ;; we found some chars
606 ;; before we stopped the parse
607 (setq tokval (subseq string sindex start))
609 else ;; immediately stopped at a special char
612 (failure (&optional why)
613 (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
616 (.parse-error "impossible state: ~d [~s]" state string)))
619 (0 ;; starting to parse
620 (ecase (read-token t)
622 (:question (setq state 7))
623 (:hash (setq state 8))
624 (:slash (setq state 3))
625 (:string (setq state 1))
626 (:end (setq state 9))))
627 (1 ;; seen <token><special char>
628 (let ((token tokval))
629 (ecase (read-token t)
630 (:colon (setq scheme token)
631 (if* (equalp "urn" scheme)
633 else (setq state 2)))
634 (:question (push token path-components)
636 (:hash (push token path-components)
638 (:slash (push token path-components)
639 (push "/" path-components)
642 (:end (push token path-components)
645 (ecase (read-token t)
647 (:question (setq state 7))
648 (:hash (setq state 8))
649 (:slash (setq state 3))
650 (:string (setq state 10))
651 (:end (setq state 9))))
652 (10 ;; seen <scheme>:<token>
653 (let ((token tokval))
654 (ecase (read-token t)
656 (:question (push token path-components)
658 (:hash (push token path-components)
660 (:slash (push token path-components)
663 (:end (push token path-components)
665 (3 ;; seen / or <scheme>:/
666 (ecase (read-token t)
668 (:question (push "/" path-components)
670 (:hash (push "/" path-components)
672 (:slash (setq state 4))
673 (:string (push "/" path-components)
674 (push tokval path-components)
676 (:end (push "/" path-components)
678 (4 ;; seen [<scheme>:]//
679 (ecase (read-token t)
681 (:question (failure))
684 (if* (and (equalp "file" scheme)
687 (push "/" path-components)
690 (:string (setq host tokval)
693 (11 ;; seen [<scheme>:]//<host>
694 (ecase (read-token t)
695 (:colon (setq state 5))
696 (:question (setq state 7))
697 (:hash (setq state 8))
698 (:slash (push "/" path-components)
700 (:string (impossible))
701 (:end (setq state 9))))
702 (5 ;; seen [<scheme>:]//<host>:
703 (ecase (read-token t)
705 (:question (failure))
707 (:slash (push "/" path-components)
709 (:string (setq port tokval)
712 (12 ;; seen [<scheme>:]//<host>:[<port>]
713 (ecase (read-token t)
715 (:question (setq state 7))
716 (:hash (setq state 8))
717 (:slash (push "/" path-components)
719 (:string (impossible))
720 (:end (setq state 9))))
722 (ecase (read-token :path)
723 (:question (setq state 7))
724 (:hash (setq state 8))
725 (:string (push tokval path-components)
727 (:end (setq state 9))))
729 (ecase (read-token :path)
730 (:question (setq state 7))
731 (:hash (setq state 8))
732 (:string (impossible))
733 (:end (setq state 9))))
737 then *strict-illegal-query-characters*
738 else *illegal-query-characters*))
739 (ecase (prog1 (read-token :query)
740 (setq illegal-chars *illegal-characters*))
741 (:hash (setq state 8))
742 (:string (setq query tokval)
744 (:end (setq state 9))))
746 (ecase (read-token :query)
747 (:hash (setq state 8))
748 (:string (impossible))
749 (:end (setq state 9))))
751 (ecase (read-token :rest)
752 (:string (setq fragment tokval)
754 (:end (setq state 9))))
759 (apply #'concatenate 'string (nreverse path-components))
762 (15 ;; seen urn:, read nid now
763 (case (read-token :colon *valid-nid-characters*)
764 (:string (setq nid tokval)
766 (t (failure "missing namespace identifier"))))
767 (16 ;; seen urn:<nid>
769 (:colon (setq state 17))
770 (t (failure "missing namespace specific string"))))
771 (17 ;; seen urn:<nid>:, rest is nss
772 (return (values scheme
776 (setq illegal-chars *reserved-nss-characters*)
780 "internal error in parse engine, wrong state: ~s." state)))))))
782 (defun escape-p (string)
783 (declare (optimize (speed 3)))
785 (max (the fixnum (length string))))
787 (declare (fixnum i max))
788 (when (char= #\% (char string i))
791 (defun parse-path (path-string escape)
792 (do* ((xpath-list (delimited-string-to-list path-string #\/))
795 (if* (string= "" (car xpath-list))
796 then (setf (car xpath-list) :absolute)
797 else (push :relative xpath-list))
799 (pl (cdr path-list) (cdr pl))
801 ((null pl) path-list)
803 (if* (cdr (setq segments
804 (if* (string= "" (car pl))
806 else (delimited-string-to-list (car pl) #\;))))
807 then ;; there is a param
809 (mapcar #'(lambda (s)
810 (decode-escaped-encoding s escape
816 (decode-escaped-encoding (car segments) escape
820 (defun decode-escaped-encoding (string escape
821 &optional (reserved-chars
822 *reserved-characters*))
823 ;;Return a string with the real characters.
824 (when (null escape) (return-from decode-escaped-encoding string))
827 (maxpos (length string))
829 (flet ((next-ansii-substring ()
830 (let ((pos (or (position #\% string :start curpos)
832 (when (and (= curpos 0)
834 (return-from decode-escaped-encoding string))
841 (next-encoded-substring ()
842 (let ((pos (or (loop for i from curpos below maxpos by 3
843 unless (char= (aref string i)
848 (let ((octets (handler-case (make-array (/ (- pos curpos)
850 :element-type '(unsigned-byte 8)
853 (.parse-error "Unsyntactic escaped encoding in ~s." string)))))
854 (loop for i from curpos below pos by 3
855 do (vector-push (handler-case
856 (parse-integer string
861 (.parse-error "Non-hexidecimal digits after %: ~c~c."
863 (aref string (+ 2 i)))))
866 (let* ((decoded-string (babel:octets-to-string octets
868 (rpos (if reserved-chars
869 (position-if #'(lambda (ch)
870 (not (or (> (char-code ch) 127)
871 (= (sbit reserved-chars (char-code ch)) 0))))
874 (with-output-to-string (out)
875 (loop for ch across decoded-string
877 do (let ((code (char-code ch)))
879 ((or (null reserved-chars)
881 (= (sbit reserved-chars code) 0))
888 ((< code #x200000) 4)
889 ((< code #x4000000) 5)
892 (t (write-string (subseq string i (+ i 3)) out)
898 while (< curpos maxpos)
899 do (next-ansii-substring)
900 while (< curpos maxpos)
901 do (next-encoded-substring)))
910 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
913 (defun render-uri (uri stream
914 &aux (escape (uri-escaped uri))
915 (*print-pretty* nil))
916 (when (null (uri-string uri))
917 (setf (uri-string uri)
918 (let ((scheme (uri-scheme uri))
919 (host (uri-host uri))
920 (port (uri-port uri))
921 (path (uri-path uri))
922 (query (uri-query uri))
923 (fragment (uri-fragment uri)))
926 (encode-escaped-encoding
927 (string-downcase ;; for upper case lisps
928 (symbol-name scheme))
929 *reserved-characters* escape))
931 (when (or host (eq :file scheme)) "//")
933 (encode-escaped-encoding
934 host *reserved-authority-characters* escape))
937 #-allegro (format nil "~D" port)
938 #+allegro (with-output-to-string (s)
939 (excl::maybe-print-fast s port))
941 (encode-escaped-encoding (or path "/")
943 ;;*reserved-path-characters*
946 (when query (encode-escaped-encoding query nil escape))
948 (when fragment (encode-escaped-encoding fragment nil escape))))))
950 then (format stream "~a" (uri-string uri))
951 else (uri-string uri)))
953 (defun render-parsed-path (path-list escape)
955 (first (car path-list))
956 (pl (cdr path-list) (cdr pl))
957 (pe (car pl) (car pl)))
959 (when res (apply #'concatenate 'string (nreverse res))))
960 (when (or (null first)
961 (prog1 (eq :absolute first)
966 (encode-escaped-encoding pe *reserved-path-characters* escape)
968 else ;; contains params
969 (push (encode-escaped-encoding
970 (car pe) *reserved-path-characters* escape)
972 (dolist (item (cdr pe))
974 (push (encode-escaped-encoding
975 item *reserved-path-characters* escape)
978 (defun render-urn (urn stream
979 &aux (*print-pretty* nil))
980 (when (null (uri-string urn))
981 (setf (uri-string urn)
982 (let ((nid (urn-nid urn))
984 (concatenate 'string "urn:" nid ":" nss))))
986 then (format stream "~a" (uri-string urn))
987 else (uri-string urn)))
989 (defun encode-escaped-encoding (string reserved-chars escape)
990 (when (null escape) (return-from encode-escaped-encoding string))
991 (with-output-to-string (out)
992 (loop for ch across string
993 do (let ((code (char-code ch)))
994 (if (and (< code 128)
995 (or (null reserved-chars)
996 (= 0 (sbit reserved-chars code))))
998 (loop for octet across (babel:string-to-octets (string ch) :encoding :utf-8)
999 do (format out "%~(~2,'0x~)" octet)))))))
1001 (defmethod print-object ((uri uri) stream)
1003 then (print-unreadable-object (uri stream :type t) (render-uri uri stream))
1004 else (render-uri uri stream)))
1006 (defmethod print-object ((urn urn) stream)
1008 then (print-unreadable-object (urn stream :type t) (render-urn urn stream))
1009 else (render-urn urn stream)))
1011 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1012 ;; merging and unmerging
1014 (defmethod merge-uris ((uri string) (base string) &optional place)
1015 (merge-uris (parse-uri uri) (parse-uri base) place))
1017 (defmethod merge-uris ((uri uri) (base string) &optional place)
1018 (merge-uris uri (parse-uri base) place))
1020 (defmethod merge-uris ((uri string) (base uri) &optional place)
1021 (merge-uris (parse-uri uri) base place))
1024 (defmethod merge-uris ((uri uri) (base uri) &optional place)
1025 ;; See ../doc/rfc2396.txt for info on the algorithm we use to merge
1030 (when (and (null (uri-parsed-path uri))
1031 (null (uri-scheme uri))
1032 (null (uri-host uri))
1033 (null (uri-port uri))
1034 (null (uri-query uri)))
1035 (return-from merge-uris
1036 (let ((new (copy-uri base :place place)))
1037 (when (uri-query uri)
1038 (setf (uri-query new) (uri-query uri)))
1039 (when (uri-fragment uri)
1040 (setf (uri-fragment new) (uri-fragment uri)))
1043 (setq uri (copy-uri uri :place place))
1046 (when (uri-scheme uri)
1047 (return-from merge-uris uri))
1048 (setf (uri-scheme uri) (uri-scheme base))
1051 (when (uri-host uri) (go :done))
1052 (setf (uri-host uri) (uri-host base))
1053 (setf (uri-port uri) (uri-port base))
1056 (let ((p (uri-parsed-path uri)))
1059 ;; The following form causes our implementation to be at odds with
1060 ;; RFC 2396, however this is apparently what was intended by the
1061 ;; authors of the RFC. Specifically, (merge-uris "?y" "/foo")
1062 ;; should return #<uri /foo?y> instead of #<uri ?y>, according to
1064 ;;; http://www.apache.org/~fielding/uri/rev-2002/issues.html#003-relative-query
1066 (setf (uri-path uri) (uri-path base))
1069 (when (and p (eq :absolute (car p)))
1070 (when (equal '(:absolute "") p)
1071 ;; Canonicalize the way parsing does:
1072 (setf (uri-path uri) nil))
1077 (or (uri-parsed-path base)
1078 ;; needed because we canonicalize away a path of just `/':
1080 (path (uri-parsed-path uri))
1082 (when (not (eq :absolute (car base-path)))
1083 (error "Cannot merge ~a and ~a, since latter is not absolute."
1088 (append (butlast base-path)
1089 (if* path then (cdr path) else '(""))))
1092 (let ((last (last new-path-list)))
1093 (if* (atom (car last))
1094 then (when (string= "." (car last))
1095 (setf (car last) ""))
1096 else (when (string= "." (caar last))
1097 (setf (caar last) ""))))
1099 (delete "." new-path-list :test #'(lambda (a b)
1105 (let ((npl (cdr new-path-list))
1108 (string= ".." (let ((l (car (last npl))))
1115 :test #'(lambda (a b)
1120 (when (null index) (return))
1122 ;; The RFC says, in 6g, "that the implementation may handle
1123 ;; this error by retaining these components in the resolved
1124 ;; path, by removing them from the resolved path, or by
1125 ;; avoiding traversal of the reference." The examples in C.2
1126 ;; imply that we should do the first thing (retain them), so
1127 ;; that's what we'll do.
1130 then (setq npl (cddr npl))
1132 (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1133 (setf (cdr tmp) (cdddr tmp))))
1134 (setf (cdr new-path-list) npl)
1135 (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1138 ;; don't complain if new-path-list starts with `..'. See comment
1139 ;; above about this step.
1142 (when (or (equal '(:absolute "") new-path-list)
1143 (equal '(:absolute) new-path-list))
1144 (setq new-path-list nil))
1145 (setf (uri-path uri)
1146 (render-parsed-path new-path-list
1147 ;; don't know, so have to assume:
1152 (return-from merge-uris uri)))
1154 (defmethod enough-uri ((uri string) (base string) &optional place)
1155 (enough-uri (parse-uri uri) (parse-uri base) place))
1157 (defmethod enough-uri ((uri uri) (base string) &optional place)
1158 (enough-uri uri (parse-uri base) place))
1160 (defmethod enough-uri ((uri string) (base uri) &optional place)
1161 (enough-uri (parse-uri uri) base place))
1163 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1164 (let ((new-scheme nil)
1167 (new-parsed-path nil))
1169 (when (or (and (uri-scheme uri)
1170 (not (equalp (uri-scheme uri) (uri-scheme base))))
1172 (not (equalp (uri-host uri) (uri-host base))))
1173 (not (equalp (uri-port uri) (uri-port base))))
1174 (return-from enough-uri uri))
1176 (when (null (uri-host uri))
1177 (setq new-host (uri-host base)))
1178 (when (null (uri-port uri))
1179 (setq new-port (uri-port base)))
1181 (when (null (uri-scheme uri))
1182 (setq new-scheme (uri-scheme base)))
1184 ;; Now, for the hard one, path.
1185 ;; We essentially do here what enough-namestring does.
1186 (do* ((base-path (uri-parsed-path base))
1187 (path (uri-parsed-path uri))
1188 (bp base-path (cdr bp))
1190 ((or (null bp) (null p))
1191 ;; If p is nil, that means we have something like
1192 ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1193 ;; new-parsed-path will be nil.
1195 (setq new-parsed-path (copy-list p))
1196 (when (not (symbolp (car new-parsed-path)))
1197 (push :relative new-parsed-path))))
1198 (if* (equal (car bp) (car p))
1200 else (setq new-parsed-path (copy-list p))
1201 (when (not (symbolp (car new-parsed-path)))
1202 (push :relative new-parsed-path))
1206 (when new-parsed-path
1207 (render-parsed-path new-parsed-path
1208 ;; don't know, so have to assume:
1210 (new-query (uri-query uri))
1211 (new-fragment (uri-fragment uri))
1212 (new-plist (copy-list (uri-plist uri))))
1213 (if* (and (null new-scheme)
1217 (null new-parsed-path)
1219 (null new-fragment))
1220 then ;; can't have a completely empty uri!
1222 :class (class-of uri)
1227 :class (class-of uri)
1233 :parsed-path new-parsed-path
1235 :fragment new-fragment
1236 :plist new-plist)))))
1238 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1239 ;; support for interning URIs
1241 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1243 (apply #'make-hash-table :size size
1244 :hash-function 'uri-hash
1245 :test 'uri= :values nil keys)
1247 (apply #'make-hash-table :size size keys))
1249 (defun gethash-uri (uri table)
1250 #+allegro (gethash uri table)
1252 (let* ((hash (uri-hash uri))
1253 (existing (gethash hash table)))
1254 (dolist (u existing)
1256 (return-from gethash-uri (values u t))))
1259 (defun puthash-uri (uri table)
1260 #+allegro (excl:puthash-key uri table)
1262 (let ((existing (gethash (uri-hash uri) table)))
1263 (dolist (u existing)
1265 (return-from puthash-uri u)))
1266 (setf (gethash (uri-hash uri) table)
1267 (cons uri existing))
1271 (defun uri-hash (uri)
1272 (if* (uri-hashcode uri)
1274 else (setf (uri-hashcode uri)
1277 (render-uri uri nil)
1280 (render-uri uri nil))))))
1282 (defvar *uris* (make-uri-space))
1284 (defun uri-space () *uris*)
1286 (defun (setf uri-space) (new-val)
1287 (setq *uris* new-val))
1289 ;; bootstrapping (uri= changed from function to method):
1290 (when (fboundp 'uri=) (fmakunbound 'uri=))
1292 (defgeneric uri= (uri1 uri2))
1293 (defmethod uri= ((uri1 uri) (uri2 uri))
1294 (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1295 (return-from uri= nil))
1296 ;; RFC2396 says: a URL with an explicit ":port", where the port is
1297 ;; the default for the scheme, is the equivalent to one where the
1298 ;; port is elided. Hmmmm. This means that this function has to be
1299 ;; scheme dependent. Grrrr.
1300 (let ((default-port (case (uri-scheme uri1)
1305 (and (equalp (uri-host uri1) (uri-host uri2))
1306 (eql (or (uri-port uri1) default-port)
1307 (or (uri-port uri2) default-port))
1308 (string= (uri-path uri1) (uri-path uri2))
1309 (string= (uri-query uri1) (uri-query uri2))
1310 (string= (uri-fragment uri1) (uri-fragment uri2)))))
1312 (defmethod uri= ((urn1 urn) (urn2 urn))
1313 (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1314 (return-from uri= nil))
1315 (and (equalp (urn-nid urn1) (urn-nid urn2))
1316 (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1318 (defun urn-nss-equal (nss1 nss2 &aux len)
1319 ;; Return t iff the nss values are the same.
1320 ;; %2c and %2C are equivalent.
1321 (when (or (null nss1) (null nss2)
1322 (not (= (setq len (length nss1))
1324 (return-from urn-nss-equal nil))
1329 (setq c1 (char nss1 i))
1330 (setq c2 (char nss2 i))
1333 (if* (and (char= #\% c1) (char= #\% c2))
1334 then (setq state :percent+1)
1335 elseif (char/= c1 c2)
1338 (when (char-not-equal c1 c2) (return nil))
1339 (setq state :percent+2))
1341 (when (char-not-equal c1 c2) (return nil))
1342 (setq state :char)))))
1344 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1345 (let ((uri (gethash-uri xuri uri-space)))
1348 else (puthash-uri xuri uri-space))))
1350 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1351 (intern-uri (parse-uri uri) uri-space))
1353 (defun unintern-uri (uri &optional (uri-space *uris*))
1355 then (clrhash uri-space)
1357 then (remhash uri uri-space)
1358 else (error "bad uri: ~s." uri)))
1360 (defmacro do-all-uris ((var &optional uri-space result-form)
1363 "do-all-uris (var [[uri-space] result-form])
1364 {declaration}* {tag | statement}*
1365 Executes the forms once for each uri with var bound to the current uri"
1368 (g-uri-space (gensym))
1369 (body (third (parse-body forms env))))
1370 `(let ((,g-uri-space (or ,uri-space *uris*)))
1372 (flet ((,f (,var &optional ,g-ignore)
1373 (declare (ignore-if-unused ,var ,g-ignore))
1375 (maphash #',f ,g-uri-space))
1376 (return ,result-form)))))
1378 (defun sharp-u (stream chr arg)
1379 (declare (ignore chr arg))
1380 (let ((arg (read stream nil nil t)))
1384 then (parse-uri arg)
1387 (internal-reader-error
1389 "#u takes a string or list argument: ~s" arg)))))
1392 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1394 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1398 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1400 ;; (don't run under emacs with M-x fi:common-lisp)
1403 (eval-when (:compile-toplevel :load-toplevel :execute)
1407 (defun gc (&rest options)
1408 (declare (ignore options))
1413 (defun time-uri-module ()
1414 (declare (optimize (speed 3) (safety 0) (debug 0)))
1415 (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1416 (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1417 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1418 (format t "~&;;; starting timing testing 1...~%")
1419 (time (dotimes (i 100000) (parse-uri uri)))
1421 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1422 (format t "~&;;; starting timing testing 2...~%")
1423 (let ((uri (parse-uri uri)))
1424 (time (dotimes (i 100000)
1425 ;; forces no caching of the printed representation:
1426 (setf (uri-string uri) nil)
1427 (format nil "~a" uri))))
1429 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1430 (format t "~&;;; starting timing testing 3...~%")
1433 (dotimes (i 100000) (parse-uri uri2))
1434 (let ((uri (parse-uri uri)))
1436 ;; forces no caching of the printed representation:
1437 (setf (uri-string uri) nil)
1438 (format nil "~a" uri)))))))
1440 ;;******** reference output (ultra, modified 5.0.1):
1441 ;;; starting timing testing 1...
1442 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1443 ; cpu time (gc) 600 msec user, 10 msec system
1444 ; cpu time (total) 14,310 msec user, 10 msec system
1445 ; real time 14,465 msec
1447 ; 1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1448 ;;; starting timing testing 2...
1449 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1450 ; cpu time (gc) 280 msec user, 20 msec system
1451 ; cpu time (total) 27,780 msec user, 20 msec system
1452 ; real time 27,897 msec
1454 ; 1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1455 ;;; starting timing testing 3...
1456 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1457 ; cpu time (gc) 1,290 msec user, 30 msec system
1458 ; cpu time (total) 53,580 msec user, 40 msec system
1459 ; real time 54,062 msec
1461 ; 7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1463 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1464 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1466 ;;; starting timing testing 1...
1467 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1468 ; cpu time (gc) 400 msec user, 0 msec system
1469 ; cpu time (total) 14,920 msec user, 0 msec system
1470 ; real time 15,082 msec
1472 ; 1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1473 ;;; starting timing testing 2...
1474 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1475 ; cpu time (gc) 300 msec user, 0 msec system
1476 ; cpu time (total) 27,790 msec user, 10 msec system
1477 ; real time 28,025 msec
1479 ; 1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1480 ;;; starting timing testing 3...
1481 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1482 ; cpu time (gc) 920 msec user, 10 msec system
1483 ; cpu time (total) 48,820 msec user, 30 msec system
1484 ; real time 49,188 msec
1486 ; 3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes