configmanager: Add parsers() method to return an array of supported config formats
[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 format = import("string", "format");
14
15 local hosts = hosts;
16 local full_sessions = full_sessions;
17 local bare_sessions = bare_sessions;
18
19 local modulemanager = require "core.modulemanager";
20 local logger = require "util.logger";
21 local log = 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 local add_task = require "util.timer".add_task;
30 local gettime = require "socket".gettime;
31
32 local st = require "util.stanza";
33
34 local c2s_timeout = config_get("*", "core", "c2s_timeout");
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(conn, 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         if c2s_timeout then
58                 add_task(c2s_timeout, function ()
59                         if session.type == "c2s_unauthed" then
60                                 session:close("connection-timeout");
61                         end
62                 end);
63         end
64                 
65         return session;
66 end
67
68 function destroy_session(session, err)
69         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
70         
71         -- Remove session/resource from user's session list
72         if session.full_jid then
73                 hosts[session.host].events.fire_event("resource-unbind", {session=session, error=err});
74
75                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
76                 full_sessions[session.full_jid] = nil;
77                         
78                 if not next(hosts[session.host].sessions[session.username].sessions) then
79                         log("debug", "All resources of %s are now offline", session.username);
80                         hosts[session.host].sessions[session.username] = nil;
81                         bare_sessions[session.username..'@'..session.host] = nil;
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                 local sessions = { sessions = {} };
113                 hosts[session.host].sessions[session.username] = sessions;
114                 bare_sessions[session.username..'@'..session.host] = sessions;
115         else
116                 local sessions = hosts[session.host].sessions[session.username].sessions;
117                 local limit = config_get(session.host, "core", "max_resources") or 10;
118                 if #sessions >= limit then
119                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
120                 end
121                 if sessions[resource] then
122                         -- Resource conflict
123                         local policy = config_get(session.host, "core", "conflict_resolve");
124                         local increment;
125                         if policy == "random" then
126                                 resource = uuid_generate();
127                                 increment = true;
128                         elseif policy == "increment" then
129                                 increment = true; -- TODO ping old resource
130                         elseif policy == "kick_new" then
131                                 return nil, "cancel", "conflict", "Resource already exists";
132                         else -- if policy == "kick_old" then
133                                 sessions[resource]:close {
134                                         condition = "conflict";
135                                         text = "Replaced by new connection";
136                                 };
137                                 if not next(sessions) then
138                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
139                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
140                                 end
141                         end
142                         if increment and sessions[resource] then
143                                 local count = 1;
144                                 while sessions[resource.."#"..count] do
145                                         count = count + 1;
146                                 end
147                                 resource = resource.."#"..count;
148                         end
149                 end
150         end
151         
152         session.resource = resource;
153         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
154         hosts[session.host].sessions[session.username].sessions[resource] = session;
155         full_sessions[session.full_jid] = session;
156         
157         session.roster = rm_load_roster(session.username, session.host);
158         
159         hosts[session.host].events.fire_event("resource-bind", {session=session});
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.host = nameprep(session.host);
168         session.version = tonumber(attr.version) or 0;
169         session.streamid = uuid_generate();
170         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
171
172         if not hosts[session.host] then
173                 -- We don't serve this host...
174                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
175                 return;
176         end
177
178         send("<?xml version='1.0'?>");
179         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));
180
181         (session.log or log)("debug", "Sent reply <stream:stream> to client");
182         session.notopen = nil;
183
184         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
185         -- since we now have a new stream header, session is secured
186         if session.secure == false then
187                 session.secure = true;
188         end
189
190         local features = st.stanza("stream:features");
191         fire_event("stream-features", session, features);
192
193         send(features);
194
195 end
196
197 function streamclosed(session)
198         session.send("</stream:stream>");
199         session.notopen = true;
200 end
201
202 function send_to_available_resources(user, host, stanza)
203         local jid = user.."@"..host;
204         local count = 0;
205         local user = bare_sessions[jid];
206         if user then
207                 for k, session in pairs(user.sessions) do
208                         if session.presence then
209                                 session.send(stanza);
210                                 count = count + 1;
211                         end
212                 end
213         end
214         return count;
215 end
216
217 function send_to_interested_resources(user, host, stanza)
218         local jid = user.."@"..host;
219         local count = 0;
220         local user = bare_sessions[jid];
221         if user then
222                 for k, session in pairs(user.sessions) do
223                         if session.interested then
224                                 session.send(stanza);
225                                 count = count + 1;
226                         end
227                 end
228         end
229         return count;
230 end
231
232 return _M;