httpserver.lua 5.9 KB

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