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
54 #:make-uri-space ; interning...
61 #:uri-parse-error ;; Added by KMR
66 (eval-when (:compile-toplevel) (declaim (optimize (speed 3))))
70 (defun parse-body (forms &optional env)
71 "Parses a body, returns (VALUES docstring declarations forms)"
72 (declare (ignore env))
73 ;; fixme -- need to add parsing of multiple declarations
74 (let (docstring declarations)
75 (when (stringp (car forms))
76 (setq docstring (car forms))
77 (setq forms (cdr forms)))
78 (when (and (listp (car forms))
79 (symbolp (caar forms))
80 (string-equal (symbol-name '#:declare)
81 (symbol-name (caar forms))))
82 (setq declarations (car forms))
83 (setq forms (cdr forms)))
84 (values docstring declarations forms)))
87 (defun shrink-vector (str size)
89 (excl::.primcall 'sys::shrink-svector str size)
91 (setq str (sb-kernel:shrink-vector str size))
93 (lisp::shrink-vector str size)
95 (system::shrink-vector$vector str size)
97 (common-lisp::shrink-vector str size)
98 #-(or allegro cmu lispworks sbcl scl)
99 (setq str (subseq str 0 size))
103 ;; KMR: Added new condition to handle cross-implementation variances
104 ;; in the parse-error condition many implementations define
106 (define-condition uri-parse-error (parse-error)
107 ((fmt-control :initarg :fmt-control :accessor fmt-control)
108 (fmt-arguments :initarg :fmt-arguments :accessor fmt-arguments ))
109 (:report (lambda (c stream)
110 (format stream "Parse error:")
111 (apply #'format stream (fmt-control c) (fmt-arguments c)))))
113 (defun .parse-error (fmt &rest args)
114 (error 'uri-parse-error :fmt-control fmt :fmt-arguments args))
117 (defun internal-reader-error (stream fmt &rest args)
118 (apply #'format stream fmt args))
120 #-allegro (defvar *current-case-mode* :case-insensitive-upper)
121 #+allegro (eval-when (:compile-toplevel :load-toplevel :execute)
122 (import '(excl:*current-case-mode*
123 excl:delimited-string-to-list
125 excl::internal-reader-error
129 (defmethod position-char (char (string string) start max)
130 (declare (optimize (speed 3) (safety 0) (space 0))
131 (fixnum start max) (string string))
132 (do* ((i start (1+ i)))
135 (when (char= char (char string i)) (return i))))
138 (defun delimited-string-to-list (string &optional (separator #\space)
140 (declare (optimize (speed 3) (safety 0) (space 0)
141 (compilation-speed 0))
143 (type character separator))
144 (do* ((len (length string))
147 (end (position-char separator string pos len)
148 (position-char separator string pos len)))
151 (push (subseq string pos) output)
152 (when (and (plusp len) (not skip-terminal))
155 (declare (type fixnum pos len)
156 (type (or null fixnum) end))
157 (push (subseq string pos end) output)
158 (setq pos (1+ end))))
161 (eval-when (:compile-toplevel :load-toplevel :execute)
162 (defvar if*-keyword-list '("then" "thenret" "else" "elseif"))
164 (defmacro if* (&rest args)
165 (do ((xx (reverse args) (cdr xx))
172 (cond ((eq state :compl)
174 (t (error "if*: illegal form ~s" args))))
175 (cond ((and (symbolp (car xx))
176 (member (symbol-name (car xx))
178 :test #'string-equal))
179 (setq lookat (symbol-name (car xx)))))
181 (cond ((eq state :init)
182 (cond (lookat (cond ((string-equal lookat "thenret")
186 "if*: bad keyword ~a" lookat))))
189 (push (car xx) col))))
192 (cond ((string-equal lookat "else")
195 "if*: multiples elses")))
198 (push `(t ,@col) totalcol))
199 ((string-equal lookat "then")
201 (t (error "if*: bad keyword ~s"
203 (t (push (car xx) col))))
207 "if*: keyword ~s at the wrong place " (car xx)))
208 (t (setq state :compl)
209 (push `(,(car xx) ,@col) totalcol))))
211 (cond ((not (string-equal lookat "elseif"))
212 (error "if*: missing elseif clause ")))
213 (setq state :init))))))
219 (scheme :initarg :scheme :initform nil :accessor uri-scheme)
220 (host :initarg :host :initform nil :accessor uri-host)
221 (port :initarg :port :initform nil :accessor uri-port)
222 (path :initarg :path :initform nil :accessor uri-path)
223 (query :initarg :query :initform nil :accessor uri-query)
224 (fragment :initarg :fragment :initform nil :accessor uri-fragment)
225 (plist :initarg :plist :initform nil :accessor uri-plist)
229 ;; used to prevent unnessary work, looking for chars to escape and
231 :initarg :escaped :initform nil :accessor uri-escaped)
233 ;; the cached printable representation of the URI. It *might* be
234 ;; different than the original string, though, because the user might
235 ;; have escaped non-reserved chars--they won't be escaped when the URI
237 :initarg :string :initform nil :accessor uri-string)
239 ;; the cached parsed representation of the URI path.
240 :initarg :parsed-path
242 :accessor .uri-parsed-path)
244 ;; cached sxhash, so we don't have to compute it more than once.
245 :initarg :hashcode :initform nil :accessor uri-hashcode)))
248 ((nid :initarg :nid :initform nil :accessor urn-nid)
249 (nss :initarg :nss :initform nil :accessor urn-nss)))
251 (eval-when (:compile-toplevel :execute)
252 (defmacro clear-caching-on-slot-change (name)
253 `(defmethod (setf ,name) :around (new-value (self uri))
254 (declare (ignore new-value))
255 (prog1 (call-next-method)
256 (setf (uri-string self) nil)
257 ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
258 (setf (uri-hashcode self) nil))))
261 (clear-caching-on-slot-change uri-scheme)
262 (clear-caching-on-slot-change uri-host)
263 (clear-caching-on-slot-change uri-port)
264 (clear-caching-on-slot-change uri-path)
265 (clear-caching-on-slot-change uri-query)
266 (clear-caching-on-slot-change uri-fragment)
269 (defmethod make-load-form ((self uri) &optional env)
270 (declare (ignore env))
271 `(make-instance ',(class-name (class-of self))
272 :scheme ,(uri-scheme self)
273 :host ,(uri-host self)
274 :port ,(uri-port self)
275 :path ',(uri-path self)
276 :query ,(uri-query self)
277 :fragment ,(uri-fragment self)
278 :plist ',(uri-plist self)
279 :string ,(uri-string self)
280 :parsed-path ',(.uri-parsed-path self)))
282 (defmethod uri-p ((thing uri)) t)
283 (defmethod uri-p ((thing t)) nil)
287 (scheme (when uri (uri-scheme uri)))
288 (host (when uri (uri-host uri)))
289 (port (when uri (uri-port uri)))
290 (path (when uri (uri-path uri)))
292 (when uri (copy-list (.uri-parsed-path uri))))
293 (query (when uri (uri-query uri)))
294 (fragment (when uri (uri-fragment uri)))
295 (plist (when uri (copy-list (uri-plist uri))))
296 (class (when uri (class-of uri)))
297 &aux (escaped (when uri (uri-escaped uri))))
299 then (setf (uri-scheme place) scheme)
300 (setf (uri-host place) host)
301 (setf (uri-port place) port)
302 (setf (uri-path place) path)
303 (setf (.uri-parsed-path place) parsed-path)
304 (setf (uri-query place) query)
305 (setf (uri-fragment place) fragment)
306 (setf (uri-plist place) plist)
307 (setf (uri-escaped place) escaped)
308 (setf (uri-string place) nil)
309 (setf (uri-hashcode place) nil)
311 elseif (eq 'uri class)
312 then ;; allow the compiler to optimize the call to make-instance:
314 :scheme scheme :host host :port port :path path
315 :parsed-path parsed-path
316 :query query :fragment fragment :plist plist
317 :escaped escaped :string nil :hashcode nil)
318 else (make-instance class
319 :scheme scheme :host host :port port :path path
320 :parsed-path parsed-path
321 :query query :fragment fragment :plist plist
322 :escaped escaped :string nil :hashcode nil)))
324 (defmethod uri-parsed-path ((uri uri))
326 (when (null (.uri-parsed-path uri))
327 (setf (.uri-parsed-path uri)
328 (parse-path (uri-path uri) (uri-escaped uri))))
329 (.uri-parsed-path uri)))
331 (defmethod (setf uri-parsed-path) (path-list (uri uri))
332 (assert (and (consp path-list)
333 (or (member (car path-list) '(:absolute :relative)
335 (setf (uri-path uri) (render-parsed-path path-list t))
336 (setf (.uri-parsed-path uri) path-list)
339 (defun uri-authority (uri)
341 (let ((*print-pretty* nil))
342 (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
345 (if* (equalp "urn" (uri-scheme uri))
347 else (error "URI is not a URN: ~s." uri)))
350 (if* (equalp "urn" (uri-scheme uri))
352 else (error "URI is not a URN: ~s." uri)))
354 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
357 (defparameter *excluded-characters*
359 (loop for i from 0 to #x1f
360 collect (code-char i))
361 '(;; `delims' (except #\%, because it's handled specially):
362 #\< #\> #\" #\space #\#
365 #\{ #\} #\| #\\ #\^ #\[ #\] #\`)))
367 (defun reserved-char-vector (chars &key except)
368 (do* ((a (make-array 127 :element-type 'bit :initial-element 0))
369 (chars chars (cdr chars))
370 (c (car chars) (car chars)))
372 (if* (and except (member c except :test #'char=))
374 else (setf (sbit a (char-int c)) 1))))
376 (defparameter *reserved-characters*
377 (reserved-char-vector
378 (append *excluded-characters*
379 '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
380 (defparameter *reserved-authority-characters*
381 (reserved-char-vector
382 (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
383 (defparameter *reserved-path-characters*
384 (reserved-char-vector
385 (append *excluded-characters*
387 ;;;;The rfc says this should be here, but it doesn't make sense.
391 (defparameter *reserved-fragment-characters*
392 (reserved-char-vector (remove #\# *excluded-characters*)))
394 (eval-when (:compile-toplevel :execute)
395 (defun gen-char-range-list (start end)
397 (endcode (1+ (char-int end)))
398 (chcode (char-int start)
402 ;; - has to be first, otherwise it signifies a range!
404 then (setq res (nreverse res))
407 else (nreverse res)))
408 (if* (= #.(char-int #\-) chcode)
410 else (push (code-char chcode) res))))
413 (defparameter *valid-nid-characters*
414 (reserved-char-vector
415 '#.(nconc (gen-char-range-list #\a #\z)
416 (gen-char-range-list #\A #\Z)
417 (gen-char-range-list #\0 #\9)
419 (defparameter *reserved-nss-characters*
420 (reserved-char-vector
421 (append *excluded-characters* '(#\& #\~ #\/ #\?))))
423 (defparameter *illegal-characters*
424 (reserved-char-vector (remove #\# *excluded-characters*)))
425 (defparameter *strict-illegal-query-characters*
426 (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
427 (defparameter *illegal-query-characters*
428 (reserved-char-vector
429 *excluded-characters* :except '(#\^ #\| #\#)))
432 (defun parse-uri (thing &key (class 'uri) &aux escape)
433 (when (uri-p thing) (return-from parse-uri thing))
435 (setq escape (escape-p thing))
436 (multiple-value-bind (scheme host port path query fragment)
437 (parse-uri-string thing)
441 (case *current-case-mode*
442 ((:case-insensitive-upper :case-sensitive-upper)
444 ((:case-insensitive-lower :case-sensitive-lower)
446 (decode-escaped-encoding scheme escape))
447 (find-package :keyword))))
449 (when (and scheme (eq :urn scheme))
450 (return-from parse-uri
451 (make-instance 'urn :scheme scheme :nid host :nss path)))
453 (when host (setq host (decode-escaped-encoding host escape)))
455 (setq port (read-from-string port))
456 (when (not (numberp port)) (error "port is not a number: ~s." port))
457 (when (not (plusp port))
458 (error "port is not a positive integer: ~d." port))
459 (when (eql port (case scheme
465 (when (or (string= "" path)
466 (and ;; we canonicalize away a reference to just /:
468 (member scheme '(:http :https :ftp) :test #'eq)
473 (decode-escaped-encoding path escape *reserved-path-characters*)))
474 (when query (setq query (decode-escaped-encoding query escape)))
477 (decode-escaped-encoding fragment escape
478 *reserved-fragment-characters*)))
480 then ;; allow the compiler to optimize the make-instance call:
489 else ;; do it the slow way:
499 (defmethod uri ((thing uri))
502 (defmethod uri ((thing string))
505 (defmethod uri ((thing t))
506 (error "Cannot coerce ~s to a uri." thing))
508 (defvar *strict-parse* t)
510 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
511 (declare (optimize (speed 3)))
512 ;; Speed is important, so use a specialized state machine instead of
513 ;; regular expressions for parsing the URI string. The regexp we are
522 (end (length string))
527 (path-components '())
530 ;; namespace identifier, for urn parsing only:
532 (declare (fixnum state start end))
533 (flet ((read-token (kind &optional legal-chars)
537 else (let ((sindex start)
540 (declare (fixnum sindex))
543 (when (>= start end) (return nil))
544 (setq c (char string start))
545 (let ((ci (char-int c)))
547 then (if* (and (eq :colon kind) (eq c #\:))
549 elseif (= 0 (sbit legal-chars ci))
552 URI ~s contains illegal character ~s at position ~d."
554 elseif (and (< ci 128)
556 (= 1 (sbit illegal-chars ci)))
557 then (.parse-error "~
558 URI ~s contains illegal character ~s at position ~d."
562 (#\? (return :question))
563 (#\# (return :hash))))
564 (:query (case c (#\# (return :hash))))
567 (#\: (return :colon))
568 (#\? (return :question))
570 (#\/ (return :slash)))))
572 (if* (> start sindex)
573 then ;; we found some chars
574 ;; before we stopped the parse
575 (setq tokval (subseq string sindex start))
577 else ;; immediately stopped at a special char
580 (failure (&optional why)
581 (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
584 (.parse-error "impossible state: ~d [~s]" state string)))
587 (0 ;; starting to parse
588 (ecase (read-token t)
590 (:question (setq state 7))
591 (:hash (setq state 8))
592 (:slash (setq state 3))
593 (:string (setq state 1))
594 (:end (setq state 9))))
595 (1 ;; seen <token><special char>
596 (let ((token tokval))
597 (ecase (read-token t)
598 (:colon (setq scheme token)
599 (if* (equalp "urn" scheme)
601 else (setq state 2)))
602 (:question (push token path-components)
604 (:hash (push token path-components)
606 (:slash (push token path-components)
607 (push "/" path-components)
610 (:end (push token path-components)
613 (ecase (read-token t)
615 (:question (setq state 7))
616 (:hash (setq state 8))
617 (:slash (setq state 3))
618 (:string (setq state 10))
619 (:end (setq state 9))))
620 (10 ;; seen <scheme>:<token>
621 (let ((token tokval))
622 (ecase (read-token t)
624 (:question (push token path-components)
626 (:hash (push token path-components)
628 (:slash (push token path-components)
631 (:end (push token path-components)
633 (3 ;; seen / or <scheme>:/
634 (ecase (read-token t)
636 (:question (push "/" path-components)
638 (:hash (push "/" path-components)
640 (:slash (setq state 4))
641 (:string (push "/" path-components)
642 (push tokval path-components)
644 (:end (push "/" path-components)
646 (4 ;; seen [<scheme>:]//
647 (ecase (read-token t)
649 (:question (failure))
652 (if* (and (equalp "file" scheme)
655 (push "/" path-components)
658 (:string (setq host tokval)
661 (11 ;; seen [<scheme>:]//<host>
662 (ecase (read-token t)
663 (:colon (setq state 5))
664 (:question (setq state 7))
665 (:hash (setq state 8))
666 (:slash (push "/" path-components)
668 (:string (impossible))
669 (:end (setq state 9))))
670 (5 ;; seen [<scheme>:]//<host>:
671 (ecase (read-token t)
673 (:question (failure))
675 (:slash (push "/" path-components)
677 (:string (setq port tokval)
680 (12 ;; seen [<scheme>:]//<host>:[<port>]
681 (ecase (read-token t)
683 (:question (setq state 7))
684 (:hash (setq state 8))
685 (:slash (push "/" path-components)
687 (:string (impossible))
688 (:end (setq state 9))))
690 (ecase (read-token :path)
691 (:question (setq state 7))
692 (:hash (setq state 8))
693 (:string (push tokval path-components)
695 (:end (setq state 9))))
697 (ecase (read-token :path)
698 (:question (setq state 7))
699 (:hash (setq state 8))
700 (:string (impossible))
701 (:end (setq state 9))))
705 then *strict-illegal-query-characters*
706 else *illegal-query-characters*))
707 (ecase (prog1 (read-token :query)
708 (setq illegal-chars *illegal-characters*))
709 (:hash (setq state 8))
710 (:string (setq query tokval)
712 (:end (setq state 9))))
714 (ecase (read-token :query)
715 (:hash (setq state 8))
716 (:string (impossible))
717 (:end (setq state 9))))
719 (ecase (read-token :rest)
720 (:string (setq fragment tokval)
722 (:end (setq state 9))))
727 (apply #'concatenate 'string (nreverse path-components))
730 (15 ;; seen urn:, read nid now
731 (case (read-token :colon *valid-nid-characters*)
732 (:string (setq nid tokval)
734 (t (failure "missing namespace identifier"))))
735 (16 ;; seen urn:<nid>
737 (:colon (setq state 17))
738 (t (failure "missing namespace specific string"))))
739 (17 ;; seen urn:<nid>:, rest is nss
740 (return (values scheme
744 (setq illegal-chars *reserved-nss-characters*)
748 "internal error in parse engine, wrong state: ~s." state)))))))
750 (defun escape-p (string)
751 (declare (optimize (speed 3)))
753 (max (the fixnum (length string))))
755 (declare (fixnum i max))
756 (when (char= #\% (char string i))
759 (defun parse-path (path-string escape)
760 (do* ((xpath-list (delimited-string-to-list path-string #\/))
763 (if* (string= "" (car xpath-list))
764 then (setf (car xpath-list) :absolute)
765 else (push :relative xpath-list))
767 (pl (cdr path-list) (cdr pl))
769 ((null pl) path-list)
771 (if* (cdr (setq segments
772 (if* (string= "" (car pl))
774 else (delimited-string-to-list (car pl) #\;))))
775 then ;; there is a param
777 (mapcar #'(lambda (s)
778 (decode-escaped-encoding s escape
784 (decode-escaped-encoding (car segments) escape
788 (defun decode-escaped-encoding (string escape
789 &optional (reserved-chars
790 *reserved-characters*))
791 ;; Return a string with the real characters.
792 (when (null escape) (return-from decode-escaped-encoding string))
794 (max (length string))
795 (new-string (copy-seq string))
799 (shrink-vector new-string new-i))
800 (if* (char= #\% (setq ch (char string i)))
801 then (when (> (+ i 3) max)
803 "Unsyntactic escaped encoding in ~s." string))
804 (setq ch (char string (incf i)))
805 (setq ch2 (char string (incf i)))
806 (when (not (and (setq chc (digit-char-p ch 16))
807 (setq chc2 (digit-char-p ch2 16))))
809 "Non-hexidecimal digits after %: %c%c." ch ch2))
810 (let ((ci (+ (* 16 chc) chc2)))
811 (if* (or (null reserved-chars)
812 (> ci 127) ; bug11527
813 (= 0 (sbit reserved-chars ci)))
815 (setf (char new-string new-i)
817 else (setf (char new-string new-i) #\%)
818 (setf (char new-string (incf new-i)) ch)
819 (setf (char new-string (incf new-i)) ch2)))
820 else (setf (char new-string new-i) ch))))
822 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
825 (defun render-uri (uri stream
826 &aux (escape (uri-escaped uri))
827 (*print-pretty* nil))
828 (when (null (uri-string uri))
829 (setf (uri-string uri)
830 (let ((scheme (uri-scheme uri))
831 (host (uri-host uri))
832 (port (uri-port uri))
833 (path (uri-path uri))
834 (query (uri-query uri))
835 (fragment (uri-fragment uri)))
838 (encode-escaped-encoding
839 (string-downcase ;; for upper case lisps
840 (symbol-name scheme))
841 *reserved-characters* escape))
843 (when (or host (eq :file scheme)) "//")
845 (encode-escaped-encoding
846 host *reserved-authority-characters* escape))
849 #-allegro (format nil "~D" port)
850 #+allegro (with-output-to-string (s)
851 (excl::maybe-print-fast s port))
853 (encode-escaped-encoding (or path "/")
855 ;;*reserved-path-characters*
858 (when query (encode-escaped-encoding query nil escape))
860 (when fragment (encode-escaped-encoding fragment nil escape))))))
862 then (format stream "~a" (uri-string uri))
863 else (uri-string uri)))
865 (defun render-parsed-path (path-list escape)
867 (first (car path-list))
868 (pl (cdr path-list) (cdr pl))
869 (pe (car pl) (car pl)))
871 (when res (apply #'concatenate 'string (nreverse res))))
872 (when (or (null first)
873 (prog1 (eq :absolute first)
878 (encode-escaped-encoding pe *reserved-path-characters* escape)
880 else ;; contains params
881 (push (encode-escaped-encoding
882 (car pe) *reserved-path-characters* escape)
884 (dolist (item (cdr pe))
886 (push (encode-escaped-encoding
887 item *reserved-path-characters* escape)
890 (defun render-urn (urn stream
891 &aux (*print-pretty* nil))
892 (when (null (uri-string urn))
893 (setf (uri-string urn)
894 (let ((nid (urn-nid urn))
896 (concatenate 'string "urn:" nid ":" nss))))
898 then (format stream "~a" (uri-string urn))
899 else (uri-string urn)))
901 (defparameter *escaped-encoding*
902 (vector #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f))
904 (defun encode-escaped-encoding (string reserved-chars escape)
905 (when (null escape) (return-from encode-escaped-encoding string))
906 ;; Make a string as big as it possibly needs to be (3 times the original
907 ;; size), and truncate it at the end.
908 (do* ((max (length string))
909 (new-max (* 3 max)) ;; worst case new size
910 (new-string (make-string new-max))
915 (shrink-vector new-string (incf new-i)))
916 (setq ci (char-int (setq c (char string i))))
917 (if* (or (null reserved-chars)
919 (= 0 (sbit reserved-chars ci)))
922 (setf (char new-string new-i) c)
923 else ;; need to escape it
924 (multiple-value-bind (q r) (truncate ci 16)
925 (setf (char new-string (incf new-i)) #\%)
926 (setf (char new-string (incf new-i)) (elt *escaped-encoding* q))
927 (setf (char new-string (incf new-i))
928 (elt *escaped-encoding* r))))))
930 (defmethod print-object ((uri uri) stream)
932 then (print-unreadable-object (uri stream :type t) (render-uri uri stream))
933 else (render-uri uri stream)))
935 (defmethod print-object ((urn urn) stream)
937 then (print-unreadable-object (urn stream :type t) (render-urn urn stream))
938 else (render-urn urn stream)))
940 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
941 ;; merging and unmerging
943 (defmethod merge-uris ((uri string) (base string) &optional place)
944 (merge-uris (parse-uri uri) (parse-uri base) place))
946 (defmethod merge-uris ((uri uri) (base string) &optional place)
947 (merge-uris uri (parse-uri base) place))
949 (defmethod merge-uris ((uri string) (base uri) &optional place)
950 (merge-uris (parse-uri uri) base place))
953 (defmethod merge-uris ((uri uri) (base uri) &optional place)
954 ;; See ../doc/rfc2396.txt for info on the algorithm we use to merge
959 (when (and (null (uri-parsed-path uri))
960 (null (uri-scheme uri))
961 (null (uri-host uri))
962 (null (uri-port uri))
963 (null (uri-query uri)))
964 (return-from merge-uris
965 (let ((new (copy-uri base :place place)))
966 (when (uri-query uri)
967 (setf (uri-query new) (uri-query uri)))
968 (when (uri-fragment uri)
969 (setf (uri-fragment new) (uri-fragment uri)))
972 (setq uri (copy-uri uri :place place))
975 (when (uri-scheme uri)
976 (return-from merge-uris uri))
977 (setf (uri-scheme uri) (uri-scheme base))
980 (when (uri-host uri) (go :done))
981 (setf (uri-host uri) (uri-host base))
982 (setf (uri-port uri) (uri-port base))
985 (let ((p (uri-parsed-path uri)))
988 ;; The following form causes our implementation to be at odds with
989 ;; RFC 2396, however this is apparently what was intended by the
990 ;; authors of the RFC. Specifically, (merge-uris "?y" "/foo")
991 ;; should return #<uri /foo?y> instead of #<uri ?y>, according to
993 ;;; http://www.apache.org/~fielding/uri/rev-2002/issues.html#003-relative-query
995 (setf (uri-path uri) (uri-path base))
998 (when (and p (eq :absolute (car p)))
999 (when (equal '(:absolute "") p)
1000 ;; Canonicalize the way parsing does:
1001 (setf (uri-path uri) nil))
1006 (or (uri-parsed-path base)
1007 ;; needed because we canonicalize away a path of just `/':
1009 (path (uri-parsed-path uri))
1011 (when (not (eq :absolute (car base-path)))
1012 (error "Cannot merge ~a and ~a, since latter is not absolute."
1017 (append (butlast base-path)
1018 (if* path then (cdr path) else '(""))))
1021 (let ((last (last new-path-list)))
1022 (if* (atom (car last))
1023 then (when (string= "." (car last))
1024 (setf (car last) ""))
1025 else (when (string= "." (caar last))
1026 (setf (caar last) ""))))
1028 (delete "." new-path-list :test #'(lambda (a b)
1034 (let ((npl (cdr new-path-list))
1037 (string= ".." (let ((l (car (last npl))))
1044 :test #'(lambda (a b)
1049 (when (null index) (return))
1051 ;; The RFC says, in 6g, "that the implementation may handle
1052 ;; this error by retaining these components in the resolved
1053 ;; path, by removing them from the resolved path, or by
1054 ;; avoiding traversal of the reference." The examples in C.2
1055 ;; imply that we should do the first thing (retain them), so
1056 ;; that's what we'll do.
1059 then (setq npl (cddr npl))
1061 (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1062 (setf (cdr tmp) (cdddr tmp))))
1063 (setf (cdr new-path-list) npl)
1064 (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1067 ;; don't complain if new-path-list starts with `..'. See comment
1068 ;; above about this step.
1071 (when (or (equal '(:absolute "") new-path-list)
1072 (equal '(:absolute) new-path-list))
1073 (setq new-path-list nil))
1074 (setf (uri-path uri)
1075 (render-parsed-path new-path-list
1076 ;; don't know, so have to assume:
1081 (return-from merge-uris uri)))
1083 (defmethod enough-uri ((uri string) (base string) &optional place)
1084 (enough-uri (parse-uri uri) (parse-uri base) place))
1086 (defmethod enough-uri ((uri uri) (base string) &optional place)
1087 (enough-uri uri (parse-uri base) place))
1089 (defmethod enough-uri ((uri string) (base uri) &optional place)
1090 (enough-uri (parse-uri uri) base place))
1092 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1093 (let ((new-scheme nil)
1096 (new-parsed-path nil))
1098 (when (or (and (uri-scheme uri)
1099 (not (equalp (uri-scheme uri) (uri-scheme base))))
1101 (not (equalp (uri-host uri) (uri-host base))))
1102 (not (equalp (uri-port uri) (uri-port base))))
1103 (return-from enough-uri uri))
1105 (when (null (uri-host uri))
1106 (setq new-host (uri-host base)))
1107 (when (null (uri-port uri))
1108 (setq new-port (uri-port base)))
1110 (when (null (uri-scheme uri))
1111 (setq new-scheme (uri-scheme base)))
1113 ;; Now, for the hard one, path.
1114 ;; We essentially do here what enough-namestring does.
1115 (do* ((base-path (uri-parsed-path base))
1116 (path (uri-parsed-path uri))
1117 (bp base-path (cdr bp))
1119 ((or (null bp) (null p))
1120 ;; If p is nil, that means we have something like
1121 ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1122 ;; new-parsed-path will be nil.
1124 (setq new-parsed-path (copy-list p))
1125 (when (not (symbolp (car new-parsed-path)))
1126 (push :relative new-parsed-path))))
1127 (if* (equal (car bp) (car p))
1129 else (setq new-parsed-path (copy-list p))
1130 (when (not (symbolp (car new-parsed-path)))
1131 (push :relative new-parsed-path))
1135 (when new-parsed-path
1136 (render-parsed-path new-parsed-path
1137 ;; don't know, so have to assume:
1139 (new-query (uri-query uri))
1140 (new-fragment (uri-fragment uri))
1141 (new-plist (copy-list (uri-plist uri))))
1142 (if* (and (null new-scheme)
1146 (null new-parsed-path)
1148 (null new-fragment))
1149 then ;; can't have a completely empty uri!
1151 :class (class-of uri)
1156 :class (class-of uri)
1162 :parsed-path new-parsed-path
1164 :fragment new-fragment
1165 :plist new-plist)))))
1167 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1168 ;; support for interning URIs
1170 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1172 (apply #'make-hash-table :size size
1173 :hash-function 'uri-hash
1174 :test 'uri= :values nil keys)
1176 (apply #'make-hash-table :size size keys))
1178 (defun gethash-uri (uri table)
1179 #+allegro (gethash uri table)
1181 (let* ((hash (uri-hash uri))
1182 (existing (gethash hash table)))
1183 (dolist (u existing)
1185 (return-from gethash-uri (values u t))))
1188 (defun puthash-uri (uri table)
1189 #+allegro (excl:puthash-key uri table)
1191 (let ((existing (gethash (uri-hash uri) table)))
1192 (dolist (u existing)
1194 (return-from puthash-uri u)))
1195 (setf (gethash (uri-hash uri) table)
1196 (cons uri existing))
1200 (defun uri-hash (uri)
1201 (if* (uri-hashcode uri)
1203 else (setf (uri-hashcode uri)
1206 (render-uri uri nil)
1209 (render-uri uri nil))))))
1211 (defvar *uris* (make-uri-space))
1213 (defun uri-space () *uris*)
1215 (defun (setf uri-space) (new-val)
1216 (setq *uris* new-val))
1218 ;; bootstrapping (uri= changed from function to method):
1219 (when (fboundp 'uri=) (fmakunbound 'uri=))
1221 (defgeneric uri= (uri1 uri2))
1222 (defmethod uri= ((uri1 uri) (uri2 uri))
1223 (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1224 (return-from uri= nil))
1225 ;; RFC2396 says: a URL with an explicit ":port", where the port is
1226 ;; the default for the scheme, is the equivalent to one where the
1227 ;; port is elided. Hmmmm. This means that this function has to be
1228 ;; scheme dependent. Grrrr.
1229 (let ((default-port (case (uri-scheme uri1)
1234 (and (equalp (uri-host uri1) (uri-host uri2))
1235 (eql (or (uri-port uri1) default-port)
1236 (or (uri-port uri2) default-port))
1237 (string= (uri-path uri1) (uri-path uri2))
1238 (string= (uri-query uri1) (uri-query uri2))
1239 (string= (uri-fragment uri1) (uri-fragment uri2)))))
1241 (defmethod uri= ((urn1 urn) (urn2 urn))
1242 (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1243 (return-from uri= nil))
1244 (and (equalp (urn-nid urn1) (urn-nid urn2))
1245 (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1247 (defun urn-nss-equal (nss1 nss2 &aux len)
1248 ;; Return t iff the nss values are the same.
1249 ;; %2c and %2C are equivalent.
1250 (when (or (null nss1) (null nss2)
1251 (not (= (setq len (length nss1))
1253 (return-from urn-nss-equal nil))
1258 (setq c1 (char nss1 i))
1259 (setq c2 (char nss2 i))
1262 (if* (and (char= #\% c1) (char= #\% c2))
1263 then (setq state :percent+1)
1264 elseif (char/= c1 c2)
1267 (when (char-not-equal c1 c2) (return nil))
1268 (setq state :percent+2))
1270 (when (char-not-equal c1 c2) (return nil))
1271 (setq state :char)))))
1273 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1274 (let ((uri (gethash-uri xuri uri-space)))
1277 else (puthash-uri xuri uri-space))))
1279 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1280 (intern-uri (parse-uri uri) uri-space))
1282 (defun unintern-uri (uri &optional (uri-space *uris*))
1284 then (clrhash uri-space)
1286 then (remhash uri uri-space)
1287 else (error "bad uri: ~s." uri)))
1289 (defmacro do-all-uris ((var &optional uri-space result-form)
1292 "do-all-uris (var [[uri-space] result-form])
1293 {declaration}* {tag | statement}*
1294 Executes the forms once for each uri with var bound to the current uri"
1297 (g-uri-space (gensym))
1298 (body (third (parse-body forms env))))
1299 `(let ((,g-uri-space (or ,uri-space *uris*)))
1301 (flet ((,f (,var &optional ,g-ignore)
1302 (declare (ignore-if-unused ,var ,g-ignore))
1304 (maphash #',f ,g-uri-space))
1305 (return ,result-form)))))
1307 (defun sharp-u (stream chr arg)
1308 (declare (ignore chr arg))
1309 (let ((arg (read stream nil nil t)))
1313 then (parse-uri arg)
1316 (internal-reader-error
1318 "#u takes a string or list argument: ~s" arg)))))
1321 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1323 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1327 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1329 ;; (don't run under emacs with M-x fi:common-lisp)
1332 (eval-when (:compile-toplevel :load-toplevel :execute)
1336 (defun gc (&rest options)
1337 (declare (ignore options))
1342 (defun time-uri-module ()
1343 (declare (optimize (speed 3) (safety 0) (debug 0)))
1344 (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1345 (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1346 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1347 (format t "~&;;; starting timing testing 1...~%")
1348 (time (dotimes (i 100000) (parse-uri uri)))
1350 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1351 (format t "~&;;; starting timing testing 2...~%")
1352 (let ((uri (parse-uri uri)))
1353 (time (dotimes (i 100000)
1354 ;; forces no caching of the printed representation:
1355 (setf (uri-string uri) nil)
1356 (format nil "~a" uri))))
1358 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1359 (format t "~&;;; starting timing testing 3...~%")
1362 (dotimes (i 100000) (parse-uri uri2))
1363 (let ((uri (parse-uri uri)))
1365 ;; forces no caching of the printed representation:
1366 (setf (uri-string uri) nil)
1367 (format nil "~a" uri)))))))
1369 ;;******** reference output (ultra, modified 5.0.1):
1370 ;;; starting timing testing 1...
1371 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1372 ; cpu time (gc) 600 msec user, 10 msec system
1373 ; cpu time (total) 14,310 msec user, 10 msec system
1374 ; real time 14,465 msec
1376 ; 1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1377 ;;; starting timing testing 2...
1378 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1379 ; cpu time (gc) 280 msec user, 20 msec system
1380 ; cpu time (total) 27,780 msec user, 20 msec system
1381 ; real time 27,897 msec
1383 ; 1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1384 ;;; starting timing testing 3...
1385 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1386 ; cpu time (gc) 1,290 msec user, 30 msec system
1387 ; cpu time (total) 53,580 msec user, 40 msec system
1388 ; real time 54,062 msec
1390 ; 7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1392 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1393 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1395 ;;; starting timing testing 1...
1396 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1397 ; cpu time (gc) 400 msec user, 0 msec system
1398 ; cpu time (total) 14,920 msec user, 0 msec system
1399 ; real time 15,082 msec
1401 ; 1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1402 ;;; starting timing testing 2...
1403 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1404 ; cpu time (gc) 300 msec user, 0 msec system
1405 ; cpu time (total) 27,790 msec user, 10 msec system
1406 ; real time 28,025 msec
1408 ; 1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1409 ;;; starting timing testing 3...
1410 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1411 ; cpu time (gc) 920 msec user, 10 msec system
1412 ; cpu time (total) 48,820 msec user, 30 msec system
1413 ; real time 49,188 msec
1415 ; 3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes