asynchttpserver.nim 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 a high performance asynchronous HTTP server.
  10. ##
  11. ## This HTTP server has not been designed to be used in production, but
  12. ## for testing applications locally. Because of this, when deploying your
  13. ## application in production you should use a reverse proxy (for example nginx)
  14. ## instead of allowing users to connect directly to this server.
  15. runnableExamples("-r:off"):
  16. # This example will create an HTTP server on an automatically chosen port.
  17. # It will respond to all requests with a `200 OK` response code and "Hello World"
  18. # as the response body.
  19. import std/asyncdispatch
  20. proc main {.async.} =
  21. var server = newAsyncHttpServer()
  22. proc cb(req: Request) {.async.} =
  23. echo (req.reqMethod, req.url, req.headers)
  24. let headers = {"Content-type": "text/plain; charset=utf-8"}
  25. await req.respond(Http200, "Hello World", headers.newHttpHeaders())
  26. server.listen(Port(0)) # or Port(8080) to hardcode the standard HTTP port.
  27. let port = server.getPort
  28. echo "test this with: curl localhost:" & $port.uint16 & "/"
  29. while true:
  30. if server.shouldAcceptRequest():
  31. await server.acceptRequest(cb)
  32. else:
  33. # too many concurrent connections, `maxFDs` exceeded
  34. # wait 500ms for FDs to be closed
  35. await sleepAsync(500)
  36. waitFor main()
  37. import asyncnet, asyncdispatch, parseutils, uri, strutils
  38. import httpcore
  39. from nativesockets import getLocalAddr, Domain, AF_INET, AF_INET6
  40. import std/private/since
  41. export httpcore except parseHeader
  42. const
  43. maxLine = 8*1024
  44. # TODO: If it turns out that the decisions that asynchttpserver makes
  45. # explicitly, about whether to close the client sockets or upgrade them are
  46. # wrong, then add a return value which determines what to do for the callback.
  47. # Also, maybe move `client` out of `Request` object and into the args for
  48. # the proc.
  49. type
  50. Request* = object
  51. client*: AsyncSocket # TODO: Separate this into a Response object?
  52. reqMethod*: HttpMethod
  53. headers*: HttpHeaders
  54. protocol*: tuple[orig: string, major, minor: int]
  55. url*: Uri
  56. hostname*: string ## The hostname of the client that made the request.
  57. body*: string
  58. AsyncHttpServer* = ref object
  59. socket: AsyncSocket
  60. reuseAddr: bool
  61. reusePort: bool
  62. maxBody: int ## The maximum content-length that will be read for the body.
  63. maxFDs: int
  64. proc getPort*(self: AsyncHttpServer): Port {.since: (1, 5, 1).} =
  65. ## Returns the port `self` was bound to.
  66. ##
  67. ## Useful for identifying what port `self` is bound to, if it
  68. ## was chosen automatically, for example via `listen(Port(0))`.
  69. runnableExamples:
  70. from std/nativesockets import Port
  71. let server = newAsyncHttpServer()
  72. server.listen(Port(0))
  73. assert server.getPort.uint16 > 0
  74. server.close()
  75. result = getLocalAddr(self.socket)[1]
  76. proc newAsyncHttpServer*(reuseAddr = true, reusePort = false,
  77. maxBody = 8388608): AsyncHttpServer =
  78. ## Creates a new `AsyncHttpServer` instance.
  79. result = AsyncHttpServer(reuseAddr: reuseAddr, reusePort: reusePort, maxBody: maxBody)
  80. proc addHeaders(msg: var string, headers: HttpHeaders) =
  81. for k, v in headers:
  82. msg.add(k & ": " & v & "\c\L")
  83. proc sendHeaders*(req: Request, headers: HttpHeaders): Future[void] =
  84. ## Sends the specified headers to the requesting client.
  85. var msg = ""
  86. addHeaders(msg, headers)
  87. return req.client.send(msg)
  88. proc respond*(req: Request, code: HttpCode, content: string,
  89. headers: HttpHeaders = nil): Future[void] =
  90. ## Responds to the request with the specified `HttpCode`, headers and
  91. ## content.
  92. ##
  93. ## This procedure will **not** close the client socket.
  94. ##
  95. ## Example:
  96. ##
  97. ## .. code-block:: Nim
  98. ## import std/json
  99. ## proc handler(req: Request) {.async.} =
  100. ## if req.url.path == "/hello-world":
  101. ## let msg = %* {"message": "Hello World"}
  102. ## let headers = newHttpHeaders([("Content-Type","application/json")])
  103. ## await req.respond(Http200, $msg, headers)
  104. ## else:
  105. ## await req.respond(Http404, "Not Found")
  106. var msg = "HTTP/1.1 " & $code & "\c\L"
  107. if headers != nil:
  108. msg.addHeaders(headers)
  109. # If the headers did not contain a Content-Length use our own
  110. if headers.isNil() or not headers.hasKey("Content-Length"):
  111. msg.add("Content-Length: ")
  112. # this particular way saves allocations:
  113. msg.addInt content.len
  114. msg.add "\c\L"
  115. msg.add "\c\L"
  116. msg.add(content)
  117. result = req.client.send(msg)
  118. proc respondError(req: Request, code: HttpCode): Future[void] =
  119. ## Responds to the request with the specified `HttpCode`.
  120. let content = $code
  121. var msg = "HTTP/1.1 " & content & "\c\L"
  122. msg.add("Content-Length: " & $content.len & "\c\L\c\L")
  123. msg.add(content)
  124. result = req.client.send(msg)
  125. proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] =
  126. var i = protocol.skipIgnoreCase("HTTP/")
  127. if i != 5:
  128. raise newException(ValueError, "Invalid request protocol. Got: " &
  129. protocol)
  130. result.orig = protocol
  131. i.inc protocol.parseSaturatedNatural(result.major, i)
  132. i.inc # Skip .
  133. i.inc protocol.parseSaturatedNatural(result.minor, i)
  134. proc sendStatus(client: AsyncSocket, status: string): Future[void] =
  135. client.send("HTTP/1.1 " & status & "\c\L\c\L")
  136. func hasChunkedEncoding(request: Request): bool =
  137. ## Searches for a chunked transfer encoding
  138. const transferEncoding = "Transfer-Encoding"
  139. if request.headers.hasKey(transferEncoding):
  140. for encoding in seq[string](request.headers[transferEncoding]):
  141. if "chunked" == encoding.strip:
  142. # Returns true if it is both an HttpPost and has chunked encoding
  143. return request.reqMethod == HttpPost
  144. return false
  145. proc processRequest(
  146. server: AsyncHttpServer,
  147. req: FutureVar[Request],
  148. client: AsyncSocket,
  149. address: string,
  150. lineFut: FutureVar[string],
  151. callback: proc (request: Request): Future[void] {.closure, gcsafe.},
  152. ): Future[bool] {.async.} =
  153. # Alias `request` to `req.mget()` so we don't have to write `mget` everywhere.
  154. template request(): Request =
  155. req.mget()
  156. # GET /path HTTP/1.1
  157. # Header: val
  158. # \n
  159. request.headers.clear()
  160. request.body = ""
  161. request.hostname.shallowCopy(address)
  162. assert client != nil
  163. request.client = client
  164. # We should skip at least one empty line before the request
  165. # https://tools.ietf.org/html/rfc7230#section-3.5
  166. for i in 0..1:
  167. lineFut.mget().setLen(0)
  168. lineFut.clean()
  169. await client.recvLineInto(lineFut, maxLength = maxLine) # TODO: Timeouts.
  170. if lineFut.mget == "":
  171. client.close()
  172. return false
  173. if lineFut.mget.len > maxLine:
  174. await request.respondError(Http413)
  175. client.close()
  176. return false
  177. if lineFut.mget != "\c\L":
  178. break
  179. # First line - GET /path HTTP/1.1
  180. var i = 0
  181. for linePart in lineFut.mget.split(' '):
  182. case i
  183. of 0:
  184. case linePart
  185. of "GET": request.reqMethod = HttpGet
  186. of "POST": request.reqMethod = HttpPost
  187. of "HEAD": request.reqMethod = HttpHead
  188. of "PUT": request.reqMethod = HttpPut
  189. of "DELETE": request.reqMethod = HttpDelete
  190. of "PATCH": request.reqMethod = HttpPatch
  191. of "OPTIONS": request.reqMethod = HttpOptions
  192. of "CONNECT": request.reqMethod = HttpConnect
  193. of "TRACE": request.reqMethod = HttpTrace
  194. else:
  195. asyncCheck request.respondError(Http400)
  196. return true # Retry processing of request
  197. of 1:
  198. try:
  199. parseUri(linePart, request.url)
  200. except ValueError:
  201. asyncCheck request.respondError(Http400)
  202. return true
  203. of 2:
  204. try:
  205. request.protocol = parseProtocol(linePart)
  206. except ValueError:
  207. asyncCheck request.respondError(Http400)
  208. return true
  209. else:
  210. await request.respondError(Http400)
  211. return true
  212. inc i
  213. # Headers
  214. while true:
  215. i = 0
  216. lineFut.mget.setLen(0)
  217. lineFut.clean()
  218. await client.recvLineInto(lineFut, maxLength = maxLine)
  219. if lineFut.mget == "":
  220. client.close(); return false
  221. if lineFut.mget.len > maxLine:
  222. await request.respondError(Http413)
  223. client.close(); return false
  224. if lineFut.mget == "\c\L": break
  225. let (key, value) = parseHeader(lineFut.mget)
  226. request.headers[key] = value
  227. # Ensure the client isn't trying to DoS us.
  228. if request.headers.len > headerLimit:
  229. await client.sendStatus("400 Bad Request")
  230. request.client.close()
  231. return false
  232. if request.reqMethod == HttpPost:
  233. # Check for Expect header
  234. if request.headers.hasKey("Expect"):
  235. if "100-continue" in request.headers["Expect"]:
  236. await client.sendStatus("100 Continue")
  237. else:
  238. await client.sendStatus("417 Expectation Failed")
  239. # Read the body
  240. # - Check for Content-length header
  241. if request.headers.hasKey("Content-Length"):
  242. var contentLength = 0
  243. if parseSaturatedNatural(request.headers["Content-Length"], contentLength) == 0:
  244. await request.respond(Http400, "Bad Request. Invalid Content-Length.")
  245. return true
  246. else:
  247. if contentLength > server.maxBody:
  248. await request.respondError(Http413)
  249. return false
  250. request.body = await client.recv(contentLength)
  251. if request.body.len != contentLength:
  252. await request.respond(Http400, "Bad Request. Content-Length does not match actual.")
  253. return true
  254. elif hasChunkedEncoding(request):
  255. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
  256. var sizeOrData = 0
  257. var bytesToRead = 0
  258. request.body = ""
  259. while true:
  260. lineFut.mget.setLen(0)
  261. lineFut.clean()
  262. # The encoding format alternates between specifying a number of bytes to read
  263. # and the data to be read, of the previously specified size
  264. if sizeOrData mod 2 == 0:
  265. # Expect a number of chars to read
  266. await client.recvLineInto(lineFut, maxLength = maxLine)
  267. try:
  268. bytesToRead = lineFut.mget.parseHexInt
  269. except ValueError:
  270. # Malformed request
  271. await request.respond(Http411, ("Invalid chunked transfer encoding - " &
  272. "chunk data size must be hex encoded"))
  273. return true
  274. else:
  275. if bytesToRead == 0:
  276. # Done reading chunked data
  277. break
  278. # Read bytesToRead and add to body
  279. let chunk = await client.recv(bytesToRead)
  280. request.body.add(chunk)
  281. # Skip \r\n (chunk terminating bytes per spec)
  282. let separator = await client.recv(2)
  283. if separator != "\r\n":
  284. await request.respond(Http400, "Bad Request. Encoding separator must be \\r\\n")
  285. return true
  286. inc sizeOrData
  287. elif request.reqMethod == HttpPost:
  288. await request.respond(Http411, "Content-Length required.")
  289. return true
  290. # Call the user's callback.
  291. await callback(request)
  292. if "upgrade" in request.headers.getOrDefault("connection"):
  293. return false
  294. # The request has been served, from this point on returning `true` means the
  295. # connection will not be closed and will be kept in the connection pool.
  296. # Persistent connections
  297. if (request.protocol == HttpVer11 and
  298. cmpIgnoreCase(request.headers.getOrDefault("connection"), "close") != 0) or
  299. (request.protocol == HttpVer10 and
  300. cmpIgnoreCase(request.headers.getOrDefault("connection"), "keep-alive") == 0):
  301. # In HTTP 1.1 we assume that connection is persistent. Unless connection
  302. # header states otherwise.
  303. # In HTTP 1.0 we assume that the connection should not be persistent.
  304. # Unless the connection header states otherwise.
  305. return true
  306. else:
  307. request.client.close()
  308. return false
  309. proc processClient(server: AsyncHttpServer, client: AsyncSocket, address: string,
  310. callback: proc (request: Request):
  311. Future[void] {.closure, gcsafe.}) {.async.} =
  312. var request = newFutureVar[Request]("asynchttpserver.processClient")
  313. request.mget().url = initUri()
  314. request.mget().headers = newHttpHeaders()
  315. var lineFut = newFutureVar[string]("asynchttpserver.processClient")
  316. lineFut.mget() = newStringOfCap(80)
  317. while not client.isClosed:
  318. let retry = await processRequest(
  319. server, request, client, address, lineFut, callback
  320. )
  321. if not retry:
  322. client.close()
  323. break
  324. const
  325. nimMaxDescriptorsFallback* {.intdefine.} = 16_000 ## fallback value for \
  326. ## when `maxDescriptors` is not available.
  327. ## This can be set on the command line during compilation
  328. ## via `-d:nimMaxDescriptorsFallback=N`
  329. proc listen*(server: AsyncHttpServer; port: Port; address = ""; domain = AF_INET) =
  330. ## Listen to the given port and address.
  331. when declared(maxDescriptors):
  332. server.maxFDs = try: maxDescriptors() except: nimMaxDescriptorsFallback
  333. else:
  334. server.maxFDs = nimMaxDescriptorsFallback
  335. server.socket = newAsyncSocket(domain)
  336. if server.reuseAddr:
  337. server.socket.setSockOpt(OptReuseAddr, true)
  338. if server.reusePort:
  339. server.socket.setSockOpt(OptReusePort, true)
  340. server.socket.bindAddr(port, address)
  341. server.socket.listen()
  342. proc shouldAcceptRequest*(server: AsyncHttpServer;
  343. assumedDescriptorsPerRequest = 5): bool {.inline.} =
  344. ## Returns true if the process's current number of opened file
  345. ## descriptors is still within the maximum limit and so it's reasonable to
  346. ## accept yet another request.
  347. result = assumedDescriptorsPerRequest < 0 or
  348. (activeDescriptors() + assumedDescriptorsPerRequest < server.maxFDs)
  349. proc acceptRequest*(server: AsyncHttpServer,
  350. callback: proc (request: Request): Future[void] {.closure, gcsafe.}) {.async.} =
  351. ## Accepts a single request. Write an explicit loop around this proc so that
  352. ## errors can be handled properly.
  353. var (address, client) = await server.socket.acceptAddr()
  354. asyncCheck processClient(server, client, address, callback)
  355. proc serve*(server: AsyncHttpServer, port: Port,
  356. callback: proc (request: Request): Future[void] {.closure, gcsafe.},
  357. address = "";
  358. assumedDescriptorsPerRequest = -1;
  359. domain = AF_INET) {.async.} =
  360. ## Starts the process of listening for incoming HTTP connections on the
  361. ## specified address and port.
  362. ##
  363. ## When a request is made by a client the specified callback will be called.
  364. ##
  365. ## If `assumedDescriptorsPerRequest` is 0 or greater the server cares about
  366. ## the process's maximum file descriptor limit. It then ensures that the
  367. ## process still has the resources for `assumedDescriptorsPerRequest`
  368. ## file descriptors before accepting a connection.
  369. ##
  370. ## You should prefer to call `acceptRequest` instead with a custom server
  371. ## loop so that you're in control over the error handling and logging.
  372. listen server, port, address, domain
  373. while true:
  374. if shouldAcceptRequest(server, assumedDescriptorsPerRequest):
  375. var (address, client) = await server.socket.acceptAddr()
  376. asyncCheck processClient(server, client, address, callback)
  377. else:
  378. poll()
  379. #echo(f.isNil)
  380. #echo(f.repr)
  381. proc close*(server: AsyncHttpServer) =
  382. ## Terminates the async http server instance.
  383. server.socket.close()