3 (c) 2008 Steven Barth <steven@midlink.org>
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
15 local ipairs, pairs = ipairs, pairs
16 local tostring, tonumber = tostring, tonumber
17 local pcall, assert = pcall, assert
19 local os = require "os"
20 local io = require "io"
21 local util = require "luci.util"
22 local ltn12 = require "luci.ltn12"
23 local proto = require "luci.http.protocol"
24 local string = require "string"
25 local date = require "luci.http.protocol.date"
27 module "luci.ttpd.server"
34 IOResource = util.class()
36 function IOResource.__init__(self, fd, offset, len)
37 self.fd, self.offset, self.len = fd, offset, len
43 function VHost.__init__(self, handler)
44 self.handler = handler
48 function VHost.process(self, request, sourcein, sinkerr, ...)
49 local handler = self.handler
51 local uri = request.env.REQUEST_URI:match("^([^?]*)")
54 request.env.SCRIPT_NAME = ""
57 request.env.PATH_INFO = uri
59 for k, dhandler in pairs(self.dhandler) do
60 if k == uri or k.."/" == uri:sub(1, #k+1) then
62 request.env.SCRIPT_NAME = k
63 request.env.PATH_INFO = uri:sub(#k+1)
69 return handler:process(request, sourcein, sinkerr, ...)
73 function VHost.get_default_handler(self)
77 function VHost.set_default_handler(self, handler)
78 self.handler = handler
81 function VHost.get_handlers(self)
85 function VHost.set_handler(self, match, handler)
86 self.dhandler[match] = handler
93 function Server.__init__(self, host)
101 function Server.get_default_vhost(self)
105 function Server.set_default_vhost(self, vhost)
109 function Server.get_vhosts(self)
113 function Server.set_vhost(self, name, vhost)
114 self.vhosts[name] = vhost
117 function Server.flush(self)
118 if #self.wbuf > 0 then
119 self._write(self.wbuf)
124 function Server.read(self, len)
125 while #self.rbuf < len do
126 self.rbuf = self.rbuf .. self._read(len - #self.rbuf)
129 local chunk = self.rbuf:sub(1, len)
130 self.rbuf = self.rbuf:sub(len + 1)
134 function Server.limitsource(self, limit)
141 local read = (limit > BUFSIZE) and BUFSIZE or limit
143 return self:read(read)
148 -- Adapted from Luaposix
149 function Server.receiveheaders(self)
150 local line, name, value, err
153 line, err = self:readline()
154 if err then return nil, err end
155 -- headers go until a blank line is found
157 -- get field-name and value
158 _, _, name, value = line:find("^(.-):%s*(.*)")
159 if not (name and value) then return nil, "malformed reponse headers" end
161 -- get next line (value might be folded)
162 line, err = self:readline()
163 if err then return nil, err end
164 -- unfold any folded values
165 while line:find("^%s") do
166 value = value .. line
167 line = self:readline()
168 if err then return nil, err end
170 -- save pair in table
171 if headers[name] then headers[name] = headers[name] .. ", " .. value
172 else headers[name] = value end
177 function Server.readchunk(self)
178 -- get chunk size, skip extention
179 local line, err = self:readline()
180 if err then return nil, err end
181 local size = tonumber(line:gsub(";.*", ""), 16)
182 if not size then return nil, "invalid chunk size" end
183 -- was it the last chunk?
185 -- if not, get chunk and skip terminating CRLF
186 local chunk, err, part = self:read(size)
187 if chunk then self:readline() end
190 -- if it was, read trailers into headers table
191 headers, err = self:receiveheaders()
192 if not headers then return nil, err end
196 function Server.readline(self)
197 if #self.rbuf < 1 then
198 self.rbuf = self._read(BUFSIZE)
202 local le = self.rbuf:find("\r\n", nil, true)
204 if le == 1 then -- EoH
205 self.rbuf = self.rbuf:sub(le + 2)
208 local line = self.rbuf:sub(1, le - 1)
209 self.rbuf = self.rbuf:sub(le + 2)
213 if #self.rbuf >= BUFSIZE then
214 return nil, "Invalid Request"
216 self.rbuf = self.rbuf .. self._read(BUFSIZE-#self.rbuf)
221 function Server.sink(self)
222 return function(chunk, err)
226 local stat, err = pcall(self.write, self, chunk)
238 function Server.chunksink(self)
239 return function(chunk, err)
240 local stat, err = pcall(self.writechunk, self, chunk)
249 function Server.writechunk(self, chunk, err)
251 if not chunk then return self._write("0\r\n\r\n") end
252 local size = string.format("%X\r\n", #chunk)
253 return self._write(size .. chunk .. "\r\n")
256 function Server.write(self, chunk)
258 local missing = BUFSIZE - #self.wbuf
259 self.wbuf = self.wbuf .. chunk:sub(1, missing)
260 chunk = chunk:sub(missing + 1)
261 if #self.wbuf == BUFSIZE then
262 assert(self._write(self.wbuf))
268 function Server.close(self)
273 function Server.sendfile(self, fd, offset, len)
275 self._sendfile(fd, offset, len)
279 function Server.error(self, code, msg)
280 hcode = tostring(code)
282 self:write( "HTTP/1.0 " .. hcode .. " " ..
283 proto.statusmsg[code] .. "\r\n" )
284 self:write( "Connection: close\r\n" )
285 self:write( "Content-Type: text/plain\r\n\r\n" )
288 self:write( "HTTP-Error " .. code .. ": " .. msg .. "\r\n" )
293 function Server.process(self, functions)
294 util.update(self, functions)
296 local sourcein = ltn12.source.empty()
297 local sourcehdr = function() return self:readline() or "" end
298 local sinkerr = ltn12.sink.file( io.stderr )
299 local sinkout = self:sink()
302 local stat, message, err
306 stat, message, err = pcall(proto.parse_message_header, sourcehdr)
308 -- remote socket closed
309 if not stat and message == 0 then
314 if not stat and message == 11 then
320 if not stat or not message then
326 if message.http_version == 1.1 then
327 close = (message.env.HTTP_CONNECTION == "close")
329 close = not message.env.HTTP_CONNECTION or message.env.HTTP_CONNECTION == "close"
331 -- Uncomment this to disable keep-alive
334 if message.request_method == "get" or message.request_method == "head" then
337 elseif message.request_method == "post" then
338 -- If we have a HTTP/1.1 client and an Expect: 100-continue header then
339 -- respond with HTTP 100 Continue message
340 if message.http_version == 1.1 and message.headers['Expect'] and
341 message.headers['Expect'] == '100-continue'
343 self:write("HTTP/1.1 100 Continue\r\n\r\n")
346 if message.headers['Transfer-Encoding'] and
347 message.headers['Transfer-Encoding'] ~= "identity" then
348 sourcein = function() return self:readchunk() end
349 elseif message.env.CONTENT_LENGTH then
350 sourcein = self:limitsource(
351 tonumber(message.env.CONTENT_LENGTH)
354 self:error( 411, proto.statusmsg[411] )
358 self:error( 405, proto.statusmsg[405] )
364 local host = self.vhosts[message.env.HTTP_HOST] or self.host
366 self:error( 500, "Unable to find matching host" )
370 local response, sourceout = host:process(
371 message, sourcein, sinkerr,
375 self:error( 500, "Error processing handler" )
378 -- Post process response
380 if util.instanceof(sourceout, IOResource) then
381 if not response.headers["Content-Length"] then
382 response.headers["Content-Length"] = sourceout.len
385 if not response.headers["Content-Length"] then
386 if message.http_version == 1.1 then
387 response.headers["Transfer-Encoding"] = "chunked"
388 sinkout = self:chunksink()
393 elseif message.request_method ~= "head" then
394 response.headers["Content-Length"] = 0
398 response.headers["Connection"] = "close"
401 response.headers["Date"] = date.to_http(os.time())
404 message.env.SERVER_PROTOCOL .. " " ..
405 tostring(response.status) .. " " ..
406 proto.statusmsg[response.status] .. "\r\n"
408 header = header .. "Server: LuCIttpd/" .. tostring(VERSION) .. "\r\n"
411 for k,v in pairs(response.headers) do
412 header = header .. k .. ": " .. v .. "\r\n"
416 local stat, err = pcall(function()
417 self:write(header .. "\r\n")
420 if util.instanceof(sourceout, IOResource) then
421 self:sendfile(sourceout.fd, sourceout.offset, sourceout.len)
423 ltn12.pump.all(sourceout, sinkout)
433 -- Remote end closed the socket, so do we
435 io.stderr:write("Error sending data: " .. err .. "\n")