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;
18 local t_insert = table.insert;
19 local t_concat = table.concat;
21 local default_log = require "util.logger".init("xmlhandlers");
28 ["http://www.w3.org/XML/1998/namespace"] = "xml";
31 function init_xmlhandlers(session, stream_callbacks)
32 local ns_stack = { "" };
33 local curr_ns, name = "";
36 local xml_handlers = {};
37 local log = session.log or default_log;
39 local cb_streamopened = stream_callbacks.streamopened;
40 local cb_streamclosed = stream_callbacks.streamclosed;
41 local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end;
42 local cb_handlestanza = stream_callbacks.handlestanza;
44 local stream_tag = stream_callbacks.stream_tag;
45 local stream_default_ns = stream_callbacks.default_ns;
48 function xml_handlers:StartElement(tagname, attr)
49 if stanza and #chardata > 0 then
50 -- We have some character data in the buffer
51 stanza:text(t_concat(chardata));
54 local curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
56 curr_ns, name = "", curr_ns;
59 if curr_ns ~= stream_default_ns then
64 for i, k in ipairs(attr) do
65 if type(k) == "string" then
66 local ns, nm = k:match("^([^|]+)|?([^|]-)$")
70 attr[ns..":"..nm] = attr[k];
71 attr[i] = ns..":"..nm;
78 if not stanza then --if we are not currently inside a stanza
79 if session.notopen then
80 if tagname == stream_tag then
81 if cb_streamopened then
82 cb_streamopened(session, attr);
85 -- Garbage before stream?
86 cb_error(session, "no-stream");
90 if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
91 cb_error(session, "invalid-top-level-element");
94 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)
110 curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
112 curr_ns, name = "", curr_ns;
114 if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
115 if tagname == stream_tag then
116 if cb_streamclosed then
117 cb_streamclosed(session);
120 elseif name == "error" then
121 cb_error(session, "stream-error", stanza);
123 cb_error(session, "parse-error", "unexpected-element-close", name);
127 if #chardata > 0 then
128 -- We have some character data in the buffer
129 stanza:text(t_concat(chardata));
133 if #stanza.last_add == 0 then
134 cb_handlestanza(session, stanza);
144 return init_xmlhandlers;