uri.nim 19 KB

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