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