# # $Id: cgi.awk 12 2009-08-02 06:34:10Z stephenm $ # # # cgi stuff function cgi_init() { _hex2chr_init() _html_encode_init() } function cgi_test() { _url_decode_test() _cgi_parse_test() _html_encode_test() } function _hex2chr_init(chrs, i, hex) { # allow tab, lf, cr i = 9; hex[i] = sprintf("%02x", i) i = 10; hex[i] = sprintf("%02x", i) i = 13; hex[i] = sprintf("%02x", i) for (i = 32; i < 127; i++) { hex[i] = sprintf("%02x", i) } # default all hex to "X" for (i = 0; i < 255; i++) { _hex2chr[sprintf("%02x", i)] = "X" } for (i in hex) { _hex2chr[hex[i]] = sprintf("%c", i + 0) } } function hex2chr(hex, val) { hex = "00" hex hex = tolower(substr(hex, length(hex) - 1)) val = _hex2chr[hex] return val } function _url_decode_test(tmp, expected, i) { print("url_decode: ") tmp[0] = "e+c%3f=fu%3D"; expected[0] = "e c?=fu=" for (i in tmp) { if (url_decode(tmp[i]) != expected[i]) { print("FAIL") } } } function url_decode(url, i, c, out) { out = "" sub(/\+/, " ", url) for (i = 0; i < length(url); i++) { c = substr(url, i + 1, 1) if (c == "%") { out = out hex2chr(substr(url, i + 2, 2)) i += 2 } else { out = out c } } return out } function cgi_parse(query, defaults, out, params, i, j, count, param, val) { count = 0 for (i in defaults) { out[i] = defaults[i] } split(query, params, "&") for (i in params) { j = index(params[i], "=") if (j <= 0) continue param = url_decode(substr(params[i], 1, j - 1)) val = url_decode(substr(params[i], j + 1)) if (param in defaults) { out[param] = val count++ } } return count; } function _cgi_parse_test(defaults, out, count, pass) { print("cgi_parse: ") defaults["user"] = "" defaults["key"] = "" defaults["arg"] = "" count = cgi_parse("user=fubar&key=a%3db%3f%07+&&&User=%29", defaults, out) pass = (count == 2) && (out["user"] == "fubar") && (out["key"] == "a=b?X ") if (!pass) print("FAIL") } function cgi_header(mime_type) { print("Content-type:" mime_type) print("") } function _html_encode_init(c, i) { # tab -> space, allow lf _html_encode["\t"] = " " _html_encode["\n"] = "\n" for (i = 32; i < 127; i++) { c = sprintf("%c", i) _html_encode[c] = c } # & -> & < -> < > -> > ' -> ' " -> " _html_encode["&"] = "&" _html_encode["<"] = "<" _html_encode[">"] = ">" _html_encode["'"] = "'" _html_encode["\""] = """ } function html_encode(s, i, c, out) { out = "" for (i = 0; i < length(s); i++) { c = substr(s, i + 1, 1) out = out _html_encode[c] } return out } function _html_encode_test(out) { print("html_encode: ") out = html_encode("\b '&'") if (out != "<img src="b"> '&'") print("FAIL") } # BEGIN { cgi_init(); cgi_test(); exit }