5 local tostring = tostring;
6 local format = string.format;
7 local m_random = math.random;
8 local t_insert = table.insert;
9 local t_remove = table.remove;
10 local t_concat = table.concat;
11 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
12 local sm_destroy_session = import("core.sessionmanager", "destroy_session");
14 local default_log = require "util.logger".init("xmlhandlers");
20 function init_xmlhandlers(session, streamopened)
21 local ns_stack = { "" };
25 local xml_handlers = {};
26 local log = session.log or default_log;
27 local print = function (...) log("info", "xmlhandlers", t_concatall({...}, "\t")); end
29 local send = session.send;
32 function xml_handlers:StartElement(name, attr)
33 if stanza and #chardata > 0 then
34 -- We have some character data in the buffer
35 stanza:text(t_concat(chardata));
38 log("debug", "Start element: %s", tostring(name));
39 curr_ns,name = name:match("^(.+):([%w%-]+)$");
42 if not stanza then --if we are not currently inside a stanza
43 if session.notopen then
44 if name == "stream" then
45 streamopened(session, attr);
48 error("Client failed to open stream successfully");
50 if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
51 error("Client sent invalid top-level stanza");
54 stanza = st.stanza(name, attr); --{ to = attr.to, type = attr.type, id = attr.id, xmlns = curr_ns });
56 else -- we are inside a stanza, so add a tag
58 stanza:tag(name, attr);
61 function xml_handlers:CharacterData(data)
63 t_insert(chardata, data);
66 function xml_handlers:EndElement(name)
67 curr_ns,name = name:match("^(.+):([%w%-]+)$");
68 if (not stanza) or #stanza.last_add < 0 or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then
69 if name == "stream" then
70 log("debug", "Stream closed");
71 sm_destroy_session(session);
73 elseif name == "error" then
74 error("Stream error: "..tostring(name)..": "..tostring(stanza));
76 error("XML parse error in client stream");
79 if stanza and #chardata > 0 then
80 -- We have some character data in the buffer
81 stanza:text(t_concat(chardata));
85 if #stanza.last_add == 0 then
86 session.stanza_dispatch(stanza);
95 return init_xmlhandlers;