tools/ejabberd2prosody: Fixed private storage export
[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("debug", "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 for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
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):up();
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         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
98         return true;
99 end
100
101 -- returns true, nil on success
102 -- returns nil, err_type, err, err_message on failure
103 function bind_resource(session, resource)
104         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
105         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
106         -- We don't support binding multiple resources
107
108         resource = resource or uuid_generate();
109         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
110         
111         if not hosts[session.host].sessions[session.username] then
112                 hosts[session.host].sessions[session.username] = { sessions = {} };
113         else
114                 local sessions = hosts[session.host].sessions[session.username].sessions;
115                 local limit = config_get(session.host, "core", "max_resources") or 10;
116                 if #sessions >= limit then
117                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
118                 end
119                 if sessions[resource] then
120                         -- Resource conflict
121                         local policy = config_get(session.host, "core", "conflict_resolve");
122                         local increment;
123                         if policy == "random" then
124                                 resource = uuid_generate();
125                                 increment = true;
126                         elseif policy == "increment" then
127                                 increment = true; -- TODO ping old resource
128                         elseif policy == "kick_new" then
129                                 return nil, "cancel", "conflict", "Resource already exists";
130                         else -- if policy == "kick_old" then
131                                 sessions[resource]:close {
132                                         condition = "conflict";
133                                         text = "Replaced by new connection";
134                                 };
135                                 if not next(sessions) then
136                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
137                                 end
138                         end
139                         if increment and sessions[resource] then
140                                 local count = 1;
141                                 while sessions[resource.."#"..count] do
142                                         count = count + 1;
143                                 end
144                                 resource = resource.."#"..count;
145                         end
146                 end
147         end
148         
149         session.resource = resource;
150         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
151         hosts[session.host].sessions[session.username].sessions[resource] = session;
152         
153         session.roster = rm_load_roster(session.username, session.host);
154         
155         return true;
156 end
157
158 function streamopened(session, attr)
159         local send = session.send;
160         session.host = attr.to or error("Client failed to specify destination hostname");
161         session.host = nameprep(session.host);
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         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         local features = st.stanza("stream:features");
176         fire_event("stream-features", session, features);
177         
178         send(features);
179         
180         (session.log or log)("debug", "Sent reply <stream:stream> to client");
181         session.notopen = nil;
182 end
183
184 function streamclosed(session)
185         session.send("</stream:stream>");
186         session.notopen = true;
187 end
188
189 function send_to_available_resources(user, host, stanza)
190         local count = 0;
191         local to = stanza.attr.to;
192         stanza.attr.to = nil;
193         local h = hosts[host];
194         if h and h.type == "local" then
195                 local u = h.sessions[user];
196                 if u then
197                         for k, session in pairs(u.sessions) do
198                                 if session.presence then
199                                         session.send(stanza);
200                                         count = count + 1;
201                                 end
202                         end
203                 end
204         end
205         stanza.attr.to = to;
206         return count;
207 end
208
209 return _M;