prosody, mod_c2s, mod_s2s: Move closing of c2s and s2s sessions to respective plugins
[prosody.git] / plugins / mod_c2s.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 module:set_global();
10
11 local add_task = require "util.timer".add_task;
12 local new_xmpp_stream = require "util.xmppstream".new;
13 local nameprep = require "util.encodings".stringprep.nameprep;
14 local sessionmanager = require "core.sessionmanager";
15 local st = require "util.stanza";
16 local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
17 local uuid_generate = require "util.uuid".generate;
18
19 local xpcall, tostring, type = xpcall, tostring, type;
20 local traceback = debug.traceback;
21
22 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
23
24 local log = module._log;
25
26 local c2s_timeout = module:get_option_number("c2s_timeout");
27 local stream_close_timeout = module:get_option_number("c2s_close_timeout", 5);
28 local opt_keepalives = module:get_option_boolean("tcp_keepalives", false);
29
30 local sessions = module:shared("sessions");
31 local core_process_stanza = prosody.core_process_stanza;
32
33 local stream_callbacks = { default_ns = "jabber:client", handlestanza = core_process_stanza };
34 local listener = {};
35
36 --- Stream events handlers
37 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
38 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
39
40 function stream_callbacks.streamopened(session, attr)
41         local send = session.send;
42         session.host = nameprep(attr.to);
43         if not session.host then
44                 session:close{ condition = "improper-addressing",
45                         text = "A valid 'to' attribute is required on stream headers" };
46                 return;
47         end
48         session.version = tonumber(attr.version) or 0;
49         session.streamid = uuid_generate();
50         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
51
52         if not hosts[session.host] then
53                 -- We don't serve this host...
54                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
55                 return;
56         end
57
58         send("<?xml version='1.0'?>"..st.stanza("stream:stream", {
59                 xmlns = 'jabber:client', ["xmlns:stream"] = 'http://etherx.jabber.org/streams';
60                 id = session.streamid, from = session.host, version = '1.0', ["xml:lang"] = 'en' }):top_tag());
61
62         (session.log or log)("debug", "Sent reply <stream:stream> to client");
63         session.notopen = nil;
64
65         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
66         -- since we now have a new stream header, session is secured
67         if session.secure == false then
68                 session.secure = true;
69
70                 -- Check if TLS compression is used
71                 local sock = session.conn:socket();
72                 if sock.info then
73                         session.compressed = sock:info"compression";
74                 elseif sock.compression then
75                         session.compressed = sock:compression(); --COMPAT mw/luasec-hg
76                 end
77         end
78
79         local features = st.stanza("stream:features");
80         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
81         module:fire_event("stream-features", session, features);
82
83         send(features);
84 end
85
86 function stream_callbacks.streamclosed(session)
87         session.log("debug", "Received </stream:stream>");
88         session:close(false);
89 end
90
91 function stream_callbacks.error(session, error, data)
92         if error == "no-stream" then
93                 session.log("debug", "Invalid opening stream header");
94                 session:close("invalid-namespace");
95         elseif error == "parse-error" then
96                 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
97                 session:close("not-well-formed");
98         elseif error == "stream-error" then
99                 local condition, text = "undefined-condition";
100                 for child in data:children() do
101                         if child.attr.xmlns == xmlns_xmpp_streams then
102                                 if child.name ~= "text" then
103                                         condition = child.name;
104                                 else
105                                         text = child:get_text();
106                                 end
107                                 if condition ~= "undefined-condition" and text then
108                                         break;
109                                 end
110                         end
111                 end
112                 text = condition .. (text and (" ("..text..")") or "");
113                 session.log("info", "Session closed by remote with error: %s", text);
114                 session:close(nil, text);
115         end
116 end
117
118 local function handleerr(err) log("error", "Traceback[c2s]: %s: %s", tostring(err), traceback()); end
119 function stream_callbacks.handlestanza(session, stanza)
120         stanza = session.filter("stanzas/in", stanza);
121         if stanza then
122                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
123         end
124 end
125
126 --- Session methods
127 local function session_close(session, reason)
128         local log = session.log or log;
129         if session.conn then
130                 if session.notopen then
131                         session.send("<?xml version='1.0'?>");
132                         session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
133                 end
134                 if reason then -- nil == no err, initiated by us, false == initiated by client
135                         if type(reason) == "string" then -- assume stream error
136                                 log("debug", "Disconnecting client, <stream:error> is: %s", reason);
137                                 session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
138                         elseif type(reason) == "table" then
139                                 if reason.condition then
140                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
141                                         if reason.text then
142                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
143                                         end
144                                         if reason.extra then
145                                                 stanza:add_child(reason.extra);
146                                         end
147                                         log("debug", "Disconnecting client, <stream:error> is: %s", tostring(stanza));
148                                         session.send(stanza);
149                                 elseif reason.name then -- a stanza
150                                         log("debug", "Disconnecting client, <stream:error> is: %s", tostring(reason));
151                                         session.send(reason);
152                                 end
153                         end
154                 end
155                 
156                 session.send("</stream:stream>");
157                 function session.send() return false; end
158                 
159                 local reason = (reason and (reason.text or reason.condition)) or reason;
160                 session.log("info", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed");
161
162                 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
163                 local conn = session.conn;
164                 if reason == nil and not session.notopen and session.type == "c2s" then
165                         -- Grace time to process data from authenticated cleanly-closed stream
166                         add_task(stream_close_timeout, function ()
167                                 if not session.destroyed then
168                                         session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
169                                         sm_destroy_session(session, reason);
170                                         conn:close();
171                                 end
172                         end);
173                 else
174                         sm_destroy_session(session, reason);
175                         conn:close();
176                 end
177         end
178 end
179
180 module:hook_global("user-deleted", function(event)
181         local username, host = event.username, event.host;
182         local user = hosts[host].sessions[username];
183         if user and user.sessions then
184                 for jid, session in pairs(user.sessions) do
185                         session:close{ condition = "not-authorized", text = "Account deleted" };
186                 end
187         end
188 end, 200);
189
190 --- Port listener
191 function listener.onconnect(conn)
192         local session = sm_new_session(conn);
193         sessions[conn] = session;
194         
195         session.log("info", "Client connected");
196         
197         -- Client is using legacy SSL (otherwise mod_tls sets this flag)
198         if conn:ssl() then
199                 session.secure = true;
200
201                 -- Check if TLS compression is used
202                 local sock = conn:socket();
203                 if sock.info then
204                         session.compressed = sock:info"compression";
205                 elseif sock.compression then
206                         session.compressed = sock:compression(); --COMPAT mw/luasec-hg
207                 end
208         end
209         
210         if opt_keepalives then
211                 conn:setoption("keepalive", opt_keepalives);
212         end
213         
214         session.close = session_close;
215         
216         local stream = new_xmpp_stream(session, stream_callbacks);
217         session.stream = stream;
218         session.notopen = true;
219         
220         function session.reset_stream()
221                 session.notopen = true;
222                 session.stream:reset();
223         end
224         
225         local filter = session.filter;
226         function session.data(data)
227                 data = filter("bytes/in", data);
228                 if data then
229                         local ok, err = stream:feed(data);
230                         if ok then return; end
231                         log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
232                         session:close("not-well-formed");
233                 end
234         end
235
236         
237         if c2s_timeout then
238                 add_task(c2s_timeout, function ()
239                         if session.type == "c2s_unauthed" then
240                                 session:close("connection-timeout");
241                         end
242                 end);
243         end
244
245         session.dispatch_stanza = stream_callbacks.handlestanza;
246 end
247
248 function listener.onincoming(conn, data)
249         local session = sessions[conn];
250         if session then
251                 session.data(data);
252         end
253 end
254
255 function listener.ondisconnect(conn, err)
256         local session = sessions[conn];
257         if session then
258                 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
259                 sm_destroy_session(session, err);
260                 sessions[conn]  = nil;
261         end
262 end
263
264 function listener.associate_session(conn, session)
265         sessions[conn] = session;
266 end
267
268 module:hook("server-stopping", function(event)
269         local reason = event.reason;
270         for _, session in pairs(sessions) do
271                 session:close{ condition = "system-shutdown", text = reason };
272         end
273 end, 1000);
274
275
276
277 module:provides("net", {
278         name = "c2s";
279         listener = listener;
280         default_port = 5222;
281         encryption = "starttls";
282         multiplex = {
283                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
284         };
285 });
286
287 module:provides("net", {
288         name = "legacy_ssl";
289         listener = listener;
290         encryption = "ssl";
291         multiplex = {
292                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
293         };
294 });
295
296