aboutsummaryrefslogtreecommitdiff
path: root/common/cgi.lua
blob: 8f2acefc498f25b8ef15f971cc961190a8a666dc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
cgi = {}

cgi.none = "None"
cgi.lax = "Lax"
cgi.strict = "Strict"

-- global helpers
function string.split(self, sep)
	if not sep then sep = "%s" end

	local t = {}
	for match in (self .. sep):gmatch("(.-)" .. sep) do
		table.insert(t, match)
	end

	return t
end

function string.fromhex(self)
	return (self:gsub("..", function(cc)
		return string.char(tonumber(cc, 16))
	end))
end

function string.tohex(self)
	return (self:gsub(".", function(c)
		return string.format("%02x", string.byte(c))
	end))
end

function cgi.encode_uri(str)
	if str then
		str = str:gsub("\n", "\r\n")
		str = str:gsub("([^%w _ %- . ~])",
			function(c) return string.format("%%%02X", string.byte(c)) end)
		str = str:gsub(" ", "+")
	end

	return str
end

function cgi.decode_uri(str)
	if str then
		str = str:gsub("+", " ")
		str = str:gsub("%%(%x%x)",
			function(hex) return string.char(tonumber(hex, 16)) end)
	end

	return str
end

local function parse_params(dst, src)
	for _, pair in ipairs(src:split("&")) do
		local kv = pair:split("=")
		local key = kv[1]
		local value = kv[2]

		dst[key] = cgi.decode_uri(value)
	end
end

local function params_tostring(src)
	local dst = ""
	for k, v in pairs(src) do
		local kv = k .. "=" .. cgi.encode_uri(v)
		dst = dst .. kv .. "&"
	end

	return dst:sub(1, #dst - 1)
end

local function parse_cookies(dst, src)
	for _, pair in ipairs(src:split("; ")) do
		local kv = pair:split("=")
		local key = kv[1]
		local value = kv[2]

		dst[key] = cgi.decode_uri(value)
	end
end

-- method
cgi.method = os.getenv("REQUEST_METHOD")

-- GET/POST params
cgi.get = {}
cgi.post = {}

if cgi.method == "GET" then
	local get_params = os.getenv("QUERY_STRING")
	if get_params then
		parse_params(cgi.get, get_params)
	end
elseif cgi.method == "POST" then
	local post_params = io.read("*a")
	if post_params then
		parse_params(cgi.post, post_params)
	end
end

-- cookies
local cookies = {}

local cookie = os.getenv("HTTP_COOKIE")
if cookie then
	local c = {}
	parse_cookies(c, cookie)

	for k, v in pairs(c) do
		cookies[k] = {value = v}
	end
end

function cgi.get_cookie(name)
	if not cookies[name] then return nil end
	return cookies[name].value
end

function cgi.set_cookie(name, cookie)
	cookie._modified = true
	cookies[name] = cookie
end

-- custom headers
function cgi.request_header(name)
	return os.getenv("HTTP_" .. name:upper())
end

local resp_headers = {}
local headers_complete = false
function cgi.header(key, value)
	if not value then
		return false
	end

	if not headers_complete then
		resp_headers[key] = value
		print(key .. ": " .. value)
	end

	return not headers_complete
end

-- set cookies on exit
local function set_cookies()
	for name, c in pairs(cookies) do
		if c._modified then
			local cookie = name .. "=" .. cgi.encode_uri(c.value or "")

			if c.domain then
				cookie = cookie .. "; Domain=" .. c.domain
			end
			if c.path then
				cookie = cookie .. "; Path=" .. c.path
			end
			if c.expires then
				cookie = cookie .. "; Expires=" .. c.expires
			end
			if c.http_only then
				cookie = cookie .. "; HttpOnly"
			end
			if c.https_only then
				cookie = cookie .. "; Secure"
			end
			if c.same_site then
				cookie = cookie .. "; SameSite=" .. c.same_site
			end

			cgi.header("Set-Cookie", cookie)
		end
	end
end

-- special date format
function cgi.date(t)
	return os.date("!%a, %d %b %Y %H:%M:%S GMT", t)
end

-- (custom) content
function cgi.content(data)
	if not headers_complete then
		set_cookies()
		print()
		headers_complete = true
	end

	if data then
		print(data)
	end

	return not not data
end

function cgi.serve(data)
	if data then
		cgi.content(data)
	else
		cgi.status(500)
	end

	cgi.done()
end

-- finish response
function cgi.done()
	if not headers_complete then
		local body

		local status = tonumber(resp_headers["Status"])
		if status and status >= 400 and status < 600 then
			-- error but no content: display error page
			local f = io.open("/var/www/html/error/" .. tostring(status) .. ".html")
			if f then
				body = f:read("*a")
				f:close()
			end
		end

		cgi.content(body)
	end

	os.exit(0)
end

-- frequently used header utilities
function cgi.content_type(type)
	return cgi.header("Content-Type", type)
end

function cgi.status(code)
	return cgi.header("Status", tostring(code))
end

return cgi