uri.nim 17 KB

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