xmlhandlers: Don't restrict CDATA
[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
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 resting_session = { -- Resting, not dead
70                 destroyed = true;
71                 type = "c2s_destroyed";
72                 close = function (session)
73                         session.log("debug", "Attempt to close already-closed session");
74                 end;
75         }; resting_session.__index = resting_session;
76
77 function retire_session(session)
78         local log = session.log or log;
79         for k in pairs(session) do
80                 if k ~= "trace" and k ~= "log" and k ~= "id" then
81                         session[k] = nil;
82                 end
83         end
84
85         function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
86         function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
87         return setmetatable(session, resting_session);
88 end
89
90 function destroy_session(session, err)
91         (session.log or log)("info", "Destroying session for %s (%s@%s)", session.full_jid or "(unknown)", session.username or "(unknown)", session.host or "(unknown)");
92         if session.destroyed then return; end
93         
94         -- Remove session/resource from user's session list
95         if session.full_jid then
96                 hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
97                 full_sessions[session.full_jid] = nil;
98                 
99                 if not next(hosts[session.host].sessions[session.username].sessions) then
100                         log("debug", "All resources of %s are now offline", session.username);
101                         hosts[session.host].sessions[session.username] = nil;
102                         bare_sessions[session.username..'@'..session.host] = nil;
103                 end
104
105                 hosts[session.host].events.fire_event("resource-unbind", {session=session, error=err});
106         end
107         
108         retire_session(session);
109 end
110
111 function make_authenticated(session, username)
112         session.username = username;
113         if session.type == "c2s_unauthed" then
114                 session.type = "c2s";
115         end
116         session.log("info", "Authenticated as %s@%s", username or "(unknown)", session.host or "(unknown)");
117         return true;
118 end
119
120 -- returns true, nil on success
121 -- returns nil, err_type, err, err_message on failure
122 function bind_resource(session, resource)
123         if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end
124         if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end
125         -- We don't support binding multiple resources
126
127         resource = resourceprep(resource);
128         resource = resource ~= "" and resource or uuid_generate();
129         --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
130         
131         if not hosts[session.host].sessions[session.username] then
132                 local sessions = { sessions = {} };
133                 hosts[session.host].sessions[session.username] = sessions;
134                 bare_sessions[session.username..'@'..session.host] = sessions;
135         else
136                 local sessions = hosts[session.host].sessions[session.username].sessions;
137                 local limit = config_get(session.host, "core", "max_resources") or 10;
138                 if #sessions >= limit then
139                         return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed";
140                 end
141                 if sessions[resource] then
142                         -- Resource conflict
143                         local policy = config_get(session.host, "core", "conflict_resolve");
144                         local increment;
145                         if policy == "random" then
146                                 resource = uuid_generate();
147                                 increment = true;
148                         elseif policy == "increment" then
149                                 increment = true; -- TODO ping old resource
150                         elseif policy == "kick_new" then
151                                 return nil, "cancel", "conflict", "Resource already exists";
152                         else -- if policy == "kick_old" then
153                                 sessions[resource]:close {
154                                         condition = "conflict";
155                                         text = "Replaced by new connection";
156                                 };
157                                 if not next(sessions) then
158                                         hosts[session.host].sessions[session.username] = { sessions = sessions };
159                                         bare_sessions[session.username.."@"..session.host] = hosts[session.host].sessions[session.username];
160                                 end
161                         end
162                         if increment and sessions[resource] then
163                                 local count = 1;
164                                 while sessions[resource.."#"..count] do
165                                         count = count + 1;
166                                 end
167                                 resource = resource.."#"..count;
168                         end
169                 end
170         end
171         
172         session.resource = resource;
173         session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
174         hosts[session.host].sessions[session.username].sessions[resource] = session;
175         full_sessions[session.full_jid] = session;
176         
177         session.roster = rm_load_roster(session.username, session.host);
178         
179         hosts[session.host].events.fire_event("resource-bind", {session=session});
180         
181         return true;
182 end
183
184 function streamopened(session, attr)
185         local send = session.send;
186         session.host = attr.to;
187         if not session.host then
188                 session:close{ condition = "improper-addressing",
189                         text = "A 'to' attribute is required on stream headers" };
190                 return;
191         end
192         session.host = nameprep(session.host);
193         session.version = tonumber(attr.version) or 0;
194         session.streamid = uuid_generate();
195         (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host);
196
197         if not hosts[session.host] then
198                 -- We don't serve this host...
199                 session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)};
200                 return;
201         end
202
203         send("<?xml version='1.0'?>");
204         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));
205
206         (session.log or log)("debug", "Sent reply <stream:stream> to client");
207         session.notopen = nil;
208
209         -- If session.secure is *false* (not nil) then it means we /were/ encrypting
210         -- since we now have a new stream header, session is secured
211         if session.secure == false then
212                 session.secure = true;
213         end
214
215         local features = st.stanza("stream:features");
216         hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
217         fire_event("stream-features", session, features);
218
219         send(features);
220
221 end
222
223 function streamclosed(session)
224         session.log("debug", "Received </stream:stream>");
225         session:close();
226 end
227
228 function send_to_available_resources(user, host, stanza)
229         local jid = user.."@"..host;
230         local count = 0;
231         local user = bare_sessions[jid];
232         if user then
233                 for k, session in pairs(user.sessions) do
234                         if session.presence then
235                                 session.send(stanza);
236                                 count = count + 1;
237                         end
238                 end
239         end
240         return count;
241 end
242
243 function send_to_interested_resources(user, host, stanza)
244         local jid = user.."@"..host;
245         local count = 0;
246         local user = bare_sessions[jid];
247         if user then
248                 for k, session in pairs(user.sessions) do
249                         if session.interested then
250                                 session.send(stanza);
251                                 count = count + 1;
252                         end
253                 end
254         end
255         return count;
256 end
257
258 return _M;