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"
29 module "luci.lucid.http.server"
35 [206] = "Partial Content",
36 [301] = "Moved Permanently",
38 [304] = "Not Modified",
39 [400] = "Bad Request",
40 [401] = "Unauthorized",
43 [405] = "Method Not Allowed",
44 [408] = "Request Time-out",
45 [411] = "Length Required",
46 [412] = "Precondition Failed",
47 [416] = "Requested range not satisfiable",
48 [500] = "Internal Server Error",
49 [503] = "Server Unavailable",
52 --- Create a new IO resource response.
54 -- @param fd File descriptor
55 -- @param len Length of data
56 -- @return IO resource
57 IOResource = util.class()
59 function IOResource.__init__(self, fd, len)
60 self.fd, self.len = fd, len
64 --- Create a server handler.
68 Handler = util.class()
70 function Handler.__init__(self, name)
71 self.name = name or tostring(self)
74 --- Create a failure reply.
75 -- @param code HTTP status code
76 -- @param msg Status message
77 -- @return status code, header table, response source
78 function Handler.failure(self, code, msg)
79 return code, { ["Content-Type"] = "text/plain" }, ltn12.source.string(msg)
82 --- Add an access restriction.
83 -- @param restriction Restriction specification
84 function Handler.restrict(self, restriction)
85 if not self.restrictions then
86 self.restrictions = {restriction}
88 self.restrictions[#self.restrictions+1] = restriction
92 --- Enforce access restrictions.
93 -- @param request Request object
94 -- @return nil or HTTP statuscode, table of headers, response source
95 function Handler.checkrestricted(self, request)
96 if not self.restrictions then
100 local localif, user, pass
102 for _, r in ipairs(self.restrictions) do
104 if stat and r.interface then -- Interface restriction
106 for _, v in ipairs(request.server.interfaces) do
107 if v.addr == request.env.SERVER_ADDR then
114 if r.interface ~= localif then
119 if stat and r.user then -- User restriction
122 rh = (request.headers.Authorization or ""):match("Basic (.*)")
123 rh = rh and nixio.bin.b64decode(rh) or ""
124 user, pass = rh:match("(.*):(.*)")
127 pwe = nixio.getsp and nixio.getsp(r.user) or nixio.getpw(r.user)
128 local pwh = (user == r.user) and pwe and (pwe.pwdp or pwe.passwd)
129 if not pwh or #pwh < 1 or nixio.crypt(pass, pwh) ~= pwh then
140 ["WWW-Authenticate"] = ('Basic realm=%q'):format(self.name),
141 ["Content-Type"] = 'text/plain'
142 }, ltn12.source.string("Unauthorized")
145 --- Process a request.
146 -- @param request Request object
147 -- @param sourcein Request data source
148 -- @return HTTP statuscode, table of headers, response source
149 function Handler.process(self, request, sourcein)
150 local stat, code, hdr, sourceout
152 local stat, code, msg = self:checkrestricted(request)
153 if stat then -- Access Denied
154 return stat, code, msg
157 -- Detect request Method
158 local hname = "handle_" .. request.env.REQUEST_METHOD
161 stat, code, hdr, sourceout = pcall(self[hname], self, request, sourcein)
163 -- Check for any errors
165 return self:failure(500, code)
168 return self:failure(405, statusmsg[405])
171 return code, hdr, sourceout
175 --- Create a Virtual Host.
177 -- @return Virtual Host
180 function VHost.__init__(self)
184 --- Process a request and invoke the appropriate handler.
185 -- @param request Request object
186 -- @param ... Additional parameters passed to the handler
187 -- @return HTTP statuscode, table of headers, response source
188 function VHost.process(self, request, ...)
191 local uri = request.env.SCRIPT_NAME
192 local sc = ("/"):byte()
195 request.env.SCRIPT_NAME = ""
198 request.env.PATH_INFO = uri
200 for k, h in pairs(self.handlers) do
202 if uri == k or (uri:sub(1, #k) == k and uri:byte(#k+1) == sc) then
205 request.env.SCRIPT_NAME = k
206 request.env.PATH_INFO = uri:sub(#k+1)
212 return handler:process(request, ...)
214 return 404, nil, ltn12.source.string("No such handler")
218 --- Get a list of registered handlers.
219 -- @return Table of handlers
220 function VHost.get_handlers(self)
224 --- Register handler with a given URI prefix.
225 -- @oaram match URI prefix
226 -- @param handler Handler object
227 function VHost.set_handler(self, match, handler)
228 self.handlers[match] = handler
231 -- Remap IPv6-IPv4-compatibility addresses back to IPv4 addresses.
232 local function remapipv6(adr)
233 local map = "::ffff:"
234 if adr:sub(1, #map) == map then
235 return adr:sub(#map+1)
241 -- Create a source that decodes chunked-encoded data from a socket.
242 local function chunksource(sock, buffer)
243 buffer = buffer or ""
246 local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
247 while not count and #buffer <= 1024 do
248 local newblock, code = sock:recv(1024 - #buffer)
252 buffer = buffer .. newblock
253 _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
255 count = tonumber(count, 16)
257 return nil, -1, "invalid encoding"
258 elseif count == 0 then
260 elseif count + 2 <= #buffer - endp then
261 output = buffer:sub(endp+1, endp+count)
262 buffer = buffer:sub(endp+count+3)
265 output = buffer:sub(endp+1, endp+count)
267 if count - #output > 0 then
268 local remain, code = sock:recvall(count-#output)
272 output = output .. remain
273 count, code = sock:recvall(2)
275 count, code = sock:recvall(count+2-#buffer+endp)
285 -- Create a sink that chunk-encodes data and writes it on a given socket.
286 local function chunksink(sock)
287 return function(chunk, err)
289 return sock:writeall("0\r\n\r\n")
291 return sock:writeall(("%X\r\n%s\r\n"):format(#chunk, chunk))
297 --- Create a server object.
299 -- @return Server object
300 Server = util.class()
302 function Server.__init__(self)
306 --- Get a list of registered virtual hosts.
307 -- @return Table of virtual hosts
308 function Server.get_vhosts(self)
312 --- Register a virtual host with a given name.
313 -- @param name Hostname
314 -- @param vhost Virtual host object
315 function Server.set_vhost(self, name, vhost)
316 self.vhosts[name] = vhost
319 --- Send a fatal error message to given client and close the connection.
320 -- @param client Client socket
321 -- @param code HTTP status code
322 -- @param msg status message
323 function Server.error(self, client, code, msg)
324 hcode = tostring(code)
326 client:writeall( "HTTP/1.0 " .. hcode .. " " ..
327 statusmsg[code] .. "\r\n" )
328 client:writeall( "Connection: close\r\n" )
329 client:writeall( "Content-Type: text/plain\r\n\r\n" )
332 client:writeall( "HTTP-Error " .. code .. ": " .. msg .. "\r\n" )
339 ["Content-Length"] = "CONTENT_LENGTH",
340 ["Content-Type"] = "CONTENT_TYPE",
341 ["Content-type"] = "CONTENT_TYPE",
342 ["Accept"] = "HTTP_ACCEPT",
343 ["Accept-Charset"] = "HTTP_ACCEPT_CHARSET",
344 ["Accept-Encoding"] = "HTTP_ACCEPT_ENCODING",
345 ["Accept-Language"] = "HTTP_ACCEPT_LANGUAGE",
346 ["Connection"] = "HTTP_CONNECTION",
347 ["Cookie"] = "HTTP_COOKIE",
348 ["Host"] = "HTTP_HOST",
349 ["Referer"] = "HTTP_REFERER",
350 ["User-Agent"] = "HTTP_USER_AGENT"
353 --- Parse the request headers and prepare the environment.
354 -- @param source line-based input source
355 -- @return Request object
356 function Server.parse_headers(self, source)
358 local req = {env = env, headers = {}}
361 repeat -- Ignore empty lines
368 env.REQUEST_METHOD, env.REQUEST_URI, env.SERVER_PROTOCOL =
369 line:match("^([A-Z]+) ([^ ]+) (HTTP/1%.[01])$")
371 if not env.REQUEST_METHOD then
372 return nil, "invalid magic"
375 local key, envkey, val
380 elseif #line > 0 then
381 key, val = line:match("^([%w-]+)%s?:%s?(.*)")
383 req.headers[key] = val
384 envkey = hdr2env[key]
389 return nil, "invalid header line"
396 env.SCRIPT_NAME, env.QUERY_STRING = env.REQUEST_URI:match("([^?]*)%??(.*)")
400 --- Handle a new client connection.
401 -- @param client client socket
402 -- @param env superserver environment
403 function Server.process(self, client, env)
404 local sourcein = function() end
405 local sourcehdr = client:linesource()
410 local stat, code, msg, message, err
412 env.config.memlimit = tonumber(env.config.memlimit)
413 if env.config.memlimit and set_memory_limit then
414 set_memory_limit(env.config.memlimit)
417 client:setsockopt("socket", "rcvtimeo", 5)
418 client:setsockopt("socket", "sndtimeo", 5)
422 message, err = self:parse_headers(sourcehdr)
425 if not message or err then
426 if err == 11 then -- EAGAIN
429 return self:error(client, 400, err)
433 -- Prepare sources and sinks
434 buffer = sourcehdr(true)
435 sinkout = client:sink()
438 if client:is_tls_socket() then
439 message.env.HTTPS = "on"
443 message.env.REMOTE_ADDR = remapipv6(env.host)
444 message.env.REMOTE_PORT = env.port
446 local srvaddr, srvport = client:getsockname()
447 message.env.SERVER_ADDR = remapipv6(srvaddr)
448 message.env.SERVER_PORT = srvport
451 if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
452 close = (message.env.HTTP_CONNECTION == "close")
454 close = not message.env.HTTP_CONNECTION
455 or message.env.HTTP_CONNECTION == "close"
458 -- Uncomment this to disable keep-alive
459 close = close or env.config.nokeepalive
461 if message.env.REQUEST_METHOD == "GET"
462 or message.env.REQUEST_METHOD == "HEAD" then
465 elseif message.env.REQUEST_METHOD == "POST" then
466 -- If we have a HTTP/1.1 client and an Expect: 100-continue header
467 -- respond with HTTP 100 Continue message
468 if message.env.SERVER_PROTOCOL == "HTTP/1.1"
469 and message.headers.Expect == '100-continue' then
470 client:writeall("HTTP/1.1 100 Continue\r\n\r\n")
473 if message.headers['Transfer-Encoding'] and
474 message.headers['Transfer-Encoding'] ~= "identity" then
475 sourcein = chunksource(client, buffer)
477 elseif message.env.CONTENT_LENGTH then
478 local len = tonumber(message.env.CONTENT_LENGTH)
479 if #buffer >= len then
480 sourcein = ltn12.source.string(buffer:sub(1, len))
481 buffer = buffer:sub(len+1)
483 sourcein = ltn12.source.cat(
484 ltn12.source.string(buffer),
485 client:blocksource(nil, len - #buffer)
489 return self:error(client, 411, statusmsg[411])
494 return self:error(client, 405, statusmsg[405])
498 local host = self.vhosts[message.env.HTTP_HOST] or self.vhosts[""]
500 return self:error(client, 404, "No virtual host found")
503 local code, headers, sourceout = host:process(message, sourcein)
504 headers = headers or {}
506 -- Post process response
508 if util.instanceof(sourceout, IOResource) then
509 if not headers["Content-Length"] then
510 headers["Content-Length"] = sourceout.len
513 if not headers["Content-Length"] then
514 if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
515 headers["Transfer-Encoding"] = "chunked"
516 sinkout = chunksink(client)
521 elseif message.env.REQUEST_METHOD ~= "HEAD" then
522 headers["Content-Length"] = 0
526 headers["Connection"] = "close"
527 elseif message.env.SERVER_PROTOCOL == "HTTP/1.0" then
528 headers["Connection"] = "Keep-Alive"
531 headers["Date"] = date.to_http(os.time())
533 message.env.SERVER_PROTOCOL .. " " .. tostring(code) .. " "
535 "Server: LuCId-HTTPd/" .. VERSION
539 for k, v in pairs(headers) do
540 if type(v) == "table" then
541 for _, h in ipairs(v) do
542 header[#header+1] = k .. ": " .. h
545 header[#header+1] = k .. ": " .. v
549 header[#header+1] = ""
550 header[#header+1] = ""
553 stat, code, msg = client:writeall(table.concat(header, "\r\n"))
555 if sourceout and stat then
556 if util.instanceof(sourceout, IOResource) then
557 stat, code, msg = sourceout.fd:copyz(client, sourceout.len)
559 stat, msg = ltn12.pump.all(sourceout, sinkout)
567 nixio.syslog("err", "Error sending data to " .. env.host ..