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
63 for i, k in ipairs(attr) do
64 local ns, nm = k:match("^([^|]+)|?([^|]-)$")
68 attr[ns..":"..nm] = attr[k];
69 attr[i] = ns..":"..nm;
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 curr_ns,name = tagname:match("^(.-)|?([^%|]-)$");
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);
117 elseif name == "error" then
118 cb_error(session, "stream-error", stanza);
120 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);
141 return init_xmlhandlers;