uri.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements URI parsing as specified by RFC 3986.
  10. ##
  11. ## A Uniform Resource Identifier (URI) provides a simple and extensible
  12. ## means for identifying a resource. A URI can be further classified
  13. ## as a locator, a name, or both. The term "Uniform Resource Locator"
  14. ## (URL) refers to the subset of URIs.
  15. ##
  16. ## # Basic usage
  17. ## ## Combine URIs
  18. runnableExamples:
  19. let host = parseUri("https://nim-lang.org")
  20. assert $host == "https://nim-lang.org"
  21. assert $(host / "/blog.html") == "https://nim-lang.org/blog.html"
  22. assert $(host / "blog2.html") == "https://nim-lang.org/blog2.html"
  23. ## ## Access URI item
  24. runnableExamples:
  25. let res = parseUri("sftp://127.0.0.1:4343")
  26. assert isAbsolute(res)
  27. assert res.port == "4343"
  28. ## ## Data URI Base64
  29. runnableExamples:
  30. assert getDataUri("Hello World", "text/plain") == "data:text/plain;charset=utf-8;base64,SGVsbG8gV29ybGQ="
  31. assert getDataUri("Nim", "text/plain") == "data:text/plain;charset=utf-8;base64,Tmlt"
  32. import std/[strutils, parseutils, base64]
  33. import std/private/[since, decode_helpers]
  34. when defined(nimPreviewSlimSystem):
  35. import std/assertions
  36. type
  37. Url* = distinct string
  38. Uri* = object
  39. scheme*, username*, password*: string
  40. hostname*, port*, path*, query*, anchor*: string
  41. opaque*: bool
  42. isIpv6*: bool
  43. UriParseError* = object of ValueError
  44. proc uriParseError*(msg: string) {.noreturn.} =
  45. ## Raises a `UriParseError` exception with message `msg`.
  46. raise newException(UriParseError, msg)
  47. func encodeUrl*(s: string, usePlus = true): string =
  48. ## Encodes a URL according to RFC3986.
  49. ##
  50. ## This means that characters in the set
  51. ## `{'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~'}` are
  52. ## carried over to the result.
  53. ## All other characters are encoded as `%xx` where `xx`
  54. ## denotes its hexadecimal value.
  55. ##
  56. ## As a special rule, when the value of `usePlus` is true,
  57. ## spaces are encoded as `+` instead of `%20`.
  58. ##
  59. ## **See also:**
  60. ## * `decodeUrl func<#decodeUrl,string>`_
  61. runnableExamples:
  62. assert encodeUrl("https://nim-lang.org") == "https%3A%2F%2Fnim-lang.org"
  63. assert encodeUrl("https://nim-lang.org/this is a test") == "https%3A%2F%2Fnim-lang.org%2Fthis+is+a+test"
  64. assert encodeUrl("https://nim-lang.org/this is a test", false) == "https%3A%2F%2Fnim-lang.org%2Fthis%20is%20a%20test"
  65. result = newStringOfCap(s.len + s.len shr 2) # assume 12% non-alnum-chars
  66. let fromSpace = if usePlus: "+" else: "%20"
  67. for c in s:
  68. case c
  69. # https://tools.ietf.org/html/rfc3986#section-2.3
  70. of 'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~': add(result, c)
  71. of ' ': add(result, fromSpace)
  72. else:
  73. add(result, '%')
  74. add(result, toHex(ord(c), 2))
  75. func decodeUrl*(s: string, decodePlus = true): string =
  76. ## Decodes a URL according to RFC3986.
  77. ##
  78. ## This means that any `%xx` (where `xx` denotes a hexadecimal
  79. ## value) are converted to the character with ordinal number `xx`,
  80. ## and every other character is carried over.
  81. ## If `xx` is not a valid hexadecimal value, it is left intact.
  82. ##
  83. ## As a special rule, when the value of `decodePlus` is true, `+`
  84. ## characters are converted to a space.
  85. ##
  86. ## **See also:**
  87. ## * `encodeUrl func<#encodeUrl,string>`_
  88. runnableExamples:
  89. assert decodeUrl("https%3A%2F%2Fnim-lang.org") == "https://nim-lang.org"
  90. assert decodeUrl("https%3A%2F%2Fnim-lang.org%2Fthis+is+a+test") == "https://nim-lang.org/this is a test"
  91. assert decodeUrl("https%3A%2F%2Fnim-lang.org%2Fthis%20is%20a%20test",
  92. false) == "https://nim-lang.org/this is a test"
  93. assert decodeUrl("abc%xyz") == "abc%xyz"
  94. result = newString(s.len)
  95. var i = 0
  96. var j = 0
  97. while i < s.len:
  98. case s[i]
  99. of '%':
  100. result[j] = decodePercent(s, i)
  101. of '+':
  102. if decodePlus:
  103. result[j] = ' '
  104. else:
  105. result[j] = s[i]
  106. else: result[j] = s[i]
  107. inc(i)
  108. inc(j)
  109. setLen(result, j)
  110. func encodeQuery*(query: openArray[(string, string)], usePlus = true,
  111. omitEq = true, sep = '&'): string =
  112. ## Encodes a set of (key, value) parameters into a URL query string.
  113. ##
  114. ## Every (key, value) pair is URL-encoded and written as `key=value`. If the
  115. ## value is an empty string then the `=` is omitted, unless `omitEq` is
  116. ## false.
  117. ## The pairs are joined together by the `sep` character.
  118. ##
  119. ## The `usePlus` parameter is passed down to the `encodeUrl` function that
  120. ## is used for the URL encoding of the string values.
  121. ##
  122. ## **See also:**
  123. ## * `encodeUrl func<#encodeUrl,string>`_
  124. runnableExamples:
  125. assert encodeQuery({: }) == ""
  126. assert encodeQuery({"a": "1", "b": "2"}) == "a=1&b=2"
  127. assert encodeQuery({"a": "1", "b": ""}) == "a=1&b"
  128. assert encodeQuery({"a": "1", "b": ""}, omitEq = false, sep = ';') == "a=1;b="
  129. for elem in query:
  130. # Encode the `key = value` pairs and separate them with 'sep'
  131. if result.len > 0: result.add(sep)
  132. let (key, val) = elem
  133. result.add(encodeUrl(key, usePlus))
  134. # Omit the '=' if the value string is empty
  135. if not omitEq or val.len > 0:
  136. result.add('=')
  137. result.add(encodeUrl(val, usePlus))
  138. iterator decodeQuery*(data: string, sep = '&'): tuple[key, value: string] =
  139. ## Reads and decodes the query string `data` and yields the `(key, value)` pairs
  140. ## the data consists of. If compiled with `-d:nimLegacyParseQueryStrict`,
  141. ## a `UriParseError` is raised when there is an unencoded `=` character in a decoded
  142. ## value, which was the behavior in Nim < 1.5.1.
  143. runnableExamples:
  144. import std/sequtils
  145. assert toSeq(decodeQuery("foo=1&bar=2=3")) == @[("foo", "1"), ("bar", "2=3")]
  146. assert toSeq(decodeQuery("foo=1;bar=2=3", ';')) == @[("foo", "1"), ("bar", "2=3")]
  147. assert toSeq(decodeQuery("&a&=b&=&&")) == @[("", ""), ("a", ""), ("", "b"), ("", ""), ("", "")]
  148. proc parseData(data: string, i: int, field: var string, sep: char): int =
  149. result = i
  150. while result < data.len:
  151. let c = data[result]
  152. case c
  153. of '%': add(field, decodePercent(data, result))
  154. of '+': add(field, ' ')
  155. of '&': break
  156. else:
  157. if c == sep: break
  158. else: add(field, data[result])
  159. inc(result)
  160. var i = 0
  161. var name = ""
  162. var value = ""
  163. # decode everything in one pass:
  164. while i < data.len:
  165. setLen(name, 0) # reuse memory
  166. i = parseData(data, i, name, '=')
  167. setLen(value, 0) # reuse memory
  168. if i < data.len and data[i] == '=':
  169. inc(i) # skip '='
  170. when defined(nimLegacyParseQueryStrict):
  171. i = parseData(data, i, value, '=')
  172. else:
  173. i = parseData(data, i, value, sep)
  174. yield (name, value)
  175. if i < data.len:
  176. when defined(nimLegacyParseQueryStrict):
  177. if data[i] != '&':
  178. uriParseError("'&' expected at index '$#' for '$#'" % [$i, data])
  179. inc(i)
  180. func parseAuthority(authority: string, result: var Uri) =
  181. var i = 0
  182. var inPort = false
  183. var inIPv6 = false
  184. while i < authority.len:
  185. case authority[i]
  186. of '@':
  187. swap result.password, result.port
  188. result.port.setLen(0)
  189. swap result.username, result.hostname
  190. result.hostname.setLen(0)
  191. inPort = false
  192. of ':':
  193. if inIPv6:
  194. result.hostname.add(authority[i])
  195. else:
  196. inPort = true
  197. of '[':
  198. inIPv6 = true
  199. result.isIpv6 = true
  200. of ']':
  201. inIPv6 = false
  202. else:
  203. if inPort:
  204. result.port.add(authority[i])
  205. else:
  206. result.hostname.add(authority[i])
  207. i.inc
  208. func parsePath(uri: string, i: var int, result: var Uri) =
  209. i.inc parseUntil(uri, result.path, {'?', '#'}, i)
  210. # The 'mailto' scheme's PATH actually contains the hostname/username
  211. if cmpIgnoreCase(result.scheme, "mailto") == 0:
  212. parseAuthority(result.path, result)
  213. result.path.setLen(0)
  214. if i < uri.len and uri[i] == '?':
  215. i.inc # Skip '?'
  216. i.inc parseUntil(uri, result.query, {'#'}, i)
  217. if i < uri.len and uri[i] == '#':
  218. i.inc # Skip '#'
  219. i.inc parseUntil(uri, result.anchor, {}, i)
  220. func initUri*(isIpv6 = false): Uri =
  221. ## Initializes a URI with `scheme`, `username`, `password`,
  222. ## `hostname`, `port`, `path`, `query`, `anchor` and `isIpv6`.
  223. ##
  224. ## **See also:**
  225. ## * `Uri type <#Uri>`_ for available fields in the URI type
  226. runnableExamples:
  227. var uri2 = initUri(isIpv6 = true)
  228. uri2.scheme = "tcp"
  229. uri2.hostname = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
  230. uri2.port = "8080"
  231. assert $uri2 == "tcp://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080"
  232. result = Uri(scheme: "", username: "", password: "", hostname: "", port: "",
  233. path: "", query: "", anchor: "", isIpv6: isIpv6)
  234. func resetUri(uri: var Uri) =
  235. for f in uri.fields:
  236. when f is string:
  237. f.setLen(0)
  238. else:
  239. f = false
  240. func parseUri*(uri: string, result: var Uri) =
  241. ## Parses a URI. The `result` variable will be cleared before.
  242. ##
  243. ## **See also:**
  244. ## * `Uri type <#Uri>`_ for available fields in the URI type
  245. ## * `initUri func <#initUri>`_ for initializing a URI
  246. runnableExamples:
  247. var res = initUri()
  248. parseUri("https://nim-lang.org/docs/manual.html", res)
  249. assert res.scheme == "https"
  250. assert res.hostname == "nim-lang.org"
  251. assert res.path == "/docs/manual.html"
  252. resetUri(result)
  253. var i = 0
  254. # Check if this is a reference URI (relative URI)
  255. let doubleSlash = uri.len > 1 and uri[0] == '/' and uri[1] == '/'
  256. if i < uri.len and uri[i] == '/':
  257. # Make sure `uri` doesn't begin with '//'.
  258. if not doubleSlash:
  259. parsePath(uri, i, result)
  260. return
  261. # Scheme
  262. i.inc parseWhile(uri, result.scheme, Letters + Digits + {'+', '-', '.'}, i)
  263. if (i >= uri.len or uri[i] != ':') and not doubleSlash:
  264. # Assume this is a reference URI (relative URI)
  265. i = 0
  266. result.scheme.setLen(0)
  267. parsePath(uri, i, result)
  268. return
  269. if not doubleSlash:
  270. i.inc # Skip ':'
  271. # Authority
  272. if i+1 < uri.len and uri[i] == '/' and uri[i+1] == '/':
  273. i.inc(2) # Skip //
  274. var authority = ""
  275. i.inc parseUntil(uri, authority, {'/', '?', '#'}, i)
  276. if authority.len > 0:
  277. parseAuthority(authority, result)
  278. else:
  279. result.opaque = true
  280. # Path
  281. parsePath(uri, i, result)
  282. func parseUri*(uri: string): Uri =
  283. ## Parses a URI and returns it.
  284. ##
  285. ## **See also:**
  286. ## * `Uri type <#Uri>`_ for available fields in the URI type
  287. runnableExamples:
  288. let res = parseUri("ftp://Username:Password@Hostname")
  289. assert res.username == "Username"
  290. assert res.password == "Password"
  291. assert res.scheme == "ftp"
  292. result = initUri()
  293. parseUri(uri, result)
  294. func removeDotSegments(path: string): string =
  295. ## Collapses `..` and `.` in `path` in a similar way as done in `os.normalizedPath`
  296. ## Caution: this is buggy.
  297. runnableExamples:
  298. assert removeDotSegments("a1/a2/../a3/a4/a5/./a6/a7/.//./") == "a1/a3/a4/a5/a6/a7/"
  299. assert removeDotSegments("http://www.ai.") == "http://www.ai."
  300. # xxx adapt or reuse `pathnorm.normalizePath(path, '/')` to make this more reliable, but
  301. # taking into account url specificities such as not collapsing leading `//` in scheme
  302. # `https://`. see `turi` for failing tests.
  303. if path.len == 0: return ""
  304. var collection: seq[string] = @[]
  305. let endsWithSlash = path.endsWith '/'
  306. var i = 0
  307. var currentSegment = ""
  308. while i < path.len:
  309. case path[i]
  310. of '/':
  311. collection.add(currentSegment)
  312. currentSegment = ""
  313. of '.':
  314. if i+2 < path.len and path[i+1] == '.' and path[i+2] == '/':
  315. if collection.len > 0:
  316. discard collection.pop()
  317. i.inc 3
  318. continue
  319. elif i + 1 < path.len and path[i+1] == '/':
  320. i.inc 2
  321. continue
  322. currentSegment.add path[i]
  323. else:
  324. currentSegment.add path[i]
  325. i.inc
  326. if currentSegment != "":
  327. collection.add currentSegment
  328. result = collection.join("/")
  329. if endsWithSlash: result.add '/'
  330. func merge(base, reference: Uri): string =
  331. # http://tools.ietf.org/html/rfc3986#section-5.2.3
  332. if base.hostname != "" and base.path == "":
  333. '/' & reference.path
  334. else:
  335. let lastSegment = rfind(base.path, "/")
  336. if lastSegment == -1:
  337. reference.path
  338. else:
  339. base.path[0 .. lastSegment] & reference.path
  340. func combine*(base: Uri, reference: Uri): Uri =
  341. ## Combines a base URI with a reference URI.
  342. ##
  343. ## This uses the algorithm specified in
  344. ## `section 5.2.2 of RFC 3986 <http://tools.ietf.org/html/rfc3986#section-5.2.2>`_.
  345. ##
  346. ## This means that the slashes inside the base URIs path as well as reference
  347. ## URIs path affect the resulting URI.
  348. ##
  349. ## **See also:**
  350. ## * `/ func <#/,Uri,string>`_ for building URIs
  351. runnableExamples:
  352. let foo = combine(parseUri("https://nim-lang.org/foo/bar"), parseUri("/baz"))
  353. assert foo.path == "/baz"
  354. let bar = combine(parseUri("https://nim-lang.org/foo/bar"), parseUri("baz"))
  355. assert bar.path == "/foo/baz"
  356. let qux = combine(parseUri("https://nim-lang.org/foo/bar/"), parseUri("baz"))
  357. assert qux.path == "/foo/bar/baz"
  358. template setAuthority(dest, src): untyped =
  359. dest.hostname = src.hostname
  360. dest.username = src.username
  361. dest.port = src.port
  362. dest.password = src.password
  363. result = initUri()
  364. if reference.scheme != base.scheme and reference.scheme != "":
  365. result = reference
  366. result.path = removeDotSegments(result.path)
  367. else:
  368. if reference.hostname != "":
  369. setAuthority(result, reference)
  370. result.path = removeDotSegments(reference.path)
  371. result.query = reference.query
  372. else:
  373. if reference.path == "":
  374. result.path = base.path
  375. if reference.query != "":
  376. result.query = reference.query
  377. else:
  378. result.query = base.query
  379. else:
  380. if reference.path.startsWith("/"):
  381. result.path = removeDotSegments(reference.path)
  382. else:
  383. result.path = removeDotSegments(merge(base, reference))
  384. result.query = reference.query
  385. setAuthority(result, base)
  386. result.scheme = base.scheme
  387. result.anchor = reference.anchor
  388. func combine*(uris: varargs[Uri]): Uri =
  389. ## Combines multiple URIs together.
  390. ##
  391. ## **See also:**
  392. ## * `/ func <#/,Uri,string>`_ for building URIs
  393. runnableExamples:
  394. let foo = combine(parseUri("https://nim-lang.org/"), parseUri("docs/"),
  395. parseUri("manual.html"))
  396. assert foo.hostname == "nim-lang.org"
  397. assert foo.path == "/docs/manual.html"
  398. result = uris[0]
  399. for i in 1 ..< uris.len:
  400. result = combine(result, uris[i])
  401. func isAbsolute*(uri: Uri): bool =
  402. ## Returns true if URI is absolute, false otherwise.
  403. runnableExamples:
  404. assert parseUri("https://nim-lang.org").isAbsolute
  405. assert not parseUri("nim-lang").isAbsolute
  406. return uri.scheme != "" and (uri.hostname != "" or uri.path != "")
  407. func `/`*(x: Uri, path: string): Uri =
  408. ## Concatenates the path specified to the specified URIs path.
  409. ##
  410. ## Contrary to the `combine func <#combine,Uri,Uri>`_ you do not have to worry about
  411. ## the slashes at the beginning and end of the path and URIs path
  412. ## respectively.
  413. ##
  414. ## **See also:**
  415. ## * `combine func <#combine,Uri,Uri>`_
  416. runnableExamples:
  417. let foo = parseUri("https://nim-lang.org/foo/bar") / "/baz"
  418. assert foo.path == "/foo/bar/baz"
  419. let bar = parseUri("https://nim-lang.org/foo/bar") / "baz"
  420. assert bar.path == "/foo/bar/baz"
  421. let qux = parseUri("https://nim-lang.org/foo/bar/") / "baz"
  422. assert qux.path == "/foo/bar/baz"
  423. result = x
  424. if result.path.len == 0:
  425. if path.len == 0 or path[0] != '/':
  426. result.path = "/"
  427. result.path.add(path)
  428. return
  429. if result.path.len > 0 and result.path[result.path.len-1] == '/':
  430. if path.len > 0 and path[0] == '/':
  431. result.path.add(path[1 .. path.len-1])
  432. else:
  433. result.path.add(path)
  434. else:
  435. if path.len == 0 or path[0] != '/':
  436. result.path.add '/'
  437. result.path.add(path)
  438. func `?`*(u: Uri, query: openArray[(string, string)]): Uri =
  439. ## Concatenates the query parameters to the specified URI object.
  440. runnableExamples:
  441. let foo = parseUri("https://example.com") / "foo" ? {"bar": "qux"}
  442. assert $foo == "https://example.com/foo?bar=qux"
  443. result = u
  444. result.query = encodeQuery(query)
  445. func `$`*(u: Uri): string =
  446. ## Returns the string representation of the specified URI object.
  447. runnableExamples:
  448. assert $parseUri("https://nim-lang.org") == "https://nim-lang.org"
  449. # Get the len of all the parts.
  450. let schemeLen = u.scheme.len
  451. let usernameLen = u.username.len
  452. let passwordLen = u.password.len
  453. let hostnameLen = u.hostname.len
  454. let portLen = u.port.len
  455. let pathLen = u.path.len
  456. let queryLen = u.query.len
  457. let anchorLen = u.anchor.len
  458. # Prepare a string that fits all the parts and all punctuation chars.
  459. # 12 is the max len required by all possible punctuation chars.
  460. result = newStringOfCap(
  461. schemeLen + usernameLen + passwordLen + hostnameLen + portLen + pathLen + queryLen + anchorLen + 12
  462. )
  463. # Insert to result.
  464. if schemeLen > 0:
  465. result.add u.scheme
  466. result.add ':'
  467. if not u.opaque:
  468. result.add '/'
  469. result.add '/'
  470. if usernameLen > 0:
  471. result.add u.username
  472. if passwordLen > 0:
  473. result.add ':'
  474. result.add u.password
  475. result.add '@'
  476. if u.hostname.endsWith('/'):
  477. if u.isIpv6:
  478. result.add '['
  479. result.add u.hostname[0 .. ^2]
  480. result.add ']'
  481. else:
  482. result.add u.hostname[0 .. ^2]
  483. else:
  484. if u.isIpv6:
  485. result.add '['
  486. result.add u.hostname
  487. result.add ']'
  488. else:
  489. result.add u.hostname
  490. if portLen > 0:
  491. result.add ':'
  492. result.add u.port
  493. if pathLen > 0:
  494. if hostnameLen > 0 and u.path[0] != '/':
  495. result.add '/'
  496. result.add u.path
  497. if queryLen > 0:
  498. result.add '?'
  499. result.add u.query
  500. if anchorLen > 0:
  501. result.add '#'
  502. result.add u.anchor
  503. proc getDataUri*(data, mime: string, encoding = "utf-8"): string {.since: (1, 3).} =
  504. ## Convenience proc for `base64.encode` returns a standard Base64 Data URI (RFC-2397)
  505. ##
  506. ## **See also:**
  507. ## * `mimetypes <mimetypes.html>`_ for `mime` argument
  508. ## * https://tools.ietf.org/html/rfc2397
  509. ## * https://en.wikipedia.org/wiki/Data_URI_scheme
  510. runnableExamples: static: assert getDataUri("Nim", "text/plain") == "data:text/plain;charset=utf-8;base64,Tmlt"
  511. assert encoding.len > 0 and mime.len > 0 # Must *not* be URL-Safe, see RFC-2397
  512. let base64encoded: string = base64.encode(data)
  513. # ("data:".len + ";charset=".len + ";base64,".len) == 22
  514. result = newStringOfCap(22 + mime.len + encoding.len + base64encoded.len)
  515. result.add "data:"
  516. result.add mime
  517. result.add ";charset="
  518. result.add encoding
  519. result.add ";base64,"
  520. result.add base64encoded