httpserver.lua 6.8 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 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. --print("Method: " .. method);
  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("Requested URI: " .. 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. onRequest(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. connection:on("receive", onReceive)
  129. connection:on("sent", onSent)
  130. connection:on("disconnection",function(c)
  131. if connectionThread then
  132. connectionThread = nil
  133. collectgarbage()
  134. end
  135. end)
  136. end
  137. )
  138. -- false and nil evaluate as false
  139. local ip = wifi.sta.getip()
  140. if not ip then ip = wifi.ap.getip() end
  141. if not ip then ip = "unknown IP" end
  142. print("nodemcu-httpserver running at http://" .. ip .. ":" .. port)
  143. return s
  144. end