Merge 0.9->0.10
[prosody.git] / util / stanza.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local t_insert      =  table.insert;
11 local t_remove      =  table.remove;
12 local t_concat      =  table.concat;
13 local s_format      = string.format;
14 local s_match       =  string.match;
15 local tostring      =      tostring;
16 local setmetatable  =  setmetatable;
17 local pairs         =         pairs;
18 local ipairs        =        ipairs;
19 local type          =          type;
20 local s_gsub        =   string.gsub;
21 local s_sub         =    string.sub;
22 local s_find        =   string.find;
23 local os            =            os;
24
25 local do_pretty_printing = not os.getenv("WINDIR");
26 local getstyle, getstring;
27 if do_pretty_printing then
28         local ok, termcolours = pcall(require, "util.termcolours");
29         if ok then
30                 getstyle, getstring = termcolours.getstyle, termcolours.getstring;
31         else
32                 do_pretty_printing = nil;
33         end
34 end
35
36 local xmlns_stanzas = "urn:ietf:params:xml:ns:xmpp-stanzas";
37
38 module "stanza"
39
40 stanza_mt = { __type = "stanza" };
41 stanza_mt.__index = stanza_mt;
42 local stanza_mt = stanza_mt;
43
44 function stanza(name, attr)
45         local stanza = { name = name, attr = attr or {}, tags = {} };
46         return setmetatable(stanza, stanza_mt);
47 end
48 local stanza = stanza;
49
50 function stanza_mt:query(xmlns)
51         return self:tag("query", { xmlns = xmlns });
52 end
53
54 function stanza_mt:body(text, attr)
55         return self:tag("body", attr):text(text);
56 end
57
58 function stanza_mt:tag(name, attrs)
59         local s = stanza(name, attrs);
60         local last_add = self.last_add;
61         if not last_add then last_add = {}; self.last_add = last_add; end
62         (last_add[#last_add] or self):add_direct_child(s);
63         t_insert(last_add, s);
64         return self;
65 end
66
67 function stanza_mt:text(text)
68         local last_add = self.last_add;
69         (last_add and last_add[#last_add] or self):add_direct_child(text);
70         return self;
71 end
72
73 function stanza_mt:up()
74         local last_add = self.last_add;
75         if last_add then t_remove(last_add); end
76         return self;
77 end
78
79 function stanza_mt:reset()
80         self.last_add = nil;
81         return self;
82 end
83
84 function stanza_mt:add_direct_child(child)
85         if type(child) == "table" then
86                 t_insert(self.tags, child);
87         end
88         t_insert(self, child);
89 end
90
91 function stanza_mt:add_child(child)
92         local last_add = self.last_add;
93         (last_add and last_add[#last_add] or self):add_direct_child(child);
94         return self;
95 end
96
97 function stanza_mt:get_child(name, xmlns)
98         for _, child in ipairs(self.tags) do
99                 if (not name or child.name == name)
100                         and ((not xmlns and self.attr.xmlns == child.attr.xmlns)
101                                 or child.attr.xmlns == xmlns) then
102
103                         return child;
104                 end
105         end
106 end
107
108 function stanza_mt:get_child_text(name, xmlns)
109         local tag = self:get_child(name, xmlns);
110         if tag then
111                 return tag:get_text();
112         end
113         return nil;
114 end
115
116 function stanza_mt:child_with_name(name)
117         for _, child in ipairs(self.tags) do
118                 if child.name == name then return child; end
119         end
120 end
121
122 function stanza_mt:child_with_ns(ns)
123         for _, child in ipairs(self.tags) do
124                 if child.attr.xmlns == ns then return child; end
125         end
126 end
127
128 function stanza_mt:children()
129         local i = 0;
130         return function (a)
131                         i = i + 1
132                         return a[i];
133                 end, self, i;
134 end
135
136 function stanza_mt:childtags(name, xmlns)
137         local tags = self.tags;
138         local start_i, max_i = 1, #tags;
139         return function ()
140                 for i = start_i, max_i do
141                         local v = tags[i];
142                         if (not name or v.name == name)
143                         and ((not xmlns and self.attr.xmlns == v.attr.xmlns)
144                                 or v.attr.xmlns == xmlns) then
145                                 start_i = i+1;
146                                 return v;
147                         end
148                 end
149         end;
150 end
151
152 function stanza_mt:maptags(callback)
153         local tags, curr_tag = self.tags, 1;
154         local n_children, n_tags = #self, #tags;
155
156         local i = 1;
157         while curr_tag <= n_tags and n_tags > 0 do
158                 if self[i] == tags[curr_tag] then
159                         local ret = callback(self[i]);
160                         if ret == nil then
161                                 t_remove(self, i);
162                                 t_remove(tags, curr_tag);
163                                 n_children = n_children - 1;
164                                 n_tags = n_tags - 1;
165                                 i = i - 1;
166                                 curr_tag = curr_tag - 1;
167                         else
168                                 self[i] = ret;
169                                 tags[curr_tag] = ret;
170                         end
171                         curr_tag = curr_tag + 1;
172                 end
173                 i = i + 1;
174         end
175         return self;
176 end
177
178 function stanza_mt:find(path)
179         local pos = 1;
180         local len = #path + 1;
181
182         repeat
183                 local xmlns, name, text;
184                 local char = s_sub(path, pos, pos);
185                 if char == "@" then
186                         return self.attr[s_sub(path, pos + 1)];
187                 elseif char == "{" then
188                         xmlns, pos = s_match(path, "^([^}]+)}()", pos + 1);
189                 end
190                 name, text, pos = s_match(path, "^([^@/#]*)([/#]?)()", pos);
191                 name = name ~= "" and name or nil;
192                 if pos == len then
193                         if text == "#" then
194                                 return self:get_child_text(name, xmlns);
195                         end
196                         return self:get_child(name, xmlns);
197                 end
198                 self = self:get_child(name, xmlns);
199         until not self
200 end
201
202
203 local xml_escape
204 do
205         local escape_table = {
206                 ["'"] = "&apos;";
207                 ['"'] = "&quot;";
208                 ["<"] = "&lt;";
209                 [">"] = "&gt;";
210                 ["&"] = "&amp;";
211                 -- escape this whitespace because [\r\n\t] change into spaces in attributes
212                 -- and \r\n changes into \n in text, and we want to preserve original bytes
213                 ["\t"] = "&#x9;";
214                 ["\n"] = "&#xA;";
215                 ["\r"] = "&#xD;";
216         };
217         function xml_escape(str) return (s_gsub(str, "['&<>\"\t\n\r]", escape_table)); end
218         _M.xml_escape = xml_escape;
219 end
220
221 local function _dostring(t, buf, self, xml_escape, parentns)
222         local nsid = 0;
223         local name = t.name
224         t_insert(buf, "<"..name);
225         for k, v in pairs(t.attr) do
226                 if s_find(k, "\1", 1, true) then
227                         local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$");
228                         nsid = nsid + 1;
229                         t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'");
230                 elseif not(k == "xmlns" and v == parentns) then
231                         t_insert(buf, " "..k.."='"..xml_escape(v).."'");
232                 end
233         end
234         local len = #t;
235         if len == 0 then
236                 t_insert(buf, "/>");
237         else
238                 t_insert(buf, ">");
239                 for n=1,len do
240                         local child = t[n];
241                         if child.name then
242                                 self(child, buf, self, xml_escape, t.attr.xmlns);
243                         else
244                                 t_insert(buf, xml_escape(child));
245                         end
246                 end
247                 t_insert(buf, "</"..name..">");
248         end
249 end
250 function stanza_mt.__tostring(t)
251         local buf = {};
252         _dostring(t, buf, _dostring, xml_escape, nil);
253         return t_concat(buf);
254 end
255
256 function stanza_mt.top_tag(t)
257         local attr_string = "";
258         if t.attr then
259                 for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, xml_escape(tostring(v))); end end
260         end
261         return s_format("<%s%s>", t.name, attr_string);
262 end
263
264 function stanza_mt.get_text(t)
265         if #t.tags == 0 then
266                 return t_concat(t);
267         end
268 end
269
270 function stanza_mt.get_error(stanza)
271         local type, condition, text;
272
273         local error_tag = stanza:get_child("error");
274         if not error_tag then
275                 return nil, nil, nil;
276         end
277         type = error_tag.attr.type;
278
279         for _, child in ipairs(error_tag.tags) do
280                 if child.attr.xmlns == xmlns_stanzas then
281                         if not text and child.name == "text" then
282                                 text = child:get_text();
283                         elseif not condition then
284                                 condition = child.name;
285                         end
286                         if condition and text then
287                                 break;
288                         end
289                 end
290         end
291         return type, condition or "undefined-condition", text;
292 end
293
294 do
295         local id = 0;
296         function new_id()
297                 id = id + 1;
298                 return "lx"..id;
299         end
300 end
301
302 function preserialize(stanza)
303         local s = { name = stanza.name, attr = stanza.attr };
304         for _, child in ipairs(stanza) do
305                 if type(child) == "table" then
306                         t_insert(s, preserialize(child));
307                 else
308                         t_insert(s, child);
309                 end
310         end
311         return s;
312 end
313
314 function deserialize(stanza)
315         -- Set metatable
316         if stanza then
317                 local attr = stanza.attr;
318                 for i=1,#attr do attr[i] = nil; end
319                 local attrx = {};
320                 for att in pairs(attr) do
321                         if s_find(att, "|", 1, true) and not s_find(att, "\1", 1, true) then
322                                 local ns,na = s_match(att, "^([^|]+)|(.+)$");
323                                 attrx[ns.."\1"..na] = attr[att];
324                                 attr[att] = nil;
325                         end
326                 end
327                 for a,v in pairs(attrx) do
328                         attr[a] = v;
329                 end
330                 setmetatable(stanza, stanza_mt);
331                 for _, child in ipairs(stanza) do
332                         if type(child) == "table" then
333                                 deserialize(child);
334                         end
335                 end
336                 if not stanza.tags then
337                         -- Rebuild tags
338                         local tags = {};
339                         for _, child in ipairs(stanza) do
340                                 if type(child) == "table" then
341                                         t_insert(tags, child);
342                                 end
343                         end
344                         stanza.tags = tags;
345                 end
346         end
347
348         return stanza;
349 end
350
351 local function _clone(stanza)
352         local attr, tags = {}, {};
353         for k,v in pairs(stanza.attr) do attr[k] = v; end
354         local new = { name = stanza.name, attr = attr, tags = tags };
355         for i=1,#stanza do
356                 local child = stanza[i];
357                 if child.name then
358                         child = _clone(child);
359                         t_insert(tags, child);
360                 end
361                 t_insert(new, child);
362         end
363         return setmetatable(new, stanza_mt);
364 end
365 clone = _clone;
366
367 function message(attr, body)
368         if not body then
369                 return stanza("message", attr);
370         else
371                 return stanza("message", attr):tag("body"):text(body):up();
372         end
373 end
374 function iq(attr)
375         if attr and not attr.id then attr.id = new_id(); end
376         return stanza("iq", attr or { id = new_id() });
377 end
378
379 function reply(orig)
380         return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or orig.attr.type) });
381 end
382
383 do
384         local xmpp_stanzas_attr = { xmlns = xmlns_stanzas };
385         function error_reply(orig, type, condition, message)
386                 local t = reply(orig);
387                 t.attr.type = "error";
388                 t:tag("error", {type = type}) --COMPAT: Some day xmlns:stanzas goes here
389                         :tag(condition, xmpp_stanzas_attr):up();
390                 if (message) then t:tag("text", xmpp_stanzas_attr):text(message):up(); end
391                 return t; -- stanza ready for adding app-specific errors
392         end
393 end
394
395 function presence(attr)
396         return stanza("presence", attr);
397 end
398
399 if do_pretty_printing then
400         local style_attrk = getstyle("yellow");
401         local style_attrv = getstyle("red");
402         local style_tagname = getstyle("red");
403         local style_punc = getstyle("magenta");
404
405         local attr_format = " "..getstring(style_attrk, "%s")..getstring(style_punc, "=")..getstring(style_attrv, "'%s'");
406         local top_tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">");
407         --local tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">").."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
408         local tag_format = top_tag_format.."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
409         function stanza_mt.pretty_print(t)
410                 local children_text = "";
411                 for n, child in ipairs(t) do
412                         if type(child) == "string" then
413                                 children_text = children_text .. xml_escape(child);
414                         else
415                                 children_text = children_text .. child:pretty_print();
416                         end
417                 end
418
419                 local attr_string = "";
420                 if t.attr then
421                         for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(attr_format, k, tostring(v)); end end
422                 end
423                 return s_format(tag_format, t.name, attr_string, children_text, t.name);
424         end
425
426         function stanza_mt.pretty_top_tag(t)
427                 local attr_string = "";
428                 if t.attr then
429                         for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(attr_format, k, tostring(v)); end end
430                 end
431                 return s_format(top_tag_format, t.name, attr_string);
432         end
433 else
434         -- Sorry, fresh out of colours for you guys ;)
435         stanza_mt.pretty_print = stanza_mt.__tostring;
436         stanza_mt.pretty_top_tag = stanza_mt.top_tag;
437 end
438
439 return _M;