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