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