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