uri.scm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. uri-reference? relative-ref?
  42. build-uri-reference build-relative-ref
  43. string->uri-reference string->relative-ref))
  44. (define-record-type <uri>
  45. (make-uri scheme userinfo host port path query fragment)
  46. uri-reference?
  47. (scheme uri-scheme)
  48. (userinfo uri-userinfo)
  49. (host uri-host)
  50. (port uri-port)
  51. (path uri-path)
  52. (query uri-query)
  53. (fragment uri-fragment))
  54. ;;;
  55. ;;; Predicates.
  56. ;;;
  57. ;;; These are quick, and assume rigid validation at construction time.
  58. ;;; RFC 3986, #3.
  59. ;;;
  60. ;;; URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
  61. ;;;
  62. ;;; hier-part = "//" authority path-abempty
  63. ;;; / path-absolute
  64. ;;; / path-rootless
  65. ;;; / path-empty
  66. (define (uri? obj)
  67. (and (uri-reference? obj)
  68. (uri-scheme obj)
  69. #t))
  70. ;;; RFC 3986, #4.2.
  71. ;;;
  72. ;;; relative-ref = relative-part [ "?" query ] [ "#" fragment ]
  73. ;;;
  74. ;;; relative-part = "//" authority path-abempty
  75. ;;; / path-absolute
  76. ;;; / path-noscheme
  77. ;;; / path-empty
  78. (define (relative-ref? obj)
  79. (and (uri-reference? obj)
  80. (not (uri-scheme obj))))
  81. ;;;
  82. ;;; Constructors.
  83. ;;;
  84. (define (uri-error message . args)
  85. (throw 'uri-error message args))
  86. (define (positive-exact-integer? port)
  87. (and (number? port) (exact? port) (integer? port) (positive? port)))
  88. (define (validate-uri-reference scheme userinfo host port path query fragment)
  89. (cond
  90. ((and scheme (not (symbol? scheme)))
  91. (uri-error "Expected a symbol for the URI scheme: ~s" scheme))
  92. ((and (or userinfo port) (not host))
  93. (uri-error "Expected a host, given userinfo or port"))
  94. ((and port (not (positive-exact-integer? port)))
  95. (uri-error "Expected port to be an integer: ~s" port))
  96. ((and host (or (not (string? host)) (not (valid-host? host))))
  97. (uri-error "Expected valid host: ~s" host))
  98. ((and userinfo (not (string? userinfo)))
  99. (uri-error "Expected string for userinfo: ~s" userinfo))
  100. ((not (string? path))
  101. (uri-error "Expected string for path: ~s" path))
  102. ((and query (not (string? query)))
  103. (uri-error "Expected string for query: ~s" query))
  104. ((and fragment (not (string? fragment)))
  105. (uri-error "Expected string for fragment: ~s" fragment))
  106. ;; Strict validation of allowed paths, based on other components.
  107. ;; Refer to RFC 3986 for the details.
  108. ((not (string-null? path))
  109. (if host
  110. (cond
  111. ((not (eqv? (string-ref path 0) #\/))
  112. (uri-error
  113. "Expected absolute path starting with \"/\": ~a" path)))
  114. (cond
  115. ((string-prefix? "//" path)
  116. (uri-error
  117. "Expected path not starting with \"//\" (no host): ~a" path))
  118. ((and (not scheme)
  119. (not (eqv? (string-ref path 0) #\/))
  120. (let ((colon (string-index path #\:)))
  121. (and colon (not (string-index path #\/ 0 colon)))))
  122. (uri-error
  123. "Expected relative path's first segment without \":\": ~a"
  124. path)))))))
  125. (define* (build-uri scheme #:key userinfo host port (path "") query fragment
  126. (validate? #t))
  127. "Construct a URI object. SCHEME should be a symbol, PORT either a
  128. positive, exact integer or ‘#f’, and the rest of the fields are either
  129. strings or ‘#f’. If VALIDATE? is true, also run some consistency checks
  130. to make sure that the constructed object is a valid URI."
  131. (when validate?
  132. (unless scheme (uri-error "Missing URI scheme"))
  133. (validate-uri-reference scheme userinfo host port path query fragment))
  134. (make-uri scheme userinfo host port path query fragment))
  135. (define* (build-uri-reference #:key scheme userinfo host port (path "") query
  136. fragment (validate? #t))
  137. "Construct a URI-reference object. SCHEME should be a symbol or ‘#f’,
  138. PORT either a positive, exact integer or ‘#f’, and the rest of the
  139. fields are either strings or ‘#f’. If VALIDATE? is true, also run some
  140. consistency checks to make sure that the constructed URI is a valid URI
  141. reference."
  142. (when validate?
  143. (validate-uri-reference scheme userinfo host port path query fragment))
  144. (make-uri scheme userinfo host port path query fragment))
  145. (define* (build-relative-ref #:key userinfo host port (path "") query fragment
  146. (validate? #t))
  147. "Construct a relative-ref URI object. The arguments are the same as
  148. for ‘build-uri’ except there is no scheme."
  149. (when validate?
  150. (validate-uri-reference #f userinfo host port path query fragment))
  151. (make-uri #f userinfo host port path query fragment))
  152. ;;;
  153. ;;; Converters.
  154. ;;;
  155. ;; See RFC 3986 #3.2.2 for comments on percent-encodings, IDNA (RFC
  156. ;; 3490), and non-ASCII host names.
  157. ;;
  158. (define ipv4-regexp
  159. (make-regexp "^([0-9.]+)$"))
  160. (define ipv6-regexp
  161. (make-regexp "^([0-9a-fA-F:.]+)$"))
  162. (define domain-label-regexp
  163. (make-regexp "^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
  164. (define top-label-regexp
  165. (make-regexp "^[a-zA-Z]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
  166. (define (valid-host? host)
  167. (cond
  168. ((regexp-exec ipv4-regexp host)
  169. (false-if-exception (inet-pton AF_INET host)))
  170. ((regexp-exec ipv6-regexp host)
  171. (false-if-exception (inet-pton AF_INET6 host)))
  172. (else
  173. (let lp ((start 0))
  174. (let ((end (string-index host #\. start)))
  175. (if end
  176. (and (regexp-exec domain-label-regexp
  177. (substring host start end))
  178. (lp (1+ end)))
  179. (regexp-exec top-label-regexp host start)))))))
  180. (define userinfo-pat
  181. "[a-zA-Z0-9_.!~*'();:&=+$,-]+")
  182. (define host-pat
  183. "[a-zA-Z0-9.-]+")
  184. (define ipv6-host-pat
  185. "[0-9a-fA-F:.]+")
  186. (define port-pat
  187. "[0-9]*")
  188. (define authority-regexp
  189. (make-regexp
  190. (format #f "^//((~a)@)?((~a)|(\\[(~a)\\]))(:(~a))?$"
  191. userinfo-pat host-pat ipv6-host-pat port-pat)))
  192. (define (parse-authority authority fail)
  193. (if (equal? authority "//")
  194. ;; Allow empty authorities: file:///etc/hosts is a synonym of
  195. ;; file:/etc/hosts.
  196. (values #f #f #f)
  197. (let ((m (regexp-exec authority-regexp authority)))
  198. (if (and m (valid-host? (or (match:substring m 4)
  199. (match:substring m 6))))
  200. (values (match:substring m 2)
  201. (or (match:substring m 4)
  202. (match:substring m 6))
  203. (let ((port (match:substring m 8)))
  204. (and port (not (string-null? port))
  205. (string->number port))))
  206. (fail)))))
  207. ;;; RFC 3986, #3.
  208. ;;;
  209. ;;; URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
  210. ;;;
  211. ;;; hier-part = "//" authority path-abempty
  212. ;;; / path-absolute
  213. ;;; / path-rootless
  214. ;;; / path-empty
  215. ;;;
  216. ;;; A URI-reference is the same as URI, but where the scheme is
  217. ;;; optional. If the scheme is not present, its colon isn't present
  218. ;;; either.
  219. (define scheme-pat
  220. "[a-zA-Z][a-zA-Z0-9+.-]*")
  221. (define authority-pat
  222. "[^/?#]*")
  223. (define path-pat
  224. "[^?#]*")
  225. (define query-pat
  226. "[^#]*")
  227. (define fragment-pat
  228. ".*")
  229. (define uri-pat
  230. (format #f "^((~a):)?(//~a)?(~a)(\\?(~a))?(#(~a))?$"
  231. scheme-pat authority-pat path-pat query-pat fragment-pat))
  232. (define uri-regexp
  233. (make-regexp uri-pat))
  234. (define (string->uri-reference string)
  235. "Parse STRING into a URI-reference object. Return ‘#f’ if the string
  236. could not be parsed."
  237. (% (let ((m (regexp-exec uri-regexp string)))
  238. (unless m (abort))
  239. (let ((scheme (let ((str (match:substring m 2)))
  240. (and str (string->symbol (string-downcase str)))))
  241. (authority (match:substring m 3))
  242. (path (match:substring m 4))
  243. (query (match:substring m 6))
  244. (fragment (match:substring m 8)))
  245. ;; The regular expression already ensures all of the validation
  246. ;; requirements for URI-references, except the one that the
  247. ;; first component of a relative-ref's path can't contain a
  248. ;; colon.
  249. (unless scheme
  250. (let ((colon (string-index path #\:)))
  251. (when (and colon (not (string-index path #\/ 0 colon)))
  252. (abort))))
  253. (call-with-values
  254. (lambda ()
  255. (if authority
  256. (parse-authority authority abort)
  257. (values #f #f #f)))
  258. (lambda (userinfo host port)
  259. (make-uri scheme userinfo host port path query fragment)))))
  260. (lambda (k)
  261. #f)))
  262. (define (string->uri string)
  263. "Parse STRING into a URI object. Return ‘#f’ if the string could not
  264. be parsed. Note that this procedure will require that the URI have a
  265. scheme."
  266. (let ((uri-reference (string->uri-reference string)))
  267. (and (not (relative-ref? uri-reference))
  268. uri-reference)))
  269. (define (string->relative-ref string)
  270. "Parse STRING into a relative-ref URI object. Return ‘#f’ if the
  271. string could not be parsed."
  272. (let ((uri-reference (string->uri-reference string)))
  273. (and (relative-ref? uri-reference)
  274. uri-reference)))
  275. (define *default-ports* (make-hash-table))
  276. (define (declare-default-port! scheme port)
  277. "Declare a default port for the given URI scheme."
  278. (hashq-set! *default-ports* scheme port))
  279. (define (default-port? scheme port)
  280. (or (not port)
  281. (eqv? port (hashq-ref *default-ports* scheme))))
  282. (declare-default-port! 'http 80)
  283. (declare-default-port! 'https 443)
  284. (define* (uri->string uri #:key (include-fragment? #t))
  285. "Serialize URI to a string. If the URI has a port that is the
  286. default port for its scheme, the port is not included in the
  287. serialization."
  288. (let* ((scheme (uri-scheme uri))
  289. (userinfo (uri-userinfo uri))
  290. (host (uri-host uri))
  291. (port (uri-port uri))
  292. (path (uri-path uri))
  293. (query (uri-query uri))
  294. (fragment (uri-fragment uri)))
  295. (string-append
  296. (if scheme
  297. (string-append (symbol->string scheme) ":")
  298. "")
  299. (if host
  300. (string-append "//"
  301. (if userinfo (string-append userinfo "@")
  302. "")
  303. (if (string-index host #\:)
  304. (string-append "[" host "]")
  305. host)
  306. (if (default-port? (uri-scheme uri) port)
  307. ""
  308. (string-append ":" (number->string port))))
  309. "")
  310. path
  311. (if query
  312. (string-append "?" query)
  313. "")
  314. (if (and fragment include-fragment?)
  315. (string-append "#" fragment)
  316. ""))))
  317. ;; like call-with-output-string, but actually closes the port (doh)
  318. (define (call-with-output-string* proc)
  319. (let ((port (open-output-string)))
  320. (proc port)
  321. (let ((str (get-output-string port)))
  322. (close-port port)
  323. str)))
  324. (define (call-with-output-bytevector* proc)
  325. (call-with-values
  326. (lambda ()
  327. (open-bytevector-output-port))
  328. (lambda (port get-bytevector)
  329. (proc port)
  330. (let ((bv (get-bytevector)))
  331. (close-port port)
  332. bv))))
  333. (define (call-with-encoded-output-string encoding proc)
  334. (if (string-ci=? encoding "utf-8")
  335. (string->utf8 (call-with-output-string* proc))
  336. (call-with-output-bytevector*
  337. (lambda (port)
  338. (set-port-encoding! port encoding)
  339. (proc port)))))
  340. (define (encode-string str encoding)
  341. (if (string-ci=? encoding "utf-8")
  342. (string->utf8 str)
  343. (call-with-encoded-output-string encoding
  344. (lambda (port)
  345. (display str port)))))
  346. (define (decode-string bv encoding)
  347. (if (string-ci=? encoding "utf-8")
  348. (utf8->string bv)
  349. (let ((p (open-bytevector-input-port bv)))
  350. (set-port-encoding! p encoding)
  351. (let ((res (read-string p)))
  352. (close-port p)
  353. res))))
  354. ;; A note on characters and bytes: URIs are defined to be sequences of
  355. ;; characters in a subset of ASCII. Those characters may encode a
  356. ;; sequence of bytes (octets), which in turn may encode sequences of
  357. ;; characters in other character sets.
  358. ;;
  359. ;; Return a new string made from uri-decoding STR. Specifically,
  360. ;; turn ‘+’ into space, and hex-encoded ‘%XX’ strings into
  361. ;; their eight-bit characters.
  362. ;;
  363. (define hex-chars
  364. (string->char-set "0123456789abcdefABCDEF"))
  365. (define* (uri-decode str #:key (encoding "utf-8") (decode-plus-to-space? #t))
  366. "Percent-decode the given STR, according to ENCODING,
  367. which should be the name of a character encoding.
  368. Note that this function should not generally be applied to a full URI
  369. string. For paths, use ‘split-and-decode-uri-path’ instead. For query
  370. strings, split the query on ‘&’ and ‘=’ boundaries, and decode
  371. the components separately.
  372. Note also that percent-encoded strings encode _bytes_, not characters.
  373. There is no guarantee that a given byte sequence is a valid string
  374. encoding. Therefore this routine may signal an error if the decoded
  375. bytes are not valid for the given encoding. Pass ‘#f’ for ENCODING if
  376. you want decoded bytes as a bytevector directly. ‘set-port-encoding!’,
  377. for more information on character encodings.
  378. If DECODE-PLUS-TO-SPACE? is true, which is the default, also replace
  379. instances of the plus character (+) with a space character. This is
  380. needed when parsing application/x-www-form-urlencoded data.
  381. Returns a string of the decoded characters, or a bytevector if
  382. ENCODING was ‘#f’."
  383. (let* ((len (string-length str))
  384. (bv
  385. (call-with-output-bytevector*
  386. (lambda (port)
  387. (let lp ((i 0))
  388. (if (< i len)
  389. (let ((ch (string-ref str i)))
  390. (cond
  391. ((and (eqv? ch #\+) decode-plus-to-space?)
  392. (put-u8 port (char->integer #\space))
  393. (lp (1+ i)))
  394. ((and (< (+ i 2) len) (eqv? ch #\%)
  395. (let ((a (string-ref str (+ i 1)))
  396. (b (string-ref str (+ i 2))))
  397. (and (char-set-contains? hex-chars a)
  398. (char-set-contains? hex-chars b)
  399. (string->number (string a b) 16))))
  400. => (lambda (u8)
  401. (put-u8 port u8)
  402. (lp (+ i 3))))
  403. ((< (char->integer ch) 128)
  404. (put-u8 port (char->integer ch))
  405. (lp (1+ i)))
  406. (else
  407. (uri-error "Invalid character in encoded URI ~a: ~s"
  408. str ch))))))))))
  409. (if encoding
  410. (decode-string bv encoding)
  411. ;; Otherwise return raw bytevector
  412. bv)))
  413. (define ascii-alnum-chars
  414. (string->char-set
  415. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))
  416. ;; RFC 3986, #2.2.
  417. (define gen-delims
  418. (string->char-set ":/?#[]@"))
  419. (define sub-delims
  420. (string->char-set "!$&'()*+,l="))
  421. (define reserved-chars
  422. (char-set-union gen-delims sub-delims))
  423. ;; RFC 3986, #2.3
  424. (define unreserved-chars
  425. (char-set-union ascii-alnum-chars
  426. (string->char-set "-._~")))
  427. ;; Return a new string made from uri-encoding STR, unconditionally
  428. ;; transforming any characters not in UNESCAPED-CHARS.
  429. ;;
  430. (define* (uri-encode str #:key (encoding "utf-8")
  431. (unescaped-chars unreserved-chars))
  432. "Percent-encode any character not in the character set,
  433. UNESCAPED-CHARS.
  434. The default character set includes alphanumerics from ASCII, as well as
  435. the special characters ‘-’, ‘.’, ‘_’, and ‘~’. Any other character will
  436. be percent-encoded, by writing out the character to a bytevector within
  437. the given ENCODING, then encoding each byte as ‘%HH’, where HH is the
  438. uppercase hexadecimal representation of the byte."
  439. (define (needs-escaped? ch)
  440. (not (char-set-contains? unescaped-chars ch)))
  441. (if (string-index str needs-escaped?)
  442. (call-with-output-string*
  443. (lambda (port)
  444. (string-for-each
  445. (lambda (ch)
  446. (if (char-set-contains? unescaped-chars ch)
  447. (display ch port)
  448. (let* ((bv (encode-string (string ch) encoding))
  449. (len (bytevector-length bv)))
  450. (let lp ((i 0))
  451. (if (< i len)
  452. (let ((byte (bytevector-u8-ref bv i)))
  453. (display #\% port)
  454. (when (< byte 16)
  455. (display #\0 port))
  456. (display (string-upcase (number->string byte 16))
  457. port)
  458. (lp (1+ i))))))))
  459. str)))
  460. str))
  461. (define (split-and-decode-uri-path path)
  462. "Split PATH into its components, and decode each component,
  463. removing empty components.
  464. For example, ‘\"/foo/bar%20baz/\"’ decodes to the two-element list,
  465. ‘(\"foo\" \"bar baz\")’."
  466. (filter (lambda (x) (not (string-null? x)))
  467. (map (lambda (s) (uri-decode s #:decode-plus-to-space? #f))
  468. (string-split path #\/))))
  469. (define (encode-and-join-uri-path parts)
  470. "URI-encode each element of PARTS, which should be a list of
  471. strings, and join the parts together with ‘/’ as a delimiter.
  472. For example, the list ‘(\"scrambled eggs\" \"biscuits&gravy\")’
  473. encodes as ‘\"scrambled%20eggs/biscuits%26gravy\"’."
  474. (string-join (map uri-encode parts) "/"))