1fc2715d16e24b90ded51ff48f4cd7b05c32083a
[prosody.git] / core / s2smanager.lua
1
2 local hosts = hosts;
3 local sessions = sessions;
4 local socket = require "socket";
5 local format = string.format;
6 local t_insert = table.insert;
7 local get_traceback = debug.traceback;
8 local tostring, pairs, ipairs, getmetatable, print, newproxy, error, tonumber
9     = tostring, pairs, ipairs, getmetatable, print, newproxy, error, tonumber;
10
11 local connlisteners_get = require "net.connlisteners".get;
12 local wraptlsclient = require "net.server".wraptlsclient;
13 local modulemanager = require "core.modulemanager";
14 local st = require "stanza";
15 local stanza = st.stanza;
16
17 local uuid_gen = require "util.uuid".generate;
18
19 local logger_init = require "util.logger".init;
20
21 local log = logger_init("s2smanager");
22
23 local md5_hash = require "util.hashes".md5;
24
25 local dialback_secret = "This is very secret!!! Ha!";
26
27 local srvmap = { ["gmail.com"] = "talk.google.com", ["identi.ca"] = "hampton.controlezvous.ca", ["cdr.se"] = "jabber.cdr.se" };
28
29 module "s2smanager"
30
31 function send_to_host(from_host, to_host, data)
32         if data.name then data = tostring(data); end
33         local host = hosts[from_host].s2sout[to_host];
34         if host then
35                 -- We have a connection to this host already
36                 if host.type == "s2sout_unauthed" then
37                         host.log("debug", "trying to send over unauthed s2sout to "..to_host..", authing it now...");
38                         if not host.notopen and not host.dialback_key then
39                                 host.log("debug", "dialback had not been initiated");
40                                 initiate_dialback(host);
41                         end
42                         
43                         -- Queue stanza until we are able to send it
44                         if host.sendq then t_insert(host.sendq, data);
45                         else host.sendq = { data }; end
46                 elseif host.type == "local" or host.type == "component" then
47                         log("error", "Trying to send a stanza to ourselves??")
48                         log("error", "Traceback: %s", get_traceback());
49                         log("error", "Stanza: %s", tostring(data));
50                 else
51                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
52                         -- FIXME
53                         if host.from_host ~= from_host then
54                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
55                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
56                         end
57                         host.sends2s(data);
58                         host.log("debug", "stanza sent over "..host.type);
59                 end
60         else
61                 log("debug", "opening a new outgoing connection for this stanza");
62                 local host_session = new_outgoing(from_host, to_host);
63                 -- Store in buffer
64                 host_session.sendq = { data };
65         end
66 end
67
68 local open_sessions = 0;
69
70 function new_incoming(conn)
71         local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming" };
72         if true then
73                 session.trace = newproxy(true);
74                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("s2s session got collected, now "..open_sessions.." s2s sessions are allocated") end;
75         end
76         open_sessions = open_sessions + 1;
77         local w = conn.write;
78         session.sends2s = function (t) w(tostring(t)); end
79         return session;
80 end
81
82 function new_outgoing(from_host, to_host)
83                 local host_session = { to_host = to_host, from_host = from_host, notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
84                 hosts[from_host].s2sout[to_host] = host_session;
85                 local cl = connlisteners_get("xmppserver");
86                 
87                 local conn, handler = socket.tcp()
88                 
89                 --FIXME: Below parameters (ports/ip) are incorrect (use SRV)
90                 to_host = srvmap[to_host] or to_host;
91                 
92                 conn:settimeout(0);
93                 local success, err = conn:connect(to_host, 5269);
94                 if not success then
95                         log("warn", "s2s connect() failed: %s", err);
96                 end
97                 
98                 conn = wraptlsclient(cl, conn, to_host, 5269, 0, 1, hosts[from_host].ssl_ctx );
99                 host_session.conn = conn;
100                 
101                 -- Register this outgoing connection so that xmppserver_listener knows about it
102                 -- otherwise it will assume it is a new incoming connection
103                 cl.register_outgoing(conn, host_session);
104                 
105                 do
106                         local conn_name = "s2sout"..tostring(conn):match("[a-f0-9]*$");
107                         host_session.log = logger_init(conn_name);
108                 end
109                 
110                 local w = conn.write;
111                 host_session.sends2s = function (t) w(tostring(t)); end
112                 
113                 conn.write(format([[<stream:stream xmlns='jabber:server' xmlns:db='jabber:server:dialback' xmlns:stream='http://etherx.jabber.org/streams' from='%s' to='%s' version='1.0'>]], from_host, to_host));
114                  
115                 return host_session;
116 end
117
118 function streamopened(session, attr)
119         local send = session.sends2s;
120         
121         session.version = tonumber(attr.version) or 0;
122         if session.version >= 1.0 and not (attr.to and attr.from) then
123                 print("to: "..tostring(attr.to).." from: "..tostring(attr.from));
124                 --error(session.to_host.." failed to specify 'to' or 'from' hostname as per RFC");
125                 log("warn", (session.to_host or "(unknown)").." failed to specify 'to' or 'from' hostname as per RFC");
126         end
127         
128         if session.direction == "incoming" then
129                 -- Send a reply stream header
130                 
131                 for k,v in pairs(attr) do print("", tostring(k), ":::", tostring(v)); end
132                 
133                 session.to_host = attr.to;
134                 session.from_host = attr.from;
135         
136                 session.streamid = uuid_gen();
137                 print(session, session.from_host, "incoming s2s stream opened");
138                 send("<?xml version='1.0'?>");
139                 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback', ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host }):top_tag());
140                 if session.to_host and not hosts[session.to_host] then
141                         -- Attempting to connect to a host we don't serve
142                         session:close("host-unknown");
143                         return;
144                 end
145         elseif session.direction == "outgoing" then
146                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
147                 if not attr.id then error("stream response did not give us a streamid!!!"); end
148                 session.streamid = attr.id;
149         
150                 if not session.dialback_verifying then
151                         initiate_dialback(session);
152                 else
153                         mark_connected(session);
154                 end
155         end
156         --[[
157         local features = {};
158         modulemanager.fire_event("stream-features-s2s", session, features);
159         
160         send("<stream:features>");
161         
162         for _, feature in ipairs(features) do
163                 send(tostring(feature));
164         end
165
166         send("</stream:features>");]]
167
168         session.notopen = nil;
169 end
170
171 function initiate_dialback(session)
172         -- generate dialback key
173         session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
174         session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
175         session.log("info", "sent dialback key on outgoing s2s stream");
176 end
177
178 function generate_dialback(id, to, from)
179         return md5_hash(id..to..from..dialback_secret); -- FIXME: See XEP-185 and XEP-220
180 end
181
182 function verify_dialback(id, to, from, key)
183         return key == generate_dialback(id, to, from);
184 end
185
186 function make_authenticated(session)
187         if session.type == "s2sout_unauthed" then
188                 session.type = "s2sout";
189         elseif session.type == "s2sin_unauthed" then
190                 session.type = "s2sin";
191         else
192                 return false;
193         end
194         session.log("info", "connection is now authenticated");
195         
196         mark_connected(session);
197         
198         return true;
199 end
200
201 function mark_connected(session)
202         local sendq, send = session.sendq, session.sends2s;
203         
204         local from, to = session.from_host, session.to_host;
205         
206         session.log("debug", session.direction.." s2s connection "..from.."->"..to.." is now complete");
207         
208         local send_to_host = send_to_host;
209         function session.send(data) send_to_host(to, from, data); end
210         
211         
212         if session.direction == "outgoing" then
213                 if sendq then
214                         session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
215                         for i, data in ipairs(sendq) do
216                                 send(data);
217                                 sendq[i] = nil;
218                         end
219                         session.sendq = nil;
220                 end
221         end
222 end
223
224 function destroy_session(session)
225         (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
226         
227         -- FIXME: Flush sendq here/report errors to originators
228         
229         if session.direction == "outgoing" then
230                 hosts[session.from_host].s2sout[session.to_host] = nil;
231         end
232         
233         for k in pairs(session) do
234                 if k ~= "trace" then
235                         session[k] = nil;
236                 end
237         end
238 end
239
240 return _M;