Merge 0.9->0.10
[prosody.git] / util / xmppstream.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 local lxp = require "lxp";
10 local st = require "util.stanza";
11 local stanza_mt = st.stanza_mt;
12
13 local error = error;
14 local tostring = tostring;
15 local t_insert = table.insert;
16 local t_concat = table.concat;
17 local t_remove = table.remove;
18 local setmetatable = setmetatable;
19
20 -- COMPAT: w/LuaExpat 1.1.0
21 local lxp_supports_doctype = pcall(lxp.new, { StartDoctypeDecl = false });
22 local lxp_supports_xmldecl = pcall(lxp.new, { XmlDecl = false });
23 local lxp_supports_bytecount = not not lxp.new({}).getcurrentbytecount;
24
25 local default_stanza_size_limit = 1024*1024*10; -- 10MB
26
27 module "xmppstream"
28
29 local new_parser = lxp.new;
30
31 local xml_namespace = {
32         ["http://www.w3.org/XML/1998/namespace\1lang"] = "xml:lang";
33         ["http://www.w3.org/XML/1998/namespace\1space"] = "xml:space";
34         ["http://www.w3.org/XML/1998/namespace\1base"] = "xml:base";
35         ["http://www.w3.org/XML/1998/namespace\1id"] = "xml:id";
36 };
37
38 local xmlns_streams = "http://etherx.jabber.org/streams";
39
40 local ns_separator = "\1";
41 local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$";
42
43 _M.ns_separator = ns_separator;
44 _M.ns_pattern = ns_pattern;
45
46 local function dummy_cb() end
47
48 function new_sax_handlers(session, stream_callbacks, cb_handleprogress)
49         local xml_handlers = {};
50
51         local cb_streamopened = stream_callbacks.streamopened;
52         local cb_streamclosed = stream_callbacks.streamclosed;
53         local cb_error = stream_callbacks.error or function(session, e, stanza) error("XML stream error: "..tostring(e)..(stanza and ": "..tostring(stanza) or ""),2); end;
54         local cb_handlestanza = stream_callbacks.handlestanza;
55         cb_handleprogress = cb_handleprogress or dummy_cb;
56
57         local stream_ns = stream_callbacks.stream_ns or xmlns_streams;
58         local stream_tag = stream_callbacks.stream_tag or "stream";
59         if stream_ns ~= "" then
60                 stream_tag = stream_ns..ns_separator..stream_tag;
61         end
62         local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error");
63
64         local stream_default_ns = stream_callbacks.default_ns;
65
66         local stack = {};
67         local chardata, stanza = {};
68         local stanza_size = 0;
69         local non_streamns_depth = 0;
70         function xml_handlers:StartElement(tagname, attr)
71                 if stanza and #chardata > 0 then
72                         -- We have some character data in the buffer
73                         t_insert(stanza, t_concat(chardata));
74                         chardata = {};
75                 end
76                 local curr_ns,name = tagname:match(ns_pattern);
77                 if name == "" then
78                         curr_ns, name = "", curr_ns;
79                 end
80
81                 if curr_ns ~= stream_default_ns or non_streamns_depth > 0 then
82                         attr.xmlns = curr_ns;
83                         non_streamns_depth = non_streamns_depth + 1;
84                 end
85
86                 for i=1,#attr do
87                         local k = attr[i];
88                         attr[i] = nil;
89                         local xmlk = xml_namespace[k];
90                         if xmlk then
91                                 attr[xmlk] = attr[k];
92                                 attr[k] = nil;
93                         end
94                 end
95
96                 if not stanza then --if we are not currently inside a stanza
97                         if lxp_supports_bytecount then
98                                 stanza_size = self:getcurrentbytecount();
99                         end
100                         if session.notopen then
101                                 if tagname == stream_tag then
102                                         non_streamns_depth = 0;
103                                         if cb_streamopened then
104                                                 if lxp_supports_bytecount then
105                                                         cb_handleprogress(stanza_size);
106                                                         stanza_size = 0;
107                                                 end
108                                                 cb_streamopened(session, attr);
109                                         end
110                                 else
111                                         -- Garbage before stream?
112                                         cb_error(session, "no-stream", tagname);
113                                 end
114                                 return;
115                         end
116                         if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
117                                 cb_error(session, "invalid-top-level-element");
118                         end
119
120                         stanza = setmetatable({ name = name, attr = attr, tags = {} }, stanza_mt);
121                 else -- we are inside a stanza, so add a tag
122                         if lxp_supports_bytecount then
123                                 stanza_size = stanza_size + self:getcurrentbytecount();
124                         end
125                         t_insert(stack, stanza);
126                         local oldstanza = stanza;
127                         stanza = setmetatable({ name = name, attr = attr, tags = {} }, stanza_mt);
128                         t_insert(oldstanza, stanza);
129                         t_insert(oldstanza.tags, stanza);
130                 end
131         end
132         if lxp_supports_xmldecl then
133                 function xml_handlers:XmlDecl(version, encoding, standalone)
134                         if lxp_supports_bytecount then
135                                 cb_handleprogress(self:getcurrentbytecount());
136                         end
137                 end
138         end
139         function xml_handlers:StartCdataSection()
140                 if lxp_supports_bytecount then
141                         if stanza then
142                                 stanza_size = stanza_size + self:getcurrentbytecount();
143                         else
144                                 cb_handleprogress(self:getcurrentbytecount());
145                         end
146                 end
147         end
148         function xml_handlers:EndCdataSection()
149                 if lxp_supports_bytecount then
150                         if stanza then
151                                 stanza_size = stanza_size + self:getcurrentbytecount();
152                         else
153                                 cb_handleprogress(self:getcurrentbytecount());
154                         end
155                 end
156         end
157         function xml_handlers:CharacterData(data)
158                 if stanza then
159                         if lxp_supports_bytecount then
160                                 stanza_size = stanza_size + self:getcurrentbytecount();
161                         end
162                         t_insert(chardata, data);
163                 elseif lxp_supports_bytecount then
164                         cb_handleprogress(self:getcurrentbytecount());
165                 end
166         end
167         function xml_handlers:EndElement(tagname)
168                 if lxp_supports_bytecount then
169                         stanza_size = stanza_size + self:getcurrentbytecount()
170                 end
171                 if non_streamns_depth > 0 then
172                         non_streamns_depth = non_streamns_depth - 1;
173                 end
174                 if stanza then
175                         if #chardata > 0 then
176                                 -- We have some character data in the buffer
177                                 t_insert(stanza, t_concat(chardata));
178                                 chardata = {};
179                         end
180                         -- Complete stanza
181                         if #stack == 0 then
182                                 if lxp_supports_bytecount then
183                                         cb_handleprogress(stanza_size);
184                                 end
185                                 stanza_size = 0;
186                                 if tagname ~= stream_error_tag then
187                                         cb_handlestanza(session, stanza);
188                                 else
189                                         cb_error(session, "stream-error", stanza);
190                                 end
191                                 stanza = nil;
192                         else
193                                 stanza = t_remove(stack);
194                         end
195                 else
196                         if cb_streamclosed then
197                                 cb_streamclosed(session);
198                         end
199                 end
200         end
201
202         local function restricted_handler(parser)
203                 cb_error(session, "parse-error", "restricted-xml", "Restricted XML, see RFC 6120 section 11.1.");
204                 if not parser.stop or not parser:stop() then
205                         error("Failed to abort parsing");
206                 end
207         end
208
209         if lxp_supports_doctype then
210                 xml_handlers.StartDoctypeDecl = restricted_handler;
211         end
212         xml_handlers.Comment = restricted_handler;
213         xml_handlers.ProcessingInstruction = restricted_handler;
214
215         local function reset()
216                 stanza, chardata, stanza_size = nil, {}, 0;
217                 stack = {};
218         end
219
220         local function set_session(stream, new_session)
221                 session = new_session;
222         end
223
224         return xml_handlers, { reset = reset, set_session = set_session };
225 end
226
227 function new(session, stream_callbacks, stanza_size_limit)
228         -- Used to track parser progress (e.g. to enforce size limits)
229         local n_outstanding_bytes = 0;
230         local handle_progress;
231         if lxp_supports_bytecount then
232                 function handle_progress(n_parsed_bytes)
233                         n_outstanding_bytes = n_outstanding_bytes - n_parsed_bytes;
234                 end
235                 stanza_size_limit = stanza_size_limit or default_stanza_size_limit;
236         elseif stanza_size_limit then
237                 error("Stanza size limits are not supported on this version of LuaExpat")
238         end
239
240         local handlers, meta = new_sax_handlers(session, stream_callbacks, handle_progress);
241         local parser = new_parser(handlers, ns_separator, false);
242         local parse = parser.parse;
243
244         function session.open_stream(session, from, to)
245                 local send = session.sends2s or session.send;
246
247                 local attr = {
248                         ["xmlns:stream"] = "http://etherx.jabber.org/streams",
249                         ["xml:lang"] = "en",
250                         xmlns = stream_callbacks.default_ns,
251                         version = session.version and (session.version > 0 and "1.0" or nil),
252                         id = session.streamid,
253                         from = from or session.host, to = to,
254                 };
255                 if session.stream_attrs then
256                         session:stream_attrs(from, to, attr)
257                 end
258                 send("<?xml version='1.0'?>");
259                 send(st.stanza("stream:stream", attr):top_tag());
260                 return true;
261         end
262
263         return {
264                 reset = function ()
265                         parser = new_parser(handlers, ns_separator, false);
266                         parse = parser.parse;
267                         n_outstanding_bytes = 0;
268                         meta.reset();
269                 end,
270                 feed = function (self, data)
271                         if lxp_supports_bytecount then
272                                 n_outstanding_bytes = n_outstanding_bytes + #data;
273                         end
274                         local ok, err = parse(parser, data);
275                         if lxp_supports_bytecount and n_outstanding_bytes > stanza_size_limit then
276                                 return nil, "stanza-too-large";
277                         end
278                         return ok, err;
279                 end,
280                 set_session = meta.set_session;
281         };
282 end
283
284 return _M;