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