MUC: Fix delay@from to be room JID (fixes #1416)
[prosody.git] / plugins / mod_c2s.lua
blob15d3a9bebe8f3afa613c1ae43eb96de023c076e1
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 --
9 module:set_global();
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;
20 local tostring, type = tostring, type;
22 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
24 local log = module._log;
26 local c2s_timeout = module:get_option_number("c2s_timeout", 300);
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));
30 local measure_connections = module:measure("connections", "amount");
31 local measure_ipv6 = module:measure("ipv6", "amount");
33 local sessions = module:shared("sessions");
34 local core_process_stanza = prosody.core_process_stanza;
35 local hosts = prosody.hosts;
37 local stream_callbacks = { default_ns = "jabber:client" };
38 local listener = {};
39 local runner_callbacks = {};
41 module:hook("stats-update", function ()
42 local count = 0;
43 local ipv6 = 0;
44 for _, session in pairs(sessions) do
45 count = count + 1;
46 if session.ip and session.ip:match(":") then
47 ipv6 = ipv6 + 1;
48 end
49 end
50 measure_connections(count);
51 measure_ipv6(ipv6);
52 end);
54 --- Stream events handlers
55 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
57 function stream_callbacks.streamopened(session, attr)
58 local send = session.send;
59 local host = nameprep(attr.to);
60 if not host then
61 session:close{ condition = "improper-addressing",
62 text = "A valid 'to' attribute is required on stream headers" };
63 return;
64 end
65 if not session.host then
66 session.host = host;
67 elseif session.host ~= host then
68 session:close{ condition = "not-authorized",
69 text = "The 'to' attribute must remain the same across stream restarts" };
70 return;
71 end
72 session.version = tonumber(attr.version) or 0;
73 session.streamid = uuid_generate();
74 (session.log or log)("debug", "Client sent opening <stream:stream> to %s", session.host);
76 if not hosts[session.host] or not hosts[session.host].modules.c2s then
77 -- We don't serve this host...
78 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
79 return;
80 end
82 session:open_stream();
84 (session.log or log)("debug", "Sent reply <stream:stream> to client");
85 session.notopen = nil;
87 -- If session.secure is *false* (not nil) then it means we /were/ encrypting
88 -- since we now have a new stream header, session is secured
89 if session.secure == false then
90 session.secure = true;
91 session.encrypted = true;
93 local sock = session.conn:socket();
94 if sock.info then
95 local info = sock:info();
96 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
97 session.compressed = info.compression;
98 else
99 (session.log or log)("info", "Stream encrypted");
100 session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
104 local features = st.stanza("stream:features");
105 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
106 if features.tags[1] or session.full_jid then
107 send(features);
108 else
109 (session.log or log)("warn", "No stream features to offer");
110 session:close{ condition = "undefined-condition", text = "No stream features to proceed with" };
114 function stream_callbacks.streamclosed(session)
115 session.log("debug", "Received </stream:stream>");
116 session:close(false);
119 function stream_callbacks.error(session, error, data)
120 if error == "no-stream" then
121 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
122 session:close("invalid-namespace");
123 elseif error == "parse-error" then
124 (session.log or log)("debug", "Client XML parse error: %s", tostring(data));
125 session:close("not-well-formed");
126 elseif error == "stream-error" then
127 local condition, text = "undefined-condition";
128 for child in data:childtags(nil, xmlns_xmpp_streams) do
129 if child.name ~= "text" then
130 condition = child.name;
131 else
132 text = child:get_text();
134 if condition ~= "undefined-condition" and text then
135 break;
138 text = condition .. (text and (" ("..text..")") or "");
139 session.log("info", "Session closed by remote with error: %s", text);
140 session:close(nil, text);
144 function stream_callbacks.handlestanza(session, stanza)
145 stanza = session.filter("stanzas/in", stanza);
146 session.thread:run(stanza);
149 --- Session methods
150 local function session_close(session, reason)
151 local log = session.log or log;
152 if session.conn then
153 if session.notopen then
154 session:open_stream();
156 if reason then -- nil == no err, initiated by us, false == initiated by client
157 local stream_error = st.stanza("stream:error");
158 if type(reason) == "string" then -- assume stream error
159 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
160 elseif type(reason) == "table" then
161 if reason.condition then
162 stream_error:tag(reason.condition, stream_xmlns_attr):up();
163 if reason.text then
164 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
166 if reason.extra then
167 stream_error:add_child(reason.extra);
169 elseif reason.name then -- a stanza
170 stream_error = reason;
173 stream_error = tostring(stream_error);
174 log("debug", "Disconnecting client, <stream:error> is: %s", stream_error);
175 session.send(stream_error);
178 session.send("</stream:stream>");
179 function session.send() return false; end
181 local reason_text = (reason and (reason.name or reason.text or reason.condition)) or reason;
182 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or session.ip or "<unknown>", reason_text or "session closed");
184 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
185 local conn = session.conn;
186 if reason_text == nil and not session.notopen and session.type == "c2s" then
187 -- Grace time to process data from authenticated cleanly-closed stream
188 add_task(stream_close_timeout, function ()
189 if not session.destroyed then
190 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
191 sm_destroy_session(session, reason_text);
192 conn:close();
194 end);
195 else
196 sm_destroy_session(session, reason_text);
197 conn:close();
199 else
200 local reason_text = (reason and (reason.name or reason.text or reason.condition)) or reason;
201 sm_destroy_session(session, reason_text);
205 module:hook_global("user-deleted", function(event)
206 local username, host = event.username, event.host;
207 local user = hosts[host].sessions[username];
208 if user and user.sessions then
209 for _, session in pairs(user.sessions) do
210 session:close{ condition = "not-authorized", text = "Account deleted" };
213 end, 200);
215 module:hook_global("user-password-changed", function(event)
216 local username, host, resource = event.username, event.host, event.resource;
217 local user = hosts[host].sessions[username];
218 if user and user.sessions then
219 for r, session in pairs(user.sessions) do
220 if r ~= resource then
221 session:close{ condition = "reset", text = "Password changed" };
225 end, 200);
227 function runner_callbacks:ready()
228 self.data.conn:resume();
231 function runner_callbacks:waiting()
232 self.data.conn:pause();
235 function runner_callbacks:error(err)
236 (self.data.log or log)("error", "Traceback[c2s]: %s", err);
239 --- Port listener
240 function listener.onconnect(conn)
241 local session = sm_new_session(conn);
243 session.log("info", "Client connected");
245 -- Client is using legacy SSL (otherwise mod_tls sets this flag)
246 if conn:ssl() then
247 session.secure = true;
248 session.encrypted = true;
250 -- Check if TLS compression is used
251 local sock = conn:socket();
252 if sock.info then
253 session.compressed = sock:info"compression";
254 elseif sock.compression then
255 session.compressed = sock:compression(); --COMPAT mw/luasec-hg
259 if opt_keepalives then
260 conn:setoption("keepalive", opt_keepalives);
263 session.close = session_close;
265 local stream = new_xmpp_stream(session, stream_callbacks);
266 session.stream = stream;
267 session.notopen = true;
269 function session.reset_stream()
270 session.notopen = true;
271 session.stream:reset();
274 session.thread = runner(function (stanza)
275 core_process_stanza(session, stanza);
276 end, runner_callbacks, session);
278 local filter = session.filter;
279 function session.data(data)
280 -- Parse the data, which will store stanzas in session.pending_stanzas
281 if data then
282 data = filter("bytes/in", data);
283 if data then
284 local ok, err = stream:feed(data);
285 if not ok then
286 log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
287 session:close("not-well-formed");
293 if c2s_timeout then
294 add_task(c2s_timeout, function ()
295 if session.type == "c2s_unauthed" then
296 session:close("connection-timeout");
298 end);
301 session.dispatch_stanza = stream_callbacks.handlestanza;
303 sessions[conn] = session;
306 function listener.onincoming(conn, data)
307 local session = sessions[conn];
308 if session then
309 session.data(data);
313 function listener.ondisconnect(conn, err)
314 local session = sessions[conn];
315 if session then
316 (session.log or log)("info", "Client disconnected: %s", err or "connection closed");
317 sm_destroy_session(session, err);
318 session.conn = nil;
319 sessions[conn] = nil;
323 function listener.onreadtimeout(conn)
324 local session = sessions[conn];
325 if session then
326 return (hosts[session.host] or prosody).events.fire_event("c2s-read-timeout", { session = session });
330 local function keepalive(event)
331 local session = event.session;
332 if not session.notopen then
333 return event.session.send(' ');
337 function listener.associate_session(conn, session)
338 sessions[conn] = session;
341 function module.add_host(module)
342 module:hook("c2s-read-timeout", keepalive, -1);
345 module:hook("c2s-read-timeout", keepalive, -1);
347 module:hook("server-stopping", function(event)
348 local reason = event.reason;
349 for _, session in pairs(sessions) do
350 session:close{ condition = "system-shutdown", text = reason };
352 end, -100);
356 module:provides("net", {
357 name = "c2s";
358 listener = listener;
359 default_port = 5222;
360 encryption = "starttls";
361 multiplex = {
362 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
366 module:provides("net", {
367 name = "legacy_ssl";
368 listener = listener;
369 encryption = "ssl";
370 multiplex = {
371 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";