httpclient.nim 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2019 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a simple HTTP client that can be used to retrieve
  10. ## webpages and other data.
  11. ##
  12. ## .. warning:: Validate untrusted inputs: URI parsers and getters are not detecting malicious URIs.
  13. ##
  14. ## Retrieving a website
  15. ## ====================
  16. ##
  17. ## This example uses HTTP GET to retrieve
  18. ## `http://google.com`:
  19. ##
  20. ## ```Nim
  21. ## import std/httpclient
  22. ## var client = newHttpClient()
  23. ## try:
  24. ## echo client.getContent("http://google.com")
  25. ## finally:
  26. ## client.close()
  27. ## ```
  28. ##
  29. ## The same action can also be performed asynchronously, simply use the
  30. ## `AsyncHttpClient`:
  31. ##
  32. ## ```Nim
  33. ## import std/[asyncdispatch, httpclient]
  34. ##
  35. ## proc asyncProc(): Future[string] {.async.} =
  36. ## var client = newAsyncHttpClient()
  37. ## try:
  38. ## return await client.getContent("http://google.com")
  39. ## finally:
  40. ## client.close()
  41. ##
  42. ## echo waitFor asyncProc()
  43. ## ```
  44. ##
  45. ## The functionality implemented by `HttpClient` and `AsyncHttpClient`
  46. ## is the same, so you can use whichever one suits you best in the examples
  47. ## shown here.
  48. ##
  49. ## **Note:** You need to run asynchronous examples in an async proc
  50. ## otherwise you will get an `Undeclared identifier: 'await'` error.
  51. ##
  52. ## **Note:** An asynchronous client instance can only deal with one
  53. ## request at a time. To send multiple requests in parallel, use
  54. ## multiple client instances.
  55. ##
  56. ## Using HTTP POST
  57. ## ===============
  58. ##
  59. ## This example demonstrates the usage of the W3 HTML Validator, it
  60. ## uses `multipart/form-data` as the `Content-Type` to send the HTML to be
  61. ## validated to the server.
  62. ##
  63. ## ```Nim
  64. ## import std/[httpclient]
  65. ## var client = newHttpClient()
  66. ## var data = newMultipartData()
  67. ## data["output"] = "soap12"
  68. ## data["uploaded_file"] = ("test.html", "text/html",
  69. ## "<html><head></head><body><p>test</p></body></html>")
  70. ## try:
  71. ## echo client.postContent("http://validator.w3.org/check", multipart=data)
  72. ## finally:
  73. ## client.close()
  74. ## ```
  75. ##
  76. ## To stream files from disk when performing the request, use `addFiles`.
  77. ##
  78. ## **Note:** This will allocate a new `Mimetypes` database every time you call
  79. ## it, you can pass your own via the `mimeDb` parameter to avoid this.
  80. ##
  81. ## ```Nim
  82. ## import std/[httpclient, mimetypes]
  83. ## let mimes = newMimetypes()
  84. ## var client = newHttpClient()
  85. ## var data = newMultipartData()
  86. ## data.addFiles({"uploaded_file": "test.html"}, mimeDb = mimes)
  87. ## try:
  88. ## echo client.postContent("http://validator.w3.org/check", multipart=data)
  89. ## finally:
  90. ## client.close()
  91. ## ```
  92. ##
  93. ## You can also make post requests with custom headers.
  94. ## This example sets `Content-Type` to `application/json`
  95. ## and uses a json object for the body
  96. ##
  97. ## ```Nim
  98. ## import std/[httpclient, json]
  99. ##
  100. ## let client = newHttpClient()
  101. ## client.headers = newHttpHeaders({ "Content-Type": "application/json" })
  102. ## let body = %*{
  103. ## "data": "some text"
  104. ## }
  105. ## try:
  106. ## let response = client.request("http://some.api", httpMethod = HttpPost, body = $body)
  107. ## echo response.status
  108. ## finally:
  109. ## client.close()
  110. ## ```
  111. ##
  112. ## Progress reporting
  113. ## ==================
  114. ##
  115. ## You may specify a callback procedure to be called during an HTTP request.
  116. ## This callback will be executed every second with information about the
  117. ## progress of the HTTP request.
  118. ##
  119. ## ```Nim
  120. ## import std/[asyncdispatch, httpclient]
  121. ##
  122. ## proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} =
  123. ## echo("Downloaded ", progress, " of ", total)
  124. ## echo("Current rate: ", speed div 1000, "kb/s")
  125. ##
  126. ## proc asyncProc() {.async.} =
  127. ## var client = newAsyncHttpClient()
  128. ## client.onProgressChanged = onProgressChanged
  129. ## try:
  130. ## discard await client.getContent("http://speedtest-ams2.digitalocean.com/100mb.test")
  131. ## finally:
  132. ## client.close()
  133. ##
  134. ## waitFor asyncProc()
  135. ## ```
  136. ##
  137. ## If you would like to remove the callback simply set it to `nil`.
  138. ##
  139. ## ```Nim
  140. ## client.onProgressChanged = nil
  141. ## ```
  142. ##
  143. ## .. warning:: The `total` reported by httpclient may be 0 in some cases.
  144. ##
  145. ##
  146. ## SSL/TLS support
  147. ## ===============
  148. ## This requires the OpenSSL library. Fortunately it's widely used and installed
  149. ## on many operating systems. httpclient will use SSL automatically if you give
  150. ## any of the functions a url with the `https` schema, for example:
  151. ## `https://github.com/`.
  152. ##
  153. ## You will also have to compile with `ssl` defined like so:
  154. ## `nim c -d:ssl ...`.
  155. ##
  156. ## Certificate validation is performed by default.
  157. ##
  158. ## A set of directories and files from the `ssl_certs <ssl_certs.html>`_
  159. ## module are scanned to locate CA certificates.
  160. ##
  161. ## Example of setting SSL verification parameters in a new client:
  162. ##
  163. ## ```Nim
  164. ## import std/[net, httpclient]
  165. ## var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyPeer))
  166. ## ```
  167. ##
  168. ## There are three options for verify mode:
  169. ##
  170. ## * ``CVerifyNone``: certificates are not verified;
  171. ## * ``CVerifyPeer``: certificates are verified;
  172. ## * ``CVerifyPeerUseEnvVars``: certificates are verified and the optional
  173. ## environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to
  174. ## locate certificates
  175. ##
  176. ## See `newContext <net.html#newContext.string,string,string,string>`_ to tweak or disable certificate validation.
  177. ##
  178. ## Timeouts
  179. ## ========
  180. ##
  181. ## Currently only the synchronous functions support a timeout.
  182. ## The timeout is
  183. ## measured in milliseconds, once it is set any call on a socket which may
  184. ## block will be susceptible to this timeout.
  185. ##
  186. ## It may be surprising but the
  187. ## function as a whole can take longer than the specified timeout, only
  188. ## individual internal calls on the socket are affected. In practice this means
  189. ## that as long as the server is sending data an exception will not be raised,
  190. ## if however data does not reach the client within the specified timeout a
  191. ## `TimeoutError` exception will be raised.
  192. ##
  193. ## Here is how to set a timeout when creating an `HttpClient` instance:
  194. ##
  195. ## ```Nim
  196. ## import std/httpclient
  197. ##
  198. ## let client = newHttpClient(timeout = 42)
  199. ## ```
  200. ##
  201. ## Proxy
  202. ## =====
  203. ##
  204. ## A proxy can be specified as a param to any of the procedures defined in
  205. ## this module. To do this, use the `newProxy` constructor. Unfortunately,
  206. ## only basic authentication is supported at the moment.
  207. ##
  208. ## Some examples on how to configure a Proxy for `HttpClient`:
  209. ##
  210. ## ```Nim
  211. ## import std/httpclient
  212. ##
  213. ## let myProxy = newProxy("http://myproxy.network")
  214. ## let client = newHttpClient(proxy = myProxy)
  215. ## ```
  216. ##
  217. ## Use proxies with basic authentication:
  218. ##
  219. ## ```Nim
  220. ## import std/httpclient
  221. ##
  222. ## let myProxy = newProxy("http://myproxy.network", auth="user:password")
  223. ## let client = newHttpClient(proxy = myProxy)
  224. ## ```
  225. ##
  226. ## Get Proxy URL from environment variables:
  227. ##
  228. ## ```Nim
  229. ## import std/httpclient
  230. ##
  231. ## var url = ""
  232. ## try:
  233. ## if existsEnv("http_proxy"):
  234. ## url = getEnv("http_proxy")
  235. ## elif existsEnv("https_proxy"):
  236. ## url = getEnv("https_proxy")
  237. ## except ValueError:
  238. ## echo "Unable to parse proxy from environment variables."
  239. ##
  240. ## let myProxy = newProxy(url = url)
  241. ## let client = newHttpClient(proxy = myProxy)
  242. ## ```
  243. ##
  244. ## Redirects
  245. ## =========
  246. ##
  247. ## The maximum redirects can be set with the `maxRedirects` of `int` type,
  248. ## it specifies the maximum amount of redirects to follow,
  249. ## it defaults to `5`, you can set it to `0` to disable redirects.
  250. ##
  251. ## Here you can see an example about how to set the `maxRedirects` of `HttpClient`:
  252. ##
  253. ## ```Nim
  254. ## import std/httpclient
  255. ##
  256. ## let client = newHttpClient(maxRedirects = 0)
  257. ## ```
  258. ##
  259. import std/private/since
  260. import std/[
  261. net, strutils, uri, parseutils, base64, os, mimetypes,
  262. math, random, httpcore, times, tables, streams, monotimes,
  263. asyncnet, asyncdispatch, asyncfile, nativesockets,
  264. ]
  265. when defined(nimPreviewSlimSystem):
  266. import std/[assertions, syncio]
  267. export httpcore except parseHeader # TODO: The `except` doesn't work
  268. type
  269. Response* = ref object
  270. version*: string
  271. status*: string
  272. headers*: HttpHeaders
  273. body: string
  274. bodyStream*: Stream
  275. AsyncResponse* = ref object
  276. version*: string
  277. status*: string
  278. headers*: HttpHeaders
  279. body: string
  280. bodyStream*: FutureStream[string]
  281. proc code*(response: Response | AsyncResponse): HttpCode
  282. {.raises: [ValueError, OverflowDefect].} =
  283. ## Retrieves the specified response's `HttpCode`.
  284. ##
  285. ## Raises a `ValueError` if the response's `status` does not have a
  286. ## corresponding `HttpCode`.
  287. return response.status[0 .. 2].parseInt.HttpCode
  288. proc contentType*(response: Response | AsyncResponse): string {.inline.} =
  289. ## Retrieves the specified response's content type.
  290. ##
  291. ## This is effectively the value of the "Content-Type" header.
  292. response.headers.getOrDefault("content-type")
  293. proc contentLength*(response: Response | AsyncResponse): int =
  294. ## Retrieves the specified response's content length.
  295. ##
  296. ## This is effectively the value of the "Content-Length" header.
  297. ##
  298. ## A `ValueError` exception will be raised if the value is not an integer.
  299. ## If the Content-Length header is not set in the response, ContentLength is set to the value -1.
  300. var contentLengthHeader = response.headers.getOrDefault("Content-Length", HttpHeaderValues(@["-1"]))
  301. result = contentLengthHeader.parseInt()
  302. proc lastModified*(response: Response | AsyncResponse): DateTime =
  303. ## Retrieves the specified response's last modified time.
  304. ##
  305. ## This is effectively the value of the "Last-Modified" header.
  306. ##
  307. ## Raises a `ValueError` if the parsing fails or the value is not a correctly
  308. ## formatted time.
  309. var lastModifiedHeader = response.headers.getOrDefault("last-modified")
  310. result = parse(lastModifiedHeader, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", utc())
  311. proc body*(response: Response): string =
  312. ## Retrieves the specified response's body.
  313. ##
  314. ## The response's body stream is read synchronously.
  315. if response.body.len == 0:
  316. response.body = response.bodyStream.readAll()
  317. return response.body
  318. proc body*(response: AsyncResponse): Future[string] {.async.} =
  319. ## Reads the response's body and caches it. The read is performed only
  320. ## once.
  321. if response.body.len == 0:
  322. response.body = await readAll(response.bodyStream)
  323. return response.body
  324. type
  325. Proxy* = ref object
  326. url*: Uri
  327. auth*: string
  328. MultipartEntry = object
  329. name, content: string
  330. case isFile: bool
  331. of true:
  332. filename, contentType: string
  333. fileSize: int64
  334. isStream: bool
  335. else: discard
  336. MultipartEntries* = openArray[tuple[name, content: string]]
  337. MultipartData* = ref object
  338. content: seq[MultipartEntry]
  339. ProtocolError* = object of IOError ## exception that is raised when server
  340. ## does not conform to the implemented
  341. ## protocol
  342. HttpRequestError* = object of IOError ## Thrown in the `getContent` proc
  343. ## and `postContent` proc,
  344. ## when the server returns an error
  345. const defUserAgent* = "Nim-httpclient/" & NimVersion
  346. proc httpError(msg: string) =
  347. var e: ref ProtocolError
  348. new(e)
  349. e.msg = msg
  350. raise e
  351. proc fileError(msg: string) =
  352. var e: ref IOError
  353. new(e)
  354. e.msg = msg
  355. raise e
  356. when not defined(ssl):
  357. type SslContext = ref object
  358. var defaultSslContext {.threadvar.}: SslContext
  359. proc getDefaultSSL(): SslContext =
  360. result = defaultSslContext
  361. when defined(ssl):
  362. if result == nil:
  363. defaultSslContext = newContext(verifyMode = CVerifyPeer)
  364. result = defaultSslContext
  365. doAssert result != nil, "failure to initialize the SSL context"
  366. proc newProxy*(url: string; auth = ""): Proxy =
  367. ## Constructs a new `TProxy` object.
  368. result = Proxy(url: parseUri(url), auth: auth)
  369. proc newProxy*(url: Uri; auth = ""): Proxy =
  370. ## Constructs a new `TProxy` object.
  371. result = Proxy(url: url, auth: auth)
  372. proc newMultipartData*: MultipartData {.inline.} =
  373. ## Constructs a new `MultipartData` object.
  374. MultipartData()
  375. proc `$`*(data: MultipartData): string {.since: (1, 1).} =
  376. ## convert MultipartData to string so it's human readable when echo
  377. ## see https://github.com/nim-lang/Nim/issues/11863
  378. const sep = "-".repeat(30)
  379. result = ""
  380. for pos, entry in data.content:
  381. result.add(sep & center($pos, 3) & sep)
  382. result.add("\nname=\"" & entry.name & "\"")
  383. if entry.isFile:
  384. result.add("; filename=\"" & entry.filename & "\"\n")
  385. result.add("Content-Type: " & entry.contentType)
  386. result.add("\n\n" & entry.content & "\n")
  387. proc add*(p: MultipartData, name, content: string, filename: string = "",
  388. contentType: string = "", useStream = true) =
  389. ## Add a value to the multipart data.
  390. ##
  391. ## When `useStream` is `false`, the file will be read into memory.
  392. ##
  393. ## Raises a `ValueError` exception if
  394. ## `name`, `filename` or `contentType` contain newline characters.
  395. if {'\c', '\L'} in name:
  396. raise newException(ValueError, "name contains a newline character")
  397. if {'\c', '\L'} in filename:
  398. raise newException(ValueError, "filename contains a newline character")
  399. if {'\c', '\L'} in contentType:
  400. raise newException(ValueError, "contentType contains a newline character")
  401. var entry = MultipartEntry(
  402. name: name,
  403. content: content,
  404. isFile: filename.len > 0
  405. )
  406. if entry.isFile:
  407. entry.isStream = useStream
  408. entry.filename = filename
  409. entry.contentType = contentType
  410. p.content.add(entry)
  411. proc add*(p: MultipartData, xs: MultipartEntries): MultipartData
  412. {.discardable.} =
  413. ## Add a list of multipart entries to the multipart data `p`. All values are
  414. ## added without a filename and without a content type.
  415. ##
  416. ## ```Nim
  417. ## data.add({"action": "login", "format": "json"})
  418. ## ```
  419. for name, content in xs.items:
  420. p.add(name, content)
  421. result = p
  422. proc newMultipartData*(xs: MultipartEntries): MultipartData =
  423. ## Create a new multipart data object and fill it with the entries `xs`
  424. ## directly.
  425. ##
  426. ## ```Nim
  427. ## var data = newMultipartData({"action": "login", "format": "json"})
  428. ## ```
  429. result = MultipartData()
  430. for entry in xs:
  431. result.add(entry.name, entry.content)
  432. proc addFiles*(p: MultipartData, xs: openArray[tuple[name, file: string]],
  433. mimeDb = newMimetypes(), useStream = true):
  434. MultipartData {.discardable.} =
  435. ## Add files to a multipart data object. The files will be streamed from disk
  436. ## when the request is being made. When `stream` is `false`, the files are
  437. ## instead read into memory, but beware this is very memory ineffecient even
  438. ## for small files. The MIME types will automatically be determined.
  439. ## Raises an `IOError` if the file cannot be opened or reading fails. To
  440. ## manually specify file content, filename and MIME type, use `[]=` instead.
  441. ##
  442. ## ```Nim
  443. ## data.addFiles({"uploaded_file": "public/test.html"})
  444. ## ```
  445. for name, file in xs.items:
  446. var contentType: string = ""
  447. let (_, fName, ext) = splitFile(file)
  448. if ext.len > 0:
  449. contentType = mimeDb.getMimetype(ext[1..ext.high], "")
  450. let content = if useStream: file else: readFile(file)
  451. p.add(name, content, fName & ext, contentType, useStream = useStream)
  452. result = p
  453. proc `[]=`*(p: MultipartData, name, content: string) {.inline.} =
  454. ## Add a multipart entry to the multipart data `p`. The value is added
  455. ## without a filename and without a content type.
  456. ##
  457. ## ```Nim
  458. ## data["username"] = "NimUser"
  459. ## ```
  460. p.add(name, content)
  461. proc `[]=`*(p: MultipartData, name: string,
  462. file: tuple[name, contentType, content: string]) {.inline.} =
  463. ## Add a file to the multipart data `p`, specifying filename, contentType
  464. ## and content manually.
  465. ##
  466. ## ```Nim
  467. ## data["uploaded_file"] = ("test.html", "text/html",
  468. ## "<html><head></head><body><p>test</p></body></html>")
  469. ## ```
  470. p.add(name, file.content, file.name, file.contentType, useStream = false)
  471. proc getBoundary(p: MultipartData): string =
  472. if p == nil or p.content.len == 0: return
  473. while true:
  474. result = $rand(int.high)
  475. for i, entry in p.content:
  476. if result in entry.content: break
  477. elif i == p.content.high: return
  478. proc sendFile(socket: Socket | AsyncSocket,
  479. entry: MultipartEntry) {.multisync.} =
  480. const chunkSize = 2^18
  481. let file =
  482. when socket is AsyncSocket: openAsync(entry.content)
  483. else: newFileStream(entry.content, fmRead)
  484. var buffer: string
  485. while true:
  486. buffer =
  487. when socket is AsyncSocket: (await read(file, chunkSize))
  488. else: readStr(file, chunkSize)
  489. if buffer.len == 0: break
  490. await socket.send(buffer)
  491. file.close()
  492. proc getNewLocation(lastURL: Uri, headers: HttpHeaders): Uri =
  493. let newLocation = headers.getOrDefault"Location"
  494. if newLocation == "": httpError("location header expected")
  495. # Relative URLs. (Not part of the spec, but soon will be.)
  496. let parsedLocation = parseUri(newLocation)
  497. if parsedLocation.hostname == "" and parsedLocation.path != "":
  498. result = lastURL
  499. result.path = parsedLocation.path
  500. result.query = parsedLocation.query
  501. result.anchor = parsedLocation.anchor
  502. else:
  503. result = parsedLocation
  504. proc generateHeaders(requestUrl: Uri, httpMethod: HttpMethod, headers: HttpHeaders,
  505. proxy: Proxy): string =
  506. # GET
  507. result = $httpMethod
  508. result.add ' '
  509. if proxy.isNil or requestUrl.scheme == "https":
  510. # /path?query
  511. if not requestUrl.path.startsWith("/"): result.add '/'
  512. result.add(requestUrl.path)
  513. if requestUrl.query.len > 0:
  514. result.add("?" & requestUrl.query)
  515. else:
  516. # Remove the 'http://' from the URL for CONNECT requests for TLS connections.
  517. var modifiedUrl = requestUrl
  518. if requestUrl.scheme == "https": modifiedUrl.scheme = ""
  519. result.add($modifiedUrl)
  520. # HTTP/1.1\c\l
  521. result.add(" HTTP/1.1" & httpNewLine)
  522. # Host header.
  523. if not headers.hasKey("Host"):
  524. if requestUrl.port == "":
  525. add(result, "Host: " & requestUrl.hostname & httpNewLine)
  526. else:
  527. add(result, "Host: " & requestUrl.hostname & ":" & requestUrl.port & httpNewLine)
  528. # Connection header.
  529. if not headers.hasKey("Connection"):
  530. add(result, "Connection: Keep-Alive" & httpNewLine)
  531. # Proxy auth header.
  532. if not proxy.isNil and proxy.auth != "":
  533. let auth = base64.encode(proxy.auth)
  534. add(result, "Proxy-Authorization: Basic " & auth & httpNewLine)
  535. for key, val in headers:
  536. add(result, key & ": " & val & httpNewLine)
  537. add(result, httpNewLine)
  538. type
  539. ProgressChangedProc*[ReturnType] =
  540. proc (total, progress, speed: BiggestInt):
  541. ReturnType {.closure, gcsafe.}
  542. HttpClientBase*[SocketType] = ref object
  543. socket: SocketType
  544. connected: bool
  545. currentURL: Uri ## Where we are currently connected.
  546. headers*: HttpHeaders ## Headers to send in requests.
  547. maxRedirects: Natural ## Maximum redirects, set to `0` to disable.
  548. userAgent: string
  549. timeout*: int ## Only used for blocking HttpClient for now.
  550. proxy: Proxy
  551. ## `nil` or the callback to call when request progress changes.
  552. when SocketType is Socket:
  553. onProgressChanged*: ProgressChangedProc[void]
  554. else:
  555. onProgressChanged*: ProgressChangedProc[Future[void]]
  556. when defined(ssl):
  557. sslContext: net.SslContext
  558. contentTotal: BiggestInt
  559. contentProgress: BiggestInt
  560. oneSecondProgress: BiggestInt
  561. lastProgressReport: MonoTime
  562. when SocketType is AsyncSocket:
  563. bodyStream: FutureStream[string]
  564. parseBodyFut: Future[void]
  565. else:
  566. bodyStream: Stream
  567. getBody: bool ## When `false`, the body is never read in requestAux.
  568. type
  569. HttpClient* = HttpClientBase[Socket]
  570. proc newHttpClient*(userAgent = defUserAgent, maxRedirects = 5,
  571. sslContext = getDefaultSSL(), proxy: Proxy = nil,
  572. timeout = -1, headers = newHttpHeaders()): HttpClient =
  573. ## Creates a new HttpClient instance.
  574. ##
  575. ## `userAgent` specifies the user agent that will be used when making
  576. ## requests.
  577. ##
  578. ## `maxRedirects` specifies the maximum amount of redirects to follow,
  579. ## default is 5.
  580. ##
  581. ## `sslContext` specifies the SSL context to use for HTTPS requests.
  582. ## See `SSL/TLS support <#sslslashtls-support>`_
  583. ##
  584. ## `proxy` specifies an HTTP proxy to use for this HTTP client's
  585. ## connections.
  586. ##
  587. ## `timeout` specifies the number of milliseconds to allow before a
  588. ## `TimeoutError` is raised.
  589. ##
  590. ## `headers` specifies the HTTP Headers.
  591. runnableExamples:
  592. import std/strutils
  593. let exampleHtml = newHttpClient().getContent("http://example.com")
  594. assert "Example Domain" in exampleHtml
  595. assert "Pizza" notin exampleHtml
  596. new result
  597. result.headers = headers
  598. result.userAgent = userAgent
  599. result.maxRedirects = maxRedirects
  600. result.proxy = proxy
  601. result.timeout = timeout
  602. result.onProgressChanged = nil
  603. result.bodyStream = newStringStream()
  604. result.getBody = true
  605. when defined(ssl):
  606. result.sslContext = sslContext
  607. type
  608. AsyncHttpClient* = HttpClientBase[AsyncSocket]
  609. proc newAsyncHttpClient*(userAgent = defUserAgent, maxRedirects = 5,
  610. sslContext = getDefaultSSL(), proxy: Proxy = nil,
  611. headers = newHttpHeaders()): AsyncHttpClient =
  612. ## Creates a new AsyncHttpClient instance.
  613. ##
  614. ## `userAgent` specifies the user agent that will be used when making
  615. ## requests.
  616. ##
  617. ## `maxRedirects` specifies the maximum amount of redirects to follow,
  618. ## default is 5.
  619. ##
  620. ## `sslContext` specifies the SSL context to use for HTTPS requests.
  621. ##
  622. ## `proxy` specifies an HTTP proxy to use for this HTTP client's
  623. ## connections.
  624. ##
  625. ## `headers` specifies the HTTP Headers.
  626. runnableExamples:
  627. import std/[asyncdispatch, strutils]
  628. proc asyncProc(): Future[string] {.async.} =
  629. let client = newAsyncHttpClient()
  630. result = await client.getContent("http://example.com")
  631. let exampleHtml = waitFor asyncProc()
  632. assert "Example Domain" in exampleHtml
  633. assert "Pizza" notin exampleHtml
  634. new result
  635. result.headers = headers
  636. result.userAgent = userAgent
  637. result.maxRedirects = maxRedirects
  638. result.proxy = proxy
  639. result.timeout = -1 # TODO
  640. result.onProgressChanged = nil
  641. result.bodyStream = newFutureStream[string]("newAsyncHttpClient")
  642. result.getBody = true
  643. when defined(ssl):
  644. result.sslContext = sslContext
  645. proc close*(client: HttpClient | AsyncHttpClient) =
  646. ## Closes any connections held by the HTTP client.
  647. if client.connected:
  648. client.socket.close()
  649. client.connected = false
  650. proc getSocket*(client: HttpClient): Socket {.inline.} =
  651. ## Get network socket, useful if you want to find out more details about the connection.
  652. ##
  653. ## This example shows info about local and remote endpoints:
  654. ##
  655. ## ```Nim
  656. ## if client.connected:
  657. ## echo client.getSocket.getLocalAddr
  658. ## echo client.getSocket.getPeerAddr
  659. ## ```
  660. return client.socket
  661. proc getSocket*(client: AsyncHttpClient): AsyncSocket {.inline.} =
  662. return client.socket
  663. proc reportProgress(client: HttpClient | AsyncHttpClient,
  664. progress: BiggestInt) {.multisync.} =
  665. client.contentProgress += progress
  666. client.oneSecondProgress += progress
  667. if (getMonoTime() - client.lastProgressReport).inSeconds >= 1:
  668. if not client.onProgressChanged.isNil:
  669. await client.onProgressChanged(client.contentTotal,
  670. client.contentProgress,
  671. client.oneSecondProgress)
  672. client.oneSecondProgress = 0
  673. client.lastProgressReport = getMonoTime()
  674. proc recvFull(client: HttpClient | AsyncHttpClient, size: int, timeout: int,
  675. keep: bool): Future[int] {.multisync.} =
  676. ## Ensures that all the data requested is read and returned.
  677. var readLen = 0
  678. while true:
  679. if size == readLen: break
  680. let remainingSize = size - readLen
  681. let sizeToRecv = min(remainingSize, net.BufferSize)
  682. when client.socket is Socket:
  683. let data = client.socket.recv(sizeToRecv, timeout)
  684. else:
  685. let data = await client.socket.recv(sizeToRecv)
  686. if data == "":
  687. client.close()
  688. break # We've been disconnected.
  689. readLen.inc(data.len)
  690. if keep:
  691. await client.bodyStream.write(data)
  692. await reportProgress(client, data.len)
  693. return readLen
  694. proc parseChunks(client: HttpClient | AsyncHttpClient): Future[void]
  695. {.multisync.} =
  696. while true:
  697. var chunkSize = 0
  698. var chunkSizeStr = await client.socket.recvLine()
  699. var i = 0
  700. if chunkSizeStr == "":
  701. httpError("Server terminated connection prematurely")
  702. while i < chunkSizeStr.len:
  703. case chunkSizeStr[i]
  704. of '0'..'9':
  705. chunkSize = chunkSize shl 4 or (ord(chunkSizeStr[i]) - ord('0'))
  706. of 'a'..'f':
  707. chunkSize = chunkSize shl 4 or (ord(chunkSizeStr[i]) - ord('a') + 10)
  708. of 'A'..'F':
  709. chunkSize = chunkSize shl 4 or (ord(chunkSizeStr[i]) - ord('A') + 10)
  710. of ';':
  711. # http://tools.ietf.org/html/rfc2616#section-3.6.1
  712. # We don't care about chunk-extensions.
  713. break
  714. else:
  715. httpError("Invalid chunk size: " & chunkSizeStr)
  716. inc(i)
  717. if chunkSize <= 0:
  718. discard await recvFull(client, 2, client.timeout, false) # Skip \c\L
  719. break
  720. var bytesRead = await recvFull(client, chunkSize, client.timeout, true)
  721. if bytesRead != chunkSize:
  722. httpError("Server terminated connection prematurely")
  723. bytesRead = await recvFull(client, 2, client.timeout, false) # Skip \c\L
  724. if bytesRead != 2:
  725. httpError("Server terminated connection prematurely")
  726. # Trailer headers will only be sent if the request specifies that we want
  727. # them: http://tools.ietf.org/html/rfc2616#section-3.6.1
  728. proc parseBody(client: HttpClient | AsyncHttpClient, headers: HttpHeaders,
  729. httpVersion: string): Future[void] {.multisync.} =
  730. # Reset progress from previous requests.
  731. client.contentTotal = 0
  732. client.contentProgress = 0
  733. client.oneSecondProgress = 0
  734. client.lastProgressReport = MonoTime()
  735. when client is AsyncHttpClient:
  736. assert(not client.bodyStream.finished)
  737. if headers.getOrDefault"Transfer-Encoding" == "chunked":
  738. await parseChunks(client)
  739. else:
  740. # -REGION- Content-Length
  741. # (http://tools.ietf.org/html/rfc2616#section-4.4) NR.3
  742. var contentLengthHeader = headers.getOrDefault"Content-Length"
  743. if contentLengthHeader != "":
  744. var length = contentLengthHeader.parseInt()
  745. client.contentTotal = length
  746. if length > 0:
  747. let recvLen = await client.recvFull(length, client.timeout, true)
  748. if recvLen == 0:
  749. client.close()
  750. httpError("Got disconnected while trying to read body.")
  751. if recvLen != length:
  752. httpError("Received length doesn't match expected length. Wanted " &
  753. $length & " got: " & $recvLen)
  754. else:
  755. # (http://tools.ietf.org/html/rfc2616#section-4.4) NR.4 TODO
  756. # -REGION- Connection: Close
  757. # (http://tools.ietf.org/html/rfc2616#section-4.4) NR.5
  758. let implicitConnectionClose =
  759. httpVersion == "1.0" or
  760. # This doesn't match the HTTP spec, but it fixes issues for non-conforming servers.
  761. (httpVersion == "1.1" and headers.getOrDefault"Connection" == "")
  762. if headers.getOrDefault"Connection" == "close" or implicitConnectionClose:
  763. while true:
  764. let recvLen = await client.recvFull(4000, client.timeout, true)
  765. if recvLen != 4000:
  766. client.close()
  767. break
  768. when client is AsyncHttpClient:
  769. client.bodyStream.complete()
  770. else:
  771. client.bodyStream.setPosition(0)
  772. # If the server will close our connection, then no matter the method of
  773. # reading the body, we need to close our socket.
  774. if headers.getOrDefault"Connection" == "close":
  775. client.close()
  776. proc parseResponse(client: HttpClient | AsyncHttpClient,
  777. getBody: bool): Future[Response | AsyncResponse]
  778. {.multisync.} =
  779. new result
  780. var parsedStatus = false
  781. var linei = 0
  782. var fullyRead = false
  783. var lastHeaderName = ""
  784. var line = ""
  785. result.headers = newHttpHeaders()
  786. while true:
  787. linei = 0
  788. when client is HttpClient:
  789. line = client.socket.recvLine(client.timeout)
  790. else:
  791. line = await client.socket.recvLine()
  792. if line == "":
  793. # We've been disconnected.
  794. client.close()
  795. break
  796. if line == httpNewLine:
  797. fullyRead = true
  798. break
  799. if not parsedStatus:
  800. # Parse HTTP version info and status code.
  801. var le = skipIgnoreCase(line, "HTTP/", linei)
  802. if le <= 0:
  803. httpError("invalid http version, `" & line & "`")
  804. inc(linei, le)
  805. le = skipIgnoreCase(line, "1.1", linei)
  806. if le > 0: result.version = "1.1"
  807. else:
  808. le = skipIgnoreCase(line, "1.0", linei)
  809. if le <= 0: httpError("unsupported http version")
  810. result.version = "1.0"
  811. inc(linei, le)
  812. # Status code
  813. linei.inc skipWhitespace(line, linei)
  814. result.status = line[linei .. ^1]
  815. parsedStatus = true
  816. else:
  817. # Parse headers
  818. # There's at least one char because empty lines are handled above (with client.close)
  819. if line[0] in {' ', '\t'}:
  820. # Check if it's a multiline header value, if so, append to the header we're currently parsing
  821. # This works because a line with a header must start with the header name without any leading space
  822. # See https://datatracker.ietf.org/doc/html/rfc7230, section 3.2 and 3.2.4
  823. # Multiline headers are deprecated in the spec, but it's better to parse them than crash
  824. if lastHeaderName == "":
  825. # Some extra unparsable lines in the HTTP output - we ignore them
  826. discard
  827. else:
  828. result.headers.table[result.headers.toCaseInsensitive(lastHeaderName)][^1].add "\n" & line
  829. else:
  830. var name = ""
  831. var le = parseUntil(line, name, ':', linei)
  832. if le <= 0: httpError("Invalid headers - received empty header name")
  833. if line.len == le: httpError("Invalid headers - no colon after header name")
  834. inc(linei, le) # Skip the parsed header name
  835. inc(linei) # Skip :
  836. # If we want to be HTTP spec compliant later, error on linei == line.len (for empty header value)
  837. lastHeaderName = name # Remember the header name for the possible multi-line header
  838. result.headers.add(name, line[linei .. ^1].strip())
  839. if result.headers.len > headerLimit:
  840. httpError("too many headers")
  841. if not fullyRead:
  842. httpError("Connection was closed before full request has been made")
  843. when client is HttpClient:
  844. result.bodyStream = newStringStream()
  845. else:
  846. result.bodyStream = newFutureStream[string]("parseResponse")
  847. if getBody and result.code != Http204:
  848. client.bodyStream = result.bodyStream
  849. when client is HttpClient:
  850. parseBody(client, result.headers, result.version)
  851. else:
  852. assert(client.parseBodyFut.isNil or client.parseBodyFut.finished)
  853. # do not wait here for the body request to complete
  854. client.parseBodyFut = parseBody(client, result.headers, result.version)
  855. client.parseBodyFut.addCallback do():
  856. if client.parseBodyFut.failed:
  857. client.bodyStream.fail(client.parseBodyFut.error)
  858. else:
  859. when client is AsyncHttpClient:
  860. result.bodyStream.complete()
  861. proc newConnection(client: HttpClient | AsyncHttpClient,
  862. url: Uri) {.multisync.} =
  863. if client.currentURL.hostname != url.hostname or
  864. client.currentURL.scheme != url.scheme or
  865. client.currentURL.port != url.port or
  866. (not client.connected):
  867. # Connect to proxy if specified
  868. let connectionUrl =
  869. if client.proxy.isNil: url else: client.proxy.url
  870. let isSsl = connectionUrl.scheme.toLowerAscii() == "https"
  871. if isSsl and not defined(ssl):
  872. raise newException(HttpRequestError,
  873. "SSL support is not available. Cannot connect over SSL. Compile with -d:ssl to enable.")
  874. if client.connected:
  875. client.close()
  876. client.connected = false
  877. # TODO: I should be able to write 'net.Port' here...
  878. let port =
  879. if connectionUrl.port == "":
  880. if isSsl:
  881. nativesockets.Port(443)
  882. else:
  883. nativesockets.Port(80)
  884. else: nativesockets.Port(connectionUrl.port.parseInt)
  885. when client is HttpClient:
  886. client.socket = net.dial(connectionUrl.hostname, port)
  887. elif client is AsyncHttpClient:
  888. client.socket = await asyncnet.dial(connectionUrl.hostname, port)
  889. else: {.fatal: "Unsupported client type".}
  890. when defined(ssl):
  891. if isSsl:
  892. try:
  893. client.sslContext.wrapConnectedSocket(
  894. client.socket, handshakeAsClient, connectionUrl.hostname)
  895. except:
  896. client.socket.close()
  897. raise getCurrentException()
  898. # If need to CONNECT through proxy
  899. if url.scheme == "https" and not client.proxy.isNil:
  900. when defined(ssl):
  901. # Pass only host:port for CONNECT
  902. var connectUrl = initUri()
  903. connectUrl.hostname = url.hostname
  904. connectUrl.port = if url.port != "": url.port else: "443"
  905. let proxyHeaderString = generateHeaders(connectUrl, HttpConnect,
  906. newHttpHeaders(), client.proxy)
  907. await client.socket.send(proxyHeaderString)
  908. let proxyResp = await parseResponse(client, false)
  909. if not proxyResp.status.startsWith("200"):
  910. raise newException(HttpRequestError,
  911. "The proxy server rejected a CONNECT request, " &
  912. "so a secure connection could not be established.")
  913. client.sslContext.wrapConnectedSocket(
  914. client.socket, handshakeAsClient, url.hostname)
  915. else:
  916. raise newException(HttpRequestError,
  917. "SSL support is not available. Cannot connect over SSL. Compile with -d:ssl to enable.")
  918. # May be connected through proxy but remember actual URL being accessed
  919. client.currentURL = url
  920. client.connected = true
  921. proc readFileSizes(client: HttpClient | AsyncHttpClient,
  922. multipart: MultipartData) {.multisync.} =
  923. for entry in multipart.content.mitems():
  924. if not entry.isFile: continue
  925. if not entry.isStream:
  926. entry.fileSize = entry.content.len
  927. continue
  928. # TODO: look into making getFileSize work with async
  929. let fileSize = getFileSize(entry.content)
  930. entry.fileSize = fileSize
  931. proc format(entry: MultipartEntry, boundary: string): string =
  932. result = "--" & boundary & httpNewLine
  933. result.add("Content-Disposition: form-data; name=\"" & entry.name & "\"")
  934. if entry.isFile:
  935. result.add("; filename=\"" & entry.filename & "\"" & httpNewLine)
  936. result.add("Content-Type: " & entry.contentType & httpNewLine)
  937. else:
  938. result.add(httpNewLine & httpNewLine & entry.content)
  939. proc format(client: HttpClient | AsyncHttpClient,
  940. multipart: MultipartData): Future[seq[string]] {.multisync.} =
  941. result = @[]
  942. let bound = getBoundary(multipart)
  943. client.headers["Content-Type"] = "multipart/form-data; boundary=" & bound
  944. await client.readFileSizes(multipart)
  945. var length: int64 = int64(0)
  946. for entry in multipart.content:
  947. result.add(format(entry, bound) & httpNewLine)
  948. if entry.isFile:
  949. length += entry.fileSize + httpNewLine.len
  950. result.add "--" & bound & "--" & httpNewLine
  951. for s in result: length += s.len
  952. client.headers["Content-Length"] = $length
  953. proc override(fallback, override: HttpHeaders): HttpHeaders =
  954. # Right-biased map union for `HttpHeaders`
  955. result = newHttpHeaders()
  956. # Copy by value
  957. result.table[] = fallback.table[]
  958. if override.isNil:
  959. # Return the copy of fallback so it does not get modified
  960. return result
  961. for k, vs in override.table:
  962. result[k] = vs
  963. proc requestAux(client: HttpClient | AsyncHttpClient, url: Uri,
  964. httpMethod: HttpMethod, body = "", headers: HttpHeaders = nil,
  965. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  966. {.multisync.} =
  967. # Helper that actually makes the request. Does not handle redirects.
  968. if url.scheme == "":
  969. raise newException(ValueError, "No uri scheme supplied.")
  970. when client is AsyncHttpClient:
  971. if not client.parseBodyFut.isNil:
  972. # let the current operation finish before making another request
  973. await client.parseBodyFut
  974. client.parseBodyFut = nil
  975. await newConnection(client, url)
  976. var newHeaders: HttpHeaders
  977. var data: seq[string] = @[]
  978. if multipart != nil and multipart.content.len > 0:
  979. # `format` modifies `client.headers`, see
  980. # https://github.com/nim-lang/Nim/pull/18208#discussion_r647036979
  981. data = await client.format(multipart)
  982. newHeaders = client.headers.override(headers)
  983. else:
  984. newHeaders = client.headers.override(headers)
  985. # Only change headers if they have not been specified already
  986. if not newHeaders.hasKey("Content-Length"):
  987. if body.len != 0:
  988. newHeaders["Content-Length"] = $body.len
  989. elif httpMethod notin {HttpGet, HttpHead}:
  990. newHeaders["Content-Length"] = "0"
  991. if not newHeaders.hasKey("user-agent") and client.userAgent.len > 0:
  992. newHeaders["User-Agent"] = client.userAgent
  993. let headerString = generateHeaders(url, httpMethod, newHeaders,
  994. client.proxy)
  995. await client.socket.send(headerString)
  996. if data.len > 0:
  997. var buffer: string = ""
  998. for i, entry in multipart.content:
  999. buffer.add data[i]
  1000. if not entry.isFile: continue
  1001. if buffer.len > 0:
  1002. await client.socket.send(buffer)
  1003. buffer.setLen(0)
  1004. if entry.isStream:
  1005. await client.socket.sendFile(entry)
  1006. else:
  1007. await client.socket.send(entry.content)
  1008. buffer.add httpNewLine
  1009. # send the rest and the last boundary
  1010. await client.socket.send(buffer & data[^1])
  1011. elif body.len > 0:
  1012. await client.socket.send(body)
  1013. let getBody = httpMethod notin {HttpHead, HttpConnect} and
  1014. client.getBody
  1015. result = await parseResponse(client, getBody)
  1016. proc request*(client: HttpClient | AsyncHttpClient, url: Uri | string,
  1017. httpMethod: HttpMethod | string = HttpGet, body = "",
  1018. headers: HttpHeaders = nil,
  1019. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1020. {.multisync.} =
  1021. ## Connects to the hostname specified by the URL and performs a request
  1022. ## using the custom method string specified by `httpMethod`.
  1023. ##
  1024. ## Connection will be kept alive. Further requests on the same `client` to
  1025. ## the same hostname will not require a new connection to be made. The
  1026. ## connection can be closed by using the `close` procedure.
  1027. ##
  1028. ## This procedure will follow redirects up to a maximum number of redirects
  1029. ## specified in `client.maxRedirects`.
  1030. ##
  1031. ## You need to make sure that the `url` doesn't contain any newline
  1032. ## characters. Failing to do so will raise `AssertionDefect`.
  1033. ##
  1034. ## `headers` are HTTP headers that override the `client.headers` for
  1035. ## this specific request only and will not be persisted.
  1036. ##
  1037. ## **Deprecated since v1.5**: use HttpMethod enum instead; string parameter httpMethod is deprecated
  1038. when url is string:
  1039. doAssert(not url.contains({'\c', '\L'}), "url shouldn't contain any newline characters")
  1040. let url = parseUri(url)
  1041. when httpMethod is string:
  1042. {.warning:
  1043. "Deprecated since v1.5; use HttpMethod enum instead; string parameter httpMethod is deprecated".}
  1044. let httpMethod = case httpMethod
  1045. of "HEAD":
  1046. HttpHead
  1047. of "GET":
  1048. HttpGet
  1049. of "POST":
  1050. HttpPost
  1051. of "PUT":
  1052. HttpPut
  1053. of "DELETE":
  1054. HttpDelete
  1055. of "TRACE":
  1056. HttpTrace
  1057. of "OPTIONS":
  1058. HttpOptions
  1059. of "CONNECT":
  1060. HttpConnect
  1061. of "PATCH":
  1062. HttpPatch
  1063. else:
  1064. raise newException(ValueError, "Invalid HTTP method name: " & httpMethod)
  1065. result = await client.requestAux(url, httpMethod, body, headers, multipart)
  1066. var lastURL = url
  1067. for i in 1..client.maxRedirects:
  1068. let statusCode = result.code
  1069. if statusCode notin {Http301, Http302, Http303, Http307, Http308}:
  1070. break
  1071. let redirectTo = getNewLocation(lastURL, result.headers)
  1072. var redirectMethod: HttpMethod
  1073. var redirectBody: string
  1074. # For more informations about the redirect methods see:
  1075. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
  1076. case statusCode
  1077. of Http301, Http302, Http303:
  1078. # The method is changed to GET unless it is GET or HEAD (RFC2616)
  1079. if httpMethod notin {HttpGet, HttpHead}:
  1080. redirectMethod = HttpGet
  1081. else:
  1082. redirectMethod = httpMethod
  1083. # The body is stripped away
  1084. redirectBody = ""
  1085. # Delete any header value associated with the body
  1086. if not headers.isNil():
  1087. headers.del("Content-Length")
  1088. headers.del("Content-Type")
  1089. headers.del("Transfer-Encoding")
  1090. of Http307, Http308:
  1091. # The method and the body are unchanged
  1092. redirectMethod = httpMethod
  1093. redirectBody = body
  1094. else:
  1095. # Unreachable
  1096. raiseAssert "unreachable"
  1097. # Check if the redirection is to the same domain or a sub-domain (foo.com
  1098. # -> sub.foo.com)
  1099. if redirectTo.hostname != lastURL.hostname and
  1100. not redirectTo.hostname.endsWith("." & lastURL.hostname):
  1101. # Perform some cleanup of the header values
  1102. if headers != nil:
  1103. # Delete the Host header
  1104. headers.del("Host")
  1105. # Do not send any sensitive info to a unknown host
  1106. headers.del("Authorization")
  1107. result = await client.requestAux(redirectTo, redirectMethod, redirectBody,
  1108. headers, multipart)
  1109. lastURL = redirectTo
  1110. proc responseContent(resp: Response | AsyncResponse): Future[string] {.multisync.} =
  1111. ## Returns the content of a response as a string.
  1112. ##
  1113. ## A `HttpRequestError` will be raised if the server responds with a
  1114. ## client error (status code 4xx) or a server error (status code 5xx).
  1115. if resp.code.is4xx or resp.code.is5xx:
  1116. raise newException(HttpRequestError, resp.status.move)
  1117. else:
  1118. return await resp.bodyStream.readAll()
  1119. proc head*(client: HttpClient | AsyncHttpClient,
  1120. url: Uri | string): Future[Response | AsyncResponse] {.multisync.} =
  1121. ## Connects to the hostname specified by the URL and performs a HEAD request.
  1122. ##
  1123. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1124. result = await client.request(url, HttpHead)
  1125. proc get*(client: HttpClient | AsyncHttpClient,
  1126. url: Uri | string): Future[Response | AsyncResponse] {.multisync.} =
  1127. ## Connects to the hostname specified by the URL and performs a GET request.
  1128. ##
  1129. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1130. result = await client.request(url, HttpGet)
  1131. proc getContent*(client: HttpClient | AsyncHttpClient,
  1132. url: Uri | string): Future[string] {.multisync.} =
  1133. ## Connects to the hostname specified by the URL and returns the content of a GET request.
  1134. let resp = await get(client, url)
  1135. return await responseContent(resp)
  1136. proc delete*(client: HttpClient | AsyncHttpClient,
  1137. url: Uri | string): Future[Response | AsyncResponse] {.multisync.} =
  1138. ## Connects to the hostname specified by the URL and performs a DELETE request.
  1139. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1140. result = await client.request(url, HttpDelete)
  1141. proc deleteContent*(client: HttpClient | AsyncHttpClient,
  1142. url: Uri | string): Future[string] {.multisync.} =
  1143. ## Connects to the hostname specified by the URL and returns the content of a DELETE request.
  1144. let resp = await delete(client, url)
  1145. return await responseContent(resp)
  1146. proc post*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1147. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1148. {.multisync.} =
  1149. ## Connects to the hostname specified by the URL and performs a POST request.
  1150. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1151. result = await client.request(url, HttpPost, body, multipart=multipart)
  1152. proc postContent*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1153. multipart: MultipartData = nil): Future[string]
  1154. {.multisync.} =
  1155. ## Connects to the hostname specified by the URL and returns the content of a POST request.
  1156. let resp = await post(client, url, body, multipart)
  1157. return await responseContent(resp)
  1158. proc put*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1159. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1160. {.multisync.} =
  1161. ## Connects to the hostname specified by the URL and performs a PUT request.
  1162. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1163. result = await client.request(url, HttpPut, body, multipart=multipart)
  1164. proc putContent*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1165. multipart: MultipartData = nil): Future[string] {.multisync.} =
  1166. ## Connects to the hostname specified by the URL andreturns the content of a PUT request.
  1167. let resp = await put(client, url, body, multipart)
  1168. return await responseContent(resp)
  1169. proc patch*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1170. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1171. {.multisync.} =
  1172. ## Connects to the hostname specified by the URL and performs a PATCH request.
  1173. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1174. result = await client.request(url, HttpPatch, body, multipart=multipart)
  1175. proc patchContent*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1176. multipart: MultipartData = nil): Future[string]
  1177. {.multisync.} =
  1178. ## Connects to the hostname specified by the URL and returns the content of a PATCH request.
  1179. let resp = await patch(client, url, body, multipart)
  1180. return await responseContent(resp)
  1181. proc downloadFile*(client: HttpClient, url: Uri | string, filename: string) =
  1182. ## Downloads `url` and saves it to `filename`.
  1183. client.getBody = false
  1184. defer:
  1185. client.getBody = true
  1186. let resp = client.get(url)
  1187. if resp.code.is4xx or resp.code.is5xx:
  1188. raise newException(HttpRequestError, resp.status)
  1189. client.bodyStream = newFileStream(filename, fmWrite)
  1190. if client.bodyStream.isNil:
  1191. fileError("Unable to open file")
  1192. parseBody(client, resp.headers, resp.version)
  1193. client.bodyStream.close()
  1194. proc downloadFileEx(client: AsyncHttpClient,
  1195. url: Uri | string, filename: string): Future[void] {.async.} =
  1196. ## Downloads `url` and saves it to `filename`.
  1197. client.getBody = false
  1198. let resp = await client.get(url)
  1199. if resp.code.is4xx or resp.code.is5xx:
  1200. raise newException(HttpRequestError, resp.status)
  1201. client.bodyStream = newFutureStream[string]("downloadFile")
  1202. var file = openAsync(filename, fmWrite)
  1203. defer: file.close()
  1204. # Let `parseBody` write response data into client.bodyStream in the
  1205. # background.
  1206. let parseBodyFut = parseBody(client, resp.headers, resp.version)
  1207. parseBodyFut.addCallback do():
  1208. if parseBodyFut.failed:
  1209. client.bodyStream.fail(parseBodyFut.error)
  1210. # The `writeFromStream` proc will complete once all the data in the
  1211. # `bodyStream` has been written to the file.
  1212. await file.writeFromStream(client.bodyStream)
  1213. proc downloadFile*(client: AsyncHttpClient, url: Uri | string,
  1214. filename: string): Future[void] =
  1215. result = newFuture[void]("downloadFile")
  1216. try:
  1217. result = downloadFileEx(client, url, filename)
  1218. except Exception as exc:
  1219. result.fail(exc)
  1220. finally:
  1221. result.addCallback(
  1222. proc () = client.getBody = true
  1223. )