uri.scm 18 KB

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