2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
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" };
39 local runner_callbacks
= {};
41 module
:hook("stats-update", function ()
44 for _
, session
in pairs(sessions
) do
46 if session
.ip
and session
.ip
:match(":") then
50 measure_connections(count
);
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
);
61 session
:close
{ condition
= "improper-addressing",
62 text
= "A valid 'to' attribute is required on stream headers" };
65 if not session
.host
then
67 elseif session
.host
~= host
then
68 session
:close
{ condition
= "not-authorized",
69 text
= "The 'to' attribute must remain the same across stream restarts" };
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
)};
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();
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
;
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
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
;
132 text
= child
:get_text();
134 if condition
~= "undefined-condition" and text
then
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
);
150 local function session_close(session
, reason
)
151 local log = session
.log or log;
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();
164 stream_error
:tag("text", stream_xmlns_attr
):text(reason
.text
):up();
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
);
196 sm_destroy_session(session
, reason_text
);
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" };
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" };
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
);
240 function listener
.onconnect(conn
)
241 local session
= sm_new_session(conn
);
242 sessions
[conn
] = session
;
244 session
.log("info", "Client connected");
246 -- Client is using legacy SSL (otherwise mod_tls sets this flag)
248 session
.secure
= true;
249 session
.encrypted
= true;
251 -- Check if TLS compression is used
252 local sock
= conn
:socket();
254 session
.compressed
= sock
:info
"compression";
255 elseif sock
.compression
then
256 session
.compressed
= sock
:compression(); --COMPAT mw/luasec-hg
260 if opt_keepalives
then
261 conn
:setoption("keepalive", opt_keepalives
);
264 session
.close
= session_close
;
266 local stream
= new_xmpp_stream(session
, stream_callbacks
);
267 session
.stream
= stream
;
268 session
.notopen
= true;
270 function session
.reset_stream()
271 session
.notopen
= true;
272 session
.stream
:reset();
275 session
.thread
= runner(function (stanza
)
276 core_process_stanza(session
, stanza
);
277 end, runner_callbacks
, session
);
279 local filter
= session
.filter
;
280 function session
.data(data
)
281 -- Parse the data, which will store stanzas in session.pending_stanzas
283 data
= filter("bytes/in", data
);
285 local ok
, err
= stream
:feed(data
);
287 log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err
), #data
, data
:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
288 session
:close("not-well-formed");
295 add_task(c2s_timeout
, function ()
296 if session
.type == "c2s_unauthed" then
297 session
:close("connection-timeout");
302 session
.dispatch_stanza
= stream_callbacks
.handlestanza
;
305 function listener
.onincoming(conn
, data
)
306 local session
= sessions
[conn
];
312 function listener
.ondisconnect(conn
, err
)
313 local session
= sessions
[conn
];
315 (session
.log or log)("info", "Client disconnected: %s", err
or "connection closed");
316 sm_destroy_session(session
, err
);
318 sessions
[conn
] = nil;
322 function listener
.onreadtimeout(conn
)
323 local session
= sessions
[conn
];
325 return (hosts
[session
.host
] or prosody
).events
.fire_event("c2s-read-timeout", { session
= session
});
329 local function keepalive(event
)
330 local session
= event
.session
;
331 if not session
.notopen
then
332 return event
.session
.send(' ');
336 function listener
.associate_session(conn
, session
)
337 sessions
[conn
] = session
;
340 function module
.add_host(module
)
341 module
:hook("c2s-read-timeout", keepalive
, -1);
344 module
:hook("c2s-read-timeout", keepalive
, -1);
346 module
:hook("server-stopping", function(event
)
347 local reason
= event
.reason
;
348 for _
, session
in pairs(sessions
) do
349 session
:close
{ condition
= "system-shutdown", text
= reason
};
355 module
:provides("net", {
359 encryption
= "starttls";
361 pattern
= "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";
365 module
:provides("net", {
370 pattern
= "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:client%1.*>";