1 -------------------------------------------------------------------------------
4 -- Written by Timm S. Mueller <tmueller@neoscientists.org>
7 -- Lua FastCGI protocol implementation - specifically written for
8 -- the ''external server'' configuration (via IP socket).
10 -- Methods that must be implemented by the user:
11 -- - FastCGI:have_params() - signals that all arguments have been
14 -- Methods that can be implemented by the user:
15 -- - FastCGI:update_stream() - stream created/updated (for POST)
16 -- - FastCGI:have_stream() - stream completed (for POST)
19 -- LuaSocket and Bit library
21 -------------------------------------------------------------------------------
23 local Class = require "tek.class"
24 local socket = require "socket"
25 local bit = require "bit"
27 local insert, remove, concat, pairs, ipairs, error, assert =
28 table.insert, table.remove, table.concat, pairs, ipairs, error, assert
29 local tonumber, setmetatable, unpack, type =
30 tonumber, setmetatable, unpack, type
31 local char = string.char
34 module("tek.class.fastcgi", tek.class)
35 _VERSION = "FastCGI 0.6"
37 -------------------------------------------------------------------------------
39 -------------------------------------------------------------------------------
41 local FIFO = Class:newClass { _NAME = "_fcgi_fifo" }
43 function FIFO.new(class, self)
45 self.buf = self.buf or { }
46 return Class.new(class, self)
49 function FIFO:write(s)
52 elseif self.buf[#self.buf] ~= -1 then
53 insert(self.buf, -1) -- EOF
57 function FIFO:readn(len)
60 p = remove(self.buf, 1)
65 insert(self.buf, -1) -- push back EOF
66 break -- end of stream, EOF in next turn
69 if l > len then -- break buffer fragment in two
70 insert(t, p:sub(1, len))
71 insert(self.buf, 1, p:sub(len + 1))
81 local last = remove(self.buf)
82 if last ~= -1 then -- not EOF
83 insert(self.buf, last) -- push back
86 local s = concat(self.buf)
91 function FIFO:read(...)
92 if self.buf[1] == -1 then
96 for _, what in ipairs(arg) do
99 elseif type(what) == "number" then
100 s = self:readn(tonumber(what))
102 error("unknwon format")
109 -- FCGI encoded lengths and key/value pairs:
111 function FIFO:readlen()
112 local l = self:read(1)
113 if not l then return end
118 local t = self:read(3)
119 if not t then return end
120 return (l % 128) * 16777216 + t:byte(1) * 65536 +
121 t:byte(2) * 256 + t:byte(3)
124 function FIFO:readkeyvals()
126 local l1, l2, key, val
129 if not l1 then break end
131 if not l2 then break end
139 -------------------------------------------------------------------------------
141 -------------------------------------------------------------------------------
143 FCGI_BEGIN_REQUEST = 1
144 FCGI_ABORT_REQUEST = 2
152 FCGI_GET_VALUES_RESULT = 10
153 FCGI_UNKNOWN_TYPE = 11
155 local FCGI_RESPONDER = 1
156 local FCGI_REQUEST_COMPLETE = 0
157 local FCGI_UNKNOWN_ROLE = 3
159 local function encodelen(buf, l)
161 insert(buf, char(bit.rshift(bit.band(l, 0x7f000000), 24) + 128))
162 insert(buf, char(bit.rshift(bit.band(l, 0x00ff0000), 16)))
163 insert(buf, char(bit.rshift(bit.band(l, 0x0000ff00), 8)))
165 insert(buf, char(bit.band(l, 0xff)))
168 local function encodekeyvals(t)
170 for key, val in pairs(t) do
171 encodelen(buf, key:len())
172 encodelen(buf, val:len())
181 function FastCGI.new(class, self)
186 return Class.new(class, self)
189 function FastCGI:readrecord()
190 local t, err = self.socket:receive(8)
191 if not t then return end
192 if err then error(err) end
196 id = t:byte(3) * 256 + t:byte(4),
197 len = t:byte(5) * 256 + t:byte(6)
202 r.content, err = self.socket:receive(r.len)
203 if not r.content then return end
204 if err then error(err) end
206 local pad = t:byte(7)
208 t, err = self.socket:receive(pad)
209 if not t then return end
210 if err then error(err) end
215 function FastCGI:write(type, id, s)
216 local totlen = s:len()
219 local len = min(totlen, 65535)
223 char(bit.rshift(id, 8)), -- id1
224 char(id % 256), -- id0
225 char(bit.rshift(len, 8)), -- len1
226 char(len % 256), -- len0
229 s:sub(totpos, totpos + len - 1) -- content
231 totpos = totpos + len
232 totlen = totlen - len
235 local pos, res, err = 1
237 res, err = self.socket:send(buf, pos)
247 -------------------------------------------------------------------------------
248 -- success, msg = write_stdout(req_id, data): Write out data on the FastCGI
249 -- stdout stream, in reply to a request of the given Id. The result is true,
250 -- indicating success, or nil followed by an error message.
251 -------------------------------------------------------------------------------
253 function FastCGI:write_stdout(id, s)
254 return self:write(FCGI_STDOUT, id, s)
257 function FastCGI:collectstream(r)
258 local req = self.requests[r.id]
259 local s = req.streams[r.type]
262 req.streams[r.type] = s
265 s:write() -- append EOF
266 return s, true -- finished
272 -------------------------------------------------------------------------------
273 -- success, msg = endrequest(request[, protstatus[, appstatus]]):
274 -- Confirms the end of a FastCGI request. Optionally, the application can
275 -- signify a protocol status (by default, FCGI_REQUEST_COMPLETE) and an
276 -- application status (by default, 0). See
277 -- [[FastCGI protocol][http://www.fastcgi.com/devkit/doc/fcgi-spec.html]]
278 -- specification for details.
279 -- The result will be true, indicating success, or nil followed by an
281 -------------------------------------------------------------------------------
283 function FastCGI:endrequest(req, protstatus, appstatus)
284 protstatus = protstatus or req.protstatus or FCGI_REQUEST_COMPLETE
285 appstatus = appstatus or req.appstatus or 0
286 self.requests[req.id] = nil -- delete request
287 return self:write(FCGI_END_REQUEST, req.id, concat {
288 char(bit.rshift(bit.band(appstatus, 0x7f000000), 24)),
289 char(bit.rshift(bit.band(appstatus, 0x00ff0000), 16)),
290 char(bit.rshift(bit.band(appstatus, 0x0000ff00), 8)),
291 char(bit.band(appstatus, 0xff)),
293 char(0), char(0), char(0)
297 function FastCGI:newrequest(id, role, flags)
298 assert(not self.requests[id])
299 local req = { id = id, role = role, flags = flags, streams = { } }
300 self.requests[id] = req
304 function FastCGI:processrecord(r)
307 local req = self.requests[r.id]
309 if r.type == FCGI_BEGIN_REQUEST then
311 local role = c:byte(1) * 256 + c:byte(2)
312 if role == FCGI_RESPONDER then
314 local flags = c:byte(3)
315 req = self:newrequest(r.id, role, flags)
316 return true -- continue
319 return self:endrequest(req, FCGI_UNKNOWN_ROLE)
322 if not req then -- request already closed
323 return true -- continue
326 if r.type == FCGI_ABORT_REQUEST then
327 return self:abortrequest(req)
329 elseif r.type == FCGI_GET_VALUES then
330 local s, fin = self:collectstream(r)
333 for k in pairs(s:readkeyvals()) do
334 if k == "FCGI_MAX_CONNS" then
335 res.FCGI_MAX_CONNS = "16"
336 elseif k == "FCGI_MAX_REQS" then
337 res.FCGI_MAX_CONNS = "32"
338 elseif k == "FCGI_MAX_REQS" then
339 res.FCGI_MAX_CONNS = "1"
342 res = encodekeyvals(res)
343 return self:write(FCGI_GET_VALUES_RESULT, 0, res)
346 elseif r.type == FCGI_PARAMS then
347 local s, fin = self:collectstream(r)
349 req.params = s:readkeyvals()
350 return self:have_params(req, req.params)
353 elseif r.type == self.FCGI_STDIN or r.type == self.FCGI_DATA then
354 local s, fin = self:collectstream(r)
356 return self:have_stream(req, r.type, s)
358 return self:update_stream(req, r.type, s)
363 local buf = char(r.type) .. char(0):rep(7)
364 return self:write(FCGI_UNKNOWN_TYPE, 0, buf)
367 return true -- continue
370 -------------------------------------------------------------------------------
371 -- serve(socket): Serve the FastCGI protocol on the supplied socket until
372 -- FastCGI:stop() is called.
373 -------------------------------------------------------------------------------
375 function FastCGI:serve(socket)
379 while self.serving do
380 local r = self:readrecord()
384 if not self:processrecord(r) then
390 -------------------------------------------------------------------------------
391 -- stop(): Stop acting as a server. This will cause FastCGI:serve() to
393 -------------------------------------------------------------------------------
395 function FastCGI:stop()
399 -------------------------------------------------------------------------------
400 -- success, msg = abortrequest(req_id): Called when the webserver aborts the
401 -- request of the given Id. The return value is the result from
402 -- FastCGI:endrequest().
403 -------------------------------------------------------------------------------
405 function FastCGI:abortrequest(req)
406 -- request aborted by webserver, confirm:
407 return self:endrequest(req)
410 -------------------------------------------------------------------------------
411 -- continue = have_params(req_id, params):
412 -- Signals the arrival of all parameters that belong to the request of the
413 -- given Id; params is a table containing all received parameters as
414 -- key/value pairs. The return value is a boolean indicating success and,
415 -- effectively, whether processing of the request should continue.
416 -- This method must be implemented by the user before anything useful can be
417 -- done with a FastCGI request.
418 -------------------------------------------------------------------------------
420 function FastCGI:have_params()
424 function FastCGI:update_stream()