httpserver.lua 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. local function startServing(fileServeFunction, connection, req, args)
  15. connectionThread = coroutine.create(function(fileServeFunction, bufferedConnection, req, args)
  16. fileServeFunction(bufferedConnection, req, args)
  17. -- The bufferedConnection may still hold some data that hasn't been sent. Flush it before closing.
  18. if not bufferedConnection:flush() then
  19. connection:close()
  20. connectionThread = nil
  21. end
  22. end)
  23. local BufferedConnectionClass = dofile("httpserver-connection.lc")
  24. local bufferedConnection = BufferedConnectionClass:new(connection)
  25. local status, err = coroutine.resume(connectionThread, fileServeFunction, bufferedConnection, req, args)
  26. if not status then
  27. print("Error: ", err)
  28. end
  29. end
  30. local function handleRequest(connection, req)
  31. collectgarbage()
  32. local method = req.method
  33. local uri = req.uri
  34. local fileServeFunction = nil
  35. if #(uri.file) > 32 then
  36. -- nodemcu-firmware cannot handle long filenames.
  37. uri.args = {code = 400, errorString = "Bad Request"}
  38. fileServeFunction = dofile("httpserver-error.lc")
  39. else
  40. local fileExists = file.open(uri.file, "r")
  41. file.close()
  42. if not fileExists then
  43. -- gzip check
  44. fileExists = file.open(uri.file .. ".gz", "r")
  45. file.close()
  46. if fileExists then
  47. --print("gzip variant exists, serving that one")
  48. uri.file = uri.file .. ".gz"
  49. uri.isGzipped = true
  50. end
  51. end
  52. if not fileExists then
  53. uri.args = {code = 404, errorString = "Not Found"}
  54. fileServeFunction = dofile("httpserver-error.lc")
  55. elseif uri.isScript then
  56. fileServeFunction = dofile(uri.file)
  57. else
  58. if allowStatic[method] then
  59. uri.args = {file = uri.file, ext = uri.ext, isGzipped = uri.isGzipped}
  60. fileServeFunction = dofile("httpserver-static.lc")
  61. else
  62. uri.args = {code = 405, errorString = "Method not supported"}
  63. fileServeFunction = dofile("httpserver-error.lc")
  64. end
  65. end
  66. end
  67. startServing(fileServeFunction, connection, req, uri.args)
  68. end
  69. local function onReceive(connection, payload)
  70. collectgarbage()
  71. local conf = dofile("httpserver-conf.lc")
  72. local auth
  73. local user = "Anonymous"
  74. -- as suggest by anyn99 (https://github.com/marcoskirsch/nodemcu-httpserver/issues/36#issuecomment-167442461)
  75. -- Some browsers send the POST data in multiple chunks.
  76. -- Collect data packets until the size of HTTP body meets the Content-Length stated in header
  77. if payload:find("Content%-Length:") or bBodyMissing then
  78. if fullPayload then fullPayload = fullPayload .. payload else fullPayload = payload end
  79. if (tonumber(string.match(fullPayload, "%d+", fullPayload:find("Content%-Length:")+16)) > #fullPayload:sub(fullPayload:find("\r\n\r\n", 1, true)+4, #fullPayload)) then
  80. bBodyMissing = true
  81. return
  82. else
  83. --print("HTTP packet assembled! size: "..#fullPayload)
  84. payload = fullPayload
  85. fullPayload, bBodyMissing = nil
  86. end
  87. end
  88. collectgarbage()
  89. -- parse payload and decide what to serve.
  90. local req = dofile("httpserver-request.lc")(payload)
  91. print(req.method .. ": " .. req.request)
  92. if conf.auth.enabled then
  93. auth = dofile("httpserver-basicauth.lc")
  94. user = auth.authenticate(payload) -- authenticate returns nil on failed auth
  95. end
  96. if user and req.methodIsValid and (req.method == "GET" or req.method == "POST" or req.method == "PUT") then
  97. handleRequest(connection, req)
  98. else
  99. local args = {}
  100. local fileServeFunction = dofile("httpserver-error.lc")
  101. if not user then
  102. args = {code = 401, errorString = "Not Authorized", headers = {auth.authErrorHeader()}}
  103. elseif req.methodIsValid then
  104. args = {code = 501, errorString = "Not Implemented"}
  105. else
  106. args = {code = 400, errorString = "Bad Request"}
  107. end
  108. startServing(fileServeFunction, connection, req, args)
  109. end
  110. end
  111. local function onSent(connection, payload)
  112. collectgarbage()
  113. if connectionThread then
  114. local connectionThreadStatus = coroutine.status(connectionThread)
  115. if connectionThreadStatus == "suspended" then
  116. -- Not finished sending file, resume.
  117. local status, err = coroutine.resume(connectionThread)
  118. if not status then
  119. print(err)
  120. end
  121. elseif connectionThreadStatus == "dead" then
  122. -- We're done sending file.
  123. connection:close()
  124. connectionThread = nil
  125. end
  126. end
  127. end
  128. local function onDisconnect(connection, payload)
  129. if connectionThread then
  130. connectionThread = nil
  131. collectgarbage()
  132. end
  133. end
  134. connection:on("receive", onReceive)
  135. connection:on("sent", onSent)
  136. connection:on("disconnection", onDisconnect)
  137. end
  138. )
  139. return s
  140. end