1b6aee177335b72ad6c70cde08ad73214b6fa178
[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 full_sessions = full_sessions;
19 local bare_sessions = bare_sessions;
20
21 local modulemanager = require "core.modulemanager";
22 local log = require "util.logger".init("sessionmanager");
23 local error = error;
24 local uuid_generate = require "util.uuid".generate;
25 local rm_load_roster = require "core.rostermanager".load_roster;
26 local config_get = require "core.configmanager".get;
27 local nameprep = require "util.encodings".stringprep.nameprep;
28
29 local fire_event = require "core.eventmanager".fire_event;
30
31 local gettime = require "socket".gettime;
32
33 local st = require "util.stanza";
34
35 local newproxy = newproxy;
36 local getmetatable = getmetatable;
37
38 module "sessionmanager"
39
40 local open_sessions = 0;
41
42 function new_session(conn)
43         local session = { conn = conn, type = "c2s_unauthed", conntime = gettime() };
44         if true then
45                 session.trace = newproxy(true);
46                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
47         end
48         open_sessions = open_sessions + 1;
49         log("debug", "open sessions now: ".. open_sessions);
50         local w = conn.write;
51         session.send = function (t) w(tostring(t)); end
52         session.ip = conn.ip();
53         return session;
54 end
55
56 function destroy_session(session, err)
57         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
58         
59         -- Send unavailable presence
60         if session.presence then
61                 local pres = st.presence{ type = "unavailable" };
62                 if (not err) or err == "closed" then err = "connection closed"; end
63                 pres:tag("status"):text("Disconnected: "..err):up();
64                 session:dispatch_stanza(pres);
65         end
66         
67         -- Remove session/resource from user's session list
68         if session.full_jid then
69                 hosts[session.host].events.fire_event("resource-unbind", session);
70
71                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
72                 full_sessions[session.full_jid] = nil;
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                         bare_sessions[session.username..'@'..session.host] = nil;
78                 end
79         end
80         
81         for k in pairs(session) do
82                 if k ~= "trace" then
83                         session[k] = nil;
84                 end
85         end
86 end
87
88 function make_authenticated(session, username)
89         session.username = username;
90         if session.type == "c2s_unauthed" then
91                 session.type = "c2s";
92         end
93         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
94         return true;
95 end
96
97 -- returns true, nil on success
98 -- returns nil, err_type, err, err_message on failure
99 function bind_resource(session, resource)
100         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
101         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
102         -- We don't support binding multiple resources
103
104         resource = resource or uuid_generate();
105         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
106         
107         if not hosts[session.host].sessions[session.username] then
108                 local sessions = { sessions = {} };
109                 hosts[session.host].sessions[session.username] = sessions;
110                 bare_sessions[session.username..'@'..session.host] = sessions;
111         else
112                 local sessions = hosts[session.host].sessions[session.username].sessions;
113                 local limit = config_get(session.host, "core", "max_resources") or 10;
114                 if #sessions >= limit then
115                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
116                 end
117                 if sessions[resource] then
118                         -- Resource conflict
119                         local policy = config_get(session.host, "core", "conflict_resolve");
120                         local increment;
121                         if policy == "random" then
122                                 resource = uuid_generate();
123                                 increment = true;
124                         elseif policy == "increment" then
125                                 increment = true; -- TODO ping old resource
126                         elseif policy == "kick_new" then
127                                 return nil, "cancel", "conflict", "Resource already exists";
128                         else -- if policy == "kick_old" then
129                                 sessions[resource]:close {
130                                         condition = "conflict";
131                                         text = "Replaced by new connection";
132                                 };
133                                 if not next(sessions) then
134                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
135                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
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         full_sessions[session.full_jid] = session;
152         
153         session.roster = rm_load_roster(session.username, session.host);
154         
155         hosts[session.host].events.fire_event("resource-bind", session);
156         
157         return true;
158 end
159
160 function streamopened(session, attr)
161         local send = session.send;
162         session.host = attr.to or error("Client failed to specify destination hostname");
163         session.host = nameprep(session.host);
164         session.version = tonumber(attr.version) or 0;
165         session.streamid = m_random(1000000, 99999999);
166         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
167         
168         send("<?xml version='1.0'?>");
169         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));
170
171         if not hosts[session.host] then
172                 -- We don't serve this host...
173                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
174                 return;
175         end
176         
177         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
178         -- since we now have a new stream header, session is secured
179         if session.secure == false then
180                 session.secure = true;
181         end
182                                                 
183         local features = st.stanza("stream:features");
184         fire_event("stream-features", session, features);
185         
186         send(features);
187         
188         (session.log or log)("debug", "Sent reply <stream:stream> to client");
189         session.notopen = nil;
190 end
191
192 function streamclosed(session)
193         session.send("</stream:stream>");
194         session.notopen = true;
195 end
196
197 function send_to_available_resources(user, host, stanza)
198         local count = 0;
199         local to = stanza.attr.to;
200         stanza.attr.to = nil;
201         local h = hosts[host];
202         if h and h.type == "local" then
203                 local u = h.sessions[user];
204                 if u then
205                         for k, session in pairs(u.sessions) do
206                                 if session.presence then
207                                         session.send(stanza);
208                                         count = count + 1;
209                                 end
210                         end
211                 end
212         end
213         stanza.attr.to = to;
214         return count;
215 end
216
217 return _M;