httpserver.lua 6.7 KB

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