httpserver.lua 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. --websocket
  71. if payload:find("Upgrade: websocket") then
  72. dofile('httpserver-websocket.lc')(connection, payload)
  73. return
  74. end
  75. collectgarbage()
  76. local auth
  77. local user = "Anonymous"
  78. -- as suggest by anyn99 (https://github.com/marcoskirsch/nodemcu-httpserver/issues/36#issuecomment-167442461)
  79. -- Some browsers send the POST data in multiple chunks.
  80. -- Collect data packets until the size of HTTP body meets the Content-Length stated in header
  81. if payload:find("Content%-Length:") or bBodyMissing then
  82. if fullPayload then fullPayload = fullPayload .. payload else fullPayload = payload end
  83. if (tonumber(string.match(fullPayload, "%d+", fullPayload:find("Content%-Length:")+16)) > #fullPayload:sub(fullPayload:find("\r\n\r\n", 1, true)+4, #fullPayload)) then
  84. bBodyMissing = true
  85. return
  86. else
  87. --print("HTTP packet assembled! size: "..#fullPayload)
  88. payload = fullPayload
  89. fullPayload, bBodyMissing = nil
  90. end
  91. end
  92. collectgarbage()
  93. -- parse payload and decide what to serve.
  94. local req = dofile("httpserver-request.lc")(payload)
  95. print(req.method .. ": " .. req.request)
  96. if conf.auth.enabled then
  97. auth = dofile("httpserver-basicauth.lc")
  98. user = auth.authenticate(payload) -- authenticate returns nil on failed auth
  99. req.user = user -- store authenticated user to req table
  100. end
  101. if user and req.methodIsValid and (req.method == "GET" or req.method == "POST" or req.method == "PUT") then
  102. handleRequest(connection, req)
  103. else
  104. local args = {}
  105. local fileServeFunction = dofile("httpserver-error.lc")
  106. if not user then
  107. args = {code = 401, errorString = "Not Authorized", headers = {auth.authErrorHeader()}}
  108. elseif req.methodIsValid then
  109. args = {code = 501, errorString = "Not Implemented"}
  110. else
  111. args = {code = 400, errorString = "Bad Request"}
  112. end
  113. startServing(fileServeFunction, connection, req, args)
  114. end
  115. end
  116. local function onSent(connection, payload)
  117. collectgarbage()
  118. if connectionThread then
  119. local connectionThreadStatus = coroutine.status(connectionThread)
  120. if connectionThreadStatus == "suspended" then
  121. -- Not finished sending file, resume.
  122. local status, err = coroutine.resume(connectionThread)
  123. if not status then
  124. print(err)
  125. 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. -- false and nil evaluate as false
  145. local ip = wifi.sta.getip()
  146. if not ip then ip = wifi.ap.getip() end
  147. if not ip then ip = "unknown IP" end
  148. print("nodemcu-httpserver running at http://" .. ip .. ":" .. port)
  149. return s
  150. end