httpserver.lua 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 = false
  56. if not file.exists(uri.file) then
  57. -- print(uri.file .. " not found, checking gz version...")
  58. -- gzip check
  59. if file.exists(uri.file .. ".gz") then
  60. -- print("gzip variant exists, serving that one")
  61. uri.file = uri.file .. ".gz"
  62. uri.isGzipped = true
  63. fileExists = true
  64. end
  65. else
  66. fileExists = true
  67. end
  68. if not fileExists then
  69. uri.args = {code = 404, errorString = "Not Found", logFunction = log}
  70. fileServeFunction = dofile("httpserver-error.lc")
  71. elseif uri.isScript then
  72. fileServeFunction = dofile(uri.file)
  73. else
  74. if allowStatic[method] then
  75. uri.args = {file = uri.file, ext = uri.ext, isGzipped = uri.isGzipped}
  76. fileServeFunction = dofile("httpserver-static.lc")
  77. else
  78. uri.args = {code = 405, errorString = "Method not supported", logFunction = log}
  79. fileServeFunction = dofile("httpserver-error.lc")
  80. end
  81. end
  82. end
  83. startServing(fileServeFunction, connection, req, uri.args)
  84. end
  85. local function onReceive(connection, payload)
  86. collectgarbage()
  87. local conf = dofile("httpserver-conf.lc")
  88. local auth
  89. local user = "Anonymous"
  90. -- as suggest by anyn99 (https://github.com/marcoskirsch/nodemcu-httpserver/issues/36#issuecomment-167442461)
  91. -- Some browsers send the POST data in multiple chunks.
  92. -- Collect data packets until the size of HTTP body meets the Content-Length stated in header
  93. if payload:find("Content%-Length:") or bBodyMissing then
  94. if fullPayload then fullPayload = fullPayload .. payload else fullPayload = payload end
  95. if (tonumber(string.match(fullPayload, "%d+", fullPayload:find("Content%-Length:")+16)) > #fullPayload:sub(fullPayload:find("\r\n\r\n", 1, true)+4, #fullPayload)) then
  96. bBodyMissing = true
  97. return
  98. else
  99. --print("HTTP packet assembled! size: "..#fullPayload)
  100. payload = fullPayload
  101. fullPayload, bBodyMissing = nil
  102. end
  103. end
  104. collectgarbage()
  105. -- parse payload and decide what to serve.
  106. local req = dofile("httpserver-request.lc")(payload)
  107. log(connection, req.method, req.request)
  108. if conf.auth.enabled then
  109. auth = dofile("httpserver-basicauth.lc")
  110. user = auth.authenticate(payload) -- authenticate returns nil on failed auth
  111. end
  112. if user and req.methodIsValid and (req.method == "GET" or req.method == "POST" or req.method == "PUT") then
  113. req.user = user
  114. handleRequest(connection, req, handleError)
  115. else
  116. local args = {}
  117. local fileServeFunction = dofile("httpserver-error.lc")
  118. if not user then
  119. args = {code = 401, errorString = "Not Authorized", headers = {auth.authErrorHeader()}, logFunction = log}
  120. elseif req.methodIsValid then
  121. args = {code = 501, errorString = "Not Implemented", logFunction = log}
  122. else
  123. args = {code = 400, errorString = "Bad Request", logFunction = log}
  124. end
  125. startServing(fileServeFunction, connection, req, args)
  126. end
  127. end
  128. local function onSent(connection, payload)
  129. collectgarbage()
  130. if connectionThread then
  131. local connectionThreadStatus = coroutine.status(connectionThread)
  132. if connectionThreadStatus == "suspended" then
  133. -- Not finished sending file, resume.
  134. local status, err = coroutine.resume(connectionThread)
  135. if not status then
  136. log(connection, "Error: "..err)
  137. log(connection, "closing connection", "error")
  138. connection:close()
  139. connectionThread = nil
  140. collectgarbage()
  141. end
  142. elseif connectionThreadStatus == "dead" then
  143. -- We're done sending file.
  144. log(connection, "closing connection","thread is dead")
  145. connection:close()
  146. connectionThread = nil
  147. collectgarbage()
  148. end
  149. end
  150. end
  151. local function onDisconnect(connection, payload)
  152. -- this should rather be a log call, but log is not available here
  153. -- print("disconnected")
  154. if connectionThread then
  155. connectionThread = nil
  156. collectgarbage()
  157. end
  158. end
  159. connection:on("receive", onReceive)
  160. connection:on("sent", onSent)
  161. connection:on("disconnection", onDisconnect)
  162. end
  163. )
  164. return s
  165. end