1 ;; -*- mode: common-lisp; package: puri -*-
3 ;; For general URI information see RFC2396.
5 ;; copyright (c) 1999-2002 Franz Inc, Berkeley, CA - All rights reserved.
6 ;; copyright (c) 2002-2005 Franz Inc, Oakland, CA - All rights reserved.
7 ;; copyright (c) 2003-2010 Kevin Rosenberg
9 ;; This code is free software; you can redistribute it and/or
10 ;; modify it under the terms of the version 2.1 of
11 ;; the GNU Lesser General Public License as published by
12 ;; the Free Software Foundation, as clarified by the
13 ;; preamble found here:
14 ;; http://opensource.franz.com/preamble.html
16 ;; Versions ported from Franz's opensource release
17 ;; uri.cl,v 2.3.6.4.2.1 2001/08/09 17:42:39 layer
18 ;; uri.cl,v 2.9.84.1 2005/08/11 18:38:52 layer
20 ;; This code is distributed in the hope that it will be useful,
21 ;; but without any warranty; without even the implied warranty of
22 ;; merchantability or fitness for a particular purpose. See the GNU
23 ;; Lesser General Public License for more details.
29 #-allegro (:nicknames #:net.uri)
31 #:uri ; the type and a function
35 #:uri-scheme ; and slots
41 #:uri-authority ; pseudo-slot accessor
44 #:urn-nid ; pseudo-slot accessor
45 #:urn-nss ; pseudo-slot accessor
54 #:make-uri-space ; interning...
61 #:uri-parse-error ;; Added by KMR
66 (eval-when (:compile-toplevel) (declaim (optimize (speed 3))))
70 (defun parse-body (forms &optional env)
71 "Parses a body, returns (VALUES docstring declarations forms)"
72 (declare (ignore env))
73 ;; fixme -- need to add parsing of multiple declarations
74 (let (docstring declarations)
75 (when (stringp (car forms))
76 (setq docstring (car forms))
77 (setq forms (cdr forms)))
78 (when (and (listp (car forms))
79 (symbolp (caar forms))
80 (string-equal (symbol-name '#:declare)
81 (symbol-name (caar forms))))
82 (setq declarations (car forms))
83 (setq forms (cdr forms)))
84 (values docstring declarations forms)))
87 (defun shrink-vector (str size)
89 (excl::.primcall 'sys::shrink-svector str size)
91 (setq str (sb-kernel:shrink-vector str size))
93 (lisp::shrink-vector str size)
95 (system::shrink-vector$vector str size)
97 (common-lisp::shrink-vector str size)
98 #-(or allegro cmu lispworks sbcl scl)
99 (setq str (subseq str 0 size))
103 ;; KMR: Added new condition to handle cross-implementation variances
104 ;; in the parse-error condition many implementations define
106 (define-condition uri-parse-error (parse-error)
107 ((fmt-control :initarg :fmt-control :accessor fmt-control)
108 (fmt-arguments :initarg :fmt-arguments :accessor fmt-arguments ))
109 (:report (lambda (c stream)
110 (format stream "Parse error:")
111 (apply #'format stream (fmt-control c) (fmt-arguments c)))))
113 (defun .parse-error (fmt &rest args)
114 (error 'uri-parse-error :fmt-control fmt :fmt-arguments args))
117 (defun internal-reader-error (stream fmt &rest args)
118 (apply #'format stream fmt args))
120 #-allegro (defvar *current-case-mode* :case-insensitive-upper)
121 #+allegro (eval-when (:compile-toplevel :load-toplevel :execute)
122 (import '(excl:*current-case-mode*
123 excl:delimited-string-to-list
125 excl::internal-reader-error
129 (defmethod position-char (char (string string) start max)
130 (declare (optimize (speed 3) (safety 0) (space 0))
131 (fixnum start max) (string string))
132 (do* ((i start (1+ i)))
135 (when (char= char (char string i)) (return i))))
138 (defun delimited-string-to-list (string &optional (separator #\space)
140 (declare (optimize (speed 3) (safety 0) (space 0)
141 (compilation-speed 0))
143 (type character separator))
144 (do* ((len (length string))
147 (end (position-char separator string pos len)
148 (position-char separator string pos len)))
151 (push (subseq string pos) output)
152 (when (and (plusp len) (not skip-terminal))
155 (declare (type fixnum pos len)
156 (type (or null fixnum) end))
157 (push (subseq string pos end) output)
158 (setq pos (1+ end))))
161 (eval-when (:compile-toplevel :load-toplevel :execute)
162 (defvar if*-keyword-list '("then" "thenret" "else" "elseif"))
164 (defmacro if* (&rest args)
165 (do ((xx (reverse args) (cdr xx))
172 (cond ((eq state :compl)
174 (t (error "if*: illegal form ~s" args))))
175 (cond ((and (symbolp (car xx))
176 (member (symbol-name (car xx))
178 :test #'string-equal))
179 (setq lookat (symbol-name (car xx)))))
181 (cond ((eq state :init)
182 (cond (lookat (cond ((string-equal lookat "thenret")
186 "if*: bad keyword ~a" lookat))))
189 (push (car xx) col))))
192 (cond ((string-equal lookat "else")
195 "if*: multiples elses")))
198 (push `(t ,@col) totalcol))
199 ((string-equal lookat "then")
201 (t (error "if*: bad keyword ~s"
203 (t (push (car xx) col))))
207 "if*: keyword ~s at the wrong place " (car xx)))
208 (t (setq state :compl)
209 (push `(,(car xx) ,@col) totalcol))))
211 (cond ((not (string-equal lookat "elseif"))
212 (error "if*: missing elseif clause ")))
213 (setq state :init))))))
219 (scheme :initarg :scheme :initform nil :accessor uri-scheme)
220 (host :initarg :host :initform nil :accessor uri-host)
221 (port :initarg :port :initform nil :accessor uri-port)
222 (path :initarg :path :initform nil :accessor uri-path)
223 (query :initarg :query :initform nil :accessor uri-query)
224 (fragment :initarg :fragment :initform nil :accessor uri-fragment)
225 (plist :initarg :plist :initform nil :accessor uri-plist)
229 ;; used to prevent unnessary work, looking for chars to escape and
231 :initarg :escaped :initform nil :accessor uri-escaped)
233 ;; the cached printable representation of the URI. It *might* be
234 ;; different than the original string, though, because the user might
235 ;; have escaped non-reserved chars--they won't be escaped when the URI
237 :initarg :string :initform nil :accessor uri-string)
239 ;; the cached parsed representation of the URI path.
240 :initarg :parsed-path
242 :accessor .uri-parsed-path)
244 ;; cached sxhash, so we don't have to compute it more than once.
245 :initarg :hashcode :initform nil :accessor uri-hashcode)))
248 ((nid :initarg :nid :initform nil :accessor urn-nid)
249 (nss :initarg :nss :initform nil :accessor urn-nss)))
251 (eval-when (:compile-toplevel :execute)
252 (defmacro clear-caching-on-slot-change (name)
253 `(defmethod (setf ,name) :around (new-value (self uri))
254 (declare (ignore new-value))
255 (prog1 (call-next-method)
256 (setf (uri-string self) nil)
257 ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
258 (setf (uri-hashcode self) nil))))
261 (clear-caching-on-slot-change uri-scheme)
262 (clear-caching-on-slot-change uri-host)
263 (clear-caching-on-slot-change uri-port)
264 (clear-caching-on-slot-change uri-path)
265 (clear-caching-on-slot-change uri-query)
266 (clear-caching-on-slot-change uri-fragment)
269 (defmethod make-load-form ((self uri) &optional env)
270 (declare (ignore env))
271 `(make-instance ',(class-name (class-of self))
272 :scheme ,(uri-scheme self)
273 :host ,(uri-host self)
274 :port ,(uri-port self)
275 :path ',(uri-path self)
276 :query ,(uri-query self)
277 :fragment ,(uri-fragment self)
278 :plist ',(uri-plist self)
279 :string ,(uri-string self)
280 :parsed-path ',(.uri-parsed-path self)))
282 (defmethod uri-p ((thing uri)) t)
283 (defmethod uri-p ((thing t)) nil)
287 (scheme (when uri (uri-scheme uri)))
288 (host (when uri (uri-host uri)))
289 (port (when uri (uri-port uri)))
290 (path (when uri (uri-path uri)))
292 (when uri (copy-list (.uri-parsed-path uri))))
293 (query (when uri (uri-query uri)))
294 (fragment (when uri (uri-fragment uri)))
295 (plist (when uri (copy-list (uri-plist uri))))
296 (class (when uri (class-of uri)))
297 &aux (escaped (when uri (uri-escaped uri))))
299 then (setf (uri-scheme place) scheme)
300 (setf (uri-host place) host)
301 (setf (uri-port place) port)
302 (setf (uri-path place) path)
303 (setf (.uri-parsed-path place) parsed-path)
304 (setf (uri-query place) query)
305 (setf (uri-fragment place) fragment)
306 (setf (uri-plist place) plist)
307 (setf (uri-escaped place) escaped)
308 (setf (uri-string place) nil)
309 (setf (uri-hashcode place) nil)
311 elseif (eq 'uri class)
312 then ;; allow the compiler to optimize the call to make-instance:
314 :scheme scheme :host host :port port :path path
315 :parsed-path parsed-path
316 :query query :fragment fragment :plist plist
317 :escaped escaped :string nil :hashcode nil)
318 else (make-instance class
319 :scheme scheme :host host :port port :path path
320 :parsed-path parsed-path
321 :query query :fragment fragment :plist plist
322 :escaped escaped :string nil :hashcode nil)))
324 (defmethod uri-parsed-path ((uri uri))
326 (when (null (.uri-parsed-path uri))
327 (setf (.uri-parsed-path uri)
328 (parse-path (uri-path uri) (uri-escaped uri))))
329 (.uri-parsed-path uri)))
331 (defmethod (setf uri-parsed-path) (path-list (uri uri))
332 (assert (and (consp path-list)
333 (or (member (car path-list) '(:absolute :relative)
335 (setf (uri-path uri) (render-parsed-path path-list t))
336 (setf (.uri-parsed-path uri) path-list)
339 (defun uri-authority (uri)
341 (let ((*print-pretty* nil))
342 (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
345 (if* (equalp "urn" (uri-scheme uri))
347 else (error "URI is not a URN: ~s." uri)))
350 (if* (equalp "urn" (uri-scheme uri))
352 else (error "URI is not a URN: ~s." uri)))
354 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
357 (defparameter *excluded-characters*
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.
387 (defparameter *reserved-fragment-characters*
388 (reserved-char-vector (remove #\# *excluded-characters*)))
390 (eval-when (:compile-toplevel :execute)
391 (defun gen-char-range-list (start end)
393 (endcode (1+ (char-int end)))
394 (chcode (char-int start)
398 ;; - has to be first, otherwise it signifies a range!
400 then (setq res (nreverse res))
403 else (nreverse res)))
404 (if* (= #.(char-int #\-) chcode)
406 else (push (code-char chcode) res))))
409 (defparameter *valid-nid-characters*
410 (reserved-char-vector
411 '#.(nconc (gen-char-range-list #\a #\z)
412 (gen-char-range-list #\A #\Z)
413 (gen-char-range-list #\0 #\9)
415 (defparameter *reserved-nss-characters*
416 (reserved-char-vector
417 (append *excluded-characters* '(#\& #\~ #\/ #\?))))
419 (defparameter *illegal-characters*
420 (reserved-char-vector (remove #\# *excluded-characters*)))
421 (defparameter *strict-illegal-query-characters*
422 (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
423 (defparameter *illegal-query-characters*
424 (reserved-char-vector
425 *excluded-characters* :except '(#\^ #\| #\#)))
428 (defun parse-uri (thing &key (class 'uri) &aux escape)
429 (when (uri-p thing) (return-from parse-uri thing))
431 (setq escape (escape-p thing))
432 (multiple-value-bind (scheme host port path query fragment)
433 (parse-uri-string thing)
437 (case *current-case-mode*
438 ((:case-insensitive-upper :case-sensitive-upper)
440 ((:case-insensitive-lower :case-sensitive-lower)
442 (decode-escaped-encoding scheme escape))
443 (find-package :keyword))))
445 (when (and scheme (eq :urn scheme))
446 (return-from parse-uri
447 (make-instance 'urn :scheme scheme :nid host :nss path)))
449 (when host (setq host (decode-escaped-encoding host escape)))
451 (setq port (read-from-string port))
452 (when (not (numberp port)) (error "port is not a number: ~s." port))
453 (when (not (plusp port))
454 (error "port is not a positive integer: ~d." port))
455 (when (eql port (case scheme
461 (when (or (string= "" path)
462 (and ;; we canonicalize away a reference to just /:
464 (member scheme '(:http :https :ftp) :test #'eq)
469 (decode-escaped-encoding path escape *reserved-path-characters*)))
470 (when query (setq query (decode-escaped-encoding query escape)))
473 (decode-escaped-encoding fragment escape
474 *reserved-fragment-characters*)))
476 then ;; allow the compiler to optimize the make-instance call:
485 else ;; do it the slow way:
495 (defmethod uri ((thing uri))
498 (defmethod uri ((thing string))
501 (defmethod uri ((thing t))
502 (error "Cannot coerce ~s to a uri." thing))
504 (defvar *strict-parse* t)
506 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
507 (declare (optimize (speed 3)))
508 ;; Speed is important, so use a specialized state machine instead of
509 ;; regular expressions for parsing the URI string. The regexp we are
518 (end (length string))
523 (path-components '())
526 ;; namespace identifier, for urn parsing only:
528 (declare (fixnum state start end))
529 (flet ((read-token (kind &optional legal-chars)
533 else (let ((sindex start)
536 (declare (fixnum sindex))
539 (when (>= start end) (return nil))
540 (setq c (char string start))
541 (let ((ci (char-int c)))
543 then (if* (and (eq :colon kind) (eq c #\:))
545 elseif (= 0 (sbit legal-chars ci))
548 URI ~s contains illegal character ~s at position ~d."
550 elseif (and (< ci 128)
552 (= 1 (sbit illegal-chars ci)))
553 then (.parse-error "~
554 URI ~s contains illegal character ~s at position ~d."
558 (#\? (return :question))
559 (#\# (return :hash))))
560 (:query (case c (#\# (return :hash))))
563 (#\: (return :colon))
564 (#\? (return :question))
566 (#\/ (return :slash)))))
568 (if* (> start sindex)
569 then ;; we found some chars
570 ;; before we stopped the parse
571 (setq tokval (subseq string sindex start))
573 else ;; immediately stopped at a special char
576 (failure (&optional why)
577 (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
580 (.parse-error "impossible state: ~d [~s]" state string)))
583 (0 ;; starting to parse
584 (ecase (read-token t)
586 (:question (setq state 7))
587 (:hash (setq state 8))
588 (:slash (setq state 3))
589 (:string (setq state 1))
590 (:end (setq state 9))))
591 (1 ;; seen <token><special char>
592 (let ((token tokval))
593 (ecase (read-token t)
594 (:colon (setq scheme token)
595 (if* (equalp "urn" scheme)
597 else (setq state 2)))
598 (:question (push token path-components)
600 (:hash (push token path-components)
602 (:slash (push token path-components)
603 (push "/" path-components)
606 (:end (push token path-components)
609 (ecase (read-token t)
611 (:question (setq state 7))
612 (:hash (setq state 8))
613 (:slash (setq state 3))
614 (:string (setq state 10))
615 (:end (setq state 9))))
616 (10 ;; seen <scheme>:<token>
617 (let ((token tokval))
618 (ecase (read-token t)
620 (:question (push token path-components)
622 (:hash (push token path-components)
624 (:slash (push token path-components)
627 (:end (push token path-components)
629 (3 ;; seen / or <scheme>:/
630 (ecase (read-token t)
632 (:question (push "/" path-components)
634 (:hash (push "/" path-components)
636 (:slash (setq state 4))
637 (:string (push "/" path-components)
638 (push tokval path-components)
640 (:end (push "/" path-components)
642 (4 ;; seen [<scheme>:]//
643 (ecase (read-token t)
645 (:question (failure))
648 (if* (and (equalp "file" scheme)
651 (push "/" path-components)
654 (:string (setq host tokval)
657 (11 ;; seen [<scheme>:]//<host>
658 (ecase (read-token t)
659 (:colon (setq state 5))
660 (:question (setq state 7))
661 (:hash (setq state 8))
662 (:slash (push "/" path-components)
664 (:string (impossible))
665 (:end (setq state 9))))
666 (5 ;; seen [<scheme>:]//<host>:
667 (ecase (read-token t)
669 (:question (failure))
671 (:slash (push "/" path-components)
673 (:string (setq port tokval)
676 (12 ;; seen [<scheme>:]//<host>:[<port>]
677 (ecase (read-token t)
679 (:question (setq state 7))
680 (:hash (setq state 8))
681 (:slash (push "/" path-components)
683 (:string (impossible))
684 (:end (setq state 9))))
686 (ecase (read-token :path)
687 (:question (setq state 7))
688 (:hash (setq state 8))
689 (:string (push tokval path-components)
691 (:end (setq state 9))))
693 (ecase (read-token :path)
694 (:question (setq state 7))
695 (:hash (setq state 8))
696 (:string (impossible))
697 (:end (setq state 9))))
701 then *strict-illegal-query-characters*
702 else *illegal-query-characters*))
703 (ecase (prog1 (read-token :query)
704 (setq illegal-chars *illegal-characters*))
705 (:hash (setq state 8))
706 (:string (setq query tokval)
708 (:end (setq state 9))))
710 (ecase (read-token :query)
711 (:hash (setq state 8))
712 (:string (impossible))
713 (:end (setq state 9))))
715 (ecase (read-token :rest)
716 (:string (setq fragment tokval)
718 (:end (setq state 9))))
723 (apply #'concatenate 'string (nreverse path-components))
726 (15 ;; seen urn:, read nid now
727 (case (read-token :colon *valid-nid-characters*)
728 (:string (setq nid tokval)
730 (t (failure "missing namespace identifier"))))
731 (16 ;; seen urn:<nid>
733 (:colon (setq state 17))
734 (t (failure "missing namespace specific string"))))
735 (17 ;; seen urn:<nid>:, rest is nss
736 (return (values scheme
740 (setq illegal-chars *reserved-nss-characters*)
744 "internal error in parse engine, wrong state: ~s." state)))))))
746 (defun escape-p (string)
747 (declare (optimize (speed 3)))
749 (max (the fixnum (length string))))
751 (declare (fixnum i max))
752 (when (char= #\% (char string i))
755 (defun parse-path (path-string escape)
756 (do* ((xpath-list (delimited-string-to-list path-string #\/))
759 (if* (string= "" (car xpath-list))
760 then (setf (car xpath-list) :absolute)
761 else (push :relative xpath-list))
763 (pl (cdr path-list) (cdr pl))
765 ((null pl) path-list)
767 (if* (cdr (setq segments
768 (if* (string= "" (car pl))
770 else (delimited-string-to-list (car pl) #\;))))
771 then ;; there is a param
773 (mapcar #'(lambda (s)
774 (decode-escaped-encoding s escape
780 (decode-escaped-encoding (car segments) escape
784 (defun decode-escaped-encoding (string escape
785 &optional (reserved-chars
786 *reserved-characters*))
787 ;;Return a string with the real characters.
788 (when (null escape) (return-from decode-escaped-encoding string))
791 (maxpos (length string))
793 (flet ((next-ansii-substring ()
794 (let ((pos (or (position #\% string :start curpos)
796 (when (and (= curpos 0)
798 (return-from decode-escaped-encoding string))
805 (next-encoded-substring ()
806 (let ((pos (or (loop for i from curpos below maxpos by 3
807 unless (char= (aref string i)
812 (let ((octets (handler-case (make-array (/ (- pos curpos)
814 :element-type '(unsigned-byte 8)
817 (.parse-error "Unsyntactic escaped encoding in ~s." string)))))
818 (loop for i from curpos below pos by 3
819 do (vector-push (handler-case
820 (parse-integer string
825 (.parse-error "Non-hexidecimal digits after %: ~c~c."
827 (aref string (+ 2 i)))))
830 (let* ((decoded-string (babel:octets-to-string octets
832 (rpos (if reserved-chars
833 (position-if #'(lambda (ch)
834 (not (or (> (char-code ch) 127)
835 (= (sbit reserved-chars (char-code ch)) 0))))
838 (with-output-to-string (out)
839 (loop for ch across decoded-string
841 do (let ((octet (char-code ch)))
843 ((or (null reserved-chars)
845 (= (sbit reserved-chars octet) 0))
848 (* (if (> octet 127) 2 1)
850 (t (write-string (subseq string i (+ i 3)) out)
857 while (< curpos maxpos)
858 do (next-ansii-substring)
859 while (< curpos maxpos)
860 do (next-encoded-substring)))
869 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
872 (defun render-uri (uri stream
873 &aux (escape (uri-escaped uri))
874 (*print-pretty* nil))
875 (when (null (uri-string uri))
876 (setf (uri-string uri)
877 (let ((scheme (uri-scheme uri))
878 (host (uri-host uri))
879 (port (uri-port uri))
880 (path (uri-path uri))
881 (query (uri-query uri))
882 (fragment (uri-fragment uri)))
885 (encode-escaped-encoding
886 (string-downcase ;; for upper case lisps
887 (symbol-name scheme))
888 *reserved-characters* escape))
890 (when (or host (eq :file scheme)) "//")
892 (encode-escaped-encoding
893 host *reserved-authority-characters* escape))
896 #-allegro (format nil "~D" port)
897 #+allegro (with-output-to-string (s)
898 (excl::maybe-print-fast s port))
900 (encode-escaped-encoding (or path "/")
902 ;;*reserved-path-characters*
905 (when query (encode-escaped-encoding query nil escape))
907 (when fragment (encode-escaped-encoding fragment nil escape))))))
909 then (format stream "~a" (uri-string uri))
910 else (uri-string uri)))
912 (defun render-parsed-path (path-list escape)
914 (first (car path-list))
915 (pl (cdr path-list) (cdr pl))
916 (pe (car pl) (car pl)))
918 (when res (apply #'concatenate 'string (nreverse res))))
919 (when (or (null first)
920 (prog1 (eq :absolute first)
925 (encode-escaped-encoding pe *reserved-path-characters* escape)
927 else ;; contains params
928 (push (encode-escaped-encoding
929 (car pe) *reserved-path-characters* escape)
931 (dolist (item (cdr pe))
933 (push (encode-escaped-encoding
934 item *reserved-path-characters* escape)
937 (defun render-urn (urn stream
938 &aux (*print-pretty* nil))
939 (when (null (uri-string urn))
940 (setf (uri-string urn)
941 (let ((nid (urn-nid urn))
943 (concatenate 'string "urn:" nid ":" nss))))
945 then (format stream "~a" (uri-string urn))
946 else (uri-string urn)))
948 (defun encode-escaped-encoding (string reserved-chars escape)
949 (when (null escape) (return-from encode-escaped-encoding string))
950 (with-output-to-string (out)
951 (loop for ch across string
952 do (let ((code (char-code ch)))
953 (if (and (< code 128)
954 (or (null reserved-chars)
955 (= 0 (sbit reserved-chars code))))
957 (loop for octet across (babel:string-to-octets (string ch) :encoding :utf-8)
958 do (format out "%~(~2,'0x~)" octet)))))))
960 (defmethod print-object ((uri uri) stream)
962 then (print-unreadable-object (uri stream :type t) (render-uri uri stream))
963 else (render-uri uri stream)))
965 (defmethod print-object ((urn urn) stream)
967 then (print-unreadable-object (urn stream :type t) (render-urn urn stream))
968 else (render-urn urn stream)))
970 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
971 ;; merging and unmerging
973 (defmethod merge-uris ((uri string) (base string) &optional place)
974 (merge-uris (parse-uri uri) (parse-uri base) place))
976 (defmethod merge-uris ((uri uri) (base string) &optional place)
977 (merge-uris uri (parse-uri base) place))
979 (defmethod merge-uris ((uri string) (base uri) &optional place)
980 (merge-uris (parse-uri uri) base place))
983 (defmethod merge-uris ((uri uri) (base uri) &optional place)
984 ;; See ../doc/rfc2396.txt for info on the algorithm we use to merge
989 (when (and (null (uri-parsed-path uri))
990 (null (uri-scheme uri))
991 (null (uri-host uri))
992 (null (uri-port uri))
993 (null (uri-query uri)))
994 (return-from merge-uris
995 (let ((new (copy-uri base :place place)))
996 (when (uri-query uri)
997 (setf (uri-query new) (uri-query uri)))
998 (when (uri-fragment uri)
999 (setf (uri-fragment new) (uri-fragment uri)))
1002 (setq uri (copy-uri uri :place place))
1005 (when (uri-scheme uri)
1006 (return-from merge-uris uri))
1007 (setf (uri-scheme uri) (uri-scheme base))
1010 (when (uri-host uri) (go :done))
1011 (setf (uri-host uri) (uri-host base))
1012 (setf (uri-port uri) (uri-port base))
1015 (let ((p (uri-parsed-path uri)))
1018 ;; The following form causes our implementation to be at odds with
1019 ;; RFC 2396, however this is apparently what was intended by the
1020 ;; authors of the RFC. Specifically, (merge-uris "?y" "/foo")
1021 ;; should return #<uri /foo?y> instead of #<uri ?y>, according to
1023 ;;; http://www.apache.org/~fielding/uri/rev-2002/issues.html#003-relative-query
1025 (setf (uri-path uri) (uri-path base))
1028 (when (and p (eq :absolute (car p)))
1029 (when (equal '(:absolute "") p)
1030 ;; Canonicalize the way parsing does:
1031 (setf (uri-path uri) nil))
1036 (or (uri-parsed-path base)
1037 ;; needed because we canonicalize away a path of just `/':
1039 (path (uri-parsed-path uri))
1041 (when (not (eq :absolute (car base-path)))
1042 (error "Cannot merge ~a and ~a, since latter is not absolute."
1047 (append (butlast base-path)
1048 (if* path then (cdr path) else '(""))))
1051 (let ((last (last new-path-list)))
1052 (if* (atom (car last))
1053 then (when (string= "." (car last))
1054 (setf (car last) ""))
1055 else (when (string= "." (caar last))
1056 (setf (caar last) ""))))
1058 (delete "." new-path-list :test #'(lambda (a b)
1064 (let ((npl (cdr new-path-list))
1067 (string= ".." (let ((l (car (last npl))))
1074 :test #'(lambda (a b)
1079 (when (null index) (return))
1081 ;; The RFC says, in 6g, "that the implementation may handle
1082 ;; this error by retaining these components in the resolved
1083 ;; path, by removing them from the resolved path, or by
1084 ;; avoiding traversal of the reference." The examples in C.2
1085 ;; imply that we should do the first thing (retain them), so
1086 ;; that's what we'll do.
1089 then (setq npl (cddr npl))
1091 (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1092 (setf (cdr tmp) (cdddr tmp))))
1093 (setf (cdr new-path-list) npl)
1094 (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1097 ;; don't complain if new-path-list starts with `..'. See comment
1098 ;; above about this step.
1101 (when (or (equal '(:absolute "") new-path-list)
1102 (equal '(:absolute) new-path-list))
1103 (setq new-path-list nil))
1104 (setf (uri-path uri)
1105 (render-parsed-path new-path-list
1106 ;; don't know, so have to assume:
1111 (return-from merge-uris uri)))
1113 (defmethod enough-uri ((uri string) (base string) &optional place)
1114 (enough-uri (parse-uri uri) (parse-uri base) place))
1116 (defmethod enough-uri ((uri uri) (base string) &optional place)
1117 (enough-uri uri (parse-uri base) place))
1119 (defmethod enough-uri ((uri string) (base uri) &optional place)
1120 (enough-uri (parse-uri uri) base place))
1122 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1123 (let ((new-scheme nil)
1126 (new-parsed-path nil))
1128 (when (or (and (uri-scheme uri)
1129 (not (equalp (uri-scheme uri) (uri-scheme base))))
1131 (not (equalp (uri-host uri) (uri-host base))))
1132 (not (equalp (uri-port uri) (uri-port base))))
1133 (return-from enough-uri uri))
1135 (when (null (uri-host uri))
1136 (setq new-host (uri-host base)))
1137 (when (null (uri-port uri))
1138 (setq new-port (uri-port base)))
1140 (when (null (uri-scheme uri))
1141 (setq new-scheme (uri-scheme base)))
1143 ;; Now, for the hard one, path.
1144 ;; We essentially do here what enough-namestring does.
1145 (do* ((base-path (uri-parsed-path base))
1146 (path (uri-parsed-path uri))
1147 (bp base-path (cdr bp))
1149 ((or (null bp) (null p))
1150 ;; If p is nil, that means we have something like
1151 ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1152 ;; new-parsed-path will be nil.
1154 (setq new-parsed-path (copy-list p))
1155 (when (not (symbolp (car new-parsed-path)))
1156 (push :relative new-parsed-path))))
1157 (if* (equal (car bp) (car p))
1159 else (setq new-parsed-path (copy-list p))
1160 (when (not (symbolp (car new-parsed-path)))
1161 (push :relative new-parsed-path))
1165 (when new-parsed-path
1166 (render-parsed-path new-parsed-path
1167 ;; don't know, so have to assume:
1169 (new-query (uri-query uri))
1170 (new-fragment (uri-fragment uri))
1171 (new-plist (copy-list (uri-plist uri))))
1172 (if* (and (null new-scheme)
1176 (null new-parsed-path)
1178 (null new-fragment))
1179 then ;; can't have a completely empty uri!
1181 :class (class-of uri)
1186 :class (class-of uri)
1192 :parsed-path new-parsed-path
1194 :fragment new-fragment
1195 :plist new-plist)))))
1197 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1198 ;; support for interning URIs
1200 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1202 (apply #'make-hash-table :size size
1203 :hash-function 'uri-hash
1204 :test 'uri= :values nil keys)
1206 (apply #'make-hash-table :size size keys))
1208 (defun gethash-uri (uri table)
1209 #+allegro (gethash uri table)
1211 (let* ((hash (uri-hash uri))
1212 (existing (gethash hash table)))
1213 (dolist (u existing)
1215 (return-from gethash-uri (values u t))))
1218 (defun puthash-uri (uri table)
1219 #+allegro (excl:puthash-key uri table)
1221 (let ((existing (gethash (uri-hash uri) table)))
1222 (dolist (u existing)
1224 (return-from puthash-uri u)))
1225 (setf (gethash (uri-hash uri) table)
1226 (cons uri existing))
1230 (defun uri-hash (uri)
1231 (if* (uri-hashcode uri)
1233 else (setf (uri-hashcode uri)
1236 (render-uri uri nil)
1239 (render-uri uri nil))))))
1241 (defvar *uris* (make-uri-space))
1243 (defun uri-space () *uris*)
1245 (defun (setf uri-space) (new-val)
1246 (setq *uris* new-val))
1248 ;; bootstrapping (uri= changed from function to method):
1249 (when (fboundp 'uri=) (fmakunbound 'uri=))
1251 (defgeneric uri= (uri1 uri2))
1252 (defmethod uri= ((uri1 uri) (uri2 uri))
1253 (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1254 (return-from uri= nil))
1255 ;; RFC2396 says: a URL with an explicit ":port", where the port is
1256 ;; the default for the scheme, is the equivalent to one where the
1257 ;; port is elided. Hmmmm. This means that this function has to be
1258 ;; scheme dependent. Grrrr.
1259 (let ((default-port (case (uri-scheme uri1)
1264 (and (equalp (uri-host uri1) (uri-host uri2))
1265 (eql (or (uri-port uri1) default-port)
1266 (or (uri-port uri2) default-port))
1267 (string= (uri-path uri1) (uri-path uri2))
1268 (string= (uri-query uri1) (uri-query uri2))
1269 (string= (uri-fragment uri1) (uri-fragment uri2)))))
1271 (defmethod uri= ((urn1 urn) (urn2 urn))
1272 (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1273 (return-from uri= nil))
1274 (and (equalp (urn-nid urn1) (urn-nid urn2))
1275 (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1277 (defun urn-nss-equal (nss1 nss2 &aux len)
1278 ;; Return t iff the nss values are the same.
1279 ;; %2c and %2C are equivalent.
1280 (when (or (null nss1) (null nss2)
1281 (not (= (setq len (length nss1))
1283 (return-from urn-nss-equal nil))
1288 (setq c1 (char nss1 i))
1289 (setq c2 (char nss2 i))
1292 (if* (and (char= #\% c1) (char= #\% c2))
1293 then (setq state :percent+1)
1294 elseif (char/= c1 c2)
1297 (when (char-not-equal c1 c2) (return nil))
1298 (setq state :percent+2))
1300 (when (char-not-equal c1 c2) (return nil))
1301 (setq state :char)))))
1303 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1304 (let ((uri (gethash-uri xuri uri-space)))
1307 else (puthash-uri xuri uri-space))))
1309 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1310 (intern-uri (parse-uri uri) uri-space))
1312 (defun unintern-uri (uri &optional (uri-space *uris*))
1314 then (clrhash uri-space)
1316 then (remhash uri uri-space)
1317 else (error "bad uri: ~s." uri)))
1319 (defmacro do-all-uris ((var &optional uri-space result-form)
1322 "do-all-uris (var [[uri-space] result-form])
1323 {declaration}* {tag | statement}*
1324 Executes the forms once for each uri with var bound to the current uri"
1327 (g-uri-space (gensym))
1328 (body (third (parse-body forms env))))
1329 `(let ((,g-uri-space (or ,uri-space *uris*)))
1331 (flet ((,f (,var &optional ,g-ignore)
1332 (declare (ignore-if-unused ,var ,g-ignore))
1334 (maphash #',f ,g-uri-space))
1335 (return ,result-form)))))
1337 (defun sharp-u (stream chr arg)
1338 (declare (ignore chr arg))
1339 (let ((arg (read stream nil nil t)))
1343 then (parse-uri arg)
1346 (internal-reader-error
1348 "#u takes a string or list argument: ~s" arg)))))
1351 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1357 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1359 ;; (don't run under emacs with M-x fi:common-lisp)
1362 (eval-when (:compile-toplevel :load-toplevel :execute)
1366 (defun gc (&rest options)
1367 (declare (ignore options))
1372 (defun time-uri-module ()
1373 (declare (optimize (speed 3) (safety 0) (debug 0)))
1374 (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1375 (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1376 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1377 (format t "~&;;; starting timing testing 1...~%")
1378 (time (dotimes (i 100000) (parse-uri uri)))
1380 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1381 (format t "~&;;; starting timing testing 2...~%")
1382 (let ((uri (parse-uri uri)))
1383 (time (dotimes (i 100000)
1384 ;; forces no caching of the printed representation:
1385 (setf (uri-string uri) nil)
1386 (format nil "~a" uri))))
1388 (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1389 (format t "~&;;; starting timing testing 3...~%")
1392 (dotimes (i 100000) (parse-uri uri2))
1393 (let ((uri (parse-uri uri)))
1395 ;; forces no caching of the printed representation:
1396 (setf (uri-string uri) nil)
1397 (format nil "~a" uri)))))))
1399 ;;******** reference output (ultra, modified 5.0.1):
1400 ;;; starting timing testing 1...
1401 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1402 ; cpu time (gc) 600 msec user, 10 msec system
1403 ; cpu time (total) 14,310 msec user, 10 msec system
1404 ; real time 14,465 msec
1406 ; 1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1407 ;;; starting timing testing 2...
1408 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1409 ; cpu time (gc) 280 msec user, 20 msec system
1410 ; cpu time (total) 27,780 msec user, 20 msec system
1411 ; real time 27,897 msec
1413 ; 1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1414 ;;; starting timing testing 3...
1415 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1416 ; cpu time (gc) 1,290 msec user, 30 msec system
1417 ; cpu time (total) 53,580 msec user, 40 msec system
1418 ; real time 54,062 msec
1420 ; 7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1422 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1423 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1425 ;;; starting timing testing 1...
1426 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1427 ; cpu time (gc) 400 msec user, 0 msec system
1428 ; cpu time (total) 14,920 msec user, 0 msec system
1429 ; real time 15,082 msec
1431 ; 1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1432 ;;; starting timing testing 2...
1433 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1434 ; cpu time (gc) 300 msec user, 0 msec system
1435 ; cpu time (total) 27,790 msec user, 10 msec system
1436 ; real time 28,025 msec
1438 ; 1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1439 ;;; starting timing testing 3...
1440 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1441 ; cpu time (gc) 920 msec user, 10 msec system
1442 ; cpu time (total) 48,820 msec user, 30 msec system
1443 ; real time 49,188 msec
1445 ; 3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes