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