5 local tostring = tostring;
10 local format = string.format;
11 local m_random = math.random;
12 local t_insert = table.insert;
13 local t_remove = table.remove;
14 local t_concat = table.concat;
15 local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
16 local sm_destroy_session = import("core.sessionmanager", "destroy_session");
18 local default_log = require "util.logger".init("xmlhandlers");
25 ["http://www.w3.org/XML/1998/namespace"] = "xml";
28 function init_xmlhandlers(session, stream_callbacks)
29 local ns_stack = { "" };
33 local xml_handlers = {};
34 local log = session.log or default_log;
35 --local print = function (...) log("info", "xmlhandlers", t_concatall({...}, "\t")); end
37 local send = session.send;
39 local cb_streamopened = stream_callbacks.streamopened;
40 local cb_streamclosed = stream_callbacks.streamclosed;
43 function xml_handlers:StartElement(name, attr)
44 if stanza and #chardata > 0 then
45 -- We have some character data in the buffer
46 stanza:text(t_concat(chardata));
49 curr_ns,name = name:match("^(.+)|([%w%-]+)$");
50 if curr_ns ~= "jabber:server" then
55 for i, k in ipairs(attr) do
56 if type(k) == "string" then
57 local ns, nm = k:match("^([^|]+)|?([^|]-)$")
61 attr[ns..":"..nm] = attr[k];
62 attr[i] = ns..":"..nm;
69 if not stanza then --if we are not currently inside a stanza
70 if session.notopen then
71 if name == "stream" then
72 if cb_streamopened then
73 cb_streamopened(session, attr);
77 error("Client failed to open stream successfully");
79 if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
80 error("Client sent invalid top-level stanza");
83 stanza = st.stanza(name, attr);
85 else -- we are inside a stanza, so add a tag
87 if curr_ns ~= "jabber:server" and curr_ns ~= "jabber:client" then
90 stanza:tag(name, attr);
93 function xml_handlers:CharacterData(data)
95 t_insert(chardata, data);
98 function xml_handlers:EndElement(name)
99 curr_ns,name = name:match("^(.+)|([%w%-]+)$");
100 if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
101 if name == "stream" then
102 log("debug", "Stream closed");
103 if cb_streamclosed then
104 cb_streamclosed(session);
107 elseif name == "error" then
108 error("Stream error: "..tostring(name)..": "..tostring(stanza));
110 error("XML parse error in client stream with element: "..name);
113 if stanza and #chardata > 0 then
114 -- We have some character data in the buffer
115 stanza:text(t_concat(chardata));
119 if #stanza.last_add == 0 then
120 session.stanza_dispatch(stanza);
129 return init_xmlhandlers;