util.x509: Only collect commonNames that pass idna
[prosody.git] / util / http.lua
blob3852f91ca4d09266c4a75dc2f103dabcc4d28e59
1 -- Prosody IM
2 -- Copyright (C) 2013 Florian Zeitz
3 --
4 -- This project is MIT/X11 licensed. Please see the
5 -- COPYING file in the source package for more information.
6 --
8 local format, char = string.format, string.char;
9 local pairs, ipairs = pairs, ipairs;
10 local t_insert, t_concat = table.insert, table.concat;
12 local url_codes = {};
13 for i = 0, 255 do
14 local c = char(i);
15 local u = format("%%%02x", i);
16 url_codes[c] = u;
17 url_codes[u] = c;
18 url_codes[u:upper()] = c;
19 end
20 local function urlencode(s)
21 return s and (s:gsub("[^a-zA-Z0-9.~_-]", url_codes));
22 end
23 local function urldecode(s)
24 return s and (s:gsub("%%%x%x", url_codes));
25 end
27 local function _formencodepart(s)
28 return s and (urlencode(s):gsub("%%20", "+"));
29 end
31 local function formencode(form)
32 local result = {};
33 if form[1] then -- Array of ordered { name, value }
34 for _, field in ipairs(form) do
35 t_insert(result, _formencodepart(field.name).."=".._formencodepart(field.value));
36 end
37 else -- Unordered map of name -> value
38 for name, value in pairs(form) do
39 t_insert(result, _formencodepart(name).."=".._formencodepart(value));
40 end
41 end
42 return t_concat(result, "&");
43 end
45 local function formdecode(s)
46 if not s:match("=") then return urldecode(s); end
47 local r = {};
48 for k, v in s:gmatch("([^=&]*)=([^&]*)") do
49 k, v = k:gsub("%+", "%%20"), v:gsub("%+", "%%20");
50 k, v = urldecode(k), urldecode(v);
51 t_insert(r, { name = k, value = v });
52 r[k] = v;
53 end
54 return r;
55 end
57 local function contains_token(field, token)
58 field = ","..field:gsub("[ \t]", ""):lower()..",";
59 return field:find(","..token:lower()..",", 1, true) ~= nil;
60 end
62 local function normalize_path(path, is_dir)
63 if is_dir then
64 if path:sub(-1,-1) ~= "/" then path = path.."/"; end
65 else
66 if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end
67 end
68 if path:sub(1,1) ~= "/" then path = "/"..path; end
69 return path;
70 end
72 return {
73 urlencode = urlencode, urldecode = urldecode;
74 formencode = formencode, formdecode = formdecode;
75 contains_token = contains_token;
76 normalize_path = normalize_path;