cgi-bin/tek/class/fastcgi.lua
author Timm S. Mueller <tmueller@neoscientists.org>
Wed, 24 Feb 2010 14:44:46 +0100
changeset 258 30e3e6d34685
parent 239 08efae95f502
permissions -rw-r--r--
Added HTTP headers and meta tags discouraging the browser to cache the page
when logged on or when the page content is dynamic
     1 -------------------------------------------------------------------------------
     2 --
     3 --	tek.class.fastcgi
     4 --	Written by Timm S. Mueller <tmueller@neoscientists.org>
     5 --
     6 --	OVERVIEW::
     7 --	Lua FastCGI protocol implementation - specifically written for
     8 --	the ''external server'' configuration (via IP socket).
     9 --
    10 --	Methods that must be implemented by the user:
    11 --		- FastCGI:have_params() - signals that all arguments have been
    12 --		transferred
    13 --
    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)
    17 --
    18 --	REQUIREMENTS::
    19 --	LuaSocket and Bit library
    20 --
    21 -------------------------------------------------------------------------------
    22 
    23 local Class = require "tek.class"
    24 local socket = require "socket"
    25 local bit = require "bit"
    26 
    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
    32 local min = math.min
    33 
    34 module("tek.class.fastcgi", tek.class)
    35 _VERSION = "FastCGI 0.6"
    36 
    37 -------------------------------------------------------------------------------
    38 -- local FIFO class:
    39 -------------------------------------------------------------------------------
    40 
    41 local FIFO = Class:newClass { _NAME = "_fcgi_fifo" }
    42 
    43 function FIFO.new(class, self)
    44 	self = self or { }
    45 	self.buf = self.buf or { }
    46 	return Class.new(class, self)
    47 end
    48 
    49 function FIFO:write(s)
    50 	if s and s ~= -1 then
    51 		insert(self.buf, s)
    52 	elseif self.buf[#self.buf] ~= -1 then
    53 		insert(self.buf, -1) -- EOF
    54 	end
    55 end
    56 
    57 function FIFO:readn(len)
    58 	local t, p, l = { }
    59 	while len > 0 do
    60 		p = remove(self.buf, 1)
    61 		if not p then
    62 			break -- no more data
    63 		end
    64 		if p == -1 then
    65 			insert(self.buf, -1) -- push back EOF
    66 			break -- end of stream, EOF in next turn
    67 		end
    68 		l = p:len()
    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))
    72 			break
    73 		end
    74 		insert(t, p)
    75 		len = len - l
    76 	end
    77 	return concat(t)
    78 end
    79 
    80 function FIFO:reada()
    81 	local last = remove(self.buf)
    82 	if last ~= -1 then -- not EOF
    83 		insert(self.buf, last) -- push back
    84 		last = nil
    85 	end
    86 	local s = concat(self.buf)
    87 	self.buf = { last }
    88 	return s
    89 end
    90 
    91 function FIFO:read(...)
    92 	if self.buf[1] == -1 then
    93 		return -- EOF
    94 	end
    95 	local t, s = { }
    96 	for _, what in ipairs(arg) do
    97 		if what == "*a" then
    98 			s = self:reada()
    99 		elseif type(what) == "number" then
   100 			s = self:readn(tonumber(what))
   101 		else
   102 			error("unknwon format")
   103 		end
   104 		insert(t, s)
   105 	end
   106 	return unpack(t)
   107 end
   108 
   109 --	FCGI encoded lengths and key/value pairs:
   110 
   111 function FIFO:readlen()
   112 	local l = self:read(1)
   113 	if not l then return end
   114 	l = l:byte()
   115 	if l < 128 then
   116 		return l
   117 	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)
   122 end
   123 
   124 function FIFO:readkeyvals()
   125 	local t = { }
   126 	local l1, l2, key, val
   127 	while true do
   128 		l1 = self:readlen()
   129 		if not l1 then break end
   130 		l2 = self:readlen()
   131 		if not l2 then break end
   132  		key = self:read(l1)
   133  		val = self:read(l2)
   134 		t[key] = val
   135 	end
   136 	return t
   137 end
   138 
   139 -------------------------------------------------------------------------------
   140 -- FCGI class:
   141 -------------------------------------------------------------------------------
   142 
   143 FCGI_BEGIN_REQUEST = 1
   144 FCGI_ABORT_REQUEST = 2
   145 FCGI_END_REQUEST = 3
   146 FCGI_PARAMS = 4
   147 FCGI_STDIN = 5
   148 FCGI_STDOUT = 6
   149 FCGI_STDERR = 7
   150 FCGI_DATA = 8
   151 FCGI_GET_VALUES = 9
   152 FCGI_GET_VALUES_RESULT = 10
   153 FCGI_UNKNOWN_TYPE = 11
   154 
   155 local FCGI_RESPONDER = 1
   156 local FCGI_REQUEST_COMPLETE = 0
   157 local FCGI_UNKNOWN_ROLE = 3
   158 
   159 local function encodelen(buf, l)
   160 	if l > 127 then
   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)))
   164 	end
   165 	insert(buf, char(bit.band(l, 0xff)))
   166 end
   167 
   168 local function encodekeyvals(t)
   169 	local buf = { }
   170 	for key, val in pairs(t) do
   171 		encodelen(buf, key:len())
   172 		encodelen(buf, val:len())
   173 		insert(buf, key)
   174 		insert(buf, val)
   175 	end
   176 	return concat(buf)
   177 end
   178 
   179 local FastCGI = _M
   180 
   181 function FastCGI.new(class, self)
   182 	self = self or { }
   183 	self.requests = { }
   184 	self.socket = false
   185 	self.serving = false
   186 	return Class.new(class, self)
   187 end
   188 
   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
   193 	local r = {
   194 		ver = t:byte(1),
   195 		type = t:byte(2),
   196 		id = t:byte(3) * 256 + t:byte(4),
   197 		len = t:byte(5) * 256 + t:byte(6)
   198 	}
   199 	if r.len == 0 then
   200 		r.content = ""
   201 	else
   202 		r.content, err = self.socket:receive(r.len)
   203 		if not r.content then return end
   204 		if err then error(err) end
   205 	end
   206 	local pad = t:byte(7)
   207 	if pad > 0 then
   208 		t, err = self.socket:receive(pad)
   209 		if not t then return end
   210 		if err then error(err) end
   211 	end
   212 	return r
   213 end
   214 
   215 function FastCGI:write(type, id, s)
   216 	local totlen = s:len()
   217 	local totpos = 1
   218 	while totlen > 0 do
   219 		local len = min(totlen, 65535)
   220 		local buf = concat {
   221 			char(1), -- version
   222 			char(type), -- type
   223 			char(bit.rshift(id, 8)), -- id1
   224 			char(id % 256), -- id0
   225 			char(bit.rshift(len, 8)), -- len1
   226 			char(len % 256), -- len0
   227 			char(0), -- pad = 0
   228 			char(0), -- reserved
   229 			s:sub(totpos, totpos + len - 1) -- content
   230 		}
   231 		totpos = totpos + len
   232 		totlen = totlen - len
   233 
   234 		len = buf:len()
   235 		local pos, res, err = 1
   236 		while pos <= len do
   237 			res, err = self.socket:send(buf, pos)
   238 			if not res then
   239 				return nil, err
   240 			end
   241 			pos = res + 1
   242 		end
   243 	end
   244 	return true
   245 end
   246 
   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 -------------------------------------------------------------------------------
   252 
   253 function FastCGI:write_stdout(id, s)
   254 	return self:write(FCGI_STDOUT, id, s)
   255 end
   256 
   257 function FastCGI:collectstream(r)
   258 	local req = self.requests[r.id]
   259 	local s = req.streams[r.type]
   260 	if not s then
   261 		s = FIFO:new()
   262 		req.streams[r.type] = s
   263 	end
   264 	if r.len == 0 then
   265 		s:write() -- append EOF
   266 		return s, true -- finished
   267 	end
   268 	s:write(r.content)
   269 	return s
   270 end
   271 
   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
   280 --	error message.
   281 -------------------------------------------------------------------------------
   282 
   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)),
   292 		char(protstatus),
   293 		char(0), char(0), char(0)
   294 	})
   295 end
   296 
   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
   301 	return req
   302 end
   303 
   304 function FastCGI:processrecord(r)
   305 
   306 	local c = r.content
   307 	local req = self.requests[r.id]
   308 
   309 	if r.type == FCGI_BEGIN_REQUEST then
   310 		assert(not req)
   311 		local role = c:byte(1) * 256 + c:byte(2)
   312 		if role == FCGI_RESPONDER then
   313 			-- new request
   314 			local flags = c:byte(3)
   315 			req = self:newrequest(r.id, role, flags)
   316 			return true -- continue
   317 		end
   318 		-- unknown role
   319 		return self:endrequest(req, FCGI_UNKNOWN_ROLE)
   320 	end
   321 
   322 	if not req then -- request already closed
   323 		return true -- continue
   324 	end
   325 
   326 	if r.type == FCGI_ABORT_REQUEST then
   327 		return self:abortrequest(req)
   328 
   329 	elseif r.type == FCGI_GET_VALUES then
   330 		local s, fin = self:collectstream(r)
   331 		if s and fin then
   332 			local res = { }
   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"
   340 				end
   341 			end
   342 			res = encodekeyvals(res)
   343 			return self:write(FCGI_GET_VALUES_RESULT, 0, res)
   344 		end
   345 
   346 	elseif r.type == FCGI_PARAMS then
   347 		local s, fin = self:collectstream(r)
   348 		if s and fin then
   349 			req.params = s:readkeyvals()
   350 			return self:have_params(req, req.params)
   351 		end
   352 
   353 	elseif r.type == self.FCGI_STDIN or r.type == self.FCGI_DATA then
   354 		local s, fin = self:collectstream(r)
   355 		if fin then
   356 			return self:have_stream(req, r.type, s)
   357 		else
   358 			return self:update_stream(req, r.type, s)
   359 		end
   360 
   361 	else
   362 		-- unknown record
   363 		local buf = char(r.type) .. char(0):rep(7)
   364 		return self:write(FCGI_UNKNOWN_TYPE, 0, buf)
   365 	end
   366 
   367 	return true -- continue
   368 end
   369 
   370 -------------------------------------------------------------------------------
   371 --	serve(socket): Serve the FastCGI protocol on the supplied socket until
   372 --	FastCGI:stop() is called.
   373 -------------------------------------------------------------------------------
   374 
   375 function FastCGI:serve(socket)
   376 	assert(socket)
   377 	self.socket = socket
   378 	self.serving = true
   379 	while self.serving do
   380 		local r = self:readrecord()
   381 		if not r then
   382 			break
   383 		end
   384 		if not self:processrecord(r) then
   385 			break
   386 		end
   387 	end
   388 end
   389 
   390 -------------------------------------------------------------------------------
   391 --	stop(): Stop acting as a server. This will cause FastCGI:serve() to
   392 --	return.
   393 -------------------------------------------------------------------------------
   394 
   395 function FastCGI:stop()
   396 	self.serving = false
   397 end
   398 
   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 -------------------------------------------------------------------------------
   404 
   405 function FastCGI:abortrequest(req)
   406 	-- request aborted by webserver, confirm:
   407 	return self:endrequest(req)
   408 end
   409 
   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 -------------------------------------------------------------------------------
   419 
   420 function FastCGI:have_params()
   421 	return true
   422 end
   423 
   424 function FastCGI:update_stream()
   425 	return true
   426 end