3 (c) 2009 Steven Barth <steven@midlink.org>
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
14 local ipairs, pairs = ipairs, pairs
15 local tostring, tonumber = tostring, tonumber
16 local pcall, assert, type = pcall, assert, type
17 local set_memory_limit = set_memory_limit
19 local os = require "os"
20 local nixio = require "nixio"
21 local util = require "luci.util"
22 local ltn12 = require "luci.ltn12"
23 local proto = require "luci.http.protocol"
24 local table = require "table"
25 local date = require "luci.http.protocol.date"
27 module "luci.lucid.http.server"
33 [206] = "Partial Content",
34 [301] = "Moved Permanently",
36 [304] = "Not Modified",
37 [400] = "Bad Request",
38 [401] = "Unauthorized",
41 [405] = "Method Not Allowed",
42 [408] = "Request Time-out",
43 [411] = "Length Required",
44 [412] = "Precondition Failed",
45 [416] = "Requested range not satisfiable",
46 [500] = "Internal Server Error",
47 [503] = "Server Unavailable",
51 IOResource = util.class()
53 function IOResource.__init__(self, fd, len)
54 self.fd, self.len = fd, len
58 -- Server handler implementation
59 Handler = util.class()
61 function Handler.__init__(self, name)
62 self.name = name or tostring(self)
65 -- Creates a failure reply
66 function Handler.failure(self, code, msg)
67 return code, { ["Content-Type"] = "text/plain" }, ltn12.source.string(msg)
70 -- Access Restrictions
71 function Handler.restrict(self, restriction)
72 if not self.restrictions then
73 self.restrictions = {restriction}
75 self.restrictions[#self.restrictions+1] = restriction
80 function Handler.checkrestricted(self, request)
81 if not self.restrictions then
85 local localif, user, pass
87 for _, r in ipairs(self.restrictions) do
89 if stat and r.interface then -- Interface restriction
91 for _, v in ipairs(request.server.interfaces) do
92 if v.addr == request.env.SERVER_ADDR then
99 if r.interface ~= localif then
104 if stat and r.user then -- User restriction
107 rh = (request.headers.Authorization or ""):match("Basic (.*)")
108 rh = rh and nixio.bin.b64decode(rh) or ""
109 user, pass = rh:match("(.*):(.*)")
112 pwe = nixio.getsp and nixio.getsp(r.user) or nixio.getpw(r.user)
113 local pwh = (user == r.user) and pwe and (pwe.pwdp or pwe.passwd)
114 if not pwh or #pwh < 1 or nixio.crypt(pass, pwh) ~= pwh then
125 ["WWW-Authenticate"] = ('Basic realm=%q'):format(self.name),
126 ["Content-Type"] = 'text/plain'
127 }, ltn12.source.string("Unauthorized")
130 -- Processes a request
131 function Handler.process(self, request, sourcein)
132 local stat, code, hdr, sourceout
134 local stat, code, msg = self:checkrestricted(request)
135 if stat then -- Access Denied
136 return stat, code, msg
139 -- Detect request Method
140 local hname = "handle_" .. request.env.REQUEST_METHOD
143 stat, code, hdr, sourceout = pcall(self[hname], self, request, sourcein)
145 -- Check for any errors
147 return self:failure(500, code)
150 return self:failure(405, statusmsg[405])
153 return code, hdr, sourceout
159 function VHost.__init__(self)
163 function VHost.process(self, request, ...)
166 local uri = request.env.SCRIPT_NAME
167 local sc = ("/"):byte()
170 request.env.SCRIPT_NAME = ""
173 request.env.PATH_INFO = uri
175 for k, h in pairs(self.handlers) do
177 if uri == k or (uri:sub(1, #k) == k and uri:byte(#k+1) == sc) then
180 request.env.SCRIPT_NAME = k
181 request.env.PATH_INFO = uri:sub(#k+1)
187 return handler:process(request, ...)
189 return 404, nil, ltn12.source.string("No such handler")
193 function VHost.get_handlers(self)
197 function VHost.set_handler(self, match, handler)
198 self.handlers[match] = handler
202 local function remapipv6(adr)
203 local map = "::ffff:"
204 if adr:sub(1, #map) == map then
205 return adr:sub(#map+1)
211 local function chunksource(sock, buffer)
212 buffer = buffer or ""
215 local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
216 while not count and #buffer <= 1024 do
217 local newblock, code = sock:recv(1024 - #buffer)
221 buffer = buffer .. newblock
222 _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
224 count = tonumber(count, 16)
226 return nil, -1, "invalid encoding"
227 elseif count == 0 then
229 elseif count + 2 <= #buffer - endp then
230 output = buffer:sub(endp+1, endp+count)
231 buffer = buffer:sub(endp+count+3)
234 output = buffer:sub(endp+1, endp+count)
236 if count - #output > 0 then
237 local remain, code = sock:recvall(count-#output)
241 output = output .. remain
242 count, code = sock:recvall(2)
244 count, code = sock:recvall(count+2-#buffer+endp)
254 local function chunksink(sock)
255 return function(chunk, err)
257 return sock:writeall("0\r\n\r\n")
259 return sock:writeall(("%X\r\n%s\r\n"):format(#chunk, chunk))
264 Server = util.class()
266 function Server.__init__(self)
270 function Server.get_vhosts(self)
274 function Server.set_vhost(self, name, vhost)
275 self.vhosts[name] = vhost
278 function Server.error(self, client, code, msg)
279 hcode = tostring(code)
281 client:writeall( "HTTP/1.0 " .. hcode .. " " ..
282 statusmsg[code] .. "\r\n" )
283 client:writeall( "Connection: close\r\n" )
284 client:writeall( "Content-Type: text/plain\r\n\r\n" )
287 client:writeall( "HTTP-Error " .. code .. ": " .. msg .. "\r\n" )
294 ["Content-Length"] = "CONTENT_LENGTH",
295 ["Content-Type"] = "CONTENT_TYPE",
296 ["Content-type"] = "CONTENT_TYPE",
297 ["Accept"] = "HTTP_ACCEPT",
298 ["Accept-Charset"] = "HTTP_ACCEPT_CHARSET",
299 ["Accept-Encoding"] = "HTTP_ACCEPT_ENCODING",
300 ["Accept-Language"] = "HTTP_ACCEPT_LANGUAGE",
301 ["Connection"] = "HTTP_CONNECTION",
302 ["Cookie"] = "HTTP_COOKIE",
303 ["Host"] = "HTTP_HOST",
304 ["Referer"] = "HTTP_REFERER",
305 ["User-Agent"] = "HTTP_USER_AGENT"
308 function Server.parse_headers(self, source)
310 local req = {env = env, headers = {}}
313 repeat -- Ignore empty lines
320 env.REQUEST_METHOD, env.REQUEST_URI, env.SERVER_PROTOCOL =
321 line:match("^([A-Z]+) ([^ ]+) (HTTP/1%.[01])$")
323 if not env.REQUEST_METHOD then
324 return nil, "invalid magic"
327 local key, envkey, val
332 elseif #line > 0 then
333 key, val = line:match("^([%w-]+)%s?:%s?(.*)")
335 req.headers[key] = val
336 envkey = hdr2env[key]
341 return nil, "invalid header line"
348 env.SCRIPT_NAME, env.QUERY_STRING = env.REQUEST_URI:match("([^?]*)%??(.*)")
353 function Server.process(self, client, env)
354 local sourcein = function() end
355 local sourcehdr = client:linesource()
360 local stat, code, msg, message, err
362 env.config.memlimit = tonumber(env.config.memlimit)
363 if env.config.memlimit and set_memory_limit then
364 set_memory_limit(env.config.memlimit)
367 client:setsockopt("socket", "rcvtimeo", 5)
368 client:setsockopt("socket", "sndtimeo", 5)
372 message, err = self:parse_headers(sourcehdr)
375 if not message or err then
376 if err == 11 then -- EAGAIN
379 return self:error(client, 400, err)
383 -- Prepare sources and sinks
384 buffer = sourcehdr(true)
385 sinkout = client:sink()
388 if client:is_tls_socket() then
389 message.env.HTTPS = "on"
393 message.env.REMOTE_ADDR = remapipv6(env.host)
394 message.env.REMOTE_PORT = env.port
396 local srvaddr, srvport = client:getsockname()
397 message.env.SERVER_ADDR = remapipv6(srvaddr)
398 message.env.SERVER_PORT = srvport
401 if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
402 close = (message.env.HTTP_CONNECTION == "close")
404 close = not message.env.HTTP_CONNECTION
405 or message.env.HTTP_CONNECTION == "close"
408 -- Uncomment this to disable keep-alive
409 close = close or env.config.nokeepalive
411 if message.env.REQUEST_METHOD == "GET"
412 or message.env.REQUEST_METHOD == "HEAD" then
415 elseif message.env.REQUEST_METHOD == "POST" then
416 -- If we have a HTTP/1.1 client and an Expect: 100-continue header
417 -- respond with HTTP 100 Continue message
418 if message.env.SERVER_PROTOCOL == "HTTP/1.1"
419 and message.headers.Expect == '100-continue' then
420 client:writeall("HTTP/1.1 100 Continue\r\n\r\n")
423 if message.headers['Transfer-Encoding'] and
424 message.headers['Transfer-Encoding'] ~= "identity" then
425 sourcein = chunksource(client, buffer)
427 elseif message.env.CONTENT_LENGTH then
428 local len = tonumber(message.env.CONTENT_LENGTH)
429 if #buffer >= len then
430 sourcein = ltn12.source.string(buffer:sub(1, len))
431 buffer = buffer:sub(len+1)
433 sourcein = ltn12.source.cat(
434 ltn12.source.string(buffer),
435 client:blocksource(nil, len - #buffer)
439 return self:error(client, 411, statusmsg[411])
444 return self:error(client, 405, statusmsg[405])
448 local host = self.vhosts[message.env.HTTP_HOST] or self.vhosts[""]
450 return self:error(client, 404, "No virtual host found")
453 local code, headers, sourceout = host:process(message, sourcein)
454 headers = headers or {}
456 -- Post process response
458 if util.instanceof(sourceout, IOResource) then
459 if not headers["Content-Length"] then
460 headers["Content-Length"] = sourceout.len
463 if not headers["Content-Length"] then
464 if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
465 headers["Transfer-Encoding"] = "chunked"
466 sinkout = chunksink(client)
471 elseif message.env.REQUEST_METHOD ~= "HEAD" then
472 headers["Content-Length"] = 0
476 headers["Connection"] = "close"
477 elseif message.env.SERVER_PROTOCOL == "HTTP/1.0" then
478 headers["Connection"] = "Keep-Alive"
481 headers["Date"] = date.to_http(os.time())
483 message.env.SERVER_PROTOCOL .. " " .. tostring(code) .. " "
485 "Server: LuCId-HTTPd/" .. VERSION
489 for k, v in pairs(headers) do
490 if type(v) == "table" then
491 for _, h in ipairs(v) do
492 header[#header+1] = k .. ": " .. h
495 header[#header+1] = k .. ": " .. v
499 header[#header+1] = ""
500 header[#header+1] = ""
503 stat, code, msg = client:writeall(table.concat(header, "\r\n"))
505 if sourceout and stat then
506 if util.instanceof(sourceout, IOResource) then
507 stat, code, msg = sourceout.fd:copyz(client, sourceout.len)
509 stat, msg = ltn12.pump.all(sourceout, sinkout)
517 nixio.syslog("err", "Error sending data to " .. env.host ..