httpserver.lua 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. ------------------------------------------------------------------------------
  2. -- HTTP server module
  3. --
  4. -- LICENCE: http://opensource.org/licenses/MIT
  5. -- Vladimir Dronnikov <dronnikov@gmail.com>
  6. ------------------------------------------------------------------------------
  7. local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring
  8. local http
  9. do
  10. ------------------------------------------------------------------------------
  11. -- request methods
  12. ------------------------------------------------------------------------------
  13. local make_req = function(conn, method, url)
  14. return {
  15. conn = conn,
  16. method = method,
  17. url = url,
  18. }
  19. end
  20. ------------------------------------------------------------------------------
  21. -- response methods
  22. ------------------------------------------------------------------------------
  23. local make_res = function(csend, cfini)
  24. local send = function(self, data, status)
  25. -- TODO: req.send should take care of response headers!
  26. if self.send_header then
  27. csend("HTTP/1.1 ")
  28. csend(tostring(status or 200))
  29. -- TODO: real HTTP status code/name table
  30. csend(" OK\r\n")
  31. -- we use chunked transfer encoding, to not deal with Content-Length:
  32. -- response header
  33. self:send_header("Transfer-Encoding", "chunked")
  34. -- TODO: send standard response headers, such as Server:, Date:
  35. end
  36. if data then
  37. -- NB: no headers allowed after response body started
  38. if self.send_header then
  39. self.send_header = nil
  40. -- end response headers
  41. csend("\r\n")
  42. end
  43. -- chunked transfer encoding
  44. csend(("%X\r\n"):format(#data))
  45. csend(data)
  46. csend("\r\n")
  47. end
  48. end
  49. local send_header = function(_, name, value)
  50. -- NB: quite a naive implementation
  51. csend(name)
  52. csend(": ")
  53. csend(value)
  54. csend("\r\n")
  55. end
  56. -- finalize request, optionally sending data
  57. local finish = function(self, data, status)
  58. -- NB: res.send takes care of response headers
  59. if data then
  60. self:send(data, status)
  61. end
  62. -- finalize chunked transfer encoding
  63. csend("0\r\n\r\n")
  64. -- close connection
  65. cfini()
  66. end
  67. --
  68. local res = { }
  69. res.send_header = send_header
  70. res.send = send
  71. res.finish = finish
  72. return res
  73. end
  74. ------------------------------------------------------------------------------
  75. -- HTTP parser
  76. ------------------------------------------------------------------------------
  77. local http_handler = function(handler)
  78. return function(conn)
  79. local csend = (require "fifosock").wrap(conn)
  80. local req, res
  81. local buf = ""
  82. local method, url
  83. local cfini = function()
  84. conn:on("receive", nil)
  85. conn:on("disconnection", nil)
  86. csend(function()
  87. conn:on("sent", nil)
  88. conn:close()
  89. end)
  90. end
  91. local ondisconnect = function(connection)
  92. connection:on("sent", nil)
  93. collectgarbage("collect")
  94. end
  95. -- header parser
  96. local cnt_len = 0
  97. local onheader = function(_, k, v)
  98. -- TODO: look for Content-Type: header
  99. -- to help parse body
  100. -- parse content length to know body length
  101. if k == "content-length" then
  102. cnt_len = tonumber(v)
  103. end
  104. if k == "expect" and v == "100-continue" then
  105. csend("HTTP/1.1 100 Continue\r\n")
  106. end
  107. -- delegate to request object
  108. if req and req.onheader then
  109. req:onheader(k, v)
  110. end
  111. end
  112. -- body data handler
  113. local body_len = 0
  114. local ondata = function(_, chunk)
  115. -- feed request data to request handler
  116. if not req or not req.ondata then return end
  117. req:ondata(chunk)
  118. -- NB: once length of seen chunks equals Content-Length:
  119. -- ondata(conn) is called
  120. body_len = body_len + #chunk
  121. -- print("-B", #chunk, body_len, cnt_len, node.heap())
  122. if body_len >= cnt_len then
  123. req:ondata()
  124. end
  125. end
  126. local onreceive = function(connection, chunk)
  127. -- merge chunks in buffer
  128. if buf then
  129. buf = buf .. chunk
  130. else
  131. buf = chunk
  132. end
  133. -- consume buffer line by line
  134. while #buf > 0 do
  135. -- extract line
  136. local e = buf:find("\r\n", 1, true)
  137. if not e then break end
  138. local line = buf:sub(1, e - 1)
  139. buf = buf:sub(e + 2)
  140. -- method, url?
  141. if not method then
  142. do
  143. local _
  144. -- NB: just version 1.1 assumed
  145. _, _, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
  146. end
  147. if method then
  148. -- make request and response objects
  149. req = make_req(connection, method, url)
  150. res = make_res(csend, cfini)
  151. end
  152. -- spawn request handler
  153. handler(req, res)
  154. -- header line?
  155. elseif #line > 0 then
  156. -- parse header
  157. local _, _, k, v = line:find("^([%w-]+):%s*(.+)")
  158. -- header seems ok?
  159. if k then
  160. k = k:lower()
  161. onheader(connection, k, v)
  162. end
  163. -- headers end
  164. else
  165. -- NB: we explicitly reassign receive handler so that
  166. -- next received chunks go directly to body handler
  167. connection:on("receive", ondata)
  168. -- NB: we feed the rest of the buffer as starting chunk of body
  169. ondata(connection, buf)
  170. -- buffer no longer needed
  171. buf = nil
  172. -- parser done
  173. break
  174. end
  175. end
  176. end
  177. conn:on("receive", onreceive)
  178. conn:on("disconnection", ondisconnect)
  179. end
  180. end
  181. ------------------------------------------------------------------------------
  182. -- HTTP server
  183. ------------------------------------------------------------------------------
  184. local srv
  185. local createServer = function(port, handler)
  186. -- NB: only one server at a time
  187. if srv then srv:close() end
  188. srv = net.createServer(net.TCP, 15)
  189. -- listen
  190. srv:listen(port, http_handler(handler))
  191. return srv
  192. end
  193. ------------------------------------------------------------------------------
  194. -- HTTP server methods
  195. ------------------------------------------------------------------------------
  196. http = {
  197. createServer = createServer,
  198. }
  199. end
  200. return http