2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
14 local tostring = tostring;
15 local t_insert = table.insert;
16 local t_concat = table.concat;
18 local default_log = require "util.logger".init("xmlhandlers");
25 ["http://www.w3.org/XML/1998/namespace"] = "xml";
28 local xmlns_streams = "http://etherx.jabber.org/streams";
30 local ns_separator = "\1";
31 local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$";
33 function init_xmlhandlers(session, stream_callbacks)
35 local xml_handlers = {};
36 local log = session.log or default_log;
38 local cb_streamopened = stream_callbacks.streamopened;
39 local cb_streamclosed = stream_callbacks.streamclosed;
40 local cb_error = stream_callbacks.error or function(session, e) error("XML stream error: "..tostring(e)); end;
41 local cb_handlestanza = stream_callbacks.handlestanza;
43 local stream_ns = stream_callbacks.stream_ns or xmlns_streams;
44 local stream_tag = stream_ns..ns_separator..(stream_callbacks.stream_tag or "stream");
45 local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error");
47 local stream_default_ns = stream_callbacks.default_ns;
50 function xml_handlers:StartElement(tagname, attr)
51 if stanza and #chardata > 0 then
52 -- We have some character data in the buffer
53 stanza:text(t_concat(chardata));
56 local curr_ns,name = tagname:match(ns_pattern);
58 curr_ns, name = "", curr_ns;
61 if curr_ns ~= stream_default_ns then
69 local ns, nm = k:match(ns_pattern);
73 attr[ns..":"..nm] = attr[k];
79 if not stanza then --if we are not currently inside a stanza
80 if session.notopen then
81 if tagname == stream_tag then
82 if cb_streamopened then
83 cb_streamopened(session, attr);
86 -- Garbage before stream?
87 cb_error(session, "no-stream");
91 if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
92 cb_error(session, "invalid-top-level-element");
95 stanza = st.stanza(name, attr);
96 else -- we are inside a stanza, so add a tag
98 if curr_ns ~= stream_default_ns then
101 stanza:tag(name, attr);
104 function xml_handlers:CharacterData(data)
106 t_insert(chardata, data);
109 function xml_handlers:EndElement(tagname)
111 if #chardata > 0 then
112 -- We have some character data in the buffer
113 stanza:text(t_concat(chardata));
117 if #stanza.last_add == 0 then
118 if tagname ~= stream_error_tag then
119 cb_handlestanza(session, stanza);
121 cb_error(session, "stream-error", stanza);
128 if tagname == stream_tag then
129 if cb_streamclosed then
130 cb_streamclosed(session);
133 local curr_ns,name = tagname:match(ns_pattern);
135 curr_ns, name = "", curr_ns;
137 cb_error(session, "parse-error", "unexpected-element-close", name);
139 stanza, chardata = nil, {};
145 return init_xmlhandlers;