httpserver.lua 7.1 KB

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