httpserver.lua 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. -- httpserver
  2. -- Author: Marcos Kirsch
  3. -- Starts web server in the specified port.
  4. return function (port)
  5. local s = net.createServer(net.TCP, 10) -- 10 seconds client timeout
  6. s:listen(
  7. port,
  8. function (connection)
  9. -- This variable holds the thread (actually a Lua coroutine) used for sending data back to the user.
  10. -- We do it in a separate thread because we need to send in little chunks and wait for the onSent event
  11. -- before we can send more, or we risk overflowing the mcu's buffer.
  12. local connectionThread
  13. local allowStatic = {GET=true, HEAD=true, POST=false, PUT=false, DELETE=false, TRACE=false, OPTIONS=false, CONNECT=false, PATCH=false}
  14. -- Pretty log function.
  15. local function log(connection, msg, optionalMsg)
  16. local port, ip = connection:getpeer()
  17. if(optionalMsg == nil) then
  18. print(ip .. ":" .. port, msg)
  19. else
  20. print(ip .. ":" .. port, msg, optionalMsg)
  21. end
  22. end
  23. local function startServing(fileServeFunction, connection, req, args)
  24. connectionThread = coroutine.create(function(fileServeFunction, bufferedConnection, req, args)
  25. fileServeFunction(bufferedConnection, req, args)
  26. -- The bufferedConnection may still hold some data that hasn't been sent. Flush it before closing.
  27. if not bufferedConnection:flush() then
  28. log(connection, "closing connection", "no (more) data")
  29. connection:close()
  30. connectionThread = nil
  31. collectgarbage()
  32. end
  33. end)
  34. local BufferedConnectionClass = dofile("httpserver-connection.lc")
  35. local bufferedConnection = BufferedConnectionClass:new(connection)
  36. local status, err = coroutine.resume(connectionThread, fileServeFunction, bufferedConnection, req, args)
  37. if not status then
  38. log(connection, "Error: "..err)
  39. log(connection, "closing connection", "error")
  40. connection:close()
  41. connectionThread = nil
  42. collectgarbage()
  43. end
  44. end
  45. local function handleRequest(connection, req)
  46. collectgarbage()
  47. local method = req.method
  48. local uri = req.uri
  49. local fileServeFunction = nil
  50. if #(uri.file) > 32 then
  51. -- nodemcu-firmware cannot handle long filenames.
  52. uri.args = {code = 400, errorString = "Bad Request", logFunction = log}
  53. fileServeFunction = dofile("httpserver-error.lc")
  54. else
  55. local fileExists = file.open(uri.file, "r")
  56. file.close()
  57. if not fileExists then
  58. -- gzip check
  59. fileExists = file.open(uri.file .. ".gz", "r")
  60. file.close()
  61. if fileExists then
  62. --print("gzip variant exists, serving that one")
  63. uri.file = uri.file .. ".gz"
  64. uri.isGzipped = true
  65. end
  66. end
  67. if not fileExists then
  68. uri.args = {code = 404, errorString = "Not Found", logFunction = log}
  69. fileServeFunction = dofile("httpserver-error.lc")
  70. elseif uri.isScript then
  71. fileServeFunction = dofile(uri.file)
  72. else
  73. if allowStatic[method] then
  74. uri.args = {file = uri.file, ext = uri.ext, isGzipped = uri.isGzipped}
  75. fileServeFunction = dofile("httpserver-static.lc")
  76. else
  77. uri.args = {code = 405, errorString = "Method not supported", logFunction = log}
  78. fileServeFunction = dofile("httpserver-error.lc")
  79. end
  80. end
  81. end
  82. startServing(fileServeFunction, connection, req, uri.args)
  83. end
  84. local function onReceive(connection, payload)
  85. collectgarbage()
  86. local conf = dofile("httpserver-conf.lc")
  87. local auth
  88. local user = "Anonymous"
  89. -- as suggest by anyn99 (https://github.com/marcoskirsch/nodemcu-httpserver/issues/36#issuecomment-167442461)
  90. -- Some browsers send the POST data in multiple chunks.
  91. -- Collect data packets until the size of HTTP body meets the Content-Length stated in header
  92. if payload:find("Content%-Length:") or bBodyMissing then
  93. if fullPayload then fullPayload = fullPayload .. payload else fullPayload = payload end
  94. if (tonumber(string.match(fullPayload, "%d+", fullPayload:find("Content%-Length:")+16)) > #fullPayload:sub(fullPayload:find("\r\n\r\n", 1, true)+4, #fullPayload)) then
  95. bBodyMissing = true
  96. return
  97. else
  98. --print("HTTP packet assembled! size: "..#fullPayload)
  99. payload = fullPayload
  100. fullPayload, bBodyMissing = nil
  101. end
  102. end
  103. collectgarbage()
  104. -- parse payload and decide what to serve.
  105. local req = dofile("httpserver-request.lc")(payload)
  106. log(connection, req.method, req.request)
  107. if conf.auth.enabled then
  108. auth = dofile("httpserver-basicauth.lc")
  109. user = auth.authenticate(payload) -- authenticate returns nil on failed auth
  110. end
  111. if user and req.methodIsValid and (req.method == "GET" or req.method == "POST" or req.method == "PUT") then
  112. handleRequest(connection, req, handleError)
  113. else
  114. local args = {}
  115. local fileServeFunction = dofile("httpserver-error.lc")
  116. if not user then
  117. args = {code = 401, errorString = "Not Authorized", headers = {auth.authErrorHeader()}, logFunction = log}
  118. elseif req.methodIsValid then
  119. args = {code = 501, errorString = "Not Implemented", logFunction = log}
  120. else
  121. args = {code = 400, errorString = "Bad Request", logFunction = log}
  122. end
  123. startServing(fileServeFunction, connection, req, args)
  124. end
  125. end
  126. local function onSent(connection, payload)
  127. collectgarbage()
  128. if connectionThread then
  129. local connectionThreadStatus = coroutine.status(connectionThread)
  130. if connectionThreadStatus == "suspended" then
  131. -- Not finished sending file, resume.
  132. local status, err = coroutine.resume(connectionThread)
  133. if not status then
  134. log(connection, "Error: "..err)
  135. log(connection, "closing connection", "error")
  136. connection:close()
  137. connectionThread = nil
  138. collectgarbage()
  139. end
  140. elseif connectionThreadStatus == "dead" then
  141. -- We're done sending file.
  142. log(connection, "closing connection","thread is dead")
  143. connection:close()
  144. connectionThread = nil
  145. collectgarbage()
  146. end
  147. end
  148. end
  149. local function onDisconnect(connection, payload)
  150. -- this should rather be a log call, but log is not available here
  151. -- print("disconnected")
  152. if connectionThread then
  153. connectionThread = nil
  154. collectgarbage()
  155. end
  156. end
  157. connection:on("receive", onReceive)
  158. connection:on("sent", onSent)
  159. connection:on("disconnection", onDisconnect)
  160. end
  161. )
  162. return s
  163. end