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