Merge 0.9->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 sessions = module:shared("sessions");
32 local core_process_stanza = prosody.core_process_stanza;
33 local hosts = prosody.hosts;
34
35 local stream_callbacks = { default_ns = "jabber:client" };
36 local listener = {};
37 local runner_callbacks = {};
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)", 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         send(features);
87 end
88
89 function stream_callbacks.streamclosed(session)
90         session.log("debug", "Received </stream:stream>");
91         session:close(false);
92 end
93
94 function stream_callbacks.error(session, error, data)
95         if error == "no-stream" then
96                 session.log("debug", "Invalid opening stream header");
97                 session:close("invalid-namespace");
98         elseif error == "parse-error" then
99                 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
100                 session:close("not-well-formed");
101         elseif error == "stream-error" then
102                 local condition, text = "undefined-condition";
103                 for child in data:children() do
104                         if child.attr.xmlns == xmlns_xmpp_streams then
105                                 if child.name ~= "text" then
106                                         condition = child.name;
107                                 else
108                                         text = child:get_text();
109                                 end
110                                 if condition ~= "undefined-condition" and text then
111                                         break;
112                                 end
113                         end
114                 end
115                 text = condition .. (text and (" ("..text..")") or "");
116                 session.log("info", "Session closed by remote with error: %s", text);
117                 session:close(nil, text);
118         end
119 end
120
121 function stream_callbacks.handlestanza(session, stanza)
122         stanza = session.filter("stanzas/in", stanza);
123         session.thread:run(stanza);
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                         local stream_error = st.stanza("stream:error");
136                         if type(reason) == "string" then -- assume stream error
137                                 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
138                         elseif type(reason) == "table" then
139                                 if reason.condition then
140                                         stream_error:tag(reason.condition, stream_xmlns_attr):up();
141                                         if reason.text then
142                                                 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
143                                         end
144                                         if reason.extra then
145                                                 stream_error:add_child(reason.extra);
146                                         end
147                                 elseif reason.name then -- a stanza
148                                         stream_error = reason;
149                                 end
150                         end
151                         stream_error = tostring(stream_error);
152                         log("debug", "Disconnecting client, <stream:error> is: %s", stream_error);
153                         session.send(stream_error);
154                 end
155
156                 session.send("</stream:stream>");
157                 function session.send() return false; end
158
159                 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
160                 session.log("debug", "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 function runner_callbacks:ready()
191         self.data.conn:resume();
192 end
193
194 function runner_callbacks:waiting()
195         self.data.conn:pause();
196 end
197
198 function runner_callbacks:error(err)
199         (self.data.log or log)("error", "Traceback[c2s]: %s", err);
200 end
201
202 --- Port listener
203 function listener.onconnect(conn)
204         local session = sm_new_session(conn);
205         sessions[conn] = session;
206
207         session.log("info", "Client connected");
208
209         -- Client is using legacy SSL (otherwise mod_tls sets this flag)
210         if conn:ssl() then
211                 session.secure = true;
212
213                 -- Check if TLS compression is used
214                 local sock = conn:socket();
215                 if sock.info then
216                         session.compressed = sock:info"compression";
217                 elseif sock.compression then
218                         session.compressed = sock:compression(); --COMPAT mw/luasec-hg
219                 end
220         end
221
222         if opt_keepalives then
223                 conn:setoption("keepalive", opt_keepalives);
224         end
225
226         session.close = session_close;
227
228         local stream = new_xmpp_stream(session, stream_callbacks);
229         session.stream = stream;
230         session.notopen = true;
231
232         function session.reset_stream()
233                 session.notopen = true;
234                 session.stream:reset();
235         end
236
237         session.thread = runner(function (stanza)
238                 core_process_stanza(session, stanza);
239         end, runner_callbacks, session);
240
241         local filter = session.filter;
242         function session.data(data)
243                 -- Parse the data, which will store stanzas in session.pending_stanzas
244                 if data then
245                         data = filter("bytes/in", data);
246                         if data then
247                                 local ok, err = stream:feed(data);
248                                 if not ok then
249                                         log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
250                                         session:close("not-well-formed");
251                                 end
252                         end
253                 end
254         end
255
256         if c2s_timeout then
257                 add_task(c2s_timeout, function ()
258                         if session.type == "c2s_unauthed" then
259                                 session:close("connection-timeout");
260                         end
261                 end);
262         end
263
264         session.dispatch_stanza = stream_callbacks.handlestanza;
265 end
266
267 function listener.onincoming(conn, data)
268         local session = sessions[conn];
269         if session then
270                 session.data(data);
271         end
272 end
273
274 function listener.ondisconnect(conn, err)
275         local session = sessions[conn];
276         if session then
277                 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
278                 sm_destroy_session(session, err);
279                 sessions[conn]  = nil;
280         end
281 end
282
283 function listener.onreadtimeout(conn)
284         local session = sessions[conn];
285         if session then
286                 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
287         end
288 end
289
290 local function keepalive(event)
291         return event.session.send(' ');
292 end
293
294 function listener.associate_session(conn, session)
295         sessions[conn] = session;
296 end
297
298 function module.add_host(module)
299         module:hook("c2s-read-timeout", keepalive, -1);
300 end
301
302 module:hook("c2s-read-timeout", keepalive, -1);
303
304 module:hook("server-stopping", function(event)
305         local reason = event.reason;
306         for _, session in pairs(sessions) do
307                 session:close{ condition = "system-shutdown", text = reason };
308         end
309 end, 1000);
310
311
312
313 module:provides("net", {
314         name = "c2s";
315         listener = listener;
316         default_port = 5222;
317         encryption = "starttls";
318         multiplex = {
319                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
320         };
321 });
322
323 module:provides("net", {
324         name = "legacy_ssl";
325         listener = listener;
326         encryption = "ssl";
327         multiplex = {
328                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
329         };
330 });
331
332