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;
18 local runner = require "util.async".runner;
20 local xpcall, tostring, type = xpcall, tostring, type;
21 local t_insert, t_remove = table.insert, table.remove;
23 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
25 local log = module._log;
27 local c2s_timeout = module:get_option_number("c2s_timeout");
28 local stream_close_timeout = module:get_option_number("c2s_close_timeout", 5);
29 local opt_keepalives = module:get_option_boolean("c2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
31 local sessions = module:shared("sessions");
32 local core_process_stanza = prosody.core_process_stanza;
33 local hosts = prosody.hosts;
35 local stream_callbacks = { default_ns = "jabber:client" };
37 local runner_callbacks = {};
39 --- Stream events handlers
40 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
41 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
43 function stream_callbacks.streamopened(session, attr)
44 local send = session.send;
45 session.host = nameprep(attr.to);
46 if not session.host then
47 session:close{ condition = "improper-addressing",
48 text = "A valid 'to' attribute is required on stream headers" };
51 session.version = tonumber(attr.version) or 0;
52 session.streamid = uuid_generate();
53 (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
55 if not hosts[session.host] or not hosts[session.host].modules.c2s then
56 -- We don't serve this host...
57 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
61 send("<?xml version='1.0'?>"..st.stanza("stream:stream", {
62 xmlns = 'jabber:client', ["xmlns:stream"] = 'http://etherx.jabber.org/streams';
63 id = session.streamid, from = session.host, version = '1.0', ["xml:lang"] = 'en' }):top_tag());
65 (session.log or log)("debug", "Sent reply <stream:stream> to client");
66 session.notopen = nil;
68 -- If session.secure is *false* (not nil) then it means we /were/ encrypting
69 -- since we now have a new stream header, session is secured
70 if session.secure == false then
71 session.secure = true;
72 session.encrypted = true;
74 local sock = session.conn:socket();
76 local info = sock:info();
77 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
78 session.compressed = info.compression;
80 (session.log or log)("info", "Stream encrypted");
81 session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
85 local features = st.stanza("stream:features");
86 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
90 function stream_callbacks.streamclosed(session)
91 session.log("debug", "Received </stream:stream>");
95 function stream_callbacks.error(session, error, data)
96 if error == "no-stream" then
97 session.log("debug", "Invalid opening stream header");
98 session:close("invalid-namespace");
99 elseif error == "parse-error" then
100 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
101 session:close("not-well-formed");
102 elseif error == "stream-error" then
103 local condition, text = "undefined-condition";
104 for child in data:children() do
105 if child.attr.xmlns == xmlns_xmpp_streams then
106 if child.name ~= "text" then
107 condition = child.name;
109 text = child:get_text();
111 if condition ~= "undefined-condition" and text then
116 text = condition .. (text and (" ("..text..")") or "");
117 session.log("info", "Session closed by remote with error: %s", text);
118 session:close(nil, text);
122 function stream_callbacks.handlestanza(session, stanza)
123 stanza = session.filter("stanzas/in", stanza);
124 session.thread:run(stanza);
128 local function session_close(session, reason)
129 local log = session.log or log;
131 if session.notopen then
132 session.send("<?xml version='1.0'?>");
133 session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
135 if reason then -- nil == no err, initiated by us, false == initiated by client
136 local stream_error = st.stanza("stream:error");
137 if type(reason) == "string" then -- assume stream error
138 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
139 elseif type(reason) == "table" then
140 if reason.condition then
141 stream_error:tag(reason.condition, stream_xmlns_attr):up();
143 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
146 stream_error:add_child(reason.extra);
148 elseif reason.name then -- a stanza
149 stream_error = reason;
152 stream_error = tostring(stream_error);
153 log("debug", "Disconnecting client, <stream:error> is: %s", stream_error);
154 session.send(stream_error);
157 session.send("</stream:stream>");
158 function session.send() return false; end
160 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
161 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed");
163 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
164 local conn = session.conn;
165 if reason == nil and not session.notopen and session.type == "c2s" then
166 -- Grace time to process data from authenticated cleanly-closed stream
167 add_task(stream_close_timeout, function ()
168 if not session.destroyed then
169 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
170 sm_destroy_session(session, reason);
175 sm_destroy_session(session, reason);
181 module:hook_global("user-deleted", function(event)
182 local username, host = event.username, event.host;
183 local user = hosts[host].sessions[username];
184 if user and user.sessions then
185 for jid, session in pairs(user.sessions) do
186 session:close{ condition = "not-authorized", text = "Account deleted" };
191 function runner_callbacks:ready()
192 self.data.conn:resume();
195 function runner_callbacks:waiting()
196 self.data.conn:pause();
199 function runner_callbacks:error(err)
200 (self.data.log or log)("error", "Traceback[c2s]: %s", err);
204 function listener.onconnect(conn)
205 local session = sm_new_session(conn);
206 sessions[conn] = session;
208 session.log("info", "Client connected");
210 -- Client is using legacy SSL (otherwise mod_tls sets this flag)
212 session.secure = true;
213 session.encrypted = true;
215 -- Check if TLS compression is used
216 local sock = conn:socket();
218 session.compressed = sock:info"compression";
219 elseif sock.compression then
220 session.compressed = sock:compression(); --COMPAT mw/luasec-hg
224 if opt_keepalives then
225 conn:setoption("keepalive", opt_keepalives);
228 session.close = session_close;
230 local stream = new_xmpp_stream(session, stream_callbacks);
231 session.stream = stream;
232 session.notopen = true;
234 function session.reset_stream()
235 session.notopen = true;
236 session.stream:reset();
239 session.thread = runner(function (stanza)
240 core_process_stanza(session, stanza);
241 end, runner_callbacks, session);
243 local filter = session.filter;
244 function session.data(data)
245 -- Parse the data, which will store stanzas in session.pending_stanzas
247 data = filter("bytes/in", data);
249 local ok, err = stream:feed(data);
251 log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
252 session:close("not-well-formed");
259 add_task(c2s_timeout, function ()
260 if session.type == "c2s_unauthed" then
261 session:close("connection-timeout");
266 session.dispatch_stanza = stream_callbacks.handlestanza;
269 function listener.onincoming(conn, data)
270 local session = sessions[conn];
276 function listener.ondisconnect(conn, err)
277 local session = sessions[conn];
279 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
280 sm_destroy_session(session, err);
281 sessions[conn] = nil;
285 function listener.onreadtimeout(conn)
286 local session = sessions[conn];
288 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
292 local function keepalive(event)
293 return event.session.send(' ');
296 function listener.associate_session(conn, session)
297 sessions[conn] = session;
300 function module.add_host(module)
301 module:hook("c2s-read-timeout", keepalive, -1);
304 module:hook("c2s-read-timeout", keepalive, -1);
306 module:hook("server-stopping", function(event)
307 local reason = event.reason;
308 for _, session in pairs(sessions) do
309 session:close{ condition = "system-shutdown", text = reason };
315 module:provides("net", {
319 encryption = "starttls";
321 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
325 module:provides("net", {
330 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";