efc9936644c75399d4d5921f8b0ae58703ebb8d2
[prosody.git] / core / sessionmanager.lua
1 -- Prosody IM v0.4
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 = tonumber, tostring;
12 local ipairs, pairs, print, next= ipairs, pairs, print, next;
13 local collectgarbage = collectgarbage;
14 local m_random = import("math", "random");
15 local format = import("string", "format");
16
17 local hosts = hosts;
18 local sessions = sessions;
19
20 local modulemanager = require "core.modulemanager";
21 local log = require "util.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
28 local fire_event = require "core.eventmanager".fire_event;
29
30 local gettime = require "socket".gettime;
31
32 local st = require "util.stanza";
33
34 local newproxy = newproxy;
35 local getmetatable = getmetatable;
36
37 module "sessionmanager"
38
39 local open_sessions = 0;
40
41 function new_session(conn)
42         local session = { conn = conn,  priority = 0, type = "c2s_unauthed", conntime = gettime() };
43         if true then
44                 session.trace = newproxy(true);
45                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
46         end
47         open_sessions = open_sessions + 1;
48         log("info", "open sessions now: ".. open_sessions);
49         local w = conn.write;
50         session.send = function (t) w(tostring(t)); end
51         session.ip = conn.ip();
52         return session;
53 end
54
55 function destroy_session(session, err)
56         (session.log or log)("info", "Destroying session");
57         
58         -- Send unavailable presence
59         if session.presence then
60                 local pres = st.presence{ type = "unavailable" };
61                 if (not err) or err == "closed" then err = "connection closed"; end
62                 pres:tag("status"):text("Disconnected: "..err);
63                 session:dispatch_stanza(pres);
64         end
65         
66         -- Remove session/resource from user's session list
67         if session.host and session.username then
68                 -- FIXME: How can the below ever be nil? (but they sometimes are...)
69                 if hosts[session.host] and hosts[session.host].sessions[session.username] then
70                         if session.resource then
71                                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
72                         end
73                                 
74                         if not next(hosts[session.host].sessions[session.username].sessions) then
75                                 log("debug", "All resources of %s are now offline", session.username);
76                                 hosts[session.host].sessions[session.username] = nil;
77                         end
78                 else
79                         log("error", "host or session table didn't exist, please report this! Host: %s [%s] Sessions: %s [%s]", 
80                                         tostring(hosts[session.host]), tostring(session.host),
81                                         tostring(hosts[session.host].sessions[session.username] ), tostring(session.username));
82                 end
83         end
84         
85         for k in pairs(session) do
86                 if k ~= "trace" then
87                         session[k] = nil;
88                 end
89         end
90 end
91
92 function make_authenticated(session, username)
93         session.username = username;
94         if session.type == "c2s_unauthed" then
95                 session.type = "c2s";
96         end
97         return true;
98 end
99
100 -- returns true, nil on success
101 -- returns nil, err_type, err, err_message on failure
102 function bind_resource(session, resource)
103         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
104         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
105         -- We don't support binding multiple resources
106
107         resource = resource or uuid_generate();
108         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
109         
110         if not hosts[session.host].sessions[session.username] then
111                 hosts[session.host].sessions[session.username] = { sessions = {} };
112         else
113                 local sessions = hosts[session.host].sessions[session.username].sessions;
114                 local limit = config_get(session.host, "core", "max_resources") or 10;
115                 if #sessions >= limit then
116                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
117                 end
118                 if sessions[resource] then
119                         -- Resource conflict
120                         local policy = config_get(session.host, "core", "conflict_resolve");
121                         local increment;
122                         if policy == "random" then
123                                 resource = uuid_generate();
124                                 increment = true;
125                         elseif policy == "increment" then
126                                 increment = true; -- TODO ping old resource
127                         elseif policy == "kick_new" then
128                                 return nil, "cancel", "conflict", "Resource already exists";
129                         else -- if policy == "kick_old" then
130                                 sessions[resource]:close {
131                                         condition = "conflict";
132                                         text = "Replaced by new connection";
133                                 };
134                                 if not next(sessions) then
135                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
136                                 end
137                         end
138                         if increment and sessions[resource] then
139                                 local count = 1;
140                                 while sessions[resource.."#"..count] do
141                                         count = count + 1;
142                                 end
143                                 resource = resource.."#"..count;
144                         end
145                 end
146         end
147         
148         session.resource = resource;
149         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
150         hosts[session.host].sessions[session.username].sessions[resource] = session;
151         
152         session.roster = rm_load_roster(session.username, session.host);
153         
154         return true;
155 end
156
157 function streamopened(session, attr)
158                                                 local send = session.send;
159                                                 session.host = attr.to or error("Client failed to specify destination hostname");
160                                                 session.host = nameprep(session.host);
161                                                 session.version = tonumber(attr.version) or 0;
162                                                 session.streamid = m_random(1000000, 99999999);
163                                                 (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
164                                                 
165                                                 
166                                                 send("<?xml version='1.0'?>");
167                                                 send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host));
168                                                 
169                                                 if not hosts[session.host] then
170                                                         -- We don't serve this host...
171                                                         session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
172                                                         return;
173                                                 end
174                                                 
175                                                 
176                                                 local features = st.stanza("stream:features");
177                                                 fire_event("stream-features", session, features);
178                                                 
179                                                 send(features);
180                                                 
181                                                 (session.log or log)("info", "Sent reply <stream:stream> to client");
182                                                 session.notopen = nil;
183 end
184
185 function send_to_available_resources(user, host, stanza)
186         local count = 0;
187         local to = stanza.attr.to;
188         stanza.attr.to = nil;
189         local h = hosts[host];
190         if h and h.type == "local" then
191                 local u = h.sessions[user];
192                 if u then
193                         for k, session in pairs(u.sessions) do
194                                 if session.presence then
195                                         session.send(stanza);
196                                         count = count + 1;
197                                 end
198                         end
199                 end
200         end
201         stanza.attr.to = to;
202         return count;
203 end
204
205 return _M;