sessionmanager, s2smanager: Destroyed sessions are now simply resting (not dead)...
[prosody.git] / core / sessionmanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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
10
11 local tonumber, tostring, setmetatable = tonumber, tostring, setmetatable;
12 local ipairs, pairs, print, next= ipairs, pairs, print, next;
13 local format = import("string", "format");
14
15 local hosts = hosts;
16 local full_sessions = full_sessions;
17 local bare_sessions = bare_sessions;
18
19 local modulemanager = require "core.modulemanager";
20 local logger = require "util.logger";
21 local log = logger.init("sessionmanager");
22 local error = error;
23 local uuid_generate = require "util.uuid".generate;
24 local rm_load_roster = require "core.rostermanager".load_roster;
25 local config_get = require "core.configmanager".get;
26 local nameprep = require "util.encodings".stringprep.nameprep;
27 local resourceprep = require "util.encodings".stringprep.resourceprep;
28
29 local fire_event = require "core.eventmanager".fire_event;
30 local add_task = require "util.timer".add_task;
31 local gettime = require "socket".gettime;
32
33 local st = require "util.stanza";
34
35 local c2s_timeout = config_get("*", "core", "c2s_timeout");
36
37 local newproxy = newproxy;
38 local getmetatable = getmetatable;
39
40 module "sessionmanager"
41
42 local open_sessions = 0;
43
44 function new_session(conn)
45         local session = { conn = conn, type = "c2s_unauthed", conntime = gettime() };
46         if true then
47                 session.trace = newproxy(true);
48                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
49         end
50         open_sessions = open_sessions + 1;
51         log("debug", "open sessions now: ".. open_sessions);
52         local w = conn.write;
53         session.send = function (t) w(conn, tostring(t)); end
54         session.ip = conn:ip();
55         local conn_name = "c2s"..tostring(conn):match("[a-f0-9]+$");
56         session.log = logger.init(conn_name);
57         
58         if c2s_timeout then
59                 add_task(c2s_timeout, function ()
60                         if session.type == "c2s_unauthed" then
61                                 session:close("connection-timeout");
62                         end
63                 end);
64         end
65                 
66         return session;
67 end
68
69 local resting_session = { -- Resting, not dead
70                 destroyed = true;
71         }; resting_session.__index = resting_session;
72
73 function retire_session(session)
74         local log = session.log or log;
75         for k in pairs(session) do
76                 if k ~= "trace" and k ~= "log" and k ~= "id" then
77                         session[k] = nil;
78                 end
79         end
80
81         function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
82         function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
83         return setmetatable(session, resting_session);
84 end
85
86 function destroy_session(session, err)
87         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
88         
89         -- Remove session/resource from user's session list
90         if session.full_jid then
91                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
92                 full_sessions[session.full_jid] = nil;
93                 
94                 if not next(hosts[session.host].sessions[session.username].sessions) then
95                         log("debug", "All resources of %s are now offline", session.username);
96                         hosts[session.host].sessions[session.username] = nil;
97                         bare_sessions[session.username..'@'..session.host] = nil;
98                 end
99
100                 hosts[session.host].events.fire_event("resource-unbind", {session=session, error=err});
101         end
102         
103         retire_session(session);
104 end
105
106 function make_authenticated(session, username)
107         session.username = username;
108         if session.type == "c2s_unauthed" then
109                 session.type = "c2s";
110         end
111         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
112         return true;
113 end
114
115 -- returns true, nil on success
116 -- returns nil, err_type, err, err_message on failure
117 function bind_resource(session, resource)
118         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
119         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
120         -- We don't support binding multiple resources
121
122         resource = resourceprep(resource);
123         resource = resource ~= "" and resource or uuid_generate();
124         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
125         
126         if not hosts[session.host].sessions[session.username] then
127                 local sessions = { sessions = {} };
128                 hosts[session.host].sessions[session.username] = sessions;
129                 bare_sessions[session.username..'@'..session.host] = sessions;
130         else
131                 local sessions = hosts[session.host].sessions[session.username].sessions;
132                 local limit = config_get(session.host, "core", "max_resources") or 10;
133                 if #sessions >= limit then
134                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
135                 end
136                 if sessions[resource] then
137                         -- Resource conflict
138                         local policy = config_get(session.host, "core", "conflict_resolve");
139                         local increment;
140                         if policy == "random" then
141                                 resource = uuid_generate();
142                                 increment = true;
143                         elseif policy == "increment" then
144                                 increment = true; -- TODO ping old resource
145                         elseif policy == "kick_new" then
146                                 return nil, "cancel", "conflict", "Resource already exists";
147                         else -- if policy == "kick_old" then
148                                 sessions[resource]:close {
149                                         condition = "conflict";
150                                         text = "Replaced by new connection";
151                                 };
152                                 if not next(sessions) then
153                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
154                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
155                                 end
156                         end
157                         if increment and sessions[resource] then
158                                 local count = 1;
159                                 while sessions[resource.."#"..count] do
160                                         count = count + 1;
161                                 end
162                                 resource = resource.."#"..count;
163                         end
164                 end
165         end
166         
167         session.resource = resource;
168         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
169         hosts[session.host].sessions[session.username].sessions[resource] = session;
170         full_sessions[session.full_jid] = session;
171         
172         session.roster = rm_load_roster(session.username, session.host);
173         
174         hosts[session.host].events.fire_event("resource-bind", {session=session});
175         
176         return true;
177 end
178
179 function streamopened(session, attr)
180         local send = session.send;
181         session.host = attr.to or error("Client failed to specify destination hostname");
182         session.host = nameprep(session.host);
183         session.version = tonumber(attr.version) or 0;
184         session.streamid = uuid_generate();
185         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
186
187         if not hosts[session.host] then
188                 -- We don't serve this host...
189                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
190                 return;
191         end
192
193         send("<?xml version='1.0'?>");
194         send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0' xml:lang='en'>", session.streamid, session.host));
195
196         (session.log or log)("debug", "Sent reply <stream:stream> to client");
197         session.notopen = nil;
198
199         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
200         -- since we now have a new stream header, session is secured
201         if session.secure == false then
202                 session.secure = true;
203         end
204
205         local features = st.stanza("stream:features");
206         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
207         fire_event("stream-features", session, features);
208
209         send(features);
210
211 end
212
213 function streamclosed(session)
214         session.send("</stream:stream>");
215         session.notopen = true;
216 end
217
218 function send_to_available_resources(user, host, stanza)
219         local jid = user.."@"..host;
220         local count = 0;
221         local user = bare_sessions[jid];
222         if user then
223                 for k, session in pairs(user.sessions) do
224                         if session.presence then
225                                 session.send(stanza);
226                                 count = count + 1;
227                         end
228                 end
229         end
230         return count;
231 end
232
233 function send_to_interested_resources(user, host, stanza)
234         local jid = user.."@"..host;
235         local count = 0;
236         local user = bare_sessions[jid];
237         if user then
238                 for k, session in pairs(user.sessions) do
239                         if session.interested then
240                                 session.send(stanza);
241                                 count = count + 1;
242                         end
243                 end
244         end
245         return count;
246 end
247
248 return _M;