2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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;
16 local ipairs = ipairs;
17 local t_insert = table.insert;
18 local t_concat = table.concat;
20 local default_log = require "util.logger".init("xmlhandlers");
27 ["http://www.w3.org/XML/1998/namespace"] = "xml";
30 function init_xmlhandlers(session, stream_callbacks)
31 local ns_stack = { "" };
34 local xml_handlers = {};
35 local log = session.log or default_log;
37 local cb_streamopened = stream_callbacks.streamopened;
38 local cb_streamclosed = stream_callbacks.streamclosed;
39 local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end;
40 local cb_handlestanza = stream_callbacks.handlestanza;
42 local stream_tag = stream_callbacks.stream_tag;
43 local stream_default_ns = stream_callbacks.default_ns;
46 function xml_handlers:StartElement(tagname, attr)
47 if stanza and #chardata > 0 then
48 -- We have some character data in the buffer
49 stanza:text(t_concat(chardata));
52 local curr_ns,name = tagname:match("^([^\1]*)\1?(.*)$");
54 curr_ns, name = "", curr_ns;
57 if curr_ns ~= stream_default_ns then
65 local ns, nm = k:match("^([^\1]*)\1?(.*)$");
69 attr[ns..":"..nm] = attr[k];
75 if not stanza then --if we are not currently inside a stanza
76 if session.notopen then
77 if tagname == stream_tag then
78 if cb_streamopened then
79 cb_streamopened(session, attr);
82 -- Garbage before stream?
83 cb_error(session, "no-stream");
87 if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
88 cb_error(session, "invalid-top-level-element");
91 stanza = st.stanza(name, attr);
93 else -- we are inside a stanza, so add a tag
95 if curr_ns ~= stream_default_ns then
98 stanza:tag(name, attr);
101 function xml_handlers:CharacterData(data)
103 t_insert(chardata, data);
106 function xml_handlers:EndElement(tagname)
107 local curr_ns,name = tagname:match("^([^\1]*)\1?(.*)$");
109 curr_ns, name = "", curr_ns;
111 if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
112 if tagname == stream_tag then
113 if cb_streamclosed then
114 cb_streamclosed(session);
116 elseif name == "error" then
117 cb_error(session, "stream-error", stanza);
119 cb_error(session, "parse-error", "unexpected-element-close", name);
121 stanza, chardata = nil, {};
124 if #chardata > 0 then
125 -- We have some character data in the buffer
126 stanza:text(t_concat(chardata));
130 if #stanza.last_add == 0 then
131 cb_handlestanza(session, stanza);
140 return init_xmlhandlers;