mod_c2s, mod_s2s: Log a message that stream encryption has been enabled with some...
[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
22 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
23
24 local log = module._log;
25
26 local c2s_timeout = module:get_option_number("c2s_timeout");
27 local stream_close_timeout = module:get_option_number("c2s_close_timeout", 5);
28 local opt_keepalives = module:get_option_boolean("c2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
29
30 local sessions = module:shared("sessions");
31 local core_process_stanza = prosody.core_process_stanza;
32 local hosts = prosody.hosts;
33
34 local stream_callbacks = { default_ns = "jabber:client", handlestanza = core_process_stanza };
35 local listener = {};
36
37 --- Stream events handlers
38 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
39 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
40
41 function stream_callbacks.streamopened(session, attr)
42         local send = session.send;
43         session.host = nameprep(attr.to);
44         if not session.host then
45                 session:close{ condition = "improper-addressing",
46                         text = "A valid 'to' attribute is required on stream headers" };
47                 return;
48         end
49         session.version = tonumber(attr.version) or 0;
50         session.streamid = uuid_generate();
51         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
52
53         if not hosts[session.host] or not hosts[session.host].modules.c2s then
54                 -- We don't serve this host...
55                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
56                 return;
57         end
58
59         send("<?xml version='1.0'?>"..st.stanza("stream:stream", {
60                 xmlns = 'jabber:client', ["xmlns:stream"] = 'http://etherx.jabber.org/streams';
61                 id = session.streamid, from = session.host, version = '1.0', ["xml:lang"] = 'en' }):top_tag());
62
63         (session.log or log)("debug", "Sent reply <stream:stream> to client");
64         session.notopen = nil;
65
66         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
67         -- since we now have a new stream header, session is secured
68         if session.secure == false then
69                 session.secure = 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, authenticated with %s and exchanged keys with %s",
75                                 info.protocol, info.encryption, info.authentication, info.key);
76                         session.compressed = info.compression;
77                 else
78                         (session.log or log)("info", "Stream encrypted");
79                         session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
80                 end
81         end
82
83         local features = st.stanza("stream:features");
84         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
85         send(features);
86 end
87
88 function stream_callbacks.streamclosed(session)
89         session.log("debug", "Received </stream:stream>");
90         session:close(false);
91 end
92
93 function stream_callbacks.error(session, error, data)
94         if error == "no-stream" then
95                 session.log("debug", "Invalid opening stream header");
96                 session:close("invalid-namespace");
97         elseif error == "parse-error" then
98                 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
99                 session:close("not-well-formed");
100         elseif error == "stream-error" then
101                 local condition, text = "undefined-condition";
102                 for child in data:children() do
103                         if child.attr.xmlns == xmlns_xmpp_streams then
104                                 if child.name ~= "text" then
105                                         condition = child.name;
106                                 else
107                                         text = child:get_text();
108                                 end
109                                 if condition ~= "undefined-condition" and text then
110                                         break;
111                                 end
112                         end
113                 end
114                 text = condition .. (text and (" ("..text..")") or "");
115                 session.log("info", "Session closed by remote with error: %s", text);
116                 session:close(nil, text);
117         end
118 end
119
120 local function handleerr(err) log("error", "Traceback[c2s]: %s", traceback(tostring(err), 2)); end
121 function stream_callbacks.handlestanza(session, stanza)
122         stanza = session.filter("stanzas/in", stanza);
123         if stanza then
124                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
125         end
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         local filter = session.filter;
228         function session.data(data)
229                 data = filter("bytes/in", data);
230                 if data then
231                         local ok, err = stream:feed(data);
232                         if ok then return; end
233                         log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
234                         session:close("not-well-formed");
235                 end
236         end
237
238         
239         if c2s_timeout then
240                 add_task(c2s_timeout, function ()
241                         if session.type == "c2s_unauthed" then
242                                 session:close("connection-timeout");
243                         end
244                 end);
245         end
246
247         session.dispatch_stanza = stream_callbacks.handlestanza;
248 end
249
250 function listener.onincoming(conn, data)
251         local session = sessions[conn];
252         if session then
253                 session.data(data);
254         end
255 end
256
257 function listener.ondisconnect(conn, err)
258         local session = sessions[conn];
259         if session then
260                 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
261                 sm_destroy_session(session, err);
262                 sessions[conn]  = nil;
263         end
264 end
265
266 function listener.onreadtimeout(conn)
267         local session = sessions[conn];
268         if session then
269                 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
270         end
271 end
272
273 local function keepalive(event)
274         return event.session.send(' ');
275 end
276
277 function listener.associate_session(conn, session)
278         sessions[conn] = session;
279 end
280
281 function module.add_host(module)
282         module:hook("c2s-read-timeout", keepalive, -1);
283 end
284
285 module:hook("c2s-read-timeout", keepalive, -1);
286
287 module:hook("server-stopping", function(event)
288         local reason = event.reason;
289         for _, session in pairs(sessions) do
290                 session:close{ condition = "system-shutdown", text = reason };
291         end
292 end, 1000);
293
294
295
296 module:provides("net", {
297         name = "c2s";
298         listener = listener;
299         default_port = 5222;
300         encryption = "starttls";
301         multiplex = {
302                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
303         };
304 });
305
306 module:provides("net", {
307         name = "legacy_ssl";
308         listener = listener;
309         encryption = "ssl";
310         multiplex = {
311                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
312         };
313 });
314
315