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