2 LuCI - HTTP-Interaction
5 HTTP-Header manipulator and form variable preprocessor
8 Copyright 2008 Steven Barth <steven@midlink.org>
10 Licensed under the Apache License, Version 2.0 (the "License");
11 you may not use this file except in compliance with the License.
12 You may obtain a copy of the License at
14 http://www.apache.org/licenses/LICENSE-2.0
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
24 local ltn12 = require "luci.ltn12"
25 local protocol = require "luci.http.protocol"
26 local util = require "luci.util"
27 local string = require "string"
28 local coroutine = require "coroutine"
29 local table = require "table"
31 local ipairs, pairs, next, type, tostring, error =
32 ipairs, pairs, next, type, tostring, error
34 --- LuCI Web Framework high-level HTTP functions.
37 context = util.threadlocal()
39 Request = util.class()
40 function Request.__init__(self, env, sourcein, sinkerr)
45 -- File handler nil by default to let .content() work
46 self.filehandler = nil
52 params = protocol.urldecode_params(env.QUERY_STRING or ""),
55 self.parsed_input = false
58 function Request.formvalue(self, name, noparse)
59 if not noparse and not self.parsed_input then
64 return self.message.params[name]
66 return self.message.params
70 function Request.formvaluetable(self, prefix)
72 prefix = prefix and prefix .. "." or "."
74 if not self.parsed_input then
78 local void = self.message.params[nil]
79 for k, v in pairs(self.message.params) do
80 if k:find(prefix, 1, true) == 1 then
81 vals[k:sub(#prefix + 1)] = tostring(v)
88 function Request.content(self)
89 if not self.parsed_input then
93 return self.message.content, self.message.content_length
96 function Request.getcookie(self, name)
97 local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";")
98 local p = ";" .. name .. "=(.-);"
99 local i, j, value = c:find(p)
100 return value and urldecode(value)
103 function Request.getenv(self, name)
105 return self.message.env[name]
107 return self.message.env
111 function Request.setfilehandler(self, callback)
112 self.filehandler = callback
115 function Request._parse_input(self)
116 protocol.parse_message_body(
121 self.parsed_input = true
124 --- Close the HTTP-Connection.
126 if not context.eoh then
131 if not context.closed then
132 context.closed = true
137 --- Return the request content if the request was of unknown type.
138 -- @return HTTP request body
139 -- @return HTTP request body length
141 return context.request:content()
144 --- Get a certain HTTP input value or a table of all input values.
145 -- @param name Name of the GET or POST variable to fetch
146 -- @param noparse Don't parse POST data before getting the value
147 -- @return HTTP input value or table of all input value
148 function formvalue(name, noparse)
149 return context.request:formvalue(name, noparse)
152 --- Get a table of all HTTP input values with a certain prefix.
153 -- @param prefix Prefix
154 -- @return Table of all HTTP input values with given prefix
155 function formvaluetable(prefix)
156 return context.request:formvaluetable(prefix)
159 --- Get the value of a certain HTTP-Cookie.
160 -- @param name Cookie Name
161 -- @return String containing cookie data
162 function getcookie(name)
163 return context.request:getcookie(name)
166 --- Get the value of a certain HTTP environment variable
167 -- or the environment table itself.
168 -- @param name Environment variable
169 -- @return HTTP environment value or environment table
170 function getenv(name)
171 return context.request:getenv(name)
174 --- Set a handler function for incoming user file uploads.
175 -- @param callback Handler function
176 function setfilehandler(callback)
177 return context.request:setfilehandler(callback)
180 --- Send a HTTP-Header.
181 -- @param key Header key
182 -- @param value Header value
183 function header(key, value)
184 if not context.headers then
187 context.headers[key:lower()] = value
188 coroutine.yield(2, key, value)
191 --- Set the mime type of following content data.
192 -- @param mime Mimetype of following content
193 function prepare_content(mime)
194 if not context.headers or not context.headers["content-type"] then
195 if mime == "application/xhtml+xml" then
196 if not getenv("HTTP_ACCEPT") or
197 not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then
198 mime = "text/html; charset=UTF-8"
200 header("Vary", "Accept")
202 header("Content-Type", mime)
206 --- Get the RAW HTTP input source
207 -- @return HTTP LTN12 source
209 return context.request.input
212 --- Set the HTTP status code and status message.
213 -- @param code Status code
214 -- @param message Status message
215 function status(code, message)
217 message = message or "OK"
218 context.status = code
219 coroutine.yield(1, code, message)
222 --- Send a chunk of content data to the client.
223 -- This function is as a valid LTN12 sink.
224 -- If the content chunk is nil this function will automatically invoke close.
225 -- @param content Content chunk
226 -- @param src_err Error object from source (optional)
228 function write(content, src_err)
236 elseif #content == 0 then
239 if not context.eoh then
240 if not context.status then
243 if not context.headers or not context.headers["content-type"] then
244 header("Content-Type", "text/html; charset=utf-8")
246 if not context.headers["cache-control"] then
247 header("Cache-Control", "no-cache")
248 header("Expires", "0")
255 coroutine.yield(4, content)
260 --- Splice data from a filedescriptor to the client.
261 -- @param fp File descriptor
262 -- @param size Bytes to splice (optional)
263 function splice(fd, size)
264 coroutine.yield(6, fd, size)
267 --- Redirects the client to a new URL and closes the connection.
268 -- @param url Target URL
269 function redirect(url)
271 header("Location", url)
275 --- Create a querystring out of a table of key - value pairs.
276 -- @param table Query string source table
277 -- @return Encoded HTTP query string
278 function build_querystring(q)
281 for k, v in pairs(q) do
282 if #s > 1 then s[#s+1] = "&" end
284 s[#s+1] = urldecode(k)
286 s[#s+1] = urldecode(v)
289 return table.concat(s, "")
292 --- Return the URL-decoded equivalent of a string.
293 -- @param str URL-encoded string
294 -- @param no_plus Don't decode + to " "
295 -- @return URL-decoded string
297 urldecode = protocol.urldecode
299 --- Return the URL-encoded equivalent of a string.
300 -- @param str Source string
301 -- @return URL-encoded string
303 urlencode = protocol.urlencode
305 --- Send the given data as JSON encoded string.
306 -- @param data Data to send
307 function write_json(x)
310 elseif type(x) == "table" then
312 if type(next(x)) == "number" then
314 for k, v in ipairs(x) do
323 for k, v in pairs(x) do
332 elseif type(x) == "number" or type(x) == "boolean" then
334 -- NaN is the only value that doesn't equal to itself.
340 write('"%s"' % tostring(x):gsub('["%z\1-\31]', function(c)
341 return '\\u%04x' % c:byte(1)