certmanager: Remove debug logging accidentally committed
[prosody.git] / core / sessionmanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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, setmetatable = tonumber, tostring, setmetatable;
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 local resourceprep = require "util.encodings".stringprep.resourceprep;
28 local nodeprep = require "util.encodings".stringprep.nodeprep;
29
30 local initialize_filters = require "util.filters".initialize;
31 local fire_event = require "core.eventmanager".fire_event;
32 local add_task = require "util.timer".add_task;
33 local gettime = require "socket".gettime;
34
35 local st = require "util.stanza";
36
37 local c2s_timeout = config_get("*", "core", "c2s_timeout");
38
39 local newproxy = newproxy;
40 local getmetatable = getmetatable;
41
42 module "sessionmanager"
43
44 local open_sessions = 0;
45
46 function new_session(conn)
47         local session = { conn = conn, type = "c2s_unauthed", conntime = gettime() };
48         if true then
49                 session.trace = newproxy(true);
50                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
51         end
52         open_sessions = open_sessions + 1;
53         log("debug", "open sessions now: ".. open_sessions);
54         
55         local filter = initialize_filters(session);
56         local w = conn.write;
57         session.send = function (t)
58                 if t.name then
59                         t = filter("stanzas/out", t);
60                 end
61                 if t then
62                         t = filter("bytes/out", tostring(t));
63                         if t then
64                                 return w(conn, t);
65                         end
66                 end
67         end
68         session.ip = conn:ip();
69         local conn_name = "c2s"..tostring(conn):match("[a-f0-9]+$");
70         session.log = logger.init(conn_name);
71         
72         if c2s_timeout then
73                 add_task(c2s_timeout, function ()
74                         if session.type == "c2s_unauthed" then
75                                 session:close("connection-timeout");
76                         end
77                 end);
78         end
79                 
80         return session;
81 end
82
83 local resting_session = { -- Resting, not dead
84                 destroyed = true;
85                 type = "c2s_destroyed";
86                 close = function (session)
87                         session.log("debug", "Attempt to close already-closed session");
88                 end;
89         }; resting_session.__index = resting_session;
90
91 function retire_session(session)
92         local log = session.log or log;
93         for k in pairs(session) do
94                 if k ~= "trace" and k ~= "log" and k ~= "id" then
95                         session[k] = nil;
96                 end
97         end
98
99         function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
100         function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
101         return setmetatable(session, resting_session);
102 end
103
104 function destroy_session(session, err)
105         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
106         if session.destroyed then return; end
107         
108         -- Remove session/resource from user's session list
109         if session.full_jid then
110                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
111                 full_sessions[session.full_jid] = nil;
112                 
113                 if not next(hosts[session.host].sessions[session.username].sessions) then
114                         log("debug", "All resources of %s are now offline", session.username);
115                         hosts[session.host].sessions[session.username] = nil;
116                         bare_sessions[session.username..'@'..session.host] = nil;
117                 end
118
119                 hosts[session.host].events.fire_event("resource-unbind", {session=session, error=err});
120         end
121         
122         retire_session(session);
123 end
124
125 function make_authenticated(session, username)
126         username = nodeprep(username);
127         if not username or #username == 0 then return nil, "Invalid username"; end
128         session.username = username;
129         if session.type == "c2s_unauthed" then
130                 session.type = "c2s";
131         end
132         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
133         return true;
134 end
135
136 -- returns true, nil on success
137 -- returns nil, err_type, err, err_message on failure
138 function bind_resource(session, resource)
139         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
140         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
141         -- We don't support binding multiple resources
142
143         resource = resourceprep(resource);
144         resource = resource ~= "" and resource or uuid_generate();
145         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
146         
147         if not hosts[session.host].sessions[session.username] then
148                 local sessions = { sessions = {} };
149                 hosts[session.host].sessions[session.username] = sessions;
150                 bare_sessions[session.username..'@'..session.host] = sessions;
151         else
152                 local sessions = hosts[session.host].sessions[session.username].sessions;
153                 local limit = config_get(session.host, "core", "max_resources") or 10;
154                 if #sessions >= limit then
155                         return nil, "cancel", "resource-constraint", "Resource limit reached; only "..limit.." resources allowed";
156                 end
157                 if sessions[resource] then
158                         -- Resource conflict
159                         local policy = config_get(session.host, "core", "conflict_resolve");
160                         local increment;
161                         if policy == "random" then
162                                 resource = uuid_generate();
163                                 increment = true;
164                         elseif policy == "increment" then
165                                 increment = true; -- TODO ping old resource
166                         elseif policy == "kick_new" then
167                                 return nil, "cancel", "conflict", "Resource already exists";
168                         else -- if policy == "kick_old" then
169                                 sessions[resource]:close {
170                                         condition = "conflict";
171                                         text = "Replaced by new connection";
172                                 };
173                                 if not next(sessions) then
174                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
175                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
176                                 end
177                         end
178                         if increment and sessions[resource] then
179                                 local count = 1;
180                                 while sessions[resource.."#"..count] do
181                                         count = count + 1;
182                                 end
183                                 resource = resource.."#"..count;
184                         end
185                 end
186         end
187         
188         session.resource = resource;
189         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
190         hosts[session.host].sessions[session.username].sessions[resource] = session;
191         full_sessions[session.full_jid] = session;
192         
193         local err;
194         session.roster, err = rm_load_roster(session.username, session.host);
195         if err then
196                 full_sessions[session.full_jid] = nil;
197                 hosts[session.host].sessions[session.username].sessions[resource] = nil;
198                 session.full_jid = nil;
199                 session.resource = nil;
200                 if next(bare_sessions[session.username..'@'..session.host].sessions) == nil then
201                         bare_sessions[session.username..'@'..session.host] = nil;
202                         hosts[session.host].sessions[session.username] = nil;
203                 end
204                 return nil, "cancel", "internal-server-error", "Error loading roster";
205         end
206         
207         hosts[session.host].events.fire_event("resource-bind", {session=session});
208         
209         return true;
210 end
211
212 function streamopened(session, attr)
213         local send = session.send;
214         session.host = attr.to;
215         if not session.host then
216                 session:close{ condition = "improper-addressing",
217                         text = "A 'to' attribute is required on stream headers" };
218                 return;
219         end
220         session.host = nameprep(session.host);
221         session.version = tonumber(attr.version) or 0;
222         session.streamid = uuid_generate();
223         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
224
225         if not hosts[session.host] then
226                 -- We don't serve this host...
227                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
228                 return;
229         end
230
231         send("<?xml version='1.0'?>");
232         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));
233
234         (session.log or log)("debug", "Sent reply <stream:stream> to client");
235         session.notopen = nil;
236
237         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
238         -- since we now have a new stream header, session is secured
239         if session.secure == false then
240                 session.secure = true;
241         end
242
243         local features = st.stanza("stream:features");
244         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
245         fire_event("stream-features", session, features);
246
247         send(features);
248
249 end
250
251 function streamclosed(session)
252         session.log("debug", "Received </stream:stream>");
253         session:close();
254 end
255
256 function send_to_available_resources(user, host, stanza)
257         local jid = user.."@"..host;
258         local count = 0;
259         local user = bare_sessions[jid];
260         if user then
261                 for k, session in pairs(user.sessions) do
262                         if session.presence then
263                                 session.send(stanza);
264                                 count = count + 1;
265                         end
266                 end
267         end
268         return count;
269 end
270
271 function send_to_interested_resources(user, host, stanza)
272         local jid = user.."@"..host;
273         local count = 0;
274         local user = bare_sessions[jid];
275         if user then
276                 for k, session in pairs(user.sessions) do
277                         if session.interested then
278                                 session.send(stanza);
279                                 count = count + 1;
280                         end
281                 end
282         end
283         return count;
284 end
285
286 return _M;