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