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