Merge 0.6.2/waqas with 0.6.2/MattJ
[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                 close = function (session)
72                         session.log("debug", "Attempt to close already-closed session");
73                 end;
74         }; resting_session.__index = resting_session;
75
76 function retire_session(session)
77         local log = session.log or log;
78         for k in pairs(session) do
79                 if k ~= "trace" and k ~= "log" and k ~= "id" then
80                         session[k] = nil;
81                 end
82         end
83
84         function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
85         function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
86         return setmetatable(session, resting_session);
87 end
88
89 function destroy_session(session, err)
90         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
91         if session.destroyed then return; end
92         
93         -- Remove session/resource from user's session list
94         if session.full_jid then
95                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
96                 full_sessions[session.full_jid] = nil;
97                 
98                 if not next(hosts[session.host].sessions[session.username].sessions) then
99                         log("debug", "All resources of %s are now offline", session.username);
100                         hosts[session.host].sessions[session.username] = nil;
101                         bare_sessions[session.username..'@'..session.host] = nil;
102                 end
103
104                 hosts[session.host].events.fire_event("resource-unbind", {session=session, error=err});
105         end
106         
107         retire_session(session);
108 end
109
110 function make_authenticated(session, username)
111         session.username = username;
112         if session.type == "c2s_unauthed" then
113                 session.type = "c2s";
114         end
115         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
116         return true;
117 end
118
119 -- returns true, nil on success
120 -- returns nil, err_type, err, err_message on failure
121 function bind_resource(session, resource)
122         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
123         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
124         -- We don't support binding multiple resources
125
126         resource = resourceprep(resource);
127         resource = resource ~= "" and resource or uuid_generate();
128         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
129         
130         if not hosts[session.host].sessions[session.username] then
131                 local sessions = { sessions = {} };
132                 hosts[session.host].sessions[session.username] = sessions;
133                 bare_sessions[session.username..'@'..session.host] = sessions;
134         else
135                 local sessions = hosts[session.host].sessions[session.username].sessions;
136                 local limit = config_get(session.host, "core", "max_resources") or 10;
137                 if #sessions >= limit then
138                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
139                 end
140                 if sessions[resource] then
141                         -- Resource conflict
142                         local policy = config_get(session.host, "core", "conflict_resolve");
143                         local increment;
144                         if policy == "random" then
145                                 resource = uuid_generate();
146                                 increment = true;
147                         elseif policy == "increment" then
148                                 increment = true; -- TODO ping old resource
149                         elseif policy == "kick_new" then
150                                 return nil, "cancel", "conflict", "Resource already exists";
151                         else -- if policy == "kick_old" then
152                                 sessions[resource]:close {
153                                         condition = "conflict";
154                                         text = "Replaced by new connection";
155                                 };
156                                 if not next(sessions) then
157                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
158                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
159                                 end
160                         end
161                         if increment and sessions[resource] then
162                                 local count = 1;
163                                 while sessions[resource.."#"..count] do
164                                         count = count + 1;
165                                 end
166                                 resource = resource.."#"..count;
167                         end
168                 end
169         end
170         
171         session.resource = resource;
172         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
173         hosts[session.host].sessions[session.username].sessions[resource] = session;
174         full_sessions[session.full_jid] = session;
175         
176         session.roster = rm_load_roster(session.username, session.host);
177         
178         hosts[session.host].events.fire_event("resource-bind", {session=session});
179         
180         return true;
181 end
182
183 function streamopened(session, attr)
184         local send = session.send;
185         session.host = attr.to;
186         if not session.host then
187                 session:close{ condition = "improper-addressing",
188                         text = "A 'to' attribute is required on stream headers" };
189                 return;
190         end
191         session.host = nameprep(session.host);
192         session.version = tonumber(attr.version) or 0;
193         session.streamid = uuid_generate();
194         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
195
196         if not hosts[session.host] then
197                 -- We don't serve this host...
198                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
199                 return;
200         end
201
202         send("<?xml version='1.0'?>");
203         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));
204
205         (session.log or log)("debug", "Sent reply <stream:stream> to client");
206         session.notopen = nil;
207
208         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
209         -- since we now have a new stream header, session is secured
210         if session.secure == false then
211                 session.secure = true;
212         end
213
214         local features = st.stanza("stream:features");
215         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
216         fire_event("stream-features", session, features);
217
218         send(features);
219
220 end
221
222 function streamclosed(session)
223         session.log("debug", "Received </stream:stream>");
224         session:close();
225 end
226
227 function send_to_available_resources(user, host, stanza)
228         local jid = user.."@"..host;
229         local count = 0;
230         local user = bare_sessions[jid];
231         if user then
232                 for k, session in pairs(user.sessions) do
233                         if session.presence then
234                                 session.send(stanza);
235                                 count = count + 1;
236                         end
237                 end
238         end
239         return count;
240 end
241
242 function send_to_interested_resources(user, host, stanza)
243         local jid = user.."@"..host;
244         local count = 0;
245         local user = bare_sessions[jid];
246         if user then
247                 for k, session in pairs(user.sessions) do
248                         if session.interested then
249                                 session.send(stanza);
250                                 count = count + 1;
251                         end
252                 end
253         end
254         return count;
255 end
256
257 return _M;