uri.scm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. ;;;; (web uri) --- URI manipulation tools
  2. ;;;;
  3. ;;;; Copyright (C) 1997,2001,2002,2010,2011,2012,2013,2014 Free Software Foundation, Inc.
  4. ;;;;
  5. ;;;; This library is free software; you can redistribute it and/or
  6. ;;;; modify it under the terms of the GNU Lesser General Public
  7. ;;;; License as published by the Free Software Foundation; either
  8. ;;;; version 3 of the License, or (at your option) any later version.
  9. ;;;;
  10. ;;;; This library is distributed in the hope that it will be useful,
  11. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. ;;;; Lesser General Public License for more details.
  14. ;;;;
  15. ;;;; You should have received a copy of the GNU Lesser General Public
  16. ;;;; License along with this library; if not, write to the Free Software
  17. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. ;;;;
  19. ;;; Commentary:
  20. ;; A data type for Universal Resource Identifiers, as defined in RFC
  21. ;; 3986.
  22. ;;; Code:
  23. (define-module (web uri)
  24. #:use-module (srfi srfi-9)
  25. #:use-module (ice-9 regex)
  26. #:use-module (ice-9 rdelim)
  27. #:use-module (ice-9 control)
  28. #:use-module (rnrs bytevectors)
  29. #:use-module (ice-9 binary-ports)
  30. #:export (uri?
  31. uri-scheme uri-userinfo uri-host uri-port
  32. uri-path uri-query uri-fragment
  33. build-uri
  34. build-uri-reference
  35. declare-default-port!
  36. string->uri string->uri-reference
  37. uri->string
  38. uri-decode uri-encode
  39. split-and-decode-uri-path
  40. encode-and-join-uri-path))
  41. (define-record-type <uri>
  42. (make-uri scheme userinfo host port path query fragment)
  43. uri?
  44. (scheme uri-scheme)
  45. (userinfo uri-userinfo)
  46. (host uri-host)
  47. (port uri-port)
  48. (path uri-path)
  49. (query uri-query)
  50. (fragment uri-fragment))
  51. (define (absolute-uri? obj)
  52. (and (uri? obj) (uri-scheme obj) #t))
  53. (define (uri-error message . args)
  54. (throw 'uri-error message args))
  55. (define (positive-exact-integer? port)
  56. (and (number? port) (exact? port) (integer? port) (positive? port)))
  57. (define* (validate-uri scheme userinfo host port path query fragment
  58. #:key reference?)
  59. (cond
  60. ((and (not reference?) (not (symbol? scheme)))
  61. (uri-error "Expected a symbol for the URI scheme: ~s" scheme))
  62. ((and (or userinfo port) (not host))
  63. (uri-error "Expected a host, given userinfo or port"))
  64. ((and port (not (positive-exact-integer? port)))
  65. (uri-error "Expected port to be an integer: ~s" port))
  66. ((and host (or (not (string? host)) (not (valid-host? host))))
  67. (uri-error "Expected valid host: ~s" host))
  68. ((and userinfo (not (string? userinfo)))
  69. (uri-error "Expected string for userinfo: ~s" userinfo))
  70. ((not (string? path))
  71. (uri-error "Expected string for path: ~s" path))
  72. ((and host (not (string-null? path))
  73. (not (eqv? (string-ref path 0) #\/)))
  74. (uri-error "Expected path of absolute URI to start with a /: ~a" path))))
  75. (define* (build-uri scheme #:key userinfo host port (path "") query fragment
  76. (validate? #t))
  77. "Construct a URI object. SCHEME should be a symbol, PORT either a
  78. positive, exact integer or ‘#f’, and the rest of the fields are either
  79. strings or ‘#f’. If VALIDATE? is true, also run some consistency checks
  80. to make sure that the constructed object is a valid absolute URI."
  81. (if validate?
  82. (validate-uri scheme userinfo host port path query fragment))
  83. (make-uri scheme userinfo host port path query fragment))
  84. (define* (build-uri-reference #:key scheme userinfo host port (path "") query
  85. fragment (validate? #t))
  86. "Construct a URI object. SCHEME should be a symbol or ‘#f’, PORT
  87. either a positive, exact integer or ‘#f’, and the rest of the fields
  88. are either strings or ‘#f’. If VALIDATE? is true, also run some
  89. consistency checks to make sure that the constructed URI is a valid URI
  90. reference (either an absolute URI or a relative reference)."
  91. (if validate?
  92. (validate-uri scheme userinfo host port path query fragment
  93. #:reference? #t))
  94. (make-uri scheme userinfo host port path query fragment))
  95. ;; See RFC 3986 #3.2.2 for comments on percent-encodings, IDNA (RFC
  96. ;; 3490), and non-ASCII host names.
  97. ;;
  98. (define ipv4-regexp
  99. (make-regexp "^([0-9.]+)$"))
  100. (define ipv6-regexp
  101. (make-regexp "^([0-9a-fA-F:.]+)$"))
  102. (define domain-label-regexp
  103. (make-regexp "^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
  104. (define top-label-regexp
  105. (make-regexp "^[a-zA-Z]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
  106. (define (valid-host? host)
  107. (cond
  108. ((regexp-exec ipv4-regexp host)
  109. (false-if-exception (inet-pton AF_INET host)))
  110. ((regexp-exec ipv6-regexp host)
  111. (false-if-exception (inet-pton AF_INET6 host)))
  112. (else
  113. (let lp ((start 0))
  114. (let ((end (string-index host #\. start)))
  115. (if end
  116. (and (regexp-exec domain-label-regexp
  117. (substring host start end))
  118. (lp (1+ end)))
  119. (regexp-exec top-label-regexp host start)))))))
  120. (define userinfo-pat
  121. "[a-zA-Z0-9_.!~*'();:&=+$,-]+")
  122. (define host-pat
  123. "[a-zA-Z0-9.-]+")
  124. (define ipv6-host-pat
  125. "[0-9a-fA-F:.]+")
  126. (define port-pat
  127. "[0-9]*")
  128. (define authority-regexp
  129. (make-regexp
  130. (format #f "^//((~a)@)?((~a)|(\\[(~a)\\]))(:(~a))?$"
  131. userinfo-pat host-pat ipv6-host-pat port-pat)))
  132. (define (parse-authority authority fail)
  133. (if (equal? authority "//")
  134. ;; Allow empty authorities: file:///etc/hosts is a synonym of
  135. ;; file:/etc/hosts.
  136. (values #f #f #f)
  137. (let ((m (regexp-exec authority-regexp authority)))
  138. (if (and m (valid-host? (or (match:substring m 4)
  139. (match:substring m 6))))
  140. (values (match:substring m 2)
  141. (or (match:substring m 4)
  142. (match:substring m 6))
  143. (let ((port (match:substring m 8)))
  144. (and port (not (string-null? port))
  145. (string->number port))))
  146. (fail)))))
  147. ;;; RFC 3986, #3.
  148. ;;;
  149. ;;; URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
  150. ;;;
  151. ;;; hier-part = "//" authority path-abempty
  152. ;;; / path-absolute
  153. ;;; / path-rootless
  154. ;;; / path-empty
  155. ;;;
  156. ;;; A URI-reference is the same as URI, but where the scheme is
  157. ;;; optional. If the scheme is not present, its colon isn't present
  158. ;;; either.
  159. (define scheme-pat
  160. "[a-zA-Z][a-zA-Z0-9+.-]*")
  161. (define authority-pat
  162. "[^/?#]*")
  163. (define path-pat
  164. "[^?#]*")
  165. (define query-pat
  166. "[^#]*")
  167. (define fragment-pat
  168. ".*")
  169. (define uri-pat
  170. (format #f "^((~a):)?(//~a)?(~a)(\\?(~a))?(#(~a))?$"
  171. scheme-pat authority-pat path-pat query-pat fragment-pat))
  172. (define uri-regexp
  173. (make-regexp uri-pat))
  174. (define (string->uri-reference string)
  175. "Parse the URI reference written as STRING into a URI object. Return
  176. ‘#f’ if the string could not be parsed."
  177. (% (let ((m (regexp-exec uri-regexp string)))
  178. (if (not m) (abort))
  179. (let ((scheme (let ((str (match:substring m 2)))
  180. (and str (string->symbol (string-downcase str)))))
  181. (authority (match:substring m 3))
  182. (path (match:substring m 4))
  183. (query (match:substring m 6))
  184. (fragment (match:substring m 8)))
  185. (call-with-values
  186. (lambda ()
  187. (if authority
  188. (parse-authority authority abort)
  189. (values #f #f #f)))
  190. (lambda (userinfo host port)
  191. (make-uri scheme userinfo host port path query fragment)))))
  192. (lambda (k)
  193. #f)))
  194. (define (string->uri string)
  195. "Parse STRING into an absolute URI object. Return ‘#f’ if the string
  196. could not be parsed."
  197. (let ((uri (string->uri-reference string)))
  198. (and uri (uri-scheme uri) uri)))
  199. (define *default-ports* (make-hash-table))
  200. (define (declare-default-port! scheme port)
  201. "Declare a default port for the given URI scheme."
  202. (hashq-set! *default-ports* scheme port))
  203. (define (default-port? scheme port)
  204. (or (not port)
  205. (eqv? port (hashq-ref *default-ports* scheme))))
  206. (declare-default-port! 'http 80)
  207. (declare-default-port! 'https 443)
  208. (define (uri->string uri)
  209. "Serialize URI to a string. If the URI has a port that is the
  210. default port for its scheme, the port is not included in the
  211. serialization."
  212. (let* ((scheme (uri-scheme uri))
  213. (userinfo (uri-userinfo uri))
  214. (host (uri-host uri))
  215. (port (uri-port uri))
  216. (path (uri-path uri))
  217. (query (uri-query uri))
  218. (fragment (uri-fragment uri)))
  219. (string-append
  220. (if scheme
  221. (string-append (symbol->string scheme) ":")
  222. "")
  223. (if host
  224. (string-append "//"
  225. (if userinfo (string-append userinfo "@")
  226. "")
  227. (if (string-index host #\:)
  228. (string-append "[" host "]")
  229. host)
  230. (if (default-port? (uri-scheme uri) port)
  231. ""
  232. (string-append ":" (number->string port))))
  233. "")
  234. path
  235. (if query
  236. (string-append "?" query)
  237. "")
  238. (if fragment
  239. (string-append "#" fragment)
  240. ""))))
  241. ;; like call-with-output-string, but actually closes the port (doh)
  242. (define (call-with-output-string* proc)
  243. (let ((port (open-output-string)))
  244. (proc port)
  245. (let ((str (get-output-string port)))
  246. (close-port port)
  247. str)))
  248. (define (call-with-output-bytevector* proc)
  249. (call-with-values
  250. (lambda ()
  251. (open-bytevector-output-port))
  252. (lambda (port get-bytevector)
  253. (proc port)
  254. (let ((bv (get-bytevector)))
  255. (close-port port)
  256. bv))))
  257. (define (call-with-encoded-output-string encoding proc)
  258. (if (string-ci=? encoding "utf-8")
  259. (string->utf8 (call-with-output-string* proc))
  260. (call-with-output-bytevector*
  261. (lambda (port)
  262. (set-port-encoding! port encoding)
  263. (proc port)))))
  264. (define (encode-string str encoding)
  265. (if (string-ci=? encoding "utf-8")
  266. (string->utf8 str)
  267. (call-with-encoded-output-string encoding
  268. (lambda (port)
  269. (display str port)))))
  270. (define (decode-string bv encoding)
  271. (if (string-ci=? encoding "utf-8")
  272. (utf8->string bv)
  273. (let ((p (open-bytevector-input-port bv)))
  274. (set-port-encoding! p encoding)
  275. (let ((res (read-string p)))
  276. (close-port p)
  277. res))))
  278. ;; A note on characters and bytes: URIs are defined to be sequences of
  279. ;; characters in a subset of ASCII. Those characters may encode a
  280. ;; sequence of bytes (octets), which in turn may encode sequences of
  281. ;; characters in other character sets.
  282. ;;
  283. ;; Return a new string made from uri-decoding STR. Specifically,
  284. ;; turn ‘+’ into space, and hex-encoded ‘%XX’ strings into
  285. ;; their eight-bit characters.
  286. ;;
  287. (define hex-chars
  288. (string->char-set "0123456789abcdefABCDEF"))
  289. (define* (uri-decode str #:key (encoding "utf-8") (decode-plus-to-space? #t))
  290. "Percent-decode the given STR, according to ENCODING,
  291. which should be the name of a character encoding.
  292. Note that this function should not generally be applied to a full URI
  293. string. For paths, use ‘split-and-decode-uri-path’ instead. For query
  294. strings, split the query on ‘&’ and ‘=’ boundaries, and decode
  295. the components separately.
  296. Note also that percent-encoded strings encode _bytes_, not characters.
  297. There is no guarantee that a given byte sequence is a valid string
  298. encoding. Therefore this routine may signal an error if the decoded
  299. bytes are not valid for the given encoding. Pass ‘#f’ for ENCODING if
  300. you want decoded bytes as a bytevector directly. ‘set-port-encoding!’,
  301. for more information on character encodings.
  302. If DECODE-PLUS-TO-SPACE? is true, which is the default, also replace
  303. instances of the plus character (+) with a space character. This is
  304. needed when parsing application/x-www-form-urlencoded data.
  305. Returns a string of the decoded characters, or a bytevector if
  306. ENCODING was ‘#f’."
  307. (let* ((len (string-length str))
  308. (bv
  309. (call-with-output-bytevector*
  310. (lambda (port)
  311. (let lp ((i 0))
  312. (if (< i len)
  313. (let ((ch (string-ref str i)))
  314. (cond
  315. ((and (eqv? ch #\+) decode-plus-to-space?)
  316. (put-u8 port (char->integer #\space))
  317. (lp (1+ i)))
  318. ((and (< (+ i 2) len) (eqv? ch #\%)
  319. (let ((a (string-ref str (+ i 1)))
  320. (b (string-ref str (+ i 2))))
  321. (and (char-set-contains? hex-chars a)
  322. (char-set-contains? hex-chars b)
  323. (string->number (string a b) 16))))
  324. => (lambda (u8)
  325. (put-u8 port u8)
  326. (lp (+ i 3))))
  327. ((< (char->integer ch) 128)
  328. (put-u8 port (char->integer ch))
  329. (lp (1+ i)))
  330. (else
  331. (uri-error "Invalid character in encoded URI ~a: ~s"
  332. str ch))))))))))
  333. (if encoding
  334. (decode-string bv encoding)
  335. ;; Otherwise return raw bytevector
  336. bv)))
  337. (define ascii-alnum-chars
  338. (string->char-set
  339. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))
  340. ;; RFC 3986, #2.2.
  341. (define gen-delims
  342. (string->char-set ":/?#[]@"))
  343. (define sub-delims
  344. (string->char-set "!$&'()*+,l="))
  345. (define reserved-chars
  346. (char-set-union gen-delims sub-delims))
  347. ;; RFC 3986, #2.3
  348. (define unreserved-chars
  349. (char-set-union ascii-alnum-chars
  350. (string->char-set "-._~")))
  351. ;; Return a new string made from uri-encoding STR, unconditionally
  352. ;; transforming any characters not in UNESCAPED-CHARS.
  353. ;;
  354. (define* (uri-encode str #:key (encoding "utf-8")
  355. (unescaped-chars unreserved-chars))
  356. "Percent-encode any character not in the character set,
  357. UNESCAPED-CHARS.
  358. The default character set includes alphanumerics from ASCII, as well as
  359. the special characters ‘-’, ‘.’, ‘_’, and ‘~’. Any other character will
  360. be percent-encoded, by writing out the character to a bytevector within
  361. the given ENCODING, then encoding each byte as ‘%HH’, where HH is the
  362. uppercase hexadecimal representation of the byte."
  363. (define (needs-escaped? ch)
  364. (not (char-set-contains? unescaped-chars ch)))
  365. (if (string-index str needs-escaped?)
  366. (call-with-output-string*
  367. (lambda (port)
  368. (string-for-each
  369. (lambda (ch)
  370. (if (char-set-contains? unescaped-chars ch)
  371. (display ch port)
  372. (let* ((bv (encode-string (string ch) encoding))
  373. (len (bytevector-length bv)))
  374. (let lp ((i 0))
  375. (if (< i len)
  376. (let ((byte (bytevector-u8-ref bv i)))
  377. (display #\% port)
  378. (when (< byte 16)
  379. (display #\0 port))
  380. (display (string-upcase (number->string byte 16))
  381. port)
  382. (lp (1+ i))))))))
  383. str)))
  384. str))
  385. (define (split-and-decode-uri-path path)
  386. "Split PATH into its components, and decode each component,
  387. removing empty components.
  388. For example, ‘\"/foo/bar%20baz/\"’ decodes to the two-element list,
  389. ‘(\"foo\" \"bar baz\")’."
  390. (filter (lambda (x) (not (string-null? x)))
  391. (map (lambda (s) (uri-decode s #:decode-plus-to-space? #f))
  392. (string-split path #\/))))
  393. (define (encode-and-join-uri-path parts)
  394. "URI-encode each element of PARTS, which should be a list of
  395. strings, and join the parts together with ‘/’ as a delimiter.
  396. For example, the list ‘(\"scrambled eggs\" \"biscuits&gravy\")’
  397. encodes as ‘\"scrambled%20eggs/biscuits%26gravy\"’."
  398. (string-join (map uri-encode parts) "/"))