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
120 request.env.HTTP_AUTH_USER, request.env.HTTP_AUTH_PASS = user, pass
126 ["WWW-Authenticate"] = ('Basic realm=%q'):format(self.name),
127 ["Content-Type"] = 'text/plain'
128 }, ltn12.source.string("Unauthorized")
131 -- Processes a request
132 function Handler.process(self, request, sourcein)
133 local stat, code, hdr, sourceout
135 local stat, code, msg = self:checkrestricted(request)
136 if stat then -- Access Denied
137 return stat, code, msg
140 -- Detect request Method
141 local hname = "handle_" .. request.env.REQUEST_METHOD
144 stat, code, hdr, sourceout = pcall(self[hname], self, request, sourcein)
146 -- Check for any errors
148 return self:failure(500, code)
151 return self:failure(405, statusmsg[405])
154 return code, hdr, sourceout
160 function VHost.__init__(self)
164 function VHost.process(self, request, ...)
167 local uri = request.env.SCRIPT_NAME
168 local sc = ("/"):byte()
171 request.env.SCRIPT_NAME = ""
174 request.env.PATH_INFO = uri
176 for k, h in pairs(self.handlers) do
178 if uri == k or (uri:sub(1, #k) == k and uri:byte(#k+1) == sc) then
181 request.env.SCRIPT_NAME = k
182 request.env.PATH_INFO = uri:sub(#k+1)
188 return handler:process(request, ...)
190 return 404, nil, ltn12.source.string("No such handler")
194 function VHost.get_handlers(self)
198 function VHost.set_handler(self, match, handler)
199 self.handlers[match] = handler
203 local function remapipv6(adr)
204 local map = "::ffff:"
205 if adr:sub(1, #map) == map then
206 return adr:sub(#map+1)
212 local function chunksource(sock, buffer)
213 buffer = buffer or ""
216 local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
217 while not count and #buffer <= 1024 do
218 local newblock, code = sock:recv(1024 - #buffer)
222 buffer = buffer .. newblock
223 _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
225 count = tonumber(count, 16)
227 return nil, -1, "invalid encoding"
228 elseif count == 0 then
230 elseif count + 2 <= #buffer - endp then
231 output = buffer:sub(endp+1, endp+count)
232 buffer = buffer:sub(endp+count+3)
235 output = buffer:sub(endp+1, endp+count)
237 if count - #output > 0 then
238 local remain, code = sock:recvall(count-#output)
242 output = output .. remain
243 count, code = sock:recvall(2)
245 count, code = sock:recvall(count+2-#buffer+endp)
255 local function chunksink(sock)
256 return function(chunk, err)
258 return sock:writeall("0\r\n\r\n")
260 return sock:writeall(("%X\r\n%s\r\n"):format(#chunk, tostring(chunk)))
265 Server = util.class()
267 function Server.__init__(self)
271 function Server.get_vhosts(self)
275 function Server.set_vhost(self, name, vhost)
276 self.vhosts[name] = vhost
279 function Server.error(self, client, code, msg)
280 hcode = tostring(code)
282 client:writeall( "HTTP/1.0 " .. hcode .. " " ..
283 statusmsg[code] .. "\r\n" )
284 client:writeall( "Connection: close\r\n" )
285 client:writeall( "Content-Type: text/plain\r\n\r\n" )
288 client:writeall( "HTTP-Error " .. code .. ": " .. msg .. "\r\n" )
295 ["Content-Length"] = "CONTENT_LENGTH",
296 ["Content-Type"] = "CONTENT_TYPE",
297 ["Content-type"] = "CONTENT_TYPE",
298 ["Accept"] = "HTTP_ACCEPT",
299 ["Accept-Charset"] = "HTTP_ACCEPT_CHARSET",
300 ["Accept-Encoding"] = "HTTP_ACCEPT_ENCODING",
301 ["Accept-Language"] = "HTTP_ACCEPT_LANGUAGE",
302 ["Connection"] = "HTTP_CONNECTION",
303 ["Cookie"] = "HTTP_COOKIE",
304 ["Host"] = "HTTP_HOST",
305 ["Referer"] = "HTTP_REFERER",
306 ["User-Agent"] = "HTTP_USER_AGENT"
309 function Server.parse_headers(self, source)
311 local req = {env = env, headers = {}}
314 repeat -- Ignore empty lines
321 env.REQUEST_METHOD, env.REQUEST_URI, env.SERVER_PROTOCOL =
322 line:match("^([A-Z]+) ([^ ]+) (HTTP/1%.[01])$")
324 if not env.REQUEST_METHOD then
325 return nil, "invalid magic"
328 local key, envkey, val
333 elseif #line > 0 then
334 key, val = line:match("^([%w-]+)%s?:%s?(.*)")
336 req.headers[key] = val
337 envkey = hdr2env[key]
342 return nil, "invalid header line"
349 env.SCRIPT_NAME, env.QUERY_STRING = env.REQUEST_URI:match("([^?]*)%??(.*)")
354 function Server.process(self, client, env)
355 local sourcein = function() end
356 local sourcehdr = client:linesource()
361 local stat, code, msg, message, err
363 env.config.memlimit = tonumber(env.config.memlimit)
364 if env.config.memlimit and set_memory_limit then
365 set_memory_limit(env.config.memlimit)
368 client:setsockopt("socket", "rcvtimeo", 5)
369 client:setsockopt("socket", "sndtimeo", 5)
373 message, err = self:parse_headers(sourcehdr)
376 if not message or err then
377 if err == 11 then -- EAGAIN
380 return self:error(client, 400, err)
384 -- Prepare sources and sinks
385 buffer = sourcehdr(true)
386 sinkout = client:sink()
389 if client:is_tls_socket() then
390 message.env.HTTPS = "on"
394 message.env.REMOTE_ADDR = remapipv6(env.host)
395 message.env.REMOTE_PORT = env.port
397 local srvaddr, srvport = client:getsockname()
398 message.env.SERVER_ADDR = remapipv6(srvaddr)
399 message.env.SERVER_PORT = srvport
402 if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
403 close = (message.env.HTTP_CONNECTION == "close")
405 close = not message.env.HTTP_CONNECTION
406 or message.env.HTTP_CONNECTION == "close"
409 -- Uncomment this to disable keep-alive
410 close = close or env.config.nokeepalive
412 if message.env.REQUEST_METHOD == "GET"
413 or message.env.REQUEST_METHOD == "HEAD" then
416 elseif message.env.REQUEST_METHOD == "POST" then
417 -- If we have a HTTP/1.1 client and an Expect: 100-continue header
418 -- respond with HTTP 100 Continue message
419 if message.env.SERVER_PROTOCOL == "HTTP/1.1"
420 and message.headers.Expect == '100-continue' then
421 client:writeall("HTTP/1.1 100 Continue\r\n\r\n")
424 if message.headers['Transfer-Encoding'] and
425 message.headers['Transfer-Encoding'] ~= "identity" then
426 sourcein = chunksource(client, buffer)
428 elseif message.env.CONTENT_LENGTH then
429 local len = tonumber(message.env.CONTENT_LENGTH)
430 if #buffer >= len then
431 sourcein = ltn12.source.string(buffer:sub(1, len))
432 buffer = buffer:sub(len+1)
434 sourcein = ltn12.source.cat(
435 ltn12.source.string(buffer),
436 client:blocksource(nil, len - #buffer)
440 return self:error(client, 411, statusmsg[411])
445 return self:error(client, 405, statusmsg[405])
449 local host = self.vhosts[message.env.HTTP_HOST] or self.vhosts[""]
451 return self:error(client, 404, "No virtual host found")
454 local code, headers, sourceout = host:process(message, sourcein)
455 headers = headers or {}
457 -- Post process response
459 if util.instanceof(sourceout, IOResource) then
460 if not headers["Content-Length"] then
461 headers["Content-Length"] = sourceout.len
464 if not headers["Content-Length"] and not close then
465 if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
466 headers["Transfer-Encoding"] = "chunked"
467 sinkout = chunksink(client)
472 elseif message.env.REQUEST_METHOD ~= "HEAD" then
473 headers["Content-Length"] = 0
477 headers["Connection"] = "close"
478 elseif message.env.SERVER_PROTOCOL == "HTTP/1.0" then
479 headers["Connection"] = "Keep-Alive"
482 headers["Date"] = date.to_http(os.time())
484 message.env.SERVER_PROTOCOL .. " " .. tostring(code) .. " "
486 "Server: LuCId-HTTPd/" .. VERSION
490 for k, v in pairs(headers) do
491 if type(v) == "table" then
492 for _, h in ipairs(v) do
493 header[#header+1] = k .. ": " .. h
496 header[#header+1] = k .. ": " .. v
500 header[#header+1] = ""
501 header[#header+1] = ""
504 stat, code, msg = client:writeall(table.concat(header, "\r\n"))
506 if sourceout and stat then
507 if util.instanceof(sourceout, IOResource) then
508 if not headers["Transfer-Encoding"] then
509 stat, code, msg = sourceout.fd:copyz(client, sourceout.len)
512 sourceout = sourceout.fd:blocksource(nil, sourceout.len)
517 stat, msg = ltn12.pump.all(sourceout, sinkout)
525 nixio.syslog("err", "Error sending data to " .. env.host ..