httpserver.lua 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. local bufferedConnection = {}
  16. connectionThread = coroutine.create(function(fileServeFunction, bconnection, req, args)
  17. fileServeFunction(bconnection, req, args)
  18. if not bconnection:flush() then
  19. connection:close()
  20. connectionThread = nil
  21. end
  22. end)
  23. function bufferedConnection:flush()
  24. if self.size > 0 then
  25. connection:send(table.concat(self.data, ""))
  26. self.data = {}
  27. self.size = 0
  28. return true
  29. end
  30. return false
  31. end
  32. function bufferedConnection:send(payload)
  33. local l = payload:len()
  34. if l + self.size > 1000 then
  35. if self:flush() then
  36. coroutine.yield()
  37. end
  38. end
  39. if l > 800 then
  40. connection:send(payload)
  41. coroutine.yield()
  42. else
  43. table.insert(self.data, payload)
  44. self.size = self.size + l
  45. end
  46. end
  47. bufferedConnection.size = 0
  48. bufferedConnection.data = {}
  49. local status, err = coroutine.resume(connectionThread, fileServeFunction, bufferedConnection, req, args)
  50. if not status then
  51. print("Error: ", err)
  52. end
  53. end
  54. local function onRequest(connection, req)
  55. collectgarbage()
  56. local method = req.method
  57. local uri = req.uri
  58. local fileServeFunction = nil
  59. --print("Method: " .. method);
  60. if #(uri.file) > 32 then
  61. -- nodemcu-firmware cannot handle long filenames.
  62. uri.args = {code = 400, errorString = "Bad Request"}
  63. fileServeFunction = dofile("httpserver-error.lc")
  64. else
  65. local fileExists = file.open(uri.file, "r")
  66. file.close()
  67. if not fileExists then
  68. -- gzip check
  69. fileExists = file.open(uri.file .. ".gz", "r")
  70. file.close()
  71. if fileExists then
  72. print("gzip variant exists, serving that one")
  73. uri.file = uri.file .. ".gz"
  74. uri.isGzipped = true
  75. end
  76. end
  77. if not fileExists then
  78. uri.args = {code = 404, errorString = "Not Found"}
  79. fileServeFunction = dofile("httpserver-error.lc")
  80. elseif uri.isScript then
  81. fileServeFunction = dofile(uri.file)
  82. else
  83. if allowStatic[method] then
  84. uri.args = {file = uri.file, ext = uri.ext, isGzipped = uri.isGzipped}
  85. fileServeFunction = dofile("httpserver-static.lc")
  86. else
  87. uri.args = {code = 405, errorString = "Method not supported"}
  88. fileServeFunction = dofile("httpserver-error.lc")
  89. end
  90. end
  91. end
  92. startServing(fileServeFunction, connection, req, uri.args)
  93. end
  94. local function onReceive(connection, payload)
  95. collectgarbage()
  96. local conf = dofile("httpserver-conf.lc")
  97. local auth
  98. local user = "Anonymous"
  99. -- parse payload and decide what to serve.
  100. local req = dofile("httpserver-request.lc")(payload)
  101. print("Requested URI: " .. req.request)
  102. if conf.auth.enabled then
  103. auth = dofile("httpserver-basicauth.lc")
  104. user = auth.authenticate(payload) -- authenticate returns nil on failed auth
  105. end
  106. if user and req.methodIsValid and (req.method == "GET" or req.method == "POST" or req.method == "PUT") then
  107. onRequest(connection, req)
  108. else
  109. local args = {}
  110. local fileServeFunction = dofile("httpserver-error.lc")
  111. if not user then
  112. args = {code = 401, errorString = "Not Authorized", headers = {auth.authErrorHeader()}}
  113. elseif req.methodIsValid then
  114. args = {code = 501, errorString = "Not Implemented"}
  115. else
  116. args = {code = 400, errorString = "Bad Request"}
  117. end
  118. startServing(fileServeFunction, connection, req, args)
  119. end
  120. end
  121. local function onSent(connection, payload)
  122. collectgarbage()
  123. if connectionThread then
  124. local connectionThreadStatus = coroutine.status(connectionThread)
  125. if connectionThreadStatus == "suspended" then
  126. -- Not finished sending file, resume.
  127. local status, err = coroutine.resume(connectionThread)
  128. if not status then
  129. print(err)
  130. end
  131. elseif connectionThreadStatus == "dead" then
  132. -- We're done sending file.
  133. connection:close()
  134. connectionThread = nil
  135. end
  136. end
  137. end
  138. connection:on("receive", onReceive)
  139. connection:on("sent", onSent)
  140. connection:on("disconnection",function(c)
  141. if connectionThread then
  142. connectionThread = nil
  143. collectgarbage()
  144. end
  145. end)
  146. end
  147. )
  148. -- false and nil evaluate as false
  149. local ip = wifi.sta.getip()
  150. if not ip then ip = wifi.ap.getip() end
  151. print("nodemcu-httpserver running at http://" .. ip .. ":" .. port)
  152. return s
  153. end