Automated merge with http://waqas.ath.cx:8000/
[prosody.git] / core / sessionmanager.lua
1 -- Prosody IM v0.2
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 fire_event = require "core.eventmanager".fire_event;
39
40 local gettime = require "socket".gettime;
41
42 local st = require "util.stanza";
43
44 local newproxy = newproxy;
45 local getmetatable = getmetatable;
46
47 module "sessionmanager"
48
49 local open_sessions = 0;
50
51 function new_session(conn)
52         local session = { conn = conn,  priority = 0, type = "c2s_unauthed", conntime = gettime() };
53         if true then
54                 session.trace = newproxy(true);
55                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
56         end
57         open_sessions = open_sessions + 1;
58         log("info", "open sessions now: ".. open_sessions);
59         local w = conn.write;
60         session.send = function (t) w(tostring(t)); end
61         session.ip = conn.ip();
62         return session;
63 end
64
65 function destroy_session(session, err)
66         (session.log or log)("info", "Destroying session");
67         
68         -- Send unavailable presence
69         if session.presence then
70                 local pres = st.presence{ type = "unavailable" };
71                 if (not err) or err == "closed" then err = "connection closed"; end
72                 pres:tag("status"):text("Disconnected: "..err);
73                 session:dispatch_stanza(pres);
74         end
75         
76         -- Remove session/resource from user's session list
77         if session.host and session.username then
78                 -- FIXME: How can the below ever be nil? (but they sometimes are...)
79                 if hosts[session.host] and hosts[session.host].sessions[session.username] then
80                         if session.resource then
81                                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
82                         end
83                                 
84                         if not next(hosts[session.host].sessions[session.username].sessions) then
85                                 log("debug", "All resources of %s are now offline", session.username);
86                                 hosts[session.host].sessions[session.username] = nil;
87                         end
88                 else
89                         log("error", "host or session table didn't exist, please report this! Host: %s [%s] Sessions: %s [%s]", 
90                                         tostring(hosts[session.host]), tostring(session.host),
91                                         tostring(hosts[session.host].sessions[session.username] ), tostring(session.username));
92                 end
93         end
94         
95         for k in pairs(session) do
96                 if k ~= "trace" then
97                         session[k] = nil;
98                 end
99         end
100 end
101
102 function make_authenticated(session, username)
103         session.username = username;
104         if session.type == "c2s_unauthed" then
105                 session.type = "c2s";
106         end
107         return true;
108 end
109
110 -- returns true, nil on success
111 -- returns nil, err_type, err, err_message on failure
112 function bind_resource(session, resource)
113         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
114         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
115         -- We don't support binding multiple resources
116
117         resource = resource or uuid_generate();
118         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
119         
120         if not hosts[session.host].sessions[session.username] then
121                 hosts[session.host].sessions[session.username] = { sessions = {} };
122         else
123                 local sessions = hosts[session.host].sessions[session.username].sessions;
124                 local limit = config_get(session.host, "core", "max_resources") or 10;
125                 if #sessions >= limit then
126                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
127                 end
128                 if sessions[resource] then
129                         -- Resource conflict
130                         local policy = config_get(session.host, "core", "conflict_resolve");
131                         local increment;
132                         if policy == "random" then
133                                 resource = uuid_generate();
134                                 increment = true;
135                         elseif policy == "increment" then
136                                 increment = true; -- TODO ping old resource
137                         elseif policy == "kick_new" then
138                                 return nil, "cancel", "conflict", "Resource already exists";
139                         else -- if policy == "kick_old" then
140                                 hosts[session.host].sessions[session.username].sessions[resource]:close {
141                                         condition = "conflict";
142                                         text = "Replaced by new connection";
143                                 };
144                         end
145                         if increment and sessions[resource] then
146                                 local count = 1;
147                                 while sessions[resource.."#"..count] do
148                                         count = count + 1;
149                                 end
150                                 resource = resource.."#"..count;
151                         end
152                 end
153         end
154         
155         session.resource = resource;
156         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
157         hosts[session.host].sessions[session.username].sessions[resource] = session;
158         
159         session.roster = rm_load_roster(session.username, session.host);
160         
161         return true;
162 end
163
164 function streamopened(session, attr)
165                                                 local send = session.send;
166                                                 session.host = attr.to or error("Client failed to specify destination hostname");
167                                                 session.version = tonumber(attr.version) or 0;
168                                                 session.streamid = m_random(1000000, 99999999);
169                                                 (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
170                                                 
171                                                 
172                                                 send("<?xml version='1.0'?>");
173                                                 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));
174                                                 
175                                                 if not hosts[session.host] then
176                                                         -- We don't serve this host...
177                                                         session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
178                                                         return;
179                                                 end
180                                                 
181                                                 
182                                                 local features = st.stanza("stream:features");
183                                                 fire_event("stream-features", session, features);
184                                                 
185                                                 send(features);
186                                                 
187                                                 (session.log or log)("info", "Sent reply <stream:stream> to client");
188                                                 session.notopen = nil;
189 end
190
191 function send_to_available_resources(user, host, stanza)
192         local count = 0;
193         local to = stanza.attr.to;
194         stanza.attr.to = nil;
195         local h = hosts[host];
196         if h and h.type == "local" then
197                 local u = h.sessions[user];
198                 if u then
199                         for k, session in pairs(u.sessions) do
200                                 if session.presence then
201                                         session.send(stanza);
202                                         count = count + 1;
203                                 end
204                         end
205                 end
206         end
207         stanza.attr.to = to;
208         return count;
209 end
210
211 return _M;