1 ;; -*- mode: common-lisp; package: puri -*-
2 ;; Support for URIs in Allegro.
3 ;; For general URI information see RFC2396.
5 ;; copyright (c) 1999-2001 Franz Inc, Berkeley, CA - All rights reserved.
6 ;; copyright (c) 2003 Kevin Rosenberg (porting changes)
8 ;; The software, data and information contained herein are proprietary
9 ;; to, and comprise valuable trade secrets of, Franz, Inc. They are
10 ;; given in confidence by Franz, Inc. pursuant to a written license
11 ;; agreement, and may be stored and used only in accordance with the terms
14 ;; Restricted Rights Legend
15 ;; ------------------------
16 ;; Use, duplication, and disclosure of the software, data and information
17 ;; contained herein by any agency, department or entity of the U.S.
18 ;; Government are subject to restrictions of Restricted Rights for
19 ;; Commercial Software developed at private expense as specified in
20 ;; DOD FAR Supplement 52.227-7013 (c) (1) (ii), as applicable.
22 ;; Original version from ACL 6.1:
23 ;; uri.cl,v 2.3.6.4.2.1 2001/08/09 17:42:39 layer
25 ;; $Id: src.lisp,v 1.7 2003/07/19 20:32:48 kevin Exp $
30 #:uri ; the type and a function
34 #:uri-scheme ; and slots
40 #:uri-authority ; pseudo-slot accessor
43 #:urn-nid ; pseudo-slot accessor
44 #:urn-nss ; pseudo-slot accessor
53 #:make-uri-space ; interning...
62 (eval-when (:compile-toplevel)
63 (declaim (optimize (speed 3))))
66 #-(or allegro lispworks)
67 (define-condition parse-error (error) ())
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 (sb-kernel:shrink-vector str size)
93 (lisp::shrink-vector str size)
95 (system::shrink-vector$vector str size)
96 #+(or allegro cmu sbcl lispworks)
98 #-(or allegro cmu sbcl lispworks)
103 (defun .parse-error (fmt &rest args)
104 (error (make-condition 'parse-error :format-control fmt
105 :format-arguments args)))
108 (defun internal-reader-error (stream fmt &rest args)
109 (apply #'format stream fmt args))
111 #-allegro (defvar *current-case-mode* :case-insensitive-upper)
112 #+allegro (eval-when (:compile-toplevel :load-toplevel :execute)
113 (import '(excl:*current-case-mode*
114 excl:delimited-string-to-list
117 excl::internal-reader-error
121 (defun position-char (char string start max)
122 (declare (optimize (speed 3) (safety 0) (space 0))
123 (fixnum start max) (simple-string string))
124 (do* ((i start (1+ i)))
127 (when (char= char (schar string i)) (return i))))
130 (defun delimited-string-to-list (string &optional (separator #\space)
132 (declare (optimize (speed 3) (safety 0) (space 0)
133 (compilation-speed 0))
135 (type character separator))
136 (do* ((len (length string))
139 (end (position-char separator string pos len)
140 (position-char separator string pos len)))
143 (push (subseq string pos) output)
144 (when (or (not skip-terminal) (zerop len))
147 (declare (type fixnum pos len)
148 (type (or null fixnum) end))
149 (push (subseq string pos end) output)
150 (setq pos (1+ end))))
153 (eval-when (:compile-toplevel :load-toplevel :execute)
154 (defvar if*-keyword-list '("then" "thenret" "else" "elseif"))
156 (defmacro if* (&rest args)
157 (do ((xx (reverse args) (cdr xx))
164 (cond ((eq state :compl)
166 (t (error "if*: illegal form ~s" args))))
167 (cond ((and (symbolp (car xx))
168 (member (symbol-name (car xx))
170 :test #'string-equal))
171 (setq lookat (symbol-name (car xx)))))
173 (cond ((eq state :init)
174 (cond (lookat (cond ((string-equal lookat "thenret")
178 "if*: bad keyword ~a" lookat))))
181 (push (car xx) col))))
184 (cond ((string-equal lookat "else")
187 "if*: multiples elses")))
190 (push `(t ,@col) totalcol))
191 ((string-equal lookat "then")
193 (t (error "if*: bad keyword ~s"
195 (t (push (car xx) col))))
199 "if*: keyword ~s at the wrong place " (car xx)))
200 (t (setq state :compl)
201 (push `(,(car xx) ,@col) totalcol))))
203 (cond ((not (string-equal lookat "elseif"))
204 (error "if*: missing elseif clause ")))
205 (setq state :init))))))
211 (scheme :initarg :scheme :initform nil :accessor uri-scheme)
212 (host :initarg :host :initform nil :accessor uri-host)
213 (port :initarg :port :initform nil :accessor uri-port)
214 (path :initarg :path :initform nil :accessor uri-path)
215 (query :initarg :query :initform nil :accessor uri-query)
216 (fragment :initarg :fragment :initform nil :accessor uri-fragment)
217 (plist :initarg :plist :initform nil :accessor uri-plist)
221 ;; used to prevent unnessary work, looking for chars to escape and
223 :initarg :escaped :initform nil :accessor uri-escaped)
225 ;; the cached printable representation of the URI. It *might* be
226 ;; different than the original string, though, because the user might
227 ;; have escaped non-reserved chars--they won't be escaped when the URI
229 :initarg :string :initform nil :accessor uri-string)
231 ;; the cached parsed representation of the URI path.
232 :initarg :parsed-path
234 :accessor .uri-parsed-path)
236 ;; cached sxhash, so we don't have to compute it more than once.
237 :initarg :hashcode :initform nil :accessor uri-hashcode)))
240 ((nid :initarg :nid :initform nil :accessor urn-nid)
241 (nss :initarg :nss :initform nil :accessor urn-nss)))
243 (eval-when (:compile-toplevel :execute)
244 (defmacro clear-caching-on-slot-change (name)
245 `(defmethod (setf ,name) :around (new-value (self uri))
246 (declare (ignore new-value))
247 (prog1 (call-next-method)
248 (setf (uri-string self) nil)
249 ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
250 (setf (uri-hashcode self) nil))))
253 (clear-caching-on-slot-change uri-scheme)
254 (clear-caching-on-slot-change uri-host)
255 (clear-caching-on-slot-change uri-port)
256 (clear-caching-on-slot-change uri-path)
257 (clear-caching-on-slot-change uri-query)
258 (clear-caching-on-slot-change uri-fragment)
261 (defmethod make-load-form ((self uri) &optional env)
262 (declare (ignore env))
263 `(make-instance ',(class-name (class-of self))
264 :scheme ,(uri-scheme self)
265 :host ,(uri-host self)
266 :port ,(uri-port self)
267 :path ',(uri-path self)
268 :query ,(uri-query self)
269 :fragment ,(uri-fragment self)
270 :plist ',(uri-plist self)
271 :string ,(uri-string self)
272 :parsed-path ',(.uri-parsed-path self)))
274 (defmethod uri-p ((thing uri)) t)
275 (defmethod uri-p ((thing t)) nil)
279 (scheme (when uri (uri-scheme uri)))
280 (host (when uri (uri-host uri)))
281 (port (when uri (uri-port uri)))
282 (path (when uri (uri-path uri)))
284 (when uri (copy-list (.uri-parsed-path uri))))
285 (query (when uri (uri-query uri)))
286 (fragment (when uri (uri-fragment uri)))
287 (plist (when uri (copy-list (uri-plist uri))))
288 (class (when uri (class-of uri)))
289 &aux (escaped (when uri (uri-escaped uri))))
291 then (setf (uri-scheme place) scheme)
292 (setf (uri-host place) host)
293 (setf (uri-port place) port)
294 (setf (uri-path place) path)
295 (setf (.uri-parsed-path place) parsed-path)
296 (setf (uri-query place) query)
297 (setf (uri-fragment place) fragment)
298 (setf (uri-plist place) plist)
299 (setf (uri-escaped place) escaped)
300 (setf (uri-string place) nil)
301 (setf (uri-hashcode place) nil)
303 elseif (eq 'uri class)
304 then ;; allow the compiler to optimize the call to make-instance:
306 :scheme scheme :host host :port port :path path
307 :parsed-path parsed-path
308 :query query :fragment fragment :plist plist
309 :escaped escaped :string nil :hashcode nil)
310 else (make-instance class
311 :scheme scheme :host host :port port :path path
312 :parsed-path parsed-path
313 :query query :fragment fragment :plist plist
314 :escaped escaped :string nil :hashcode nil)))
316 (defmethod uri-parsed-path ((uri uri))
318 (when (null (.uri-parsed-path uri))
319 (setf (.uri-parsed-path uri)
320 (parse-path (uri-path uri) (uri-escaped uri))))
321 (.uri-parsed-path uri)))
323 (defmethod (setf uri-parsed-path) (path-list (uri uri))
324 (assert (and (consp path-list)
325 (or (member (car path-list) '(:absolute :relative)
327 (setf (uri-path uri) (render-parsed-path path-list t))
328 (setf (.uri-parsed-path uri) path-list)
331 (defun uri-authority (uri)
333 (let ((*print-pretty* nil))
334 (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
337 (if* (equalp "urn" (uri-scheme uri))
339 else (error "URI is not a URN: ~s." uri)))
342 (if* (equalp "urn" (uri-scheme uri))
344 else (error "URI is not a URN: ~s." uri)))
346 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
349 (defparameter *excluded-characters*
350 '(;; `delims' (except #\%, because it's handled specially):
351 #\< #\> #\" #\space #\#
353 #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
355 (defun reserved-char-vector (chars &key except)
356 (do* ((a (make-array 127 :element-type 'bit :initial-element 0))
357 (chars chars (cdr chars))
358 (c (car chars) (car chars)))
360 (if* (and except (member c except :test #'char=))
362 else (setf (sbit a (char-int c)) 1))))
364 (defparameter *reserved-characters*
365 (reserved-char-vector
366 (append *excluded-characters*
367 '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
368 (defparameter *reserved-authority-characters*
369 (reserved-char-vector
370 (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
371 (defparameter *reserved-path-characters*
372 (reserved-char-vector
373 (append *excluded-characters*
375 ;;;;The rfc says this should be here, but it doesn't make sense.
378 (defparameter *reserved-path-characters2*
379 ;; These are the same characters that are in
380 ;; *reserved-path-characters*, minus #\/. Why? Because the parsed
381 ;; representation of the path can contain the %2f converted into a /.
382 ;; That's the whole point of having the parsed representation, so that
383 ;; lisp programs can deal with the path element data in the most
385 (reserved-char-vector
386 (append *excluded-characters*
388 ;;;;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 (schar 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 (:string (setq host tokval)
655 (11 ;; seen [<scheme>:]//<host>
656 (ecase (read-token t)
657 (:colon (setq state 5))
658 (:question (setq state 7))
659 (:hash (setq state 8))
660 (:slash (push "/" path-components)
662 (:string (impossible))
663 (:end (setq state 9))))
664 (5 ;; seen [<scheme>:]//<host>:
665 (ecase (read-token t)
667 (:question (failure))
669 (:slash (push "/" path-components)
671 (:string (setq port tokval)
674 (12 ;; seen [<scheme>:]//<host>:[<port>]
675 (ecase (read-token t)
677 (:question (setq state 7))
678 (:hash (setq state 8))
679 (:slash (push "/" path-components)
681 (:string (impossible))
682 (:end (setq state 9))))
684 (ecase (read-token :path)
685 (:question (setq state 7))
686 (:hash (setq state 8))
687 (:string (push tokval path-components)
689 (:end (setq state 9))))
691 (ecase (read-token :path)
692 (:question (setq state 7))
693 (:hash (setq state 8))
694 (:string (impossible))
695 (:end (setq state 9))))
699 then *strict-illegal-query-characters*
700 else *illegal-query-characters*))
701 (ecase (prog1 (read-token :query)
702 (setq illegal-chars *illegal-characters*))
703 (:hash (setq state 8))
704 (:string (setq query tokval)
706 (:end (setq state 9))))
708 (ecase (read-token :query)
709 (:hash (setq state 8))
710 (:string (impossible))
711 (:end (setq state 9))))
713 (ecase (read-token :rest)
714 (:string (setq fragment tokval)
716 (:end (setq state 9))))
721 (apply #'concatenate 'simple-string (nreverse path-components))
724 (15 ;; seen urn:, read nid now
725 (case (read-token :colon *valid-nid-characters*)
726 (:string (setq nid tokval)
728 (t (failure "missing namespace identifier"))))
729 (16 ;; seen urn:<nid>
731 (:colon (setq state 17))
732 (t (failure "missing namespace specific string"))))
733 (17 ;; seen urn:<nid>:, rest is nss
734 (return (values scheme
738 (setq illegal-chars *reserved-nss-characters*)
742 "internal error in parse engine, wrong state: ~s." state)))))))
744 (defun escape-p (string)
745 (declare (optimize (speed 3)))
747 (max (the fixnum (length string))))
749 (declare (fixnum i max))
750 (when (char= #\% (schar string i))
753 (defun parse-path (path-string escape)
754 (do* ((xpath-list (delimited-string-to-list path-string #\/))
757 (if* (string= "" (car xpath-list))
758 then (setf (car xpath-list) :absolute)
759 else (push :relative xpath-list))
761 (pl (cdr path-list) (cdr pl))
763 ((null pl) path-list)
764 (if* (cdr (setq segments (delimited-string-to-list (car pl) #\;)))
765 then ;; there is a param
766 ;;; (setf (car pl) segments)
768 (mapcar #'(lambda (s)
769 (decode-escaped-encoding
770 s escape *reserved-path-characters2*))
773 ;;; (setf (car pl) (car segments))
775 (decode-escaped-encoding
776 (car segments) escape *reserved-path-characters2*)))))
778 (defun decode-escaped-encoding (string escape
779 &optional (reserved-chars
780 *reserved-characters*))
781 ;; Return a string with the real characters.
782 (when (null escape) (return-from decode-escaped-encoding string))
784 (max (length string))
785 (new-string (copy-seq string))
789 (shrink-vector new-string new-i))
790 (if* (char= #\% (setq ch (schar string i)))
791 then (when (> (+ i 3) max)
793 "Unsyntactic escaped encoding in ~s." string))
794 (setq ch (schar string (incf i)))
795 (setq ch2 (schar string (incf i)))
796 (when (not (and (setq chc (digit-char-p ch 16))
797 (setq chc2 (digit-char-p ch2 16))))
799 "Non-hexidecimal digits after %: %c%c." ch ch2))
800 (let ((ci (+ (* 16 chc) chc2)))
801 (if* (or (null reserved-chars)
802 (= 0 (sbit reserved-chars ci)))
804 (setf (schar new-string new-i)
806 else (setf (schar new-string new-i) #\%)
807 (setf (schar new-string (incf new-i)) ch)
808 (setf (schar new-string (incf new-i)) ch2)))
809 else (setf (schar new-string new-i) ch))))
811 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
814 (defun render-uri (uri stream
815 &aux (escape (uri-escaped uri))
816 (*print-pretty* nil))
817 (when (null (uri-string uri))
818 (setf (uri-string uri)
819 (let ((scheme (uri-scheme uri))
820 (host (uri-host uri))
821 (port (uri-port uri))
822 (path (uri-path uri))
823 (query (uri-query uri))
824 (fragment (uri-fragment uri)))
825 (concatenate 'simple-string
827 (encode-escaped-encoding
828 (string-downcase ;; for upper case lisps
829 (symbol-name scheme))
830 *reserved-characters* escape))
834 (encode-escaped-encoding
835 host *reserved-authority-characters* escape))
838 #-allegro (format nil "~D" port)
839 #+allegro (with-output-to-string (s)
840 (excl::maybe-print-fast s port))
843 (encode-escaped-encoding path
845 ;;*reserved-path-characters*
848 (when query (encode-escaped-encoding query nil escape))
850 (when fragment (encode-escaped-encoding fragment nil escape))))))
852 then (format stream "~a" (uri-string uri))
853 else (uri-string uri)))
855 (defun render-parsed-path (path-list escape)
857 (first (car path-list))
858 (pl (cdr path-list) (cdr pl))
859 (pe (car pl) (car pl)))
861 (when res (apply #'concatenate 'simple-string (nreverse res))))
862 (when (or (null first)
863 (prog1 (eq :absolute first)
868 (encode-escaped-encoding pe *reserved-path-characters* escape)
870 else ;; contains params
871 (push (encode-escaped-encoding
872 (car pe) *reserved-path-characters* escape)
874 (dolist (item (cdr pe))
876 (push (encode-escaped-encoding
877 item *reserved-path-characters* escape)
880 (defun render-urn (urn stream
881 &aux (*print-pretty* nil))
882 (when (null (uri-string urn))
883 (setf (uri-string urn)
884 (let ((nid (urn-nid urn))
886 (concatenate 'simple-string "urn:" nid ":" nss))))
888 then (format stream "~a" (uri-string urn))
889 else (uri-string urn)))
891 (defparameter *escaped-encoding*
892 (vector #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f))
894 (defun encode-escaped-encoding (string reserved-chars escape)
895 (when (null escape) (return-from encode-escaped-encoding string))
896 ;; Make a string as big as it possibly needs to be (3 times the original
897 ;; size), and truncate it at the end.
898 (do* ((max (length string))
899 (new-max (* 3 max)) ;; worst case new size
900 (new-string (make-string new-max))
905 (shrink-vector new-string (incf new-i)))
906 (setq ci (char-int (setq c (schar string i))))
907 (if* (or (null reserved-chars)
909 (= 0 (sbit reserved-chars ci)))
912 (setf (schar new-string new-i) c)
913 else ;; need to escape it
914 (multiple-value-bind (q r) (truncate ci 16)
915 (setf (schar new-string (incf new-i)) #\%)
916 (setf (schar new-string (incf new-i)) (elt *escaped-encoding* q))
917 (setf (schar new-string (incf new-i))
918 (elt *escaped-encoding* r))))))
920 (defmethod print-object ((uri uri) stream)
922 then (format stream "#<~a ~a>" 'uri (render-uri uri nil))
923 else (render-uri uri stream)))
925 (defmethod print-object ((urn urn) stream)
927 then (format stream "#<~a ~a>" 'uri (render-urn urn nil))
928 else (render-urn urn stream)))
930 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
931 ;; merging and unmerging
933 (defmethod merge-uris ((uri string) (base string) &optional place)
934 (merge-uris (parse-uri uri) (parse-uri base) place))
936 (defmethod merge-uris ((uri uri) (base string) &optional place)
937 (merge-uris uri (parse-uri base) place))
939 (defmethod merge-uris ((uri string) (base uri) &optional place)
940 (merge-uris (parse-uri uri) base place))
942 (defmethod merge-uris ((uri uri) (base uri) &optional place)
943 ;; The following is from
944 ;; http://info.internet.isi.edu/in-notes/rfc/files/rfc2396.txt
945 ;; and is algorithm we use to merge URIs.
947 ;; For more information, see section 5.2 of the RFC.
951 (when (and (null (uri-parsed-path uri))
952 (null (uri-scheme uri))
953 (null (uri-host uri))
954 (null (uri-port uri))
955 (null (uri-query uri)))
956 (return-from merge-uris
957 (let ((new (copy-uri base :place place)))
958 (when (uri-query uri)
959 (setf (uri-query new) (uri-query uri)))
960 (when (uri-fragment uri)
961 (setf (uri-fragment new) (uri-fragment uri)))
964 (setq uri (copy-uri uri :place place))
967 (when (uri-scheme uri)
968 (return-from merge-uris uri))
969 (setf (uri-scheme uri) (uri-scheme base))
972 (when (uri-host uri) (go :done))
973 (setf (uri-host uri) (uri-host base))
974 (setf (uri-port uri) (uri-port base))
977 (let ((p (uri-parsed-path uri)))
978 (when (and p (eq :absolute (car p)))
979 (when (equal '(:absolute "") p)
980 ;; Canonicalize the way parsing does:
981 (setf (uri-path uri) nil))
986 (or (uri-parsed-path base)
987 ;; needed because we canonicalize away a path of just `/':
989 (path (uri-parsed-path uri))
991 (when (not (eq :absolute (car base-path)))
992 (error "Cannot merge ~a and ~a, since latter is not absolute."
997 (append (butlast base-path)
998 (if* path then (cdr path) else '(""))))
1001 (let ((last (last new-path-list)))
1002 (if* (atom (car last))
1003 then (when (string= "." (car last))
1004 (setf (car last) ""))
1005 else (when (string= "." (caar last))
1006 (setf (caar last) ""))))
1008 (delete "." new-path-list :test #'(lambda (a b)
1014 (let ((npl (cdr new-path-list))
1017 (string= ".." (let ((l (car (last npl))))
1024 :test #'(lambda (a b)
1029 (when (null index) (return))
1031 ;; The RFC says, in 6g, "that the implementation may handle
1032 ;; this error by retaining these components in the resolved
1033 ;; path, by removing them from the resolved path, or by
1034 ;; avoiding traversal of the reference." The examples in C.2
1035 ;; imply that we should do the first thing (retain them), so
1036 ;; that's what we'll do.
1039 then (setq npl (cddr npl))
1041 (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1042 (setf (cdr tmp) (cdddr tmp))))
1043 (setf (cdr new-path-list) npl)
1044 (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1047 ;; don't complain if new-path-list starts with `..'. See comment
1048 ;; above about this step.
1051 (when (or (equal '(:absolute "") new-path-list)
1052 (equal '(:absolute) new-path-list))
1053 (setq new-path-list nil))
1054 (setf (uri-path uri)
1055 (render-parsed-path new-path-list
1056 ;; don't know, so have to assume:
1061 (return-from merge-uris uri)))
1063 (defmethod enough-uri ((uri string) (base string) &optional place)
1064 (enough-uri (parse-uri uri) (parse-uri base) place))
1066 (defmethod enough-uri ((uri uri) (base string) &optional place)
1067 (enough-uri uri (parse-uri base) place))
1069 (defmethod enough-uri ((uri string) (base uri) &optional place)
1070 (enough-uri (parse-uri uri) base place))
1072 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1073 (let ((new-scheme nil)
1076 (new-parsed-path nil))
1078 (when (or (and (uri-scheme uri)
1079 (not (equalp (uri-scheme uri) (uri-scheme base))))
1081 (not (equalp (uri-host uri) (uri-host base))))
1082 (not (equalp (uri-port uri) (uri-port base))))
1083 (return-from enough-uri uri))
1085 (when (null (uri-host uri))
1086 (setq new-host (uri-host base)))
1087 (when (null (uri-port uri))
1088 (setq new-port (uri-port base)))
1090 (when (null (uri-scheme uri))
1091 (setq new-scheme (uri-scheme base)))
1093 ;; Now, for the hard one, path.
1094 ;; We essentially do here what enough-namestring does.
1095 (do* ((base-path (uri-parsed-path base))
1096 (path (uri-parsed-path uri))
1097 (bp base-path (cdr bp))
1099 ((or (null bp) (null p))
1100 ;; If p is nil, that means we have something like
1101 ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1102 ;; new-parsed-path will be nil.
1104 (setq new-parsed-path (copy-list p))
1105 (when (not (symbolp (car new-parsed-path)))
1106 (push :relative new-parsed-path))))
1107 (if* (equal (car bp) (car p))
1109 else (setq new-parsed-path (copy-list p))
1110 (when (not (symbolp (car new-parsed-path)))
1111 (push :relative new-parsed-path))
1115 (when new-parsed-path
1116 (render-parsed-path new-parsed-path
1117 ;; don't know, so have to assume:
1119 (new-query (uri-query uri))
1120 (new-fragment (uri-fragment uri))
1121 (new-plist (copy-list (uri-plist uri))))
1122 (if* (and (null new-scheme)
1126 (null new-parsed-path)
1128 (null new-fragment))
1129 then ;; can't have a completely empty uri!
1131 :class (class-of uri)
1136 :class (class-of uri)
1142 :parsed-path new-parsed-path
1144 :fragment new-fragment
1145 :plist new-plist)))))
1147 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1148 ;; support for interning URIs
1150 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1152 (apply #'make-hash-table :size size
1153 :hash-function 'uri-hash
1154 :test 'uri= :values nil keys)
1156 (apply #'make-hash-table :size size keys))
1158 (defun gethash-uri (uri table)
1159 #+allegro (gethash uri table)
1161 (let* ((hash (uri-hash uri))
1162 (existing (gethash hash table)))
1163 (dolist (u existing)
1165 (return-from gethash-uri (values u t))))
1168 (defun puthash-uri (uri table)
1169 #+allegro (excl:puthash-key uri table)
1171 (let ((existing (gethash (uri-hash uri) table)))
1172 (dolist (u existing)
1174 (return-from puthash-uri u)))
1175 (setf (gethash (uri-hash uri) table)
1176 (cons uri existing))
1180 (defun uri-hash (uri)
1181 (if* (uri-hashcode uri)
1183 else (setf (uri-hashcode uri)
1186 (render-uri uri nil)
1189 (render-uri uri nil))))))
1191 (defvar *uris* (make-uri-space))
1193 (defun uri-space () *uris*)
1195 (defun (setf uri-space) (new-val)
1196 (setq *uris* new-val))
1198 ;; bootstrapping (uri= changed from function to method):
1199 (when (fboundp 'uri=) (fmakunbound 'uri=))
1201 (defgeneric uri= (uri1 uri2))
1202 (defmethod uri= ((uri1 uri) (uri2 uri))
1203 (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1204 (return-from uri= nil))
1205 ;; RFC2396 says: a URL with an explicit ":port", where the port is
1206 ;; the default for the scheme, is the equivalent to one where the
1207 ;; port is elided. Hmmmm. This means that this function has to be
1208 ;; scheme dependent. Grrrr.
1209 (let ((default-port (case (uri-scheme uri1)
1214 (and (equalp (uri-host uri1) (uri-host uri2))
1215 (eql (or (uri-port uri1) default-port)
1216 (or (uri-port uri2) default-port))
1217 (string= (uri-path uri1) (uri-path uri2))
1218 (string= (uri-query uri1) (uri-query uri2))
1219 (string= (uri-fragment uri1) (uri-fragment uri2)))))
1221 (defmethod uri= ((urn1 urn) (urn2 urn))
1222 (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1223 (return-from uri= nil))
1224 (and (equalp (urn-nid urn1) (urn-nid urn2))
1225 (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1227 (defun urn-nss-equal (nss1 nss2 &aux len)
1228 ;; Return t iff the nss values are the same.
1229 ;; %2c and %2C are equivalent.
1230 (when (or (null nss1) (null nss2)
1231 (not (= (setq len (length nss1))
1233 (return-from urn-nss-equal nil))
1238 (setq c1 (schar nss1 i))
1239 (setq c2 (schar nss2 i))
1242 (if* (and (char= #\% c1) (char= #\% c2))
1243 then (setq state :percent+1)
1244 elseif (char/= c1 c2)
1247 (when (char-not-equal c1 c2) (return nil))
1248 (setq state :percent+2))
1250 (when (char-not-equal c1 c2) (return nil))
1251 (setq state :char)))))
1253 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1254 (let ((uri (gethash-uri xuri uri-space)))
1257 else (puthash-uri xuri uri-space))))
1259 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1260 (intern-uri (parse-uri uri) uri-space))
1262 (defun unintern-uri (uri &optional (uri-space *uris*))
1264 then (clrhash uri-space)
1266 then (remhash uri uri-space)
1267 else (error "bad uri: ~s." uri)))
1269 (defmacro do-all-uris ((var &optional uri-space result-form)
1272 "do-all-uris (var [[uri-space] result-form])
1273 {declaration}* {tag | statement}*
1274 Executes the forms once for each uri with var bound to the current uri"
1277 (g-uri-space (gensym))
1278 (body (third (parse-body forms env))))
1279 `(let ((,g-uri-space (or ,uri-space *uris*)))
1281 (flet ((,f (,var &optional ,g-ignore)
1282 (declare (ignore-if-unused ,var ,g-ignore))
1284 (maphash #',f ,g-uri-space))
1285 (return ,result-form)))))
1287 (defun sharp-u (stream chr arg)
1288 (declare (ignore chr arg))
1289 (let ((arg (read stream nil nil t)))
1293 then (parse-uri arg)
1296 (internal-reader-error
1298 "#u takes a string or list argument: ~s" arg)))))
1304 (locally (declare (special std-lisp-readtable))
1305 (let ((*readtable* std-lisp-readtable))
1306 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)))
1308 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1310 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1314 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1316 ;; (don't run under emacs with M-x fi:common-lisp)
1319 (eval-when (:compile-toplevel :load-toplevel :execute)
1323 (defun gc (&rest options)
1324 (declare (ignore options))
1329 (defun time-uri-module ()
1330 (declare (optimize (speed 3) (safety 0) (debug 0)))
1331 (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1332 (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1333 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1334 (format t "~&;;; starting timing testing 1...~%")
1335 (time (dotimes (i 100000) (parse-uri uri)))
1337 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1338 (format t "~&;;; starting timing testing 2...~%")
1339 (let ((uri (parse-uri uri)))
1340 (time (dotimes (i 100000)
1341 ;; forces no caching of the printed representation:
1342 (setf (uri-string uri) nil)
1343 (format nil "~a" uri))))
1345 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1346 (format t "~&;;; starting timing testing 3...~%")
1349 (dotimes (i 100000) (parse-uri uri2))
1350 (let ((uri (parse-uri uri)))
1352 ;; forces no caching of the printed representation:
1353 (setf (uri-string uri) nil)
1354 (format nil "~a" uri)))))))
1356 ;;******** reference output (ultra, modified 5.0.1):
1357 ;;; starting timing testing 1...
1358 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1359 ; cpu time (gc) 600 msec user, 10 msec system
1360 ; cpu time (total) 14,310 msec user, 10 msec system
1361 ; real time 14,465 msec
1363 ; 1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1364 ;;; starting timing testing 2...
1365 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1366 ; cpu time (gc) 280 msec user, 20 msec system
1367 ; cpu time (total) 27,780 msec user, 20 msec system
1368 ; real time 27,897 msec
1370 ; 1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1371 ;;; starting timing testing 3...
1372 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1373 ; cpu time (gc) 1,290 msec user, 30 msec system
1374 ; cpu time (total) 53,580 msec user, 40 msec system
1375 ; real time 54,062 msec
1377 ; 7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1379 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1380 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1382 ;;; starting timing testing 1...
1383 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1384 ; cpu time (gc) 400 msec user, 0 msec system
1385 ; cpu time (total) 14,920 msec user, 0 msec system
1386 ; real time 15,082 msec
1388 ; 1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1389 ;;; starting timing testing 2...
1390 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1391 ; cpu time (gc) 300 msec user, 0 msec system
1392 ; cpu time (total) 27,790 msec user, 10 msec system
1393 ; real time 28,025 msec
1395 ; 1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1396 ;;; starting timing testing 3...
1397 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1398 ; cpu time (gc) 920 msec user, 10 msec system
1399 ; cpu time (total) 48,820 msec user, 30 msec system
1400 ; real time 49,188 msec
1402 ; 3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes