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