#!/usr/local/bin/lua -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- 1. Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- 3. The name of the author may not be used to endorse or promote products -- derived from this software without specific prior written permission. -- This software is provided as-is; all express or implied warranties are -- disclaimed, just like the all-caps section in the BSD license. -- This is a module conformant to LTN 07. -- http://www.lua.org/notes/ltn007.html -- Usage: -- require(".../cgi.lua") -- content = CGI.content() -- CGI.content() only works the first time you call it. content is the GET and -- POST (if any) content, URL-encoded. -- -- vars = CGI.vars(content) -- -- vars is a table whose keys are the form variable names, and whose values -- are their values. -- -- unenc = CGI.de_url_encode(enc) -- enc is a string containing + for spaces, and %xx hex codes. unenc is the -- unencoded equivalent. -- -- You're on your own for replying based on the variables you find: note -- especially that cgi.lua does not print HTTP headers for you. local E, I = {}, {} CGI = E function E.content() if(getenv("REQUEST_METHOD") == "POST") then local clength = getenv("CONTENT_LENGTH") local content = read(clength) local getcontent = getenv("QUERY_STRING") if(getcontent ~= "") then content = content + "&" + getcontent end return content else return getenv("QUERY_STRING") end end function I.hex_to_ch(str) return strchar(tonumber(str,16)) end function I.split(str, delim) local result = {} local right = str local left local dloc = strfind(str, delim, 1, 1) while(dloc) do left = strsub(str,1,dloc-1) right = strsub(str,dloc+1) tinsert(result, left) str = right dloc = strfind(str, delim, 1, 1) end tinsert(result, right) return result end function E.de_url_encode(str) local spaces = gsub(str, "%+", " ") local un_pct = gsub(spaces, "%%(%x%x)", %I.hex_to_ch) return un_pct end function E.vars(content) local result = {} local vars = %I.split(content, "&") for i = 1, getn(vars) do local v = vars[i] local t = %I.split(v, "=") if getn(t) > 1 then name, value = t[1], t[2] value = %E.de_url_encode(value) else name, value = t[1], 1 end name = %E.de_url_encode(name) result[name] = value end return result end