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 = { "" };
32 local curr_ns, name = "";
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_tag = stream_callbacks.stream_tag;
44 local stream_default_ns = stream_callbacks.default_ns;
47 function xml_handlers:StartElement(tagname, attr)
48 if stanza and #chardata > 0 then
49 -- We have some character data in the buffer
50 stanza:text(t_concat(chardata));
53 local curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
55 curr_ns, name = "", curr_ns;
58 if curr_ns ~= stream_default_ns then
66 local ns, nm = k:match("^([^|]+)|?([^|]-)$")
70 attr[ns..":"..nm] = attr[k];
76 if not stanza then --if we are not currently inside a stanza
77 if session.notopen then
78 if tagname == stream_tag then
79 if cb_streamopened then
80 cb_streamopened(session, attr);
83 -- Garbage before stream?
84 cb_error(session, "no-stream");
88 if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
89 cb_error(session, "invalid-top-level-element");
92 stanza = st.stanza(name, attr);
94 else -- we are inside a stanza, so add a tag
96 if curr_ns ~= stream_default_ns then
99 stanza:tag(name, attr);
102 function xml_handlers:CharacterData(data)
104 t_insert(chardata, data);
107 function xml_handlers:EndElement(tagname)
108 curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
110 curr_ns, name = "", curr_ns;
112 if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
113 if tagname == stream_tag then
114 if cb_streamclosed then
115 cb_streamclosed(session);
118 elseif name == "error" then
119 cb_error(session, "stream-error", stanza);
121 cb_error(session, "parse-error", "unexpected-element-close", name);
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;