net.http: Update print()s to log()s - don't ask how this came to be, I have no idea :)
[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 local resourceprep = require "util.encodings".stringprep.resourceprep;
28
29 local fire_event = require "core.eventmanager".fire_event;
30 local add_task = require "util.timer".add_task;
31 local gettime = require "socket".gettime;
32
33 local st = require "util.stanza";
34
35 local c2s_timeout = config_get("*", "core", "c2s_timeout");
36
37 local newproxy = newproxy;
38 local getmetatable = getmetatable;
39
40 module "sessionmanager"
41
42 local open_sessions = 0;
43
44 function new_session(conn)
45         local session = { conn = conn, type = "c2s_unauthed", conntime = gettime() };
46         if true then
47                 session.trace = newproxy(true);
48                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
49         end
50         open_sessions = open_sessions + 1;
51         log("debug", "open sessions now: ".. open_sessions);
52         local w = conn.write;
53         session.send = function (t) w(conn, tostring(t)); end
54         session.ip = conn:ip();
55         local conn_name = "c2s"..tostring(conn):match("[a-f0-9]+$");
56         session.log = logger.init(conn_name);
57         
58         if c2s_timeout then
59                 add_task(c2s_timeout, function ()
60                         if session.type == "c2s_unauthed" then
61                                 session:close("connection-timeout");
62                         end
63                 end);
64         end
65                 
66         return session;
67 end
68
69 local function null_data_handler(conn, data) log("debug", "Discarding data from destroyed c2s session: %s", data); end
70
71 function destroy_session(session, err)
72         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
73         
74         -- Remove session/resource from user's session list
75         if session.full_jid then
76                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
77                 full_sessions[session.full_jid] = nil;
78                 
79                 if not next(hosts[session.host].sessions[session.username].sessions) then
80                         log("debug", "All resources of %s are now offline", session.username);
81                         hosts[session.host].sessions[session.username] = nil;
82                         bare_sessions[session.username..'@'..session.host] = nil;
83                 end
84
85                 hosts[session.host].events.fire_event("resource-unbind", {session=session, error=err});
86         end
87         
88         for k in pairs(session) do
89                 if k ~= "trace" then
90                         session[k] = nil;
91                 end
92         end
93         session.data = null_data_handler;
94 end
95
96 function make_authenticated(session, username)
97         session.username = username;
98         if session.type == "c2s_unauthed" then
99                 session.type = "c2s";
100         end
101         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
102         return true;
103 end
104
105 -- returns true, nil on success
106 -- returns nil, err_type, err, err_message on failure
107 function bind_resource(session, resource)
108         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
109         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
110         -- We don't support binding multiple resources
111
112         resource = resourceprep(resource);
113         resource = resource ~= "" and resource or uuid_generate();
114         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
115         
116         if not hosts[session.host].sessions[session.username] then
117                 local sessions = { sessions = {} };
118                 hosts[session.host].sessions[session.username] = sessions;
119                 bare_sessions[session.username..'@'..session.host] = sessions;
120         else
121                 local sessions = hosts[session.host].sessions[session.username].sessions;
122                 local limit = config_get(session.host, "core", "max_resources") or 10;
123                 if #sessions >= limit then
124                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
125                 end
126                 if sessions[resource] then
127                         -- Resource conflict
128                         local policy = config_get(session.host, "core", "conflict_resolve");
129                         local increment;
130                         if policy == "random" then
131                                 resource = uuid_generate();
132                                 increment = true;
133                         elseif policy == "increment" then
134                                 increment = true; -- TODO ping old resource
135                         elseif policy == "kick_new" then
136                                 return nil, "cancel", "conflict", "Resource already exists";
137                         else -- if policy == "kick_old" then
138                                 sessions[resource]:close {
139                                         condition = "conflict";
140                                         text = "Replaced by new connection";
141                                 };
142                                 if not next(sessions) then
143                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
144                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
145                                 end
146                         end
147                         if increment and sessions[resource] then
148                                 local count = 1;
149                                 while sessions[resource.."#"..count] do
150                                         count = count + 1;
151                                 end
152                                 resource = resource.."#"..count;
153                         end
154                 end
155         end
156         
157         session.resource = resource;
158         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
159         hosts[session.host].sessions[session.username].sessions[resource] = session;
160         full_sessions[session.full_jid] = session;
161         
162         session.roster = rm_load_roster(session.username, session.host);
163         
164         hosts[session.host].events.fire_event("resource-bind", {session=session});
165         
166         return true;
167 end
168
169 function streamopened(session, attr)
170         local send = session.send;
171         session.host = attr.to or error("Client failed to specify destination hostname");
172         session.host = nameprep(session.host);
173         session.version = tonumber(attr.version) or 0;
174         session.streamid = uuid_generate();
175         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
176
177         if not hosts[session.host] then
178                 -- We don't serve this host...
179                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
180                 return;
181         end
182
183         send("<?xml version='1.0'?>");
184         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));
185
186         (session.log or log)("debug", "Sent reply <stream:stream> to client");
187         session.notopen = nil;
188
189         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
190         -- since we now have a new stream header, session is secured
191         if session.secure == false then
192                 session.secure = true;
193         end
194
195         local features = st.stanza("stream:features");
196         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
197         fire_event("stream-features", session, features);
198
199         send(features);
200
201 end
202
203 function streamclosed(session)
204         session.send("</stream:stream>");
205         session.notopen = true;
206 end
207
208 function send_to_available_resources(user, host, stanza)
209         local jid = user.."@"..host;
210         local count = 0;
211         local user = bare_sessions[jid];
212         if user then
213                 for k, session in pairs(user.sessions) do
214                         if session.presence then
215                                 session.send(stanza);
216                                 count = count + 1;
217                         end
218                 end
219         end
220         return count;
221 end
222
223 function send_to_interested_resources(user, host, stanza)
224         local jid = user.."@"..host;
225         local count = 0;
226         local user = bare_sessions[jid];
227         if user then
228                 for k, session in pairs(user.sessions) do
229                         if session.interested then
230                                 session.send(stanza);
231                                 count = count + 1;
232                         end
233                 end
234         end
235         return count;
236 end
237
238 return _M;