f686fcfb6dd29605f5f68f3c5dbdf84717438530
[prosody.git] / plugins / mod_s2s / mod_s2s.lua
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 --
8
9 module:set_global();
10
11 local prosody = prosody;
12 local hosts = prosody.hosts;
13 local core_process_stanza = core_process_stanza;
14
15 local tostring, type = tostring, type;
16 local t_insert = table.insert;
17 local xpcall, traceback = xpcall, debug.traceback;
18
19 local add_task = require "util.timer".add_task;
20 local st = require "util.stanza";
21 local initialize_filters = require "util.filters".initialize;
22 local nameprep = require "util.encodings".stringprep.nameprep;
23 local new_xmpp_stream = require "util.xmppstream".new;
24 local s2s_new_incoming = require "core.s2smanager".new_incoming;
25 local s2s_new_outgoing = require "core.s2smanager".new_outgoing;
26 local s2s_destroy_session = require "core.s2smanager".destroy_session;
27 local s2s_mark_connected = require "core.s2smanager".mark_connected;
28 local uuid_gen = require "util.uuid".generate;
29 local cert_verify_identity = require "util.x509".verify_identity;
30
31 local s2sout = module:require("s2sout");
32
33 local connect_timeout = module:get_option_number("s2s_timeout", 60);
34 local stream_close_timeout = module:get_option_number("s2s_close_timeout", 5);
35
36 local sessions = module:shared("sessions");
37
38 local log = module._log;
39
40 --- Handle stanzas to remote domains
41
42 local bouncy_stanzas = { message = true, presence = true, iq = true };
43 local function bounce_sendq(session, reason)
44         local sendq = session.sendq;
45         if not sendq then return; end
46         session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
47         local dummy = {
48                 type = "s2sin";
49                 send = function(s)
50                         (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
51                 end;
52                 dummy = true;
53         };
54         for i, data in ipairs(sendq) do
55                 local reply = data[2];
56                 if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
57                         reply.attr.type = "error";
58                         reply:tag("error", {type = "cancel"})
59                                 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
60                         if reason then
61                                 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
62                                         :text("Server-to-server connection failed: "..reason):up();
63                         end
64                         core_process_stanza(dummy, reply);
65                 end
66                 sendq[i] = nil;
67         end
68         session.sendq = nil;
69 end
70
71 -- Handles stanzas to existing s2s sessions
72 function route_to_existing_session(event)
73         local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
74         if not hosts[from_host] then
75                 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
76                 return false;
77         end
78         local host = hosts[from_host].s2sout[to_host];
79         if host then
80                 -- We have a connection to this host already
81                 if host.type == "s2sout_unauthed" and (stanza.name ~= "db:verify" or not host.dialback_key) then
82                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
83
84                         -- Queue stanza until we are able to send it
85                         if host.sendq then t_insert(host.sendq, {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)});
86                         else host.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} }; end
87                         host.log("debug", "stanza [%s] queued ", stanza.name);
88                         return true;
89                 elseif host.type == "local" or host.type == "component" then
90                         log("error", "Trying to send a stanza to ourselves??")
91                         log("error", "Traceback: %s", traceback());
92                         log("error", "Stanza: %s", tostring(stanza));
93                         return false;
94                 else
95                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
96                         -- FIXME
97                         if host.from_host ~= from_host then
98                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
99                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
100                         end
101                         if host.sends2s(stanza) then
102                                 host.log("debug", "stanza sent over "..host.type);
103                                 return true;
104                         end
105                 end
106         end
107 end
108
109 -- Create a new outgoing session for a stanza
110 function route_to_new_session(event)
111         local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
112         log("debug", "opening a new outgoing connection for this stanza");
113         local host_session = s2s_new_outgoing(from_host, to_host);
114
115         -- Store in buffer
116         host_session.bounce_sendq = bounce_sendq;
117         host_session.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
118         log("debug", "stanza [%s] queued until connection complete", tostring(stanza.name));
119         s2sout.initiate_connection(host_session);
120         if (not host_session.connecting) and (not host_session.conn) then
121                 log("warn", "Connection to %s failed already, destroying session...", to_host);
122                 s2s_destroy_session(host_session, "Connection failed");
123                 return false;
124         end
125         return true;
126 end
127
128 function module.add_host(module)
129         if module:get_option_boolean("disallow_s2s", false) then
130                 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see http://prosody.im/doc/s2s#disabling");
131                 return nil, "This host has disallow_s2s set";
132         end
133         module:hook("route/remote", route_to_existing_session, 200);
134         module:hook("route/remote", route_to_new_session, 100);
135 end
136
137 --- Helper to check that a session peer's certificate is valid
138 local function check_cert_status(session)
139         local conn = session.conn:socket()
140         local cert
141         if conn.getpeercertificate then
142                 cert = conn:getpeercertificate()
143         end
144
145         if cert then
146                 local chain_valid, errors = conn:getpeerverification()
147                 -- Is there any interest in printing out all/the number of errors here?
148                 if not chain_valid then
149                         (session.log or log)("debug", "certificate chain validation result: invalid");
150                         for depth, t in ipairs(errors) do
151                                 (session.log or log)("debug", "certificate error(s) at depth %d: %s", depth-1, table.concat(t, ", "))
152                         end
153                         session.cert_chain_status = "invalid";
154                 else
155                         (session.log or log)("debug", "certificate chain validation result: valid");
156                         session.cert_chain_status = "valid";
157
158                         local host = session.direction == "incoming" and session.from_host or session.to_host
159
160                         -- We'll go ahead and verify the asserted identity if the
161                         -- connecting server specified one.
162                         if host then
163                                 if cert_verify_identity(host, "xmpp-server", cert) then
164                                         session.cert_identity_status = "valid"
165                                 else
166                                         session.cert_identity_status = "invalid"
167                                 end
168                         end
169                 end
170         end
171 end
172
173 --- XMPP stream event handlers
174
175 local stream_callbacks = { default_ns = "jabber:server", handlestanza =  core_process_stanza };
176
177 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
178
179 function stream_callbacks.streamopened(session, attr)
180         local send = session.sends2s;
181         
182         session.version = tonumber(attr.version) or 0;
183         
184         -- TODO: Rename session.secure to session.encrypted
185         if session.secure == false then
186                 session.secure = true;
187         end
188
189         if session.direction == "incoming" then
190                 -- Send a reply stream header
191                 
192                 -- Validate to/from
193                 local to, from = nameprep(attr.to), nameprep(attr.from);
194                 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
195                         session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
196                         return;
197                 end
198                 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
199                         session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
200                         return;
201                 end
202                 
203                 -- Set session.[from/to]_host if they have not been set already and if
204                 -- this session isn't already authenticated
205                 if session.type == "s2sin_unauthed" and from and not session.from_host then
206                         session.from_host = from;
207                 elseif from ~= session.from_host then
208                         session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
209                         return;
210                 end
211                 if session.type == "s2sin_unauthed" and to and not session.to_host then
212                         session.to_host = to;
213                 elseif to ~= session.to_host then
214                         session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
215                         return;
216                 end
217                 
218                 -- For convenience we'll put the sanitised values into these variables
219                 to, from = session.to_host, session.from_host;
220                 
221                 session.streamid = uuid_gen();
222                 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
223                 if to then
224                         if not hosts[to] then
225                                 -- Attempting to connect to a host we don't serve
226                                 session:close({
227                                         condition = "host-unknown";
228                                         text = "This host does not serve "..to
229                                 });
230                                 return;
231                         elseif not hosts[to].modules.s2s then
232                                 -- Attempting to connect to a host that disallows s2s
233                                 session:close({
234                                         condition = "policy-violation";
235                                         text = "Server-to-server communication is disabled for this host";
236                                 });
237                                 return;
238                         end
239                 end
240
241                 if session.secure and not session.cert_chain_status then check_cert_status(session); end
242
243                 send("<?xml version='1.0'?>");
244                 send(st.stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
245                                 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=to, to=from, version=(session.version > 0 and "1.0" or nil) }):top_tag());
246                 if session.version >= 1.0 then
247                         local features = st.stanza("stream:features");
248                         
249                         if to then
250                                 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
251                         else
252                                 (session.log or log)("warn", "No 'to' on stream header from %s means we can't offer any features", from or "unknown host");
253                         end
254                         
255                         log("debug", "Sending stream features: %s", tostring(features));
256                         send(features);
257                 end
258         elseif session.direction == "outgoing" then
259                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
260                 if not attr.id then error("stream response did not give us a streamid!!!"); end
261                 session.streamid = attr.id;
262
263                 if session.secure and not session.cert_chain_status then check_cert_status(session); end
264
265                 -- Send unauthed buffer
266                 -- (stanzas which are fine to send before dialback)
267                 -- Note that this is *not* the stanza queue (which
268                 -- we can only send if auth succeeds) :)
269                 local send_buffer = session.send_buffer;
270                 if send_buffer and #send_buffer > 0 then
271                         log("debug", "Sending s2s send_buffer now...");
272                         for i, data in ipairs(send_buffer) do
273                                 session.sends2s(tostring(data));
274                                 send_buffer[i] = nil;
275                         end
276                 end
277                 session.send_buffer = nil;
278         
279                 -- If server is pre-1.0, don't wait for features, just do dialback
280                 if session.version < 1.0 then
281                         if not session.dialback_verifying then
282                                 hosts[session.from_host].events.fire_event("s2s-authenticate-legacy", { origin = session });
283                         else
284                                 s2s_mark_connected(session);
285                         end
286                 end
287         end
288         session.notopen = nil;
289 end
290
291 function stream_callbacks.streamclosed(session)
292         (session.log or log)("debug", "Received </stream:stream>");
293         session:close();
294 end
295
296 function stream_callbacks.error(session, error, data)
297         if error == "no-stream" then
298                 session:close("invalid-namespace");
299         elseif error == "parse-error" then
300                 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
301                 session:close("not-well-formed");
302         elseif error == "stream-error" then
303                 local condition, text = "undefined-condition";
304                 for child in data:children() do
305                         if child.attr.xmlns == xmlns_xmpp_streams then
306                                 if child.name ~= "text" then
307                                         condition = child.name;
308                                 else
309                                         text = child:get_text();
310                                 end
311                                 if condition ~= "undefined-condition" and text then
312                                         break;
313                                 end
314                         end
315                 end
316                 text = condition .. (text and (" ("..text..")") or "");
317                 session.log("info", "Session closed by remote with error: %s", text);
318                 session:close(nil, text);
319         end
320 end
321
322 local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), traceback()); end
323 function stream_callbacks.handlestanza(session, stanza)
324         if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
325                 stanza.attr.xmlns = nil;
326         end
327         stanza = session.filter("stanzas/in", stanza);
328         if stanza then
329                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
330         end
331 end
332
333 local listener = {};
334
335 --- Session methods
336 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
337 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
338 local function session_close(session, reason, remote_reason)
339         local log = session.log or log;
340         if session.conn then
341                 if session.notopen then
342                         session.sends2s("<?xml version='1.0'?>");
343                         session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
344                 end
345                 if reason then
346                         if type(reason) == "string" then -- assume stream error
347                                 log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
348                                 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
349                         elseif type(reason) == "table" then
350                                 if reason.condition then
351                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
352                                         if reason.text then
353                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
354                                         end
355                                         if reason.extra then
356                                                 stanza:add_child(reason.extra);
357                                         end
358                                         log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
359                                         session.sends2s(stanza);
360                                 elseif reason.name then -- a stanza
361                                         log("info", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
362                                         session.sends2s(reason);
363                                 end
364                         end
365                 end
366                 session.sends2s("</stream:stream>");
367
368                 function session.sends2s() return false; end
369                 
370                 local reason = remote_reason or (reason and (reason.text or reason.condition)) or reason or "stream closed";
371                 session.log("info", "%s s2s stream %s->%s closed: %s", session.direction, session.from_host or "(unknown host)", session.to_host or "(unknown host)", reason);
372                 
373                 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
374                 local conn = session.conn;
375                 if not session.notopen and session.type == "s2sin" then
376                         add_task(stream_close_timeout, function ()
377                                 if not session.destroyed then
378                                         session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
379                                         s2s_destroy_session(session, reason);
380                                         conn:close();
381                                 end
382                         end);
383                 else
384                         s2s_destroy_session(session, reason);
385                         conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
386                 end
387         end
388 end
389
390 -- Session initialization logic shared by incoming and outgoing
391 local function initialize_session(session)
392         local stream = new_xmpp_stream(session, stream_callbacks);
393         session.stream = stream;
394         
395         session.notopen = true;
396                 
397         function session.reset_stream()
398                 session.notopen = true;
399                 session.stream:reset();
400         end
401         
402         local filter = session.filter;
403         function session.data(data)
404                 data = filter("bytes/in", data);
405                 if data then
406                         local ok, err = stream:feed(data);
407                         if ok then return; end
408                         (session.log or log)("warn", "Received invalid XML: %s", data);
409                         (session.log or log)("warn", "Problem was: %s", err);
410                         session:close("not-well-formed");
411                 end
412         end
413
414         session.close = session_close;
415
416         local handlestanza = stream_callbacks.handlestanza;
417         function session.dispatch_stanza(session, stanza)
418                 return handlestanza(session, stanza);
419         end
420
421         add_task(connect_timeout, function ()
422                 if session.type == "s2sin" or session.type == "s2sout" then
423                         return; -- Ok, we're connected
424                 end
425                 -- Not connected, need to close session and clean up
426                 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
427                 session.from_host or "(unknown)", session.to_host or "(unknown)");
428                 session:close("connection-timeout");
429         end);
430 end
431
432 function listener.onconnect(conn)
433         local session = sessions[conn];
434         if not session then -- New incoming connection
435                 session = s2s_new_incoming(conn);
436                 sessions[conn] = session;
437                 session.log("debug", "Incoming s2s connection");
438
439                 local filter = initialize_filters(session);
440                 local w = conn.write;
441                 session.sends2s = function (t)
442                         log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
443                         if t.name then
444                                 t = filter("stanzas/out", t);
445                         end
446                         if t then
447                                 t = filter("bytes/out", tostring(t));
448                                 if t then
449                                         return w(conn, t);
450                                 end
451                         end
452                 end
453         
454                 initialize_session(session);
455         else -- Outgoing session connected
456                 session:open_stream(session.from_host, session.to_host);
457         end
458 end
459
460 function listener.onincoming(conn, data)
461         local session = sessions[conn];
462         if session then
463                 session.data(data);
464         end
465 end
466         
467 function listener.onstatus(conn, status)
468         if status == "ssl-handshake-complete" then
469                 local session = sessions[conn];
470                 if session and session.direction == "outgoing" then
471                         session.log("debug", "Sending stream header...");
472                         session:open_stream(session.from_host, session.to_host);
473                 end
474         end
475 end
476
477 function listener.ondisconnect(conn, err)
478         local session = sessions[conn];
479         if session then
480                 if err and session.direction == "outgoing" and session.notopen then
481                         (session.log or log)("debug", "s2s connection attempt failed: %s", err);
482                         if s2sout.attempt_connection(session, err) then
483                                 (session.log or log)("debug", "...so we're going to try another target");
484                                 return; -- Session lives for now
485                         end
486                 end
487                 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
488                 s2s_destroy_session(session, err);
489                 sessions[conn] = nil;
490         end
491 end
492
493 function listener.register_outgoing(conn, session)
494         session.direction = "outgoing";
495         sessions[conn] = session;
496         initialize_session(session);
497 end
498
499 s2sout.set_listener(listener);
500
501 module:add_item("net-provider", {
502         name = "s2s";
503         listener = listener;
504         default_port = 5269;
505         encryption = "starttls";
506         multiplex = {
507                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";
508         };
509 });
510