asynchttpserver.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 you should use a reverse proxy (for example nginx) instead of
  14. ## allowing users to connect directly to this server.
  15. ##
  16. ## Basic usage
  17. ## ===========
  18. ##
  19. ## This example will create an HTTP server on port 8080. The server will
  20. ## respond to all requests with a ``200 OK`` response code and "Hello World"
  21. ## as the response body.
  22. ##
  23. ## .. code-block::nim
  24. ## import asynchttpserver, asyncdispatch
  25. ##
  26. ## var server = newAsyncHttpServer()
  27. ## proc cb(req: Request) {.async.} =
  28. ## await req.respond(Http200, "Hello World")
  29. ##
  30. ## waitFor server.serve(Port(8080), cb)
  31. import tables, asyncnet, asyncdispatch, parseutils, uri, strutils
  32. import httpcore
  33. export httpcore except parseHeader
  34. const
  35. maxLine = 8*1024
  36. # TODO: If it turns out that the decisions that asynchttpserver makes
  37. # explicitly, about whether to close the client sockets or upgrade them are
  38. # wrong, then add a return value which determines what to do for the callback.
  39. # Also, maybe move `client` out of `Request` object and into the args for
  40. # the proc.
  41. type
  42. Request* = object
  43. client*: AsyncSocket # TODO: Separate this into a Response object?
  44. reqMethod*: HttpMethod
  45. headers*: HttpHeaders
  46. protocol*: tuple[orig: string, major, minor: int]
  47. url*: Uri
  48. hostname*: string ## The hostname of the client that made the request.
  49. body*: string
  50. AsyncHttpServer* = ref object
  51. socket: AsyncSocket
  52. reuseAddr: bool
  53. reusePort: bool
  54. maxBody: int ## The maximum content-length that will be read for the body.
  55. proc newAsyncHttpServer*(reuseAddr = true, reusePort = false,
  56. maxBody = 8388608): AsyncHttpServer =
  57. ## Creates a new ``AsyncHttpServer`` instance.
  58. new result
  59. result.reuseAddr = reuseAddr
  60. result.reusePort = reusePort
  61. result.maxBody = maxBody
  62. proc addHeaders(msg: var string, headers: HttpHeaders) =
  63. for k, v in headers:
  64. msg.add(k & ": " & v & "\c\L")
  65. proc sendHeaders*(req: Request, headers: HttpHeaders): Future[void] =
  66. ## Sends the specified headers to the requesting client.
  67. var msg = ""
  68. addHeaders(msg, headers)
  69. return req.client.send(msg)
  70. proc respond*(req: Request, code: HttpCode, content: string,
  71. headers: HttpHeaders = nil): Future[void] =
  72. ## Responds to the request with the specified ``HttpCode``, headers and
  73. ## content.
  74. ##
  75. ## This procedure will **not** close the client socket.
  76. ##
  77. ## Example:
  78. ##
  79. ## .. code-block::nim
  80. ## import json
  81. ## proc handler(req: Request) {.async.} =
  82. ## if req.url.path == "/hello-world":
  83. ## let msg = %* {"message": "Hello World"}
  84. ## let headers = newHttpHeaders([("Content-Type","application/json")])
  85. ## await req.respond(Http200, $msg, headers)
  86. ## else:
  87. ## await req.respond(Http404, "Not Found")
  88. var msg = "HTTP/1.1 " & $code & "\c\L"
  89. if headers != nil:
  90. msg.addHeaders(headers)
  91. msg.add("Content-Length: ")
  92. # this particular way saves allocations:
  93. msg.add content.len
  94. msg.add "\c\L\c\L"
  95. msg.add(content)
  96. result = req.client.send(msg)
  97. proc respondError(req: Request, code: HttpCode): Future[void] =
  98. ## Responds to the request with the specified ``HttpCode``.
  99. let content = $code
  100. var msg = "HTTP/1.1 " & content & "\c\L"
  101. msg.add("Content-Length: " & $content.len & "\c\L\c\L")
  102. msg.add(content)
  103. result = req.client.send(msg)
  104. proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] =
  105. var i = protocol.skipIgnoreCase("HTTP/")
  106. if i != 5:
  107. raise newException(ValueError, "Invalid request protocol. Got: " &
  108. protocol)
  109. result.orig = protocol
  110. i.inc protocol.parseSaturatedNatural(result.major, i)
  111. i.inc # Skip .
  112. i.inc protocol.parseSaturatedNatural(result.minor, i)
  113. proc sendStatus(client: AsyncSocket, status: string): Future[void] =
  114. client.send("HTTP/1.1 " & status & "\c\L\c\L")
  115. proc parseUppercaseMethod(name: string): HttpMethod =
  116. result =
  117. case name
  118. of "GET": HttpGet
  119. of "POST": HttpPost
  120. of "HEAD": HttpHead
  121. of "PUT": HttpPut
  122. of "DELETE": HttpDelete
  123. of "PATCH": HttpPatch
  124. of "OPTIONS": HttpOptions
  125. of "CONNECT": HttpConnect
  126. of "TRACE": HttpTrace
  127. else: raise newException(ValueError, "Invalid HTTP method " & name)
  128. proc processRequest(
  129. server: AsyncHttpServer,
  130. req: FutureVar[Request],
  131. client: AsyncSocket,
  132. address: string,
  133. lineFut: FutureVar[string],
  134. callback: proc (request: Request): Future[void] {.closure, gcsafe.},
  135. ): Future[bool] {.async.} =
  136. # Alias `request` to `req.mget()` so we don't have to write `mget` everywhere.
  137. template request(): Request =
  138. req.mget()
  139. # GET /path HTTP/1.1
  140. # Header: val
  141. # \n
  142. request.headers.clear()
  143. request.body = ""
  144. request.hostname.shallowCopy(address)
  145. assert client != nil
  146. request.client = client
  147. # We should skip at least one empty line before the request
  148. # https://tools.ietf.org/html/rfc7230#section-3.5
  149. for i in 0..1:
  150. lineFut.mget().setLen(0)
  151. lineFut.clean()
  152. await client.recvLineInto(lineFut, maxLength = maxLine) # TODO: Timeouts.
  153. if lineFut.mget == "":
  154. client.close()
  155. return false
  156. if lineFut.mget.len > maxLine:
  157. await request.respondError(Http413)
  158. client.close()
  159. return false
  160. if lineFut.mget != "\c\L":
  161. break
  162. # First line - GET /path HTTP/1.1
  163. var i = 0
  164. for linePart in lineFut.mget.split(' '):
  165. case i
  166. of 0:
  167. try:
  168. request.reqMethod = parseUppercaseMethod(linePart)
  169. except ValueError:
  170. asyncCheck request.respondError(Http400)
  171. return true # Retry processing of request
  172. of 1:
  173. try:
  174. parseUri(linePart, request.url)
  175. except ValueError:
  176. asyncCheck request.respondError(Http400)
  177. return true
  178. of 2:
  179. try:
  180. request.protocol = parseProtocol(linePart)
  181. except ValueError:
  182. asyncCheck request.respondError(Http400)
  183. return true
  184. else:
  185. await request.respondError(Http400)
  186. return true
  187. inc i
  188. # Headers
  189. while true:
  190. i = 0
  191. lineFut.mget.setLen(0)
  192. lineFut.clean()
  193. await client.recvLineInto(lineFut, maxLength = maxLine)
  194. if lineFut.mget == "":
  195. client.close(); return false
  196. if lineFut.mget.len > maxLine:
  197. await request.respondError(Http413)
  198. client.close(); return false
  199. if lineFut.mget == "\c\L": break
  200. let (key, value) = parseHeader(lineFut.mget)
  201. request.headers[key] = value
  202. # Ensure the client isn't trying to DoS us.
  203. if request.headers.len > headerLimit:
  204. await client.sendStatus("400 Bad Request")
  205. request.client.close()
  206. return false
  207. if request.reqMethod == HttpPost:
  208. # Check for Expect header
  209. if request.headers.hasKey("Expect"):
  210. if "100-continue" in request.headers["Expect"]:
  211. await client.sendStatus("100 Continue")
  212. else:
  213. await client.sendStatus("417 Expectation Failed")
  214. # Read the body
  215. # - Check for Content-length header
  216. if request.headers.hasKey("Content-Length"):
  217. var contentLength = 0
  218. if parseSaturatedNatural(request.headers["Content-Length"],
  219. contentLength) == 0:
  220. await request.respond(Http400, "Bad Request. Invalid Content-Length.")
  221. return true
  222. else:
  223. if contentLength > server.maxBody:
  224. await request.respondError(Http413)
  225. return false
  226. request.body = await client.recv(contentLength)
  227. if request.body.len != contentLength:
  228. await request.respond(Http400, "Bad Request. Content-Length does not match actual.")
  229. return true
  230. elif request.reqMethod == HttpPost:
  231. await request.respond(Http411, "Content-Length required.")
  232. return true
  233. # Call the user's callback.
  234. await callback(request)
  235. if "upgrade" in request.headers.getOrDefault("connection"):
  236. return false
  237. # The request has been served, from this point on returning `true` means the
  238. # connection will not be closed and will be kept in the connection pool.
  239. # Persistent connections
  240. if (request.protocol == HttpVer11 and
  241. cmpIgnoreCase(request.headers.getOrDefault("connection"), "close") != 0) or
  242. (request.protocol == HttpVer10 and
  243. cmpIgnoreCase(request.headers.getOrDefault("connection"), "keep-alive") == 0):
  244. # In HTTP 1.1 we assume that connection is persistent. Unless connection
  245. # header states otherwise.
  246. # In HTTP 1.0 we assume that the connection should not be persistent.
  247. # Unless the connection header states otherwise.
  248. return true
  249. else:
  250. request.client.close()
  251. return false
  252. proc processClient(server: AsyncHttpServer, client: AsyncSocket, address: string,
  253. callback: proc (request: Request):
  254. Future[void] {.closure, gcsafe.}) {.async.} =
  255. var request = newFutureVar[Request]("asynchttpserver.processClient")
  256. request.mget().url = initUri()
  257. request.mget().headers = newHttpHeaders()
  258. var lineFut = newFutureVar[string]("asynchttpserver.processClient")
  259. lineFut.mget() = newStringOfCap(80)
  260. while not client.isClosed:
  261. let retry = await processRequest(
  262. server, request, client, address, lineFut, callback
  263. )
  264. if not retry: break
  265. proc serve*(server: AsyncHttpServer, port: Port,
  266. callback: proc (request: Request): Future[void] {.closure, gcsafe.},
  267. address = "") {.async.} =
  268. ## Starts the process of listening for incoming HTTP connections on the
  269. ## specified address and port.
  270. ##
  271. ## When a request is made by a client the specified callback will be called.
  272. server.socket = newAsyncSocket()
  273. if server.reuseAddr:
  274. server.socket.setSockOpt(OptReuseAddr, true)
  275. if server.reusePort:
  276. server.socket.setSockOpt(OptReusePort, true)
  277. server.socket.bindAddr(port, address)
  278. server.socket.listen()
  279. while true:
  280. var (address, client) = await server.socket.acceptAddr()
  281. asyncCheck processClient(server, client, address, callback)
  282. #echo(f.isNil)
  283. #echo(f.repr)
  284. proc close*(server: AsyncHttpServer) =
  285. ## Terminates the async http server instance.
  286. server.socket.close()
  287. when not defined(testing) and isMainModule:
  288. proc main =
  289. var server = newAsyncHttpServer()
  290. proc cb(req: Request) {.async.} =
  291. #echo(req.reqMethod, " ", req.url)
  292. #echo(req.headers)
  293. let headers = {"Date": "Tue, 29 Apr 2014 23:40:08 GMT",
  294. "Content-type": "text/plain; charset=utf-8"}
  295. await req.respond(Http200, "Hello World", headers.newHttpHeaders())
  296. asyncCheck server.serve(Port(5555), cb)
  297. runForever()
  298. main()