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