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