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
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 (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 (defun position-char (char string start max)
130 (declare (optimize (speed 3) (safety 0) (space 0))
131 (fixnum start max) (simple-string string))
132 (do* ((i start (1+ i)))
135 (when (char= char (schar 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 (or (not skip-terminal) (zerop len))
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*
358 '(;; `delims' (except #\%, because it's handled specially):
359 #\< #\> #\" #\space #\#
361 #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
363 (defun reserved-char-vector (chars &key except)
364 (do* ((a (make-array 127 :element-type 'bit :initial-element 0))
365 (chars chars (cdr chars))
366 (c (car chars) (car chars)))
368 (if* (and except (member c except :test #'char=))
370 else (setf (sbit a (char-int c)) 1))))
372 (defparameter *reserved-characters*
373 (reserved-char-vector
374 (append *excluded-characters*
375 '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
376 (defparameter *reserved-authority-characters*
377 (reserved-char-vector
378 (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
379 (defparameter *reserved-path-characters*
380 (reserved-char-vector
381 (append *excluded-characters*
383 ;;;;The rfc says this should be here, but it doesn't make sense.
386 (defparameter *reserved-path-characters2*
387 ;; These are the same characters that are in
388 ;; *reserved-path-characters*, minus #\/. Why? Because the parsed
389 ;; representation of the path can contain the %2f converted into a /.
390 ;; That's the whole point of having the parsed representation, so that
391 ;; lisp programs can deal with the path element data in the most
393 (reserved-char-vector
394 (append *excluded-characters*
396 ;;;;The rfc says this should be here, but it doesn't make sense.
399 (defparameter *reserved-fragment-characters*
400 (reserved-char-vector (remove #\# *excluded-characters*)))
402 (eval-when (:compile-toplevel :execute)
403 (defun gen-char-range-list (start end)
405 (endcode (1+ (char-int end)))
406 (chcode (char-int start)
410 ;; - has to be first, otherwise it signifies a range!
412 then (setq res (nreverse res))
415 else (nreverse res)))
416 (if* (= #.(char-int #\-) chcode)
418 else (push (code-char chcode) res))))
421 (defparameter *valid-nid-characters*
422 (reserved-char-vector
423 '#.(nconc (gen-char-range-list #\a #\z)
424 (gen-char-range-list #\A #\Z)
425 (gen-char-range-list #\0 #\9)
427 (defparameter *reserved-nss-characters*
428 (reserved-char-vector
429 (append *excluded-characters* '(#\& #\~ #\/ #\?))))
431 (defparameter *illegal-characters*
432 (reserved-char-vector (remove #\# *excluded-characters*)))
433 (defparameter *strict-illegal-query-characters*
434 (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
435 (defparameter *illegal-query-characters*
436 (reserved-char-vector
437 *excluded-characters* :except '(#\^ #\| #\#)))
440 (defun parse-uri (thing &key (class 'uri) &aux escape)
441 (when (uri-p thing) (return-from parse-uri thing))
443 (setq escape (escape-p thing))
444 (multiple-value-bind (scheme host port path query fragment)
445 (parse-uri-string thing)
449 (case *current-case-mode*
450 ((:case-insensitive-upper :case-sensitive-upper)
452 ((:case-insensitive-lower :case-sensitive-lower)
454 (decode-escaped-encoding scheme escape))
455 (find-package :keyword))))
457 (when (and scheme (eq :urn scheme))
458 (return-from parse-uri
459 (make-instance 'urn :scheme scheme :nid host :nss path)))
461 (when host (setq host (decode-escaped-encoding host escape)))
463 (setq port (read-from-string port))
464 (when (not (numberp port)) (error "port is not a number: ~s." port))
465 (when (not (plusp port))
466 (error "port is not a positive integer: ~d." port))
467 (when (eql port (case scheme
473 (when (or (string= "" path)
474 (and ;; we canonicalize away a reference to just /:
476 (member scheme '(:http :https :ftp) :test #'eq)
481 (decode-escaped-encoding path escape *reserved-path-characters*)))
482 (when query (setq query (decode-escaped-encoding query escape)))
485 (decode-escaped-encoding fragment escape
486 *reserved-fragment-characters*)))
488 then ;; allow the compiler to optimize the make-instance call:
497 else ;; do it the slow way:
507 (defmethod uri ((thing uri))
510 (defmethod uri ((thing string))
513 (defmethod uri ((thing t))
514 (error "Cannot coerce ~s to a uri." thing))
516 (defvar *strict-parse* t)
518 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
519 (declare (optimize (speed 3)))
520 ;; Speed is important, so use a specialized state machine instead of
521 ;; regular expressions for parsing the URI string. The regexp we are
530 (end (length string))
535 (path-components '())
538 ;; namespace identifier, for urn parsing only:
540 (declare (fixnum state start end))
541 (flet ((read-token (kind &optional legal-chars)
545 else (let ((sindex start)
548 (declare (fixnum sindex))
551 (when (>= start end) (return nil))
552 (setq c (schar string start))
553 (let ((ci (char-int c)))
555 then (if* (and (eq :colon kind) (eq c #\:))
557 elseif (= 0 (sbit legal-chars ci))
560 URI ~s contains illegal character ~s at position ~d."
562 elseif (and (< ci 128)
564 (= 1 (sbit illegal-chars ci)))
565 then (.parse-error "~
566 URI ~s contains illegal character ~s at position ~d."
570 (#\? (return :question))
571 (#\# (return :hash))))
572 (:query (case c (#\# (return :hash))))
575 (#\: (return :colon))
576 (#\? (return :question))
578 (#\/ (return :slash)))))
580 (if* (> start sindex)
581 then ;; we found some chars
582 ;; before we stopped the parse
583 (setq tokval (subseq string sindex start))
585 else ;; immediately stopped at a special char
588 (failure (&optional why)
589 (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
592 (.parse-error "impossible state: ~d [~s]" state string)))
595 (0 ;; starting to parse
596 (ecase (read-token t)
598 (:question (setq state 7))
599 (:hash (setq state 8))
600 (:slash (setq state 3))
601 (:string (setq state 1))
602 (:end (setq state 9))))
603 (1 ;; seen <token><special char>
604 (let ((token tokval))
605 (ecase (read-token t)
606 (:colon (setq scheme token)
607 (if* (equalp "urn" scheme)
609 else (setq state 2)))
610 (:question (push token path-components)
612 (:hash (push token path-components)
614 (:slash (push token path-components)
615 (push "/" path-components)
618 (:end (push token path-components)
621 (ecase (read-token t)
623 (:question (setq state 7))
624 (:hash (setq state 8))
625 (:slash (setq state 3))
626 (:string (setq state 10))
627 (:end (setq state 9))))
628 (10 ;; seen <scheme>:<token>
629 (let ((token tokval))
630 (ecase (read-token t)
632 (:question (push token path-components)
634 (:hash (push token path-components)
636 (:slash (push token path-components)
639 (:end (push token path-components)
641 (3 ;; seen / or <scheme>:/
642 (ecase (read-token t)
644 (:question (push "/" path-components)
646 (:hash (push "/" path-components)
648 (:slash (setq state 4))
649 (:string (push "/" path-components)
650 (push tokval path-components)
652 (:end (push "/" path-components)
654 (4 ;; seen [<scheme>:]//
655 (ecase (read-token t)
657 (:question (failure))
660 (:string (setq host tokval)
663 (11 ;; seen [<scheme>:]//<host>
664 (ecase (read-token t)
665 (:colon (setq state 5))
666 (:question (setq state 7))
667 (:hash (setq state 8))
668 (:slash (push "/" path-components)
670 (:string (impossible))
671 (:end (setq state 9))))
672 (5 ;; seen [<scheme>:]//<host>:
673 (ecase (read-token t)
675 (:question (failure))
677 (:slash (push "/" path-components)
679 (:string (setq port tokval)
682 (12 ;; seen [<scheme>:]//<host>:[<port>]
683 (ecase (read-token t)
685 (:question (setq state 7))
686 (:hash (setq state 8))
687 (:slash (push "/" path-components)
689 (:string (impossible))
690 (:end (setq state 9))))
692 (ecase (read-token :path)
693 (:question (setq state 7))
694 (:hash (setq state 8))
695 (:string (push tokval path-components)
697 (:end (setq state 9))))
699 (ecase (read-token :path)
700 (:question (setq state 7))
701 (:hash (setq state 8))
702 (:string (impossible))
703 (:end (setq state 9))))
707 then *strict-illegal-query-characters*
708 else *illegal-query-characters*))
709 (ecase (prog1 (read-token :query)
710 (setq illegal-chars *illegal-characters*))
711 (:hash (setq state 8))
712 (:string (setq query tokval)
714 (:end (setq state 9))))
716 (ecase (read-token :query)
717 (:hash (setq state 8))
718 (:string (impossible))
719 (:end (setq state 9))))
721 (ecase (read-token :rest)
722 (:string (setq fragment tokval)
724 (:end (setq state 9))))
729 (apply #'concatenate 'simple-string (nreverse path-components))
732 (15 ;; seen urn:, read nid now
733 (case (read-token :colon *valid-nid-characters*)
734 (:string (setq nid tokval)
736 (t (failure "missing namespace identifier"))))
737 (16 ;; seen urn:<nid>
739 (:colon (setq state 17))
740 (t (failure "missing namespace specific string"))))
741 (17 ;; seen urn:<nid>:, rest is nss
742 (return (values scheme
746 (setq illegal-chars *reserved-nss-characters*)
750 "internal error in parse engine, wrong state: ~s." state)))))))
752 (defun escape-p (string)
753 (declare (optimize (speed 3)))
755 (max (the fixnum (length string))))
757 (declare (fixnum i max))
758 (when (char= #\% (schar string i))
761 (defun parse-path (path-string escape)
762 (do* ((xpath-list (delimited-string-to-list path-string #\/))
765 (if* (string= "" (car xpath-list))
766 then (setf (car xpath-list) :absolute)
767 else (push :relative xpath-list))
769 (pl (cdr path-list) (cdr pl))
771 ((null pl) path-list)
772 (if* (cdr (setq segments (delimited-string-to-list (car pl) #\;)))
773 then ;; there is a param
774 ;;; (setf (car pl) segments)
776 (mapcar #'(lambda (s)
777 (decode-escaped-encoding
778 s escape *reserved-path-characters2*))
781 ;;; (setf (car pl) (car segments))
783 (decode-escaped-encoding
784 (car segments) escape *reserved-path-characters2*)))))
786 (defun decode-escaped-encoding (string escape
787 &optional (reserved-chars
788 *reserved-characters*))
789 ;; Return a string with the real characters.
790 (when (null escape) (return-from decode-escaped-encoding string))
792 (max (length string))
793 (new-string (copy-seq string))
797 (shrink-vector new-string new-i))
798 (if* (char= #\% (setq ch (schar string i)))
799 then (when (> (+ i 3) max)
801 "Unsyntactic escaped encoding in ~s." string))
802 (setq ch (schar string (incf i)))
803 (setq ch2 (schar string (incf i)))
804 (when (not (and (setq chc (digit-char-p ch 16))
805 (setq chc2 (digit-char-p ch2 16))))
807 "Non-hexidecimal digits after %: %c%c." ch ch2))
808 (let ((ci (+ (* 16 chc) chc2)))
809 (if* (or (null reserved-chars)
810 (= 0 (sbit reserved-chars ci)))
812 (setf (schar new-string new-i)
814 else (setf (schar new-string new-i) #\%)
815 (setf (schar new-string (incf new-i)) ch)
816 (setf (schar new-string (incf new-i)) ch2)))
817 else (setf (schar new-string new-i) ch))))
819 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
822 (defun render-uri (uri stream
823 &aux (escape (uri-escaped uri))
824 (*print-pretty* nil))
825 (when (null (uri-string uri))
826 (setf (uri-string uri)
827 (let ((scheme (uri-scheme uri))
828 (host (uri-host uri))
829 (port (uri-port uri))
830 (path (uri-path uri))
831 (query (uri-query uri))
832 (fragment (uri-fragment uri)))
833 (concatenate 'simple-string
835 (encode-escaped-encoding
836 (string-downcase ;; for upper case lisps
837 (symbol-name scheme))
838 *reserved-characters* escape))
842 (encode-escaped-encoding
843 host *reserved-authority-characters* escape))
846 #-allegro (format nil "~D" port)
847 #+allegro (with-output-to-string (s)
848 (excl::maybe-print-fast s port))
851 (encode-escaped-encoding path
853 ;;*reserved-path-characters*
856 (when query (encode-escaped-encoding query nil escape))
858 (when fragment (encode-escaped-encoding fragment nil escape))))))
860 then (format stream "~a" (uri-string uri))
861 else (uri-string uri)))
863 (defun render-parsed-path (path-list escape)
865 (first (car path-list))
866 (pl (cdr path-list) (cdr pl))
867 (pe (car pl) (car pl)))
869 (when res (apply #'concatenate 'simple-string (nreverse res))))
870 (when (or (null first)
871 (prog1 (eq :absolute first)
876 (encode-escaped-encoding pe *reserved-path-characters* escape)
878 else ;; contains params
879 (push (encode-escaped-encoding
880 (car pe) *reserved-path-characters* escape)
882 (dolist (item (cdr pe))
884 (push (encode-escaped-encoding
885 item *reserved-path-characters* escape)
888 (defun render-urn (urn stream
889 &aux (*print-pretty* nil))
890 (when (null (uri-string urn))
891 (setf (uri-string urn)
892 (let ((nid (urn-nid urn))
894 (concatenate 'simple-string "urn:" nid ":" nss))))
896 then (format stream "~a" (uri-string urn))
897 else (uri-string urn)))
899 (defparameter *escaped-encoding*
900 (vector #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f))
902 (defun encode-escaped-encoding (string reserved-chars escape)
903 (when (null escape) (return-from encode-escaped-encoding string))
904 ;; Make a string as big as it possibly needs to be (3 times the original
905 ;; size), and truncate it at the end.
906 (do* ((max (length string))
907 (new-max (* 3 max)) ;; worst case new size
908 (new-string (make-string new-max))
913 (shrink-vector new-string (incf new-i)))
914 (setq ci (char-int (setq c (schar string i))))
915 (if* (or (null reserved-chars)
917 (= 0 (sbit reserved-chars ci)))
920 (setf (schar new-string new-i) c)
921 else ;; need to escape it
922 (multiple-value-bind (q r) (truncate ci 16)
923 (setf (schar new-string (incf new-i)) #\%)
924 (setf (schar new-string (incf new-i)) (elt *escaped-encoding* q))
925 (setf (schar new-string (incf new-i))
926 (elt *escaped-encoding* r))))))
928 (defmethod print-object ((uri uri) stream)
930 then (format stream "#<~a ~a>" 'uri (render-uri uri nil))
931 else (render-uri uri stream)))
933 (defmethod print-object ((urn urn) stream)
935 then (format stream "#<~a ~a>" 'uri (render-urn urn nil))
936 else (render-urn urn stream)))
938 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
939 ;; merging and unmerging
941 (defmethod merge-uris ((uri string) (base string) &optional place)
942 (merge-uris (parse-uri uri) (parse-uri base) place))
944 (defmethod merge-uris ((uri uri) (base string) &optional place)
945 (merge-uris uri (parse-uri base) place))
947 (defmethod merge-uris ((uri string) (base uri) &optional place)
948 (merge-uris (parse-uri uri) base place))
950 (defmethod merge-uris ((uri uri) (base uri) &optional place)
951 ;; The following is from
952 ;; http://info.internet.isi.edu/in-notes/rfc/files/rfc2396.txt
953 ;; and is algorithm we use to merge URIs.
955 ;; For more information, see section 5.2 of the RFC.
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)))
986 (when (and p (eq :absolute (car p)))
987 (when (equal '(:absolute "") p)
988 ;; Canonicalize the way parsing does:
989 (setf (uri-path uri) nil))
994 (or (uri-parsed-path base)
995 ;; needed because we canonicalize away a path of just `/':
997 (path (uri-parsed-path uri))
999 (when (not (eq :absolute (car base-path)))
1000 (error "Cannot merge ~a and ~a, since latter is not absolute."
1005 (append (butlast base-path)
1006 (if* path then (cdr path) else '(""))))
1009 (let ((last (last new-path-list)))
1010 (if* (atom (car last))
1011 then (when (string= "." (car last))
1012 (setf (car last) ""))
1013 else (when (string= "." (caar last))
1014 (setf (caar last) ""))))
1016 (delete "." new-path-list :test #'(lambda (a b)
1022 (let ((npl (cdr new-path-list))
1025 (string= ".." (let ((l (car (last npl))))
1032 :test #'(lambda (a b)
1037 (when (null index) (return))
1039 ;; The RFC says, in 6g, "that the implementation may handle
1040 ;; this error by retaining these components in the resolved
1041 ;; path, by removing them from the resolved path, or by
1042 ;; avoiding traversal of the reference." The examples in C.2
1043 ;; imply that we should do the first thing (retain them), so
1044 ;; that's what we'll do.
1047 then (setq npl (cddr npl))
1049 (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1050 (setf (cdr tmp) (cdddr tmp))))
1051 (setf (cdr new-path-list) npl)
1052 (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1055 ;; don't complain if new-path-list starts with `..'. See comment
1056 ;; above about this step.
1059 (when (or (equal '(:absolute "") new-path-list)
1060 (equal '(:absolute) new-path-list))
1061 (setq new-path-list nil))
1062 (setf (uri-path uri)
1063 (render-parsed-path new-path-list
1064 ;; don't know, so have to assume:
1069 (return-from merge-uris uri)))
1071 (defmethod enough-uri ((uri string) (base string) &optional place)
1072 (enough-uri (parse-uri uri) (parse-uri base) place))
1074 (defmethod enough-uri ((uri uri) (base string) &optional place)
1075 (enough-uri uri (parse-uri base) place))
1077 (defmethod enough-uri ((uri string) (base uri) &optional place)
1078 (enough-uri (parse-uri uri) base place))
1080 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1081 (let ((new-scheme nil)
1084 (new-parsed-path nil))
1086 (when (or (and (uri-scheme uri)
1087 (not (equalp (uri-scheme uri) (uri-scheme base))))
1089 (not (equalp (uri-host uri) (uri-host base))))
1090 (not (equalp (uri-port uri) (uri-port base))))
1091 (return-from enough-uri uri))
1093 (when (null (uri-host uri))
1094 (setq new-host (uri-host base)))
1095 (when (null (uri-port uri))
1096 (setq new-port (uri-port base)))
1098 (when (null (uri-scheme uri))
1099 (setq new-scheme (uri-scheme base)))
1101 ;; Now, for the hard one, path.
1102 ;; We essentially do here what enough-namestring does.
1103 (do* ((base-path (uri-parsed-path base))
1104 (path (uri-parsed-path uri))
1105 (bp base-path (cdr bp))
1107 ((or (null bp) (null p))
1108 ;; If p is nil, that means we have something like
1109 ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1110 ;; new-parsed-path will be nil.
1112 (setq new-parsed-path (copy-list p))
1113 (when (not (symbolp (car new-parsed-path)))
1114 (push :relative new-parsed-path))))
1115 (if* (equal (car bp) (car p))
1117 else (setq new-parsed-path (copy-list p))
1118 (when (not (symbolp (car new-parsed-path)))
1119 (push :relative new-parsed-path))
1123 (when new-parsed-path
1124 (render-parsed-path new-parsed-path
1125 ;; don't know, so have to assume:
1127 (new-query (uri-query uri))
1128 (new-fragment (uri-fragment uri))
1129 (new-plist (copy-list (uri-plist uri))))
1130 (if* (and (null new-scheme)
1134 (null new-parsed-path)
1136 (null new-fragment))
1137 then ;; can't have a completely empty uri!
1139 :class (class-of uri)
1144 :class (class-of uri)
1150 :parsed-path new-parsed-path
1152 :fragment new-fragment
1153 :plist new-plist)))))
1155 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1156 ;; support for interning URIs
1158 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1160 (apply #'make-hash-table :size size
1161 :hash-function 'uri-hash
1162 :test 'uri= :values nil keys)
1164 (apply #'make-hash-table :size size keys))
1166 (defun gethash-uri (uri table)
1167 #+allegro (gethash uri table)
1169 (let* ((hash (uri-hash uri))
1170 (existing (gethash hash table)))
1171 (dolist (u existing)
1173 (return-from gethash-uri (values u t))))
1176 (defun puthash-uri (uri table)
1177 #+allegro (excl:puthash-key uri table)
1179 (let ((existing (gethash (uri-hash uri) table)))
1180 (dolist (u existing)
1182 (return-from puthash-uri u)))
1183 (setf (gethash (uri-hash uri) table)
1184 (cons uri existing))
1188 (defun uri-hash (uri)
1189 (if* (uri-hashcode uri)
1191 else (setf (uri-hashcode uri)
1194 (render-uri uri nil)
1197 (render-uri uri nil))))))
1199 (defvar *uris* (make-uri-space))
1201 (defun uri-space () *uris*)
1203 (defun (setf uri-space) (new-val)
1204 (setq *uris* new-val))
1206 ;; bootstrapping (uri= changed from function to method):
1207 (when (fboundp 'uri=) (fmakunbound 'uri=))
1209 (defgeneric uri= (uri1 uri2))
1210 (defmethod uri= ((uri1 uri) (uri2 uri))
1211 (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1212 (return-from uri= nil))
1213 ;; RFC2396 says: a URL with an explicit ":port", where the port is
1214 ;; the default for the scheme, is the equivalent to one where the
1215 ;; port is elided. Hmmmm. This means that this function has to be
1216 ;; scheme dependent. Grrrr.
1217 (let ((default-port (case (uri-scheme uri1)
1222 (and (equalp (uri-host uri1) (uri-host uri2))
1223 (eql (or (uri-port uri1) default-port)
1224 (or (uri-port uri2) default-port))
1225 (string= (uri-path uri1) (uri-path uri2))
1226 (string= (uri-query uri1) (uri-query uri2))
1227 (string= (uri-fragment uri1) (uri-fragment uri2)))))
1229 (defmethod uri= ((urn1 urn) (urn2 urn))
1230 (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1231 (return-from uri= nil))
1232 (and (equalp (urn-nid urn1) (urn-nid urn2))
1233 (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1235 (defun urn-nss-equal (nss1 nss2 &aux len)
1236 ;; Return t iff the nss values are the same.
1237 ;; %2c and %2C are equivalent.
1238 (when (or (null nss1) (null nss2)
1239 (not (= (setq len (length nss1))
1241 (return-from urn-nss-equal nil))
1246 (setq c1 (schar nss1 i))
1247 (setq c2 (schar nss2 i))
1250 (if* (and (char= #\% c1) (char= #\% c2))
1251 then (setq state :percent+1)
1252 elseif (char/= c1 c2)
1255 (when (char-not-equal c1 c2) (return nil))
1256 (setq state :percent+2))
1258 (when (char-not-equal c1 c2) (return nil))
1259 (setq state :char)))))
1261 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1262 (let ((uri (gethash-uri xuri uri-space)))
1265 else (puthash-uri xuri uri-space))))
1267 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1268 (intern-uri (parse-uri uri) uri-space))
1270 (defun unintern-uri (uri &optional (uri-space *uris*))
1272 then (clrhash uri-space)
1274 then (remhash uri uri-space)
1275 else (error "bad uri: ~s." uri)))
1277 (defmacro do-all-uris ((var &optional uri-space result-form)
1280 "do-all-uris (var [[uri-space] result-form])
1281 {declaration}* {tag | statement}*
1282 Executes the forms once for each uri with var bound to the current uri"
1285 (g-uri-space (gensym))
1286 (body (third (parse-body forms env))))
1287 `(let ((,g-uri-space (or ,uri-space *uris*)))
1289 (flet ((,f (,var &optional ,g-ignore)
1290 (declare (ignore-if-unused ,var ,g-ignore))
1292 (maphash #',f ,g-uri-space))
1293 (return ,result-form)))))
1295 (defun sharp-u (stream chr arg)
1296 (declare (ignore chr arg))
1297 (let ((arg (read stream nil nil t)))
1301 then (parse-uri arg)
1304 (internal-reader-error
1306 "#u takes a string or list argument: ~s" arg)))))
1312 (locally (declare (special std-lisp-readtable))
1313 (let ((*readtable* std-lisp-readtable))
1314 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)))
1316 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1318 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1322 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1324 ;; (don't run under emacs with M-x fi:common-lisp)
1327 (eval-when (:compile-toplevel :load-toplevel :execute)
1331 (defun gc (&rest options)
1332 (declare (ignore options))
1337 (defun time-uri-module ()
1338 (declare (optimize (speed 3) (safety 0) (debug 0)))
1339 (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1340 (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1341 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1342 (format t "~&;;; starting timing testing 1...~%")
1343 (time (dotimes (i 100000) (parse-uri uri)))
1345 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1346 (format t "~&;;; starting timing testing 2...~%")
1347 (let ((uri (parse-uri uri)))
1348 (time (dotimes (i 100000)
1349 ;; forces no caching of the printed representation:
1350 (setf (uri-string uri) nil)
1351 (format nil "~a" uri))))
1353 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1354 (format t "~&;;; starting timing testing 3...~%")
1357 (dotimes (i 100000) (parse-uri uri2))
1358 (let ((uri (parse-uri uri)))
1360 ;; forces no caching of the printed representation:
1361 (setf (uri-string uri) nil)
1362 (format nil "~a" uri)))))))
1364 ;;******** reference output (ultra, modified 5.0.1):
1365 ;;; starting timing testing 1...
1366 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1367 ; cpu time (gc) 600 msec user, 10 msec system
1368 ; cpu time (total) 14,310 msec user, 10 msec system
1369 ; real time 14,465 msec
1371 ; 1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1372 ;;; starting timing testing 2...
1373 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1374 ; cpu time (gc) 280 msec user, 20 msec system
1375 ; cpu time (total) 27,780 msec user, 20 msec system
1376 ; real time 27,897 msec
1378 ; 1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1379 ;;; starting timing testing 3...
1380 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1381 ; cpu time (gc) 1,290 msec user, 30 msec system
1382 ; cpu time (total) 53,580 msec user, 40 msec system
1383 ; real time 54,062 msec
1385 ; 7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1387 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1388 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1390 ;;; starting timing testing 1...
1391 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1392 ; cpu time (gc) 400 msec user, 0 msec system
1393 ; cpu time (total) 14,920 msec user, 0 msec system
1394 ; real time 15,082 msec
1396 ; 1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1397 ;;; starting timing testing 2...
1398 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1399 ; cpu time (gc) 300 msec user, 0 msec system
1400 ; cpu time (total) 27,790 msec user, 10 msec system
1401 ; real time 28,025 msec
1403 ; 1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1404 ;;; starting timing testing 3...
1405 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1406 ; cpu time (gc) 920 msec user, 10 msec system
1407 ; cpu time (total) 48,820 msec user, 30 msec system
1408 ; real time 49,188 msec
1410 ; 3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes