2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
11 local add_task = require "util.timer".add_task;
12 local new_xmpp_stream = require "util.xmppstream".new;
13 local nameprep = require "util.encodings".stringprep.nameprep;
14 local sessionmanager = require "core.sessionmanager";
15 local st = require "util.stanza";
16 local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
17 local uuid_generate = require "util.uuid".generate;
19 local xpcall, tostring, type = xpcall, tostring, type;
20 local traceback = debug.traceback;
22 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
24 local log = module._log;
26 local c2s_timeout = module:get_option_number("c2s_timeout");
27 local stream_close_timeout = module:get_option_number("c2s_close_timeout", 5);
28 local opt_keepalives = module:get_option_boolean("c2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
30 local measure_connections = module:measure("connections", "counter");
32 local sessions = module:shared("sessions");
33 local core_process_stanza = prosody.core_process_stanza;
34 local hosts = prosody.hosts;
36 local stream_callbacks = { default_ns = "jabber:client" };
39 --- Stream events handlers
40 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
42 function stream_callbacks.streamopened(session, attr)
43 local send = session.send;
44 session.host = nameprep(attr.to);
45 if not session.host then
46 session:close{ condition = "improper-addressing",
47 text = "A valid 'to' attribute is required on stream headers" };
50 session.version = tonumber(attr.version) or 0;
51 session.streamid = uuid_generate();
52 (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
54 if not hosts[session.host] or not hosts[session.host].modules.c2s then
55 -- We don't serve this host...
56 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
60 session:open_stream();
62 (session.log or log)("debug", "Sent reply <stream:stream> to client");
63 session.notopen = nil;
65 -- If session.secure is *false* (not nil) then it means we /were/ encrypting
66 -- since we now have a new stream header, session is secured
67 if session.secure == false then
68 session.secure = true;
69 session.encrypted = true;
71 local sock = session.conn:socket();
73 local info = sock:info();
74 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
75 session.compressed = info.compression;
77 (session.log or log)("info", "Stream encrypted");
78 session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
82 local features = st.stanza("stream:features");
83 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
84 if features.tags[1] or session.full_jid then
87 (session.log or log)("warn", "No features to offer");
88 session:close{ condition = "undefined-condition", text = "No features to proceed with" };
92 function stream_callbacks.streamclosed(session)
93 session.log("debug", "Received </stream:stream>");
97 function stream_callbacks.error(session, error, data)
98 if error == "no-stream" then
99 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
100 session:close("invalid-namespace");
101 elseif error == "parse-error" then
102 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
103 session:close("not-well-formed");
104 elseif error == "stream-error" then
105 local condition, text = "undefined-condition";
106 for child in data:children() do
107 if child.attr.xmlns == xmlns_xmpp_streams then
108 if child.name ~= "text" then
109 condition = child.name;
111 text = child:get_text();
113 if condition ~= "undefined-condition" and text then
118 text = condition .. (text and (" ("..text..")") or "");
119 session.log("info", "Session closed by remote with error: %s", text);
120 session:close(nil, text);
124 local function handleerr(err) log("error", "Traceback[c2s]: %s", traceback(tostring(err), 2)); end
125 function stream_callbacks.handlestanza(session, stanza)
126 stanza = session.filter("stanzas/in", stanza);
128 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
133 local function session_close(session, reason)
134 local log = session.log or log;
136 if session.notopen then
137 session:open_stream();
139 if reason then -- nil == no err, initiated by us, false == initiated by client
140 local stream_error = st.stanza("stream:error");
141 if type(reason) == "string" then -- assume stream error
142 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
143 elseif type(reason) == "table" then
144 if reason.condition then
145 stream_error:tag(reason.condition, stream_xmlns_attr):up();
147 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
150 stream_error:add_child(reason.extra);
152 elseif reason.name then -- a stanza
153 stream_error = reason;
156 stream_error = tostring(stream_error);
157 log("debug", "Disconnecting client, <stream:error> is: %s", stream_error);
158 session.send(stream_error);
161 session.send("</stream:stream>");
162 function session.send() return false; end
164 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
165 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed");
167 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
168 local conn = session.conn;
169 if reason == nil and not session.notopen and session.type == "c2s" then
170 -- Grace time to process data from authenticated cleanly-closed stream
171 add_task(stream_close_timeout, function ()
172 if not session.destroyed then
173 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
174 sm_destroy_session(session, reason);
179 sm_destroy_session(session, reason);
183 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
184 sm_destroy_session(session, reason);
188 module:hook_global("user-deleted", function(event)
189 local username, host = event.username, event.host;
190 local user = hosts[host].sessions[username];
191 if user and user.sessions then
192 for jid, session in pairs(user.sessions) do
193 session:close{ condition = "not-authorized", text = "Account deleted" };
199 function listener.onconnect(conn)
200 measure_connections(1);
201 local session = sm_new_session(conn);
202 sessions[conn] = session;
204 session.log("info", "Client connected");
206 -- Client is using legacy SSL (otherwise mod_tls sets this flag)
208 session.secure = true;
209 session.encrypted = true;
211 -- Check if TLS compression is used
212 local sock = conn:socket();
214 session.compressed = sock:info"compression";
215 elseif sock.compression then
216 session.compressed = sock:compression(); --COMPAT mw/luasec-hg
220 if opt_keepalives then
221 conn:setoption("keepalive", opt_keepalives);
224 session.close = session_close;
226 local stream = new_xmpp_stream(session, stream_callbacks);
227 session.stream = stream;
228 session.notopen = true;
230 function session.reset_stream()
231 session.notopen = true;
232 session.stream:reset();
235 local filter = session.filter;
236 function session.data(data)
237 -- Parse the data, which will store stanzas in session.pending_stanzas
239 data = filter("bytes/in", data);
241 local ok, err = stream:feed(data);
243 log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
244 session:close("not-well-formed");
251 add_task(c2s_timeout, function ()
252 if session.type == "c2s_unauthed" then
253 session:close("connection-timeout");
258 session.dispatch_stanza = stream_callbacks.handlestanza;
261 function listener.onincoming(conn, data)
262 local session = sessions[conn];
268 function listener.ondisconnect(conn, err)
269 measure_connections(-1);
270 local session = sessions[conn];
272 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
273 sm_destroy_session(session, err);
275 sessions[conn] = nil;
279 function listener.onreadtimeout(conn)
280 local session = sessions[conn];
282 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
286 local function keepalive(event)
287 return event.session.send(' ');
290 function listener.associate_session(conn, session)
291 sessions[conn] = session;
294 function module.add_host(module)
295 module:hook("c2s-read-timeout", keepalive, -1);
298 module:hook("c2s-read-timeout", keepalive, -1);
300 module:hook("server-stopping", function(event)
301 local reason = event.reason;
302 for _, session in pairs(sessions) do
303 session:close{ condition = "system-shutdown", text = reason };
309 module:provides("net", {
313 encryption = "starttls";
315 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
319 module:provides("net", {
324 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";