mod_s2s: Handle authentication of s2sin and s2sout the same way
[prosody.git] / plugins / mod_c2s.lua
blob02a0c5eba715169d2e4dc7ff064ae5c8ae6c1b5f
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
9 module:set_global();
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 tostring, type = tostring, type;
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", 300);
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", "amount");
31 local measure_ipv6 = module:measure("ipv6", "amount");
33 local sessions = module:shared("sessions");
34 local core_process_stanza = prosody.core_process_stanza;
35 local hosts = prosody.hosts;
37 local stream_callbacks = { default_ns = "jabber:client" };
38 local listener = {};
39 local runner_callbacks = {};
41 module:hook("stats-update", function ()
42 local count = 0;
43 local ipv6 = 0;
44 for _, session in pairs(sessions) do
45 count = count + 1;
46 if session.ip and session.ip:match(":") then
47 ipv6 = ipv6 + 1;
48 end
49 end
50 measure_connections(count);
51 measure_ipv6(ipv6);
52 end);
54 --- Stream events handlers
55 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
57 function stream_callbacks.streamopened(session, attr)
58 local send = session.send;
59 local host = nameprep(attr.to);
60 if not host then
61 session:close{ condition = "improper-addressing",
62 text = "A valid 'to' attribute is required on stream headers" };
63 return;
64 end
65 if not session.host then
66 session.host = host;
67 elseif session.host ~= host then
68 session:close{ condition = "not-authorized",
69 text = "The 'to' attribute must remain the same across stream restarts" };
70 return;
71 end
72 session.version = tonumber(attr.version) or 0;
73 session.streamid = uuid_generate();
74 (session.log or log)("debug", "Client sent opening <stream:stream> to %s", session.host);
76 if not hosts[session.host] or not hosts[session.host].modules.c2s then
77 -- We don't serve this host...
78 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
79 return;
80 end
82 session:open_stream();
84 (session.log or log)("debug", "Sent reply <stream:stream> to client");
85 session.notopen = nil;
87 -- If session.secure is *false* (not nil) then it means we /were/ encrypting
88 -- since we now have a new stream header, session is secured
89 if session.secure == false then
90 session.secure = true;
91 session.encrypted = true;
93 local sock = session.conn:socket();
94 if sock.info then
95 local info = sock:info();
96 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
97 session.compressed = info.compression;
98 else
99 (session.log or log)("info", "Stream encrypted");
103 local features = st.stanza("stream:features");
104 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
105 if features.tags[1] or session.full_jid then
106 send(features);
107 else
108 if session.secure then
109 -- Normally STARTTLS would be offered
110 (session.log or log)("warn", "No stream features to offer on secure session. Check authentication settings.");
111 else
112 -- Here SASL should be offered
113 (session.log or log)("warn", "No stream features to offer on insecure session. Check encryption and security settings.");
115 session:close{ condition = "undefined-condition", text = "No stream features to proceed with" };
119 function stream_callbacks.streamclosed(session)
120 session.log("debug", "Received </stream:stream>");
121 session:close(false);
124 function stream_callbacks.error(session, error, data)
125 if error == "no-stream" then
126 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
127 session:close("invalid-namespace");
128 elseif error == "parse-error" then
129 (session.log or log)("debug", "Client XML parse error: %s", data);
130 session:close("not-well-formed");
131 elseif error == "stream-error" then
132 local condition, text = "undefined-condition";
133 for child in data:childtags(nil, xmlns_xmpp_streams) do
134 if child.name ~= "text" then
135 condition = child.name;
136 else
137 text = child:get_text();
139 if condition ~= "undefined-condition" and text then
140 break;
143 text = condition .. (text and (" ("..text..")") or "");
144 session.log("info", "Session closed by remote with error: %s", text);
145 session:close(nil, text);
149 function stream_callbacks.handlestanza(session, stanza)
150 stanza = session.filter("stanzas/in", stanza);
151 session.thread:run(stanza);
154 --- Session methods
155 local function session_close(session, reason)
156 local log = session.log or log;
157 if session.conn then
158 if session.notopen then
159 session:open_stream();
161 if reason then -- nil == no err, initiated by us, false == initiated by client
162 local stream_error = st.stanza("stream:error");
163 if type(reason) == "string" then -- assume stream error
164 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
165 elseif type(reason) == "table" then
166 if reason.condition then
167 stream_error:tag(reason.condition, stream_xmlns_attr):up();
168 if reason.text then
169 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
171 if reason.extra then
172 stream_error:add_child(reason.extra);
174 elseif reason.name then -- a stanza
175 stream_error = reason;
178 stream_error = tostring(stream_error);
179 log("debug", "Disconnecting client, <stream:error> is: %s", stream_error);
180 session.send(stream_error);
183 session.send("</stream:stream>");
184 function session.send() return false; end
186 local reason_text = (reason and (reason.name or reason.text or reason.condition)) or reason;
187 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or session.ip or "<unknown>", reason_text or "session closed");
189 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
190 local conn = session.conn;
191 if reason_text == nil and not session.notopen and session.type == "c2s" then
192 -- Grace time to process data from authenticated cleanly-closed stream
193 add_task(stream_close_timeout, function ()
194 if not session.destroyed then
195 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
196 sm_destroy_session(session, reason_text);
197 conn:close();
199 end);
200 else
201 sm_destroy_session(session, reason_text);
202 conn:close();
204 else
205 local reason_text = (reason and (reason.name or reason.text or reason.condition)) or reason;
206 sm_destroy_session(session, reason_text);
210 module:hook_global("user-deleted", function(event)
211 local username, host = event.username, event.host;
212 local user = hosts[host].sessions[username];
213 if user and user.sessions then
214 for _, session in pairs(user.sessions) do
215 session:close{ condition = "not-authorized", text = "Account deleted" };
218 end, 200);
220 module:hook_global("user-password-changed", function(event)
221 local username, host, resource = event.username, event.host, event.resource;
222 local user = hosts[host].sessions[username];
223 if user and user.sessions then
224 for r, session in pairs(user.sessions) do
225 if r ~= resource then
226 session:close{ condition = "reset", text = "Password changed" };
230 end, 200);
232 function runner_callbacks:ready()
233 self.data.conn:resume();
236 function runner_callbacks:waiting()
237 self.data.conn:pause();
240 function runner_callbacks:error(err)
241 (self.data.log or log)("error", "Traceback[c2s]: %s", err);
244 --- Port listener
245 function listener.onconnect(conn)
246 local session = sm_new_session(conn);
248 session.log("info", "Client connected");
250 -- Client is using legacy SSL (otherwise mod_tls sets this flag)
251 if conn:ssl() then
252 session.secure = true;
253 session.encrypted = true;
255 -- Check if TLS compression is used
256 local sock = conn:socket();
257 if sock.info then
258 session.compressed = sock:info"compression";
262 if opt_keepalives then
263 conn:setoption("keepalive", opt_keepalives);
266 session.close = session_close;
268 local stream = new_xmpp_stream(session, stream_callbacks);
269 session.stream = stream;
270 session.notopen = true;
272 function session.reset_stream()
273 session.notopen = true;
274 session.stream:reset();
277 session.thread = runner(function (stanza)
278 core_process_stanza(session, stanza);
279 end, runner_callbacks, session);
281 local filter = session.filter;
282 function session.data(data)
283 -- Parse the data, which will store stanzas in session.pending_stanzas
284 if data then
285 data = filter("bytes/in", data);
286 if data then
287 local ok, err = stream:feed(data);
288 if not ok then
289 log("debug", "Received invalid XML (%s) %d bytes: %q", err, #data, data:sub(1, 300));
290 session:close("not-well-formed");
296 if c2s_timeout then
297 add_task(c2s_timeout, function ()
298 if session.type == "c2s_unauthed" then
299 session:close("connection-timeout");
301 end);
304 session.dispatch_stanza = stream_callbacks.handlestanza;
306 sessions[conn] = session;
309 function listener.onincoming(conn, data)
310 local session = sessions[conn];
311 if session then
312 session.data(data);
316 function listener.ondisconnect(conn, err)
317 local session = sessions[conn];
318 if session then
319 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
320 sm_destroy_session(session, err);
321 session.conn = nil;
322 sessions[conn] = nil;
326 function listener.onreadtimeout(conn)
327 local session = sessions[conn];
328 if session then
329 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
333 function listener.ondrain(conn)
334 local session = sessions[conn];
335 if session then
336 return (hosts[session.host] or prosody).events.fire_event("c2s-ondrain", { session = session });
340 local function keepalive(event)
341 local session = event.session;
342 if not session.notopen then
343 return event.session.send(' ');
347 function listener.associate_session(conn, session)
348 sessions[conn] = session;
351 function module.add_host(module)
352 module:hook("c2s-read-timeout", keepalive, -1);
355 module:hook("c2s-read-timeout", keepalive, -1);
357 module:hook("server-stopping", function(event)
358 local reason = event.reason;
359 for _, session in pairs(sessions) do
360 session:close{ condition = "system-shutdown", text = reason };
362 end, -100);
366 module:provides("net", {
367 name = "c2s";
368 listener = listener;
369 default_port = 5222;
370 encryption = "starttls";
371 multiplex = {
372 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
376 module:provides("net", {
377 name = "legacy_ssl";
378 listener = listener;
379 encryption = "ssl";
380 multiplex = {
381 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";