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" };
40 -- Connection counter resets to 0 on load and reload
41 -- Bump it up to current value
43 for _ in pairs(sessions) do
46 measure_connections(count);
49 --- Stream events handlers
50 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
52 function stream_callbacks.streamopened(session, attr)
53 local send = session.send;
54 session.host = nameprep(attr.to);
55 if not session.host then
56 session:close{ condition = "improper-addressing",
57 text = "A valid 'to' attribute is required on stream headers" };
60 session.version = tonumber(attr.version) or 0;
61 session.streamid = uuid_generate();
62 (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
64 if not hosts[session.host] or not hosts[session.host].modules.c2s then
65 -- We don't serve this host...
66 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
70 session:open_stream();
72 (session.log or log)("debug", "Sent reply <stream:stream> to client");
73 session.notopen = nil;
75 -- If session.secure is *false* (not nil) then it means we /were/ encrypting
76 -- since we now have a new stream header, session is secured
77 if session.secure == false then
78 session.secure = true;
79 session.encrypted = true;
81 local sock = session.conn:socket();
83 local info = sock:info();
84 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
85 session.compressed = info.compression;
87 (session.log or log)("info", "Stream encrypted");
88 session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
92 local features = st.stanza("stream:features");
93 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
94 if features.tags[1] or session.full_jid then
97 (session.log or log)("warn", "No features to offer");
98 session:close{ condition = "undefined-condition", text = "No features to proceed with" };
102 function stream_callbacks.streamclosed(session)
103 session.log("debug", "Received </stream:stream>");
104 session:close(false);
107 function stream_callbacks.error(session, error, data)
108 if error == "no-stream" then
109 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
110 session:close("invalid-namespace");
111 elseif error == "parse-error" then
112 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
113 session:close("not-well-formed");
114 elseif error == "stream-error" then
115 local condition, text = "undefined-condition";
116 for child in data:children() do
117 if child.attr.xmlns == xmlns_xmpp_streams then
118 if child.name ~= "text" then
119 condition = child.name;
121 text = child:get_text();
123 if condition ~= "undefined-condition" and text then
128 text = condition .. (text and (" ("..text..")") or "");
129 session.log("info", "Session closed by remote with error: %s", text);
130 session:close(nil, text);
134 local function handleerr(err) log("error", "Traceback[c2s]: %s", traceback(tostring(err), 2)); end
135 function stream_callbacks.handlestanza(session, stanza)
136 stanza = session.filter("stanzas/in", stanza);
138 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
143 local function session_close(session, reason)
144 local log = session.log or log;
146 if session.notopen then
147 session:open_stream();
149 if reason then -- nil == no err, initiated by us, false == initiated by client
150 local stream_error = st.stanza("stream:error");
151 if type(reason) == "string" then -- assume stream error
152 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
153 elseif type(reason) == "table" then
154 if reason.condition then
155 stream_error:tag(reason.condition, stream_xmlns_attr):up();
157 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
160 stream_error:add_child(reason.extra);
162 elseif reason.name then -- a stanza
163 stream_error = reason;
166 stream_error = tostring(stream_error);
167 log("debug", "Disconnecting client, <stream:error> is: %s", stream_error);
168 session.send(stream_error);
171 session.send("</stream:stream>");
172 function session.send() return false; end
174 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
175 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed");
177 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
178 local conn = session.conn;
179 if reason == nil and not session.notopen and session.type == "c2s" then
180 -- Grace time to process data from authenticated cleanly-closed stream
181 add_task(stream_close_timeout, function ()
182 if not session.destroyed then
183 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
184 sm_destroy_session(session, reason);
189 sm_destroy_session(session, reason);
193 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
194 sm_destroy_session(session, reason);
198 module:hook_global("user-deleted", function(event)
199 local username, host = event.username, event.host;
200 local user = hosts[host].sessions[username];
201 if user and user.sessions then
202 for jid, session in pairs(user.sessions) do
203 session:close{ condition = "not-authorized", text = "Account deleted" };
209 function listener.onconnect(conn)
210 measure_connections(1);
211 local session = sm_new_session(conn);
212 sessions[conn] = session;
214 session.log("info", "Client connected");
216 -- Client is using legacy SSL (otherwise mod_tls sets this flag)
218 session.secure = true;
219 session.encrypted = true;
221 -- Check if TLS compression is used
222 local sock = conn:socket();
224 session.compressed = sock:info"compression";
225 elseif sock.compression then
226 session.compressed = sock:compression(); --COMPAT mw/luasec-hg
230 if opt_keepalives then
231 conn:setoption("keepalive", opt_keepalives);
234 session.close = session_close;
236 local stream = new_xmpp_stream(session, stream_callbacks);
237 session.stream = stream;
238 session.notopen = true;
240 function session.reset_stream()
241 session.notopen = true;
242 session.stream:reset();
245 local filter = session.filter;
246 function session.data(data)
247 -- Parse the data, which will store stanzas in session.pending_stanzas
249 data = filter("bytes/in", data);
251 local ok, err = stream:feed(data);
253 log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
254 session:close("not-well-formed");
261 add_task(c2s_timeout, function ()
262 if session.type == "c2s_unauthed" then
263 session:close("connection-timeout");
268 session.dispatch_stanza = stream_callbacks.handlestanza;
271 function listener.onincoming(conn, data)
272 local session = sessions[conn];
278 function listener.ondisconnect(conn, err)
279 measure_connections(-1);
280 local session = sessions[conn];
282 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
283 sm_destroy_session(session, err);
285 sessions[conn] = nil;
289 function listener.onreadtimeout(conn)
290 local session = sessions[conn];
292 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
296 local function keepalive(event)
297 return event.session.send(' ');
300 function listener.associate_session(conn, session)
301 sessions[conn] = session;
304 function module.add_host(module)
305 module:hook("c2s-read-timeout", keepalive, -1);
308 module:hook("c2s-read-timeout", keepalive, -1);
310 module:hook("server-stopping", function(event)
311 local reason = event.reason;
312 for _, session in pairs(sessions) do
313 session:close{ condition = "system-shutdown", text = reason };
319 module:provides("net", {
323 encryption = "starttls";
325 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
329 module:provides("net", {
334 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";