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