modulemanager: Allow setting priority of stanza handlers
[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,  priority = 0, 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].sessions[session.username].sessions[session.resource] = nil;
70                 full_sessions[session.full_jid] = nil;
71                         
72                 if not next(hosts[session.host].sessions[session.username].sessions) then
73                         log("debug", "All resources of %s are now offline", session.username);
74                         hosts[session.host].sessions[session.username] = nil;
75                         bare_sessions[session.username..'@'..session.host] = nil;
76                 end
77         end
78         
79         for k in pairs(session) do
80                 if k ~= "trace" then
81                         session[k] = nil;
82                 end
83         end
84 end
85
86 function make_authenticated(session, username)
87         session.username = username;
88         if session.type == "c2s_unauthed" then
89                 session.type = "c2s";
90         end
91         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
92         return true;
93 end
94
95 -- returns true, nil on success
96 -- returns nil, err_type, err, err_message on failure
97 function bind_resource(session, resource)
98         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
99         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
100         -- We don't support binding multiple resources
101
102         resource = resource or uuid_generate();
103         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
104         
105         if not hosts[session.host].sessions[session.username] then
106                 local sessions = { sessions = {} };
107                 hosts[session.host].sessions[session.username] = sessions;
108                 bare_sessions[session.username..'@'..session.host] = sessions;
109         else
110                 local sessions = hosts[session.host].sessions[session.username].sessions;
111                 local limit = config_get(session.host, "core", "max_resources") or 10;
112                 if #sessions >= limit then
113                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
114                 end
115                 if sessions[resource] then
116                         -- Resource conflict
117                         local policy = config_get(session.host, "core", "conflict_resolve");
118                         local increment;
119                         if policy == "random" then
120                                 resource = uuid_generate();
121                                 increment = true;
122                         elseif policy == "increment" then
123                                 increment = true; -- TODO ping old resource
124                         elseif policy == "kick_new" then
125                                 return nil, "cancel", "conflict", "Resource already exists";
126                         else -- if policy == "kick_old" then
127                                 sessions[resource]:close {
128                                         condition = "conflict";
129                                         text = "Replaced by new connection";
130                                 };
131                                 if not next(sessions) then
132                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
133                                 end
134                         end
135                         if increment and sessions[resource] then
136                                 local count = 1;
137                                 while sessions[resource.."#"..count] do
138                                         count = count + 1;
139                                 end
140                                 resource = resource.."#"..count;
141                         end
142                 end
143         end
144         
145         session.resource = resource;
146         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
147         hosts[session.host].sessions[session.username].sessions[resource] = session;
148         full_sessions[session.full_jid] = session;
149         
150         session.roster = rm_load_roster(session.username, session.host);
151         
152         return true;
153 end
154
155 function streamopened(session, attr)
156         local send = session.send;
157         session.host = attr.to or error("Client failed to specify destination hostname");
158         session.host = nameprep(session.host);
159         session.version = tonumber(attr.version) or 0;
160         session.streamid = m_random(1000000, 99999999);
161         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
162         
163         send("<?xml version='1.0'?>");
164         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));
165
166         if not hosts[session.host] then
167                 -- We don't serve this host...
168                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
169                 return;
170         end
171         
172         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
173         -- since we now have a new stream header, session is secured
174         if session.secure == false then
175                 session.secure = true;
176         end
177                                                 
178         local features = st.stanza("stream:features");
179         fire_event("stream-features", session, features);
180         
181         send(features);
182         
183         (session.log or log)("debug", "Sent reply <stream:stream> to client");
184         session.notopen = nil;
185 end
186
187 function streamclosed(session)
188         session.send("</stream:stream>");
189         session.notopen = true;
190 end
191
192 function send_to_available_resources(user, host, stanza)
193         local count = 0;
194         local to = stanza.attr.to;
195         stanza.attr.to = nil;
196         local h = hosts[host];
197         if h and h.type == "local" then
198                 local u = h.sessions[user];
199                 if u then
200                         for k, session in pairs(u.sessions) do
201                                 if session.presence then
202                                         session.send(stanza);
203                                         count = count + 1;
204                                 end
205                         end
206                 end
207         end
208         stanza.attr.to = to;
209         return count;
210 end
211
212 return _M;