treewide: removed trailing whitespaces and extra newlines in 'modules'
[project/luci.git] / modules / luci-base / luasrc / sgi / cgi.lua
1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 exectime = os.clock()
5 module("luci.sgi.cgi", package.seeall)
6 local ltn12 = require("luci.ltn12")
7 require("nixio.util")
8 require("luci.http")
9 require("luci.sys")
10 require("luci.dispatcher")
11
12 -- Limited source to avoid endless blocking
13 local function limitsource(handle, limit)
14 limit = limit or 0
15 local BLOCKSIZE = ltn12.BLOCKSIZE
16
17 return function()
18 if limit < 1 then
19 handle:close()
20 return nil
21 else
22 local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit
23 limit = limit - read
24
25 local chunk = handle:read(read)
26 if not chunk then handle:close() end
27 return chunk
28 end
29 end
30 end
31
32 function run()
33 local r = luci.http.Request(
34 luci.sys.getenv(),
35 limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))),
36 ltn12.sink.file(io.stderr)
37 )
38
39 local x = coroutine.create(luci.dispatcher.httpdispatch)
40 local hcache = ""
41 local active = true
42
43 while coroutine.status(x) ~= "dead" do
44 local res, id, data1, data2 = coroutine.resume(x, r)
45
46 if not res then
47 print("Status: 500 Internal Server Error")
48 print("Content-Type: text/plain\n")
49 print(id)
50 break;
51 end
52
53 if active then
54 if id == 1 then
55 io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n")
56 elseif id == 2 then
57 hcache = hcache .. data1 .. ": " .. data2 .. "\r\n"
58 elseif id == 3 then
59 io.write(hcache)
60 io.write("\r\n")
61 elseif id == 4 then
62 io.write(tostring(data1 or ""))
63 elseif id == 5 then
64 io.flush()
65 io.close()
66 active = false
67 elseif id == 6 then
68 data1:copyz(nixio.stdout, data2)
69 data1:close()
70 end
71 end
72 end
73 end