f2d70ae66c444987cdc90e59259eed06c654c420
[prosody.git] / net / xmppserver_listener.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
10 local tostring = tostring;
11 local type = type;
12 local xpcall = xpcall;
13 local s_format = string.format;
14 local traceback = debug.traceback;
15
16 local logger = require "logger";
17 local log = logger.init("xmppserver_listener");
18 local lxp = require "lxp"
19 local new_xmpp_stream = require "util.xmppstream".new;
20 local s2s_new_incoming = require "core.s2smanager".new_incoming;
21 local s2s_streamopened = require "core.s2smanager".streamopened;
22 local s2s_streamclosed = require "core.s2smanager".streamclosed;
23 local s2s_destroy_session = require "core.s2smanager".destroy_session;
24 local s2s_attempt_connect = require "core.s2smanager".attempt_connection;
25 local stream_callbacks = { default_ns = "jabber:server",
26                 streamopened = s2s_streamopened, streamclosed = s2s_streamclosed, handlestanza =  core_process_stanza };
27
28 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
29
30 function stream_callbacks.error(session, error, data)
31         if error == "no-stream" then
32                 session:close("invalid-namespace");
33         elseif error == "parse-error" then
34                 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
35                 session:close("not-well-formed");
36         elseif error == "stream-error" then
37                 local condition, text = "undefined-condition";
38                 for child in data:children() do
39                         if child.attr.xmlns == xmlns_xmpp_streams then
40                                 if child.name ~= "text" then
41                                         condition = child.name;
42                                 else
43                                         text = child:get_text();
44                                 end
45                                 if condition ~= "undefined-condition" and text then
46                                         break;
47                                 end
48                         end
49                 end
50                 text = condition .. (text and (" ("..text..")") or "");
51                 session.log("info", "Session closed by remote with error: %s", text);
52                 session:close(nil, text);
53         end
54 end
55
56 local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), traceback()); end
57 function stream_callbacks.handlestanza(session, stanza)
58         if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
59                 stanza.attr.xmlns = nil;
60         end
61         stanza = session.filter("stanzas/in", stanza);
62         if stanza then
63                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
64         end
65 end
66
67 local connlisteners_register = require "net.connlisteners".register;
68
69 local t_insert = table.insert;
70 local t_concat = table.concat;
71 local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
72 local m_random = math.random;
73 local format = string.format;
74 local sessionmanager = require "core.sessionmanager";
75 local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
76 local st = require "util.stanza";
77
78 local sessions = {};
79 local xmppserver = { default_port = 5269, default_mode = "*a" };
80
81 -- These are session methods --
82
83 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
84 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
85 local function session_close(session, reason, remote_reason)
86         local log = session.log or log;
87         if session.conn then
88                 if session.notopen then
89                         session.sends2s("<?xml version='1.0'?>");
90                         session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
91                 end
92                 if reason then
93                         if type(reason) == "string" then -- assume stream error
94                                 log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
95                                 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
96                         elseif type(reason) == "table" then
97                                 if reason.condition then
98                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
99                                         if reason.text then
100                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
101                                         end
102                                         if reason.extra then
103                                                 stanza:add_child(reason.extra);
104                                         end
105                                         log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
106                                         session.sends2s(stanza);
107                                 elseif reason.name then -- a stanza
108                                         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));
109                                         session.sends2s(reason);
110                                 end
111                         end
112                 end
113                 session.sends2s("</stream:stream>");
114                 if session.notopen or not session.conn:close() then
115                         session.conn:close(true); -- Force FIXME: timer?
116                 end
117                 session.conn:close();
118                 xmppserver.ondisconnect(session.conn, remote_reason or (reason and (reason.text or reason.condition)) or reason or "stream closed");
119         end
120 end
121
122
123 -- End of session methods --
124
125 local function initialize_session(session)
126         local stream = new_xmpp_stream(session, stream_callbacks);
127         session.stream = stream;
128         
129         session.notopen = true;
130                 
131         function session.reset_stream()
132                 session.notopen = true;
133                 session.stream:reset();
134         end
135         
136         local filter = session.filter;
137         function session.data(data)
138                 data = filter("bytes/in", data);
139                 if data then
140                         local ok, err = stream:feed(data);
141                         if ok then return; end
142                         (session.log or log)("warn", "Received invalid XML: %s", data);
143                         (session.log or log)("warn", "Problem was: %s", err);
144                         session:close("not-well-formed");
145                 end
146         end
147
148         session.close = session_close;
149         local handlestanza = stream_callbacks.handlestanza;
150         function session.dispatch_stanza(session, stanza)
151                 return handlestanza(session, stanza);
152         end
153 end
154
155 function xmppserver.onconnect(conn)
156         if not sessions[conn] then -- May be an existing outgoing session
157                 local session = s2s_new_incoming(conn);
158                 sessions[conn] = session;
159         
160                 -- Logging functions --
161                 local conn_name = "s2sin"..tostring(conn):match("[a-f0-9]+$");
162                 session.log = logger.init(conn_name);
163                 
164                 session.log("info", "Incoming s2s connection");
165                 
166                 initialize_session(session);
167         end
168 end
169
170 function xmppserver.onincoming(conn, data)
171         local session = sessions[conn];
172         if session then
173                 session.data(data);
174         end
175 end
176         
177 function xmppserver.onstatus(conn, status)
178         if status == "ssl-handshake-complete" then
179                 local session = sessions[conn];
180                 if session and session.direction == "outgoing" then
181                         local to_host, from_host = session.to_host, session.from_host;
182                         session.log("debug", "Sending stream header...");
183                         session.sends2s(s_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));
184                 end
185         end
186 end
187
188 function xmppserver.ondisconnect(conn, err)
189         local session = sessions[conn];
190         if session then
191                 if err and err ~= "closed" and session.srv_hosts then
192                         (session.log or log)("debug", "s2s connection attempt failed: %s", err);
193                         if s2s_attempt_connect(session, err) then
194                                 (session.log or log)("debug", "...so we're going to try another target");
195                                 return; -- Session lives for now
196                         end
197                 end
198                 (session.log or log)("info", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "closed"));
199                 s2s_destroy_session(session, err);
200                 sessions[conn]  = nil;
201                 session = nil;
202         end
203 end
204
205 function xmppserver.register_outgoing(conn, session)
206         session.direction = "outgoing";
207         sessions[conn] = session;
208         
209         initialize_session(session);
210 end
211
212 connlisteners_register("xmppserver", xmppserver);
213
214
215 -- We need to perform some initialisation when a connection is created
216 -- We also need to perform that same initialisation at other points (SASL, TLS, ...)
217
218 -- ...and we need to handle data
219 -- ...and record all sessions associated with connections