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