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