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
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...
60 #:uri-parse-error ;; Added by KMR
65 (eval-when (:compile-toplevel) (declaim (optimize (speed 3))))
69 (defun parse-body (forms &optional env)
70 "Parses a body, returns (VALUES docstring declarations forms)"
71 (declare (ignore env))
72 ;; fixme -- need to add parsing of multiple declarations
73 (let (docstring declarations)
74 (when (stringp (car forms))
75 (setq docstring (car forms))
76 (setq forms (cdr forms)))
77 (when (and (listp (car forms))
78 (symbolp (caar forms))
79 (string-equal (symbol-name '#:declare)
80 (symbol-name (caar forms))))
81 (setq declarations (car forms))
82 (setq forms (cdr forms)))
83 (values docstring declarations forms)))
86 (defun shrink-vector (str size)
88 (excl::.primcall 'sys::shrink-svector str size)
90 (sb-kernel:shrink-vector str size)
92 (lisp::shrink-vector str size)
94 (system::shrink-vector$vector str size)
96 (common-lisp::shrink-vector str size)
97 #-(or allegro cmu lispworks sbcl scl)
98 (setq str (subseq str 0 size))
102 ;; KMR: Added new condition to handle cross-implementation variances
103 ;; in the parse-error condition many implementations define
105 (define-condition uri-parse-error (parse-error)
106 ((fmt-control :initarg :fmt-control :accessor fmt-control)
107 (fmt-arguments :initarg :fmt-arguments :accessor fmt-arguments ))
108 (:report (lambda (c stream)
109 (format stream "Parse error:")
110 (apply #'format stream (fmt-control c) (fmt-arguments c)))))
112 (defun .parse-error (fmt &rest args)
113 (error 'uri-parse-error :fmt-control fmt :fmt-arguments args))
116 (defun internal-reader-error (stream fmt &rest args)
117 (apply #'format stream fmt args))
119 #-allegro (defvar *current-case-mode* :case-insensitive-upper)
120 #+allegro (eval-when (:compile-toplevel :load-toplevel :execute)
121 (import '(excl:*current-case-mode*
122 excl:delimited-string-to-list
124 excl::internal-reader-error
128 (defun position-char (char string start max)
129 (declare (optimize (speed 3) (safety 0) (space 0))
130 (fixnum start max) (simple-string string))
131 (do* ((i start (1+ i)))
134 (when (char= char (schar string i)) (return i))))
137 (defun delimited-string-to-list (string &optional (separator #\space)
139 (declare (optimize (speed 3) (safety 0) (space 0)
140 (compilation-speed 0))
142 (type character separator))
143 (do* ((len (length string))
146 (end (position-char separator string pos len)
147 (position-char separator string pos len)))
150 (push (subseq string pos) output)
151 (when (or (not skip-terminal) (zerop len))
154 (declare (type fixnum pos len)
155 (type (or null fixnum) end))
156 (push (subseq string pos end) output)
157 (setq pos (1+ end))))
160 (eval-when (:compile-toplevel :load-toplevel :execute)
161 (defvar if*-keyword-list '("then" "thenret" "else" "elseif"))
163 (defmacro if* (&rest args)
164 (do ((xx (reverse args) (cdr xx))
171 (cond ((eq state :compl)
173 (t (error "if*: illegal form ~s" args))))
174 (cond ((and (symbolp (car xx))
175 (member (symbol-name (car xx))
177 :test #'string-equal))
178 (setq lookat (symbol-name (car xx)))))
180 (cond ((eq state :init)
181 (cond (lookat (cond ((string-equal lookat "thenret")
185 "if*: bad keyword ~a" lookat))))
188 (push (car xx) col))))
191 (cond ((string-equal lookat "else")
194 "if*: multiples elses")))
197 (push `(t ,@col) totalcol))
198 ((string-equal lookat "then")
200 (t (error "if*: bad keyword ~s"
202 (t (push (car xx) col))))
206 "if*: keyword ~s at the wrong place " (car xx)))
207 (t (setq state :compl)
208 (push `(,(car xx) ,@col) totalcol))))
210 (cond ((not (string-equal lookat "elseif"))
211 (error "if*: missing elseif clause ")))
212 (setq state :init))))))
218 (scheme :initarg :scheme :initform nil :accessor uri-scheme)
219 (host :initarg :host :initform nil :accessor uri-host)
220 (port :initarg :port :initform nil :accessor uri-port)
221 (path :initarg :path :initform nil :accessor uri-path)
222 (query :initarg :query :initform nil :accessor uri-query)
223 (fragment :initarg :fragment :initform nil :accessor uri-fragment)
224 (plist :initarg :plist :initform nil :accessor uri-plist)
228 ;; used to prevent unnessary work, looking for chars to escape and
230 :initarg :escaped :initform nil :accessor uri-escaped)
232 ;; the cached printable representation of the URI. It *might* be
233 ;; different than the original string, though, because the user might
234 ;; have escaped non-reserved chars--they won't be escaped when the URI
236 :initarg :string :initform nil :accessor uri-string)
238 ;; the cached parsed representation of the URI path.
239 :initarg :parsed-path
241 :accessor .uri-parsed-path)
243 ;; cached sxhash, so we don't have to compute it more than once.
244 :initarg :hashcode :initform nil :accessor uri-hashcode)))
247 ((nid :initarg :nid :initform nil :accessor urn-nid)
248 (nss :initarg :nss :initform nil :accessor urn-nss)))
250 (eval-when (:compile-toplevel :execute)
251 (defmacro clear-caching-on-slot-change (name)
252 `(defmethod (setf ,name) :around (new-value (self uri))
253 (declare (ignore new-value))
254 (prog1 (call-next-method)
255 (setf (uri-string self) nil)
256 ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
257 (setf (uri-hashcode self) nil))))
260 (clear-caching-on-slot-change uri-scheme)
261 (clear-caching-on-slot-change uri-host)
262 (clear-caching-on-slot-change uri-port)
263 (clear-caching-on-slot-change uri-path)
264 (clear-caching-on-slot-change uri-query)
265 (clear-caching-on-slot-change uri-fragment)
268 (defmethod make-load-form ((self uri) &optional env)
269 (declare (ignore env))
270 `(make-instance ',(class-name (class-of self))
271 :scheme ,(uri-scheme self)
272 :host ,(uri-host self)
273 :port ,(uri-port self)
274 :path ',(uri-path self)
275 :query ,(uri-query self)
276 :fragment ,(uri-fragment self)
277 :plist ',(uri-plist self)
278 :string ,(uri-string self)
279 :parsed-path ',(.uri-parsed-path self)))
281 (defmethod uri-p ((thing uri)) t)
282 (defmethod uri-p ((thing t)) nil)
286 (scheme (when uri (uri-scheme uri)))
287 (host (when uri (uri-host uri)))
288 (port (when uri (uri-port uri)))
289 (path (when uri (uri-path uri)))
291 (when uri (copy-list (.uri-parsed-path uri))))
292 (query (when uri (uri-query uri)))
293 (fragment (when uri (uri-fragment uri)))
294 (plist (when uri (copy-list (uri-plist uri))))
295 (class (when uri (class-of uri)))
296 &aux (escaped (when uri (uri-escaped uri))))
298 then (setf (uri-scheme place) scheme)
299 (setf (uri-host place) host)
300 (setf (uri-port place) port)
301 (setf (uri-path place) path)
302 (setf (.uri-parsed-path place) parsed-path)
303 (setf (uri-query place) query)
304 (setf (uri-fragment place) fragment)
305 (setf (uri-plist place) plist)
306 (setf (uri-escaped place) escaped)
307 (setf (uri-string place) nil)
308 (setf (uri-hashcode place) nil)
310 elseif (eq 'uri class)
311 then ;; allow the compiler to optimize the call to make-instance:
313 :scheme scheme :host host :port port :path path
314 :parsed-path parsed-path
315 :query query :fragment fragment :plist plist
316 :escaped escaped :string nil :hashcode nil)
317 else (make-instance class
318 :scheme scheme :host host :port port :path path
319 :parsed-path parsed-path
320 :query query :fragment fragment :plist plist
321 :escaped escaped :string nil :hashcode nil)))
323 (defmethod uri-parsed-path ((uri uri))
325 (when (null (.uri-parsed-path uri))
326 (setf (.uri-parsed-path uri)
327 (parse-path (uri-path uri) (uri-escaped uri))))
328 (.uri-parsed-path uri)))
330 (defmethod (setf uri-parsed-path) (path-list (uri uri))
331 (assert (and (consp path-list)
332 (or (member (car path-list) '(:absolute :relative)
334 (setf (uri-path uri) (render-parsed-path path-list t))
335 (setf (.uri-parsed-path uri) path-list)
338 (defun uri-authority (uri)
340 (let ((*print-pretty* nil))
341 (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
344 (if* (equalp "urn" (uri-scheme uri))
346 else (error "URI is not a URN: ~s." uri)))
349 (if* (equalp "urn" (uri-scheme uri))
351 else (error "URI is not a URN: ~s." uri)))
353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
356 (defparameter *excluded-characters*
357 '(;; `delims' (except #\%, because it's handled specially):
358 #\< #\> #\" #\space #\#
360 #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
362 (defun reserved-char-vector (chars &key except)
363 (do* ((a (make-array 127 :element-type 'bit :initial-element 0))
364 (chars chars (cdr chars))
365 (c (car chars) (car chars)))
367 (if* (and except (member c except :test #'char=))
369 else (setf (sbit a (char-int c)) 1))))
371 (defparameter *reserved-characters*
372 (reserved-char-vector
373 (append *excluded-characters*
374 '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
375 (defparameter *reserved-authority-characters*
376 (reserved-char-vector
377 (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
378 (defparameter *reserved-path-characters*
379 (reserved-char-vector
380 (append *excluded-characters*
382 ;;;;The rfc says this should be here, but it doesn't make sense.
385 (defparameter *reserved-path-characters2*
386 ;; These are the same characters that are in
387 ;; *reserved-path-characters*, minus #\/. Why? Because the parsed
388 ;; representation of the path can contain the %2f converted into a /.
389 ;; That's the whole point of having the parsed representation, so that
390 ;; lisp programs can deal with the path element data in the most
392 (reserved-char-vector
393 (append *excluded-characters*
395 ;;;;The rfc says this should be here, but it doesn't make sense.
398 (defparameter *reserved-fragment-characters*
399 (reserved-char-vector (remove #\# *excluded-characters*)))
401 (eval-when (:compile-toplevel :execute)
402 (defun gen-char-range-list (start end)
404 (endcode (1+ (char-int end)))
405 (chcode (char-int start)
409 ;; - has to be first, otherwise it signifies a range!
411 then (setq res (nreverse res))
414 else (nreverse res)))
415 (if* (= #.(char-int #\-) chcode)
417 else (push (code-char chcode) res))))
420 (defparameter *valid-nid-characters*
421 (reserved-char-vector
422 '#.(nconc (gen-char-range-list #\a #\z)
423 (gen-char-range-list #\A #\Z)
424 (gen-char-range-list #\0 #\9)
426 (defparameter *reserved-nss-characters*
427 (reserved-char-vector
428 (append *excluded-characters* '(#\& #\~ #\/ #\?))))
430 (defparameter *illegal-characters*
431 (reserved-char-vector (remove #\# *excluded-characters*)))
432 (defparameter *strict-illegal-query-characters*
433 (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
434 (defparameter *illegal-query-characters*
435 (reserved-char-vector
436 *excluded-characters* :except '(#\^ #\| #\#)))
439 (defun parse-uri (thing &key (class 'uri) &aux escape)
440 (when (uri-p thing) (return-from parse-uri thing))
442 (setq escape (escape-p thing))
443 (multiple-value-bind (scheme host port path query fragment)
444 (parse-uri-string thing)
448 (case *current-case-mode*
449 ((:case-insensitive-upper :case-sensitive-upper)
451 ((:case-insensitive-lower :case-sensitive-lower)
453 (decode-escaped-encoding scheme escape))
454 (find-package :keyword))))
456 (when (and scheme (eq :urn scheme))
457 (return-from parse-uri
458 (make-instance 'urn :scheme scheme :nid host :nss path)))
460 (when host (setq host (decode-escaped-encoding host escape)))
462 (setq port (read-from-string port))
463 (when (not (numberp port)) (error "port is not a number: ~s." port))
464 (when (not (plusp port))
465 (error "port is not a positive integer: ~d." port))
466 (when (eql port (case scheme
472 (when (or (string= "" path)
473 (and ;; we canonicalize away a reference to just /:
475 (member scheme '(:http :https :ftp) :test #'eq)
480 (decode-escaped-encoding path escape *reserved-path-characters*)))
481 (when query (setq query (decode-escaped-encoding query escape)))
484 (decode-escaped-encoding fragment escape
485 *reserved-fragment-characters*)))
487 then ;; allow the compiler to optimize the make-instance call:
496 else ;; do it the slow way:
506 (defmethod uri ((thing uri))
509 (defmethod uri ((thing string))
512 (defmethod uri ((thing t))
513 (error "Cannot coerce ~s to a uri." thing))
515 (defvar *strict-parse* t)
517 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
518 (declare (optimize (speed 3)))
519 ;; Speed is important, so use a specialized state machine instead of
520 ;; regular expressions for parsing the URI string. The regexp we are
529 (end (length string))
534 (path-components '())
537 ;; namespace identifier, for urn parsing only:
539 (declare (fixnum state start end))
540 (flet ((read-token (kind &optional legal-chars)
544 else (let ((sindex start)
547 (declare (fixnum sindex))
550 (when (>= start end) (return nil))
551 (setq c (schar string start))
552 (let ((ci (char-int c)))
554 then (if* (and (eq :colon kind) (eq c #\:))
556 elseif (= 0 (sbit legal-chars ci))
559 URI ~s contains illegal character ~s at position ~d."
561 elseif (and (< ci 128)
563 (= 1 (sbit illegal-chars ci)))
564 then (.parse-error "~
565 URI ~s contains illegal character ~s at position ~d."
569 (#\? (return :question))
570 (#\# (return :hash))))
571 (:query (case c (#\# (return :hash))))
574 (#\: (return :colon))
575 (#\? (return :question))
577 (#\/ (return :slash)))))
579 (if* (> start sindex)
580 then ;; we found some chars
581 ;; before we stopped the parse
582 (setq tokval (subseq string sindex start))
584 else ;; immediately stopped at a special char
587 (failure (&optional why)
588 (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
591 (.parse-error "impossible state: ~d [~s]" state string)))
594 (0 ;; starting to parse
595 (ecase (read-token t)
597 (:question (setq state 7))
598 (:hash (setq state 8))
599 (:slash (setq state 3))
600 (:string (setq state 1))
601 (:end (setq state 9))))
602 (1 ;; seen <token><special char>
603 (let ((token tokval))
604 (ecase (read-token t)
605 (:colon (setq scheme token)
606 (if* (equalp "urn" scheme)
608 else (setq state 2)))
609 (:question (push token path-components)
611 (:hash (push token path-components)
613 (:slash (push token path-components)
614 (push "/" path-components)
617 (:end (push token path-components)
620 (ecase (read-token t)
622 (:question (setq state 7))
623 (:hash (setq state 8))
624 (:slash (setq state 3))
625 (:string (setq state 10))
626 (:end (setq state 9))))
627 (10 ;; seen <scheme>:<token>
628 (let ((token tokval))
629 (ecase (read-token t)
631 (:question (push token path-components)
633 (:hash (push token path-components)
635 (:slash (push token path-components)
638 (:end (push token path-components)
640 (3 ;; seen / or <scheme>:/
641 (ecase (read-token t)
643 (:question (push "/" path-components)
645 (:hash (push "/" path-components)
647 (:slash (setq state 4))
648 (:string (push "/" path-components)
649 (push tokval path-components)
651 (:end (push "/" path-components)
653 (4 ;; seen [<scheme>:]//
654 (ecase (read-token t)
656 (:question (failure))
659 (:string (setq host tokval)
662 (11 ;; seen [<scheme>:]//<host>
663 (ecase (read-token t)
664 (:colon (setq state 5))
665 (:question (setq state 7))
666 (:hash (setq state 8))
667 (:slash (push "/" path-components)
669 (:string (impossible))
670 (:end (setq state 9))))
671 (5 ;; seen [<scheme>:]//<host>:
672 (ecase (read-token t)
674 (:question (failure))
676 (:slash (push "/" path-components)
678 (:string (setq port tokval)
681 (12 ;; seen [<scheme>:]//<host>:[<port>]
682 (ecase (read-token t)
684 (:question (setq state 7))
685 (:hash (setq state 8))
686 (:slash (push "/" path-components)
688 (:string (impossible))
689 (:end (setq state 9))))
691 (ecase (read-token :path)
692 (:question (setq state 7))
693 (:hash (setq state 8))
694 (:string (push tokval path-components)
696 (:end (setq state 9))))
698 (ecase (read-token :path)
699 (:question (setq state 7))
700 (:hash (setq state 8))
701 (:string (impossible))
702 (:end (setq state 9))))
706 then *strict-illegal-query-characters*
707 else *illegal-query-characters*))
708 (ecase (prog1 (read-token :query)
709 (setq illegal-chars *illegal-characters*))
710 (:hash (setq state 8))
711 (:string (setq query tokval)
713 (:end (setq state 9))))
715 (ecase (read-token :query)
716 (:hash (setq state 8))
717 (:string (impossible))
718 (:end (setq state 9))))
720 (ecase (read-token :rest)
721 (:string (setq fragment tokval)
723 (:end (setq state 9))))
728 (apply #'concatenate 'simple-string (nreverse path-components))
731 (15 ;; seen urn:, read nid now
732 (case (read-token :colon *valid-nid-characters*)
733 (:string (setq nid tokval)
735 (t (failure "missing namespace identifier"))))
736 (16 ;; seen urn:<nid>
738 (:colon (setq state 17))
739 (t (failure "missing namespace specific string"))))
740 (17 ;; seen urn:<nid>:, rest is nss
741 (return (values scheme
745 (setq illegal-chars *reserved-nss-characters*)
749 "internal error in parse engine, wrong state: ~s." state)))))))
751 (defun escape-p (string)
752 (declare (optimize (speed 3)))
754 (max (the fixnum (length string))))
756 (declare (fixnum i max))
757 (when (char= #\% (schar string i))
760 (defun parse-path (path-string escape)
761 (do* ((xpath-list (delimited-string-to-list path-string #\/))
764 (if* (string= "" (car xpath-list))
765 then (setf (car xpath-list) :absolute)
766 else (push :relative xpath-list))
768 (pl (cdr path-list) (cdr pl))
770 ((null pl) path-list)
771 (if* (cdr (setq segments (delimited-string-to-list (car pl) #\;)))
772 then ;; there is a param
773 ;;; (setf (car pl) segments)
775 (mapcar #'(lambda (s)
776 (decode-escaped-encoding
777 s escape *reserved-path-characters2*))
780 ;;; (setf (car pl) (car segments))
782 (decode-escaped-encoding
783 (car segments) escape *reserved-path-characters2*)))))
785 (defun decode-escaped-encoding (string escape
786 &optional (reserved-chars
787 *reserved-characters*))
788 ;; Return a string with the real characters.
789 (when (null escape) (return-from decode-escaped-encoding string))
791 (max (length string))
792 (new-string (copy-seq string))
796 (shrink-vector new-string new-i))
797 (if* (char= #\% (setq ch (schar string i)))
798 then (when (> (+ i 3) max)
800 "Unsyntactic escaped encoding in ~s." string))
801 (setq ch (schar string (incf i)))
802 (setq ch2 (schar string (incf i)))
803 (when (not (and (setq chc (digit-char-p ch 16))
804 (setq chc2 (digit-char-p ch2 16))))
806 "Non-hexidecimal digits after %: %c%c." ch ch2))
807 (let ((ci (+ (* 16 chc) chc2)))
808 (if* (or (null reserved-chars)
809 (= 0 (sbit reserved-chars ci)))
811 (setf (schar new-string new-i)
813 else (setf (schar new-string new-i) #\%)
814 (setf (schar new-string (incf new-i)) ch)
815 (setf (schar new-string (incf new-i)) ch2)))
816 else (setf (schar new-string new-i) ch))))
818 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
821 (defun render-uri (uri stream
822 &aux (escape (uri-escaped uri))
823 (*print-pretty* nil))
824 (when (null (uri-string uri))
825 (setf (uri-string uri)
826 (let ((scheme (uri-scheme uri))
827 (host (uri-host uri))
828 (port (uri-port uri))
829 (path (uri-path uri))
830 (query (uri-query uri))
831 (fragment (uri-fragment uri)))
832 (concatenate 'simple-string
834 (encode-escaped-encoding
835 (string-downcase ;; for upper case lisps
836 (symbol-name scheme))
837 *reserved-characters* escape))
841 (encode-escaped-encoding
842 host *reserved-authority-characters* escape))
845 #-allegro (format nil "~D" port)
846 #+allegro (with-output-to-string (s)
847 (excl::maybe-print-fast s port))
850 (encode-escaped-encoding path
852 ;;*reserved-path-characters*
855 (when query (encode-escaped-encoding query nil escape))
857 (when fragment (encode-escaped-encoding fragment nil escape))))))
859 then (format stream "~a" (uri-string uri))
860 else (uri-string uri)))
862 (defun render-parsed-path (path-list escape)
864 (first (car path-list))
865 (pl (cdr path-list) (cdr pl))
866 (pe (car pl) (car pl)))
868 (when res (apply #'concatenate 'simple-string (nreverse res))))
869 (when (or (null first)
870 (prog1 (eq :absolute first)
875 (encode-escaped-encoding pe *reserved-path-characters* escape)
877 else ;; contains params
878 (push (encode-escaped-encoding
879 (car pe) *reserved-path-characters* escape)
881 (dolist (item (cdr pe))
883 (push (encode-escaped-encoding
884 item *reserved-path-characters* escape)
887 (defun render-urn (urn stream
888 &aux (*print-pretty* nil))
889 (when (null (uri-string urn))
890 (setf (uri-string urn)
891 (let ((nid (urn-nid urn))
893 (concatenate 'simple-string "urn:" nid ":" nss))))
895 then (format stream "~a" (uri-string urn))
896 else (uri-string urn)))
898 (defparameter *escaped-encoding*
899 (vector #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f))
901 (defun encode-escaped-encoding (string reserved-chars escape)
902 (when (null escape) (return-from encode-escaped-encoding string))
903 ;; Make a string as big as it possibly needs to be (3 times the original
904 ;; size), and truncate it at the end.
905 (do* ((max (length string))
906 (new-max (* 3 max)) ;; worst case new size
907 (new-string (make-string new-max))
912 (shrink-vector new-string (incf new-i)))
913 (setq ci (char-int (setq c (schar string i))))
914 (if* (or (null reserved-chars)
916 (= 0 (sbit reserved-chars ci)))
919 (setf (schar new-string new-i) c)
920 else ;; need to escape it
921 (multiple-value-bind (q r) (truncate ci 16)
922 (setf (schar new-string (incf new-i)) #\%)
923 (setf (schar new-string (incf new-i)) (elt *escaped-encoding* q))
924 (setf (schar new-string (incf new-i))
925 (elt *escaped-encoding* r))))))
927 (defmethod print-object ((uri uri) stream)
929 then (format stream "#<~a ~a>" 'uri (render-uri uri nil))
930 else (render-uri uri stream)))
932 (defmethod print-object ((urn urn) stream)
934 then (format stream "#<~a ~a>" 'uri (render-urn urn nil))
935 else (render-urn urn stream)))
937 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
938 ;; merging and unmerging
940 (defmethod merge-uris ((uri string) (base string) &optional place)
941 (merge-uris (parse-uri uri) (parse-uri base) place))
943 (defmethod merge-uris ((uri uri) (base string) &optional place)
944 (merge-uris uri (parse-uri base) place))
946 (defmethod merge-uris ((uri string) (base uri) &optional place)
947 (merge-uris (parse-uri uri) base place))
949 (defmethod merge-uris ((uri uri) (base uri) &optional place)
950 ;; The following is from
951 ;; http://info.internet.isi.edu/in-notes/rfc/files/rfc2396.txt
952 ;; and is algorithm we use to merge URIs.
954 ;; For more information, see section 5.2 of the RFC.
958 (when (and (null (uri-parsed-path uri))
959 (null (uri-scheme uri))
960 (null (uri-host uri))
961 (null (uri-port uri))
962 (null (uri-query uri)))
963 (return-from merge-uris
964 (let ((new (copy-uri base :place place)))
965 (when (uri-query uri)
966 (setf (uri-query new) (uri-query uri)))
967 (when (uri-fragment uri)
968 (setf (uri-fragment new) (uri-fragment uri)))
971 (setq uri (copy-uri uri :place place))
974 (when (uri-scheme uri)
975 (return-from merge-uris uri))
976 (setf (uri-scheme uri) (uri-scheme base))
979 (when (uri-host uri) (go :done))
980 (setf (uri-host uri) (uri-host base))
981 (setf (uri-port uri) (uri-port base))
984 (let ((p (uri-parsed-path uri)))
985 (when (and p (eq :absolute (car p)))
986 (when (equal '(:absolute "") p)
987 ;; Canonicalize the way parsing does:
988 (setf (uri-path uri) nil))
993 (or (uri-parsed-path base)
994 ;; needed because we canonicalize away a path of just `/':
996 (path (uri-parsed-path uri))
998 (when (not (eq :absolute (car base-path)))
999 (error "Cannot merge ~a and ~a, since latter is not absolute."
1004 (append (butlast base-path)
1005 (if* path then (cdr path) else '(""))))
1008 (let ((last (last new-path-list)))
1009 (if* (atom (car last))
1010 then (when (string= "." (car last))
1011 (setf (car last) ""))
1012 else (when (string= "." (caar last))
1013 (setf (caar last) ""))))
1015 (delete "." new-path-list :test #'(lambda (a b)
1021 (let ((npl (cdr new-path-list))
1024 (string= ".." (let ((l (car (last npl))))
1031 :test #'(lambda (a b)
1036 (when (null index) (return))
1038 ;; The RFC says, in 6g, "that the implementation may handle
1039 ;; this error by retaining these components in the resolved
1040 ;; path, by removing them from the resolved path, or by
1041 ;; avoiding traversal of the reference." The examples in C.2
1042 ;; imply that we should do the first thing (retain them), so
1043 ;; that's what we'll do.
1046 then (setq npl (cddr npl))
1048 (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1049 (setf (cdr tmp) (cdddr tmp))))
1050 (setf (cdr new-path-list) npl)
1051 (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1054 ;; don't complain if new-path-list starts with `..'. See comment
1055 ;; above about this step.
1058 (when (or (equal '(:absolute "") new-path-list)
1059 (equal '(:absolute) new-path-list))
1060 (setq new-path-list nil))
1061 (setf (uri-path uri)
1062 (render-parsed-path new-path-list
1063 ;; don't know, so have to assume:
1068 (return-from merge-uris uri)))
1070 (defmethod enough-uri ((uri string) (base string) &optional place)
1071 (enough-uri (parse-uri uri) (parse-uri base) place))
1073 (defmethod enough-uri ((uri uri) (base string) &optional place)
1074 (enough-uri uri (parse-uri base) place))
1076 (defmethod enough-uri ((uri string) (base uri) &optional place)
1077 (enough-uri (parse-uri uri) base place))
1079 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1080 (let ((new-scheme nil)
1083 (new-parsed-path nil))
1085 (when (or (and (uri-scheme uri)
1086 (not (equalp (uri-scheme uri) (uri-scheme base))))
1088 (not (equalp (uri-host uri) (uri-host base))))
1089 (not (equalp (uri-port uri) (uri-port base))))
1090 (return-from enough-uri uri))
1092 (when (null (uri-host uri))
1093 (setq new-host (uri-host base)))
1094 (when (null (uri-port uri))
1095 (setq new-port (uri-port base)))
1097 (when (null (uri-scheme uri))
1098 (setq new-scheme (uri-scheme base)))
1100 ;; Now, for the hard one, path.
1101 ;; We essentially do here what enough-namestring does.
1102 (do* ((base-path (uri-parsed-path base))
1103 (path (uri-parsed-path uri))
1104 (bp base-path (cdr bp))
1106 ((or (null bp) (null p))
1107 ;; If p is nil, that means we have something like
1108 ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1109 ;; new-parsed-path will be nil.
1111 (setq new-parsed-path (copy-list p))
1112 (when (not (symbolp (car new-parsed-path)))
1113 (push :relative new-parsed-path))))
1114 (if* (equal (car bp) (car p))
1116 else (setq new-parsed-path (copy-list p))
1117 (when (not (symbolp (car new-parsed-path)))
1118 (push :relative new-parsed-path))
1122 (when new-parsed-path
1123 (render-parsed-path new-parsed-path
1124 ;; don't know, so have to assume:
1126 (new-query (uri-query uri))
1127 (new-fragment (uri-fragment uri))
1128 (new-plist (copy-list (uri-plist uri))))
1129 (if* (and (null new-scheme)
1133 (null new-parsed-path)
1135 (null new-fragment))
1136 then ;; can't have a completely empty uri!
1138 :class (class-of uri)
1143 :class (class-of uri)
1149 :parsed-path new-parsed-path
1151 :fragment new-fragment
1152 :plist new-plist)))))
1154 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1155 ;; support for interning URIs
1157 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1159 (apply #'make-hash-table :size size
1160 :hash-function 'uri-hash
1161 :test 'uri= :values nil keys)
1163 (apply #'make-hash-table :size size keys))
1165 (defun gethash-uri (uri table)
1166 #+allegro (gethash uri table)
1168 (let* ((hash (uri-hash uri))
1169 (existing (gethash hash table)))
1170 (dolist (u existing)
1172 (return-from gethash-uri (values u t))))
1175 (defun puthash-uri (uri table)
1176 #+allegro (excl:puthash-key uri table)
1178 (let ((existing (gethash (uri-hash uri) table)))
1179 (dolist (u existing)
1181 (return-from puthash-uri u)))
1182 (setf (gethash (uri-hash uri) table)
1183 (cons uri existing))
1187 (defun uri-hash (uri)
1188 (if* (uri-hashcode uri)
1190 else (setf (uri-hashcode uri)
1193 (render-uri uri nil)
1196 (render-uri uri nil))))))
1198 (defvar *uris* (make-uri-space))
1200 (defun uri-space () *uris*)
1202 (defun (setf uri-space) (new-val)
1203 (setq *uris* new-val))
1205 ;; bootstrapping (uri= changed from function to method):
1206 (when (fboundp 'uri=) (fmakunbound 'uri=))
1208 (defgeneric uri= (uri1 uri2))
1209 (defmethod uri= ((uri1 uri) (uri2 uri))
1210 (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1211 (return-from uri= nil))
1212 ;; RFC2396 says: a URL with an explicit ":port", where the port is
1213 ;; the default for the scheme, is the equivalent to one where the
1214 ;; port is elided. Hmmmm. This means that this function has to be
1215 ;; scheme dependent. Grrrr.
1216 (let ((default-port (case (uri-scheme uri1)
1221 (and (equalp (uri-host uri1) (uri-host uri2))
1222 (eql (or (uri-port uri1) default-port)
1223 (or (uri-port uri2) default-port))
1224 (string= (uri-path uri1) (uri-path uri2))
1225 (string= (uri-query uri1) (uri-query uri2))
1226 (string= (uri-fragment uri1) (uri-fragment uri2)))))
1228 (defmethod uri= ((urn1 urn) (urn2 urn))
1229 (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1230 (return-from uri= nil))
1231 (and (equalp (urn-nid urn1) (urn-nid urn2))
1232 (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1234 (defun urn-nss-equal (nss1 nss2 &aux len)
1235 ;; Return t iff the nss values are the same.
1236 ;; %2c and %2C are equivalent.
1237 (when (or (null nss1) (null nss2)
1238 (not (= (setq len (length nss1))
1240 (return-from urn-nss-equal nil))
1245 (setq c1 (schar nss1 i))
1246 (setq c2 (schar nss2 i))
1249 (if* (and (char= #\% c1) (char= #\% c2))
1250 then (setq state :percent+1)
1251 elseif (char/= c1 c2)
1254 (when (char-not-equal c1 c2) (return nil))
1255 (setq state :percent+2))
1257 (when (char-not-equal c1 c2) (return nil))
1258 (setq state :char)))))
1260 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1261 (let ((uri (gethash-uri xuri uri-space)))
1264 else (puthash-uri xuri uri-space))))
1266 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1267 (intern-uri (parse-uri uri) uri-space))
1269 (defun unintern-uri (uri &optional (uri-space *uris*))
1271 then (clrhash uri-space)
1273 then (remhash uri uri-space)
1274 else (error "bad uri: ~s." uri)))
1276 (defmacro do-all-uris ((var &optional uri-space result-form)
1279 "do-all-uris (var [[uri-space] result-form])
1280 {declaration}* {tag | statement}*
1281 Executes the forms once for each uri with var bound to the current uri"
1284 (g-uri-space (gensym))
1285 (body (third (parse-body forms env))))
1286 `(let ((,g-uri-space (or ,uri-space *uris*)))
1288 (flet ((,f (,var &optional ,g-ignore)
1289 (declare (ignore-if-unused ,var ,g-ignore))
1291 (maphash #',f ,g-uri-space))
1292 (return ,result-form)))))
1294 (defun sharp-u (stream chr arg)
1295 (declare (ignore chr arg))
1296 (let ((arg (read stream nil nil t)))
1300 then (parse-uri arg)
1303 (internal-reader-error
1305 "#u takes a string or list argument: ~s" arg)))))
1311 (locally (declare (special std-lisp-readtable))
1312 (let ((*readtable* std-lisp-readtable))
1313 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)))
1315 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1317 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1323 ;; (don't run under emacs with M-x fi:common-lisp)
1326 (eval-when (:compile-toplevel :load-toplevel :execute)
1330 (defun gc (&rest options)
1331 (declare (ignore options))
1336 (defun time-uri-module ()
1337 (declare (optimize (speed 3) (safety 0) (debug 0)))
1338 (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1339 (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1340 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1341 (format t "~&;;; starting timing testing 1...~%")
1342 (time (dotimes (i 100000) (parse-uri uri)))
1344 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1345 (format t "~&;;; starting timing testing 2...~%")
1346 (let ((uri (parse-uri uri)))
1347 (time (dotimes (i 100000)
1348 ;; forces no caching of the printed representation:
1349 (setf (uri-string uri) nil)
1350 (format nil "~a" uri))))
1352 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1353 (format t "~&;;; starting timing testing 3...~%")
1356 (dotimes (i 100000) (parse-uri uri2))
1357 (let ((uri (parse-uri uri)))
1359 ;; forces no caching of the printed representation:
1360 (setf (uri-string uri) nil)
1361 (format nil "~a" uri)))))))
1363 ;;******** reference output (ultra, modified 5.0.1):
1364 ;;; starting timing testing 1...
1365 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1366 ; cpu time (gc) 600 msec user, 10 msec system
1367 ; cpu time (total) 14,310 msec user, 10 msec system
1368 ; real time 14,465 msec
1370 ; 1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1371 ;;; starting timing testing 2...
1372 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1373 ; cpu time (gc) 280 msec user, 20 msec system
1374 ; cpu time (total) 27,780 msec user, 20 msec system
1375 ; real time 27,897 msec
1377 ; 1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1378 ;;; starting timing testing 3...
1379 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1380 ; cpu time (gc) 1,290 msec user, 30 msec system
1381 ; cpu time (total) 53,580 msec user, 40 msec system
1382 ; real time 54,062 msec
1384 ; 7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1386 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1387 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1389 ;;; starting timing testing 1...
1390 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1391 ; cpu time (gc) 400 msec user, 0 msec system
1392 ; cpu time (total) 14,920 msec user, 0 msec system
1393 ; real time 15,082 msec
1395 ; 1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1396 ;;; starting timing testing 2...
1397 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1398 ; cpu time (gc) 300 msec user, 0 msec system
1399 ; cpu time (total) 27,790 msec user, 10 msec system
1400 ; real time 28,025 msec
1402 ; 1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1403 ;;; starting timing testing 3...
1404 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1405 ; cpu time (gc) 920 msec user, 10 msec system
1406 ; cpu time (total) 48,820 msec user, 30 msec system
1407 ; real time 49,188 msec
1409 ; 3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes