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