Merge from waqas
[prosody.git] / core / sessionmanager.lua
1 -- Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21
22 local tonumber, tostring = tonumber, tostring;
23 local ipairs, pairs, print, next= ipairs, pairs, print, next;
24 local collectgarbage = collectgarbage;
25 local m_random = import("math", "random");
26 local format = import("string", "format");
27
28 local hosts = hosts;
29 local sessions = sessions;
30
31 local modulemanager = require "core.modulemanager";
32 local log = require "util.logger".init("sessionmanager");
33 local error = error;
34 local uuid_generate = require "util.uuid".generate;
35 local rm_load_roster = require "core.rostermanager".load_roster;
36 local config_get = require "core.configmanager".get;
37
38 local st = require "util.stanza";
39
40 local newproxy = newproxy;
41 local getmetatable = getmetatable;
42
43 module "sessionmanager"
44
45 local open_sessions = 0;
46
47 function new_session(conn)
48         local session = { conn = conn,  priority = 0, type = "c2s_unauthed" };
49         if true then
50                 session.trace = newproxy(true);
51                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end;
52         end
53         open_sessions = open_sessions + 1;
54         log("info", "open sessions now: ".. open_sessions);
55         local w = conn.write;
56         session.send = function (t) w(tostring(t)); end
57         return session;
58 end
59
60 function destroy_session(session, err)
61         (session.log or log)("info", "Destroying session");
62         
63         -- Send unavailable presence
64         if session.presence then
65                 local pres = st.presence{ type = "unavailable" };
66                 if (not err) or err == "closed" then err = "connection closed"; end
67                 pres:tag("status"):text("Disconnected: "..err);
68                 session.stanza_dispatch(pres);
69         end
70         
71         -- Remove session/resource from user's session list
72         if session.host and session.username then
73                 -- FIXME: How can the below ever be nil? (but they sometimes are...)
74                 if hosts[session.host] and hosts[session.host].sessions[session.username] then
75                         if session.resource then
76                                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
77                         end
78                                 
79                         if not next(hosts[session.host].sessions[session.username].sessions) then
80                                 log("debug", "All resources of %s are now offline", session.username);
81                                 hosts[session.host].sessions[session.username] = nil;
82                         end
83                 else
84                         log("error", "host or session table didn't exist, please report this! Host: %s [%s] Sessions: %s [%s]", 
85                                         tostring(hosts[session.host]), tostring(session.host),
86                                         tostring(hosts[session.host].sessions[session.username] ), tostring(session.username));
87                 end
88         end
89         
90         for k in pairs(session) do
91                 if k ~= "trace" then
92                         session[k] = nil;
93                 end
94         end
95 end
96
97 function make_authenticated(session, username)
98         session.username = username;
99         if session.type == "c2s_unauthed" then
100                 session.type = "c2s";
101         end
102         return true;
103 end
104
105 -- returns true, nil on success
106 -- returns nil, err_type, err, err_message on failure
107 function bind_resource(session, resource)
108         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
109         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
110         -- We don't support binding multiple resources
111
112         resource = resource or uuid_generate();
113         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
114         
115         if not hosts[session.host].sessions[session.username] then
116                 hosts[session.host].sessions[session.username] = { sessions = {} };
117         else
118                 local sessions = hosts[session.host].sessions[session.username].sessions;
119                 local limit = config_get(session.host, "core", "max_resources") or 10;
120                 if #sessions >= limit then
121                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
122                 end
123                 if sessions[resource] then
124                         -- Resource conflict
125                         local policy = config_get(session.host, "core", "conflict_resolve");
126                         local increment;
127                         if policy == "random" then
128                                 resource = uuid_generate();
129                                 increment = true;
130                         elseif policy == "increment" then
131                                 increment = true; -- TODO ping old resource
132                         elseif policy == "kick_new" then
133                                 return nil, "cancel", "conflict", "Resource already exists";
134                         else -- if policy == "kick_old" then
135                                 hosts[session.host].sessions[session.username].sessions[resource]:close {
136                                         condition = "conflict";
137                                         text = "Replaced by new connection";
138                                 };
139                         end
140                         if increment and sessions[resource] then
141                                 local count = 1;
142                                 while sessions[resource.."#"..count] do
143                                         count = count + 1;
144                                 end
145                                 resource = resource.."#"..count;
146                         end
147                 end
148         end
149         
150         session.resource = resource;
151         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
152         hosts[session.host].sessions[session.username].sessions[resource] = session;
153         
154         session.roster = rm_load_roster(session.username, session.host);
155         
156         return true;
157 end
158
159 function streamopened(session, attr)
160                                                 local send = session.send;
161                                                 session.host = attr.to or error("Client failed to specify destination hostname");
162                                                 session.version = tonumber(attr.version) or 0;
163                                                 session.streamid = m_random(1000000, 99999999);
164                                                 (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
165                                                 
166                                                 
167                                                 send("<?xml version='1.0'?>");
168                                                 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));
169                                                 
170                                                 if not hosts[session.host] then
171                                                         -- We don't serve this host...
172                                                         session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
173                                                         return;
174                                                 end
175                                                 
176                                                 
177                                                 local features = st.stanza("stream:features");
178                                                 modulemanager.fire_event("stream-features", session, features);
179                                                 
180                                                 send(features);
181                                                 
182                                                 (session.log or log)("info", "Sent reply <stream:stream> to client");
183                                                 session.notopen = nil;
184 end
185
186 function send_to_available_resources(user, host, stanza)
187         local count = 0;
188         local to = stanza.attr.to;
189         stanza.attr.to = nil;
190         local h = hosts[host];
191         if h and h.type == "local" then
192                 local u = h.sessions[user];
193                 if u then
194                         for k, session in pairs(u.sessions) do
195                                 if session.presence then
196                                         session.send(stanza);
197                                         count = count + 1;
198                                 end
199                         end
200                 end
201         end
202         stanza.attr.to = to;
203         return count;
204 end
205
206 return _M;