mod_presence: Don't depend on sessions array existing for a user when handling outgoi...
[prosody.git] / plugins / mod_presence.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 local log = module._log;
10
11 local require = require;
12 local pairs, ipairs = pairs, ipairs;
13 local t_concat, t_insert = table.concat, table.insert;
14 local s_find = string.find;
15 local tonumber = tonumber;
16
17 local st = require "util.stanza";
18 local jid_split = require "util.jid".split;
19 local jid_bare = require "util.jid".bare;
20 local hosts = hosts;
21 local NULL = {};
22
23 local rostermanager = require "core.rostermanager";
24 local sessionmanager = require "core.sessionmanager";
25 local offlinemanager = require "core.offlinemanager";
26
27 local _core_route_stanza = core_route_stanza;
28 local core_route_stanza;
29 function core_route_stanza(origin, stanza)
30         if stanza.attr.type ~= nil and stanza.attr.type ~= "unavailable" and stanza.attr.type ~= "error" then
31                 local node, host = jid_split(stanza.attr.to);
32                 host = hosts[host];
33                 if node and host and host.type == "local" then
34                         handle_inbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to), core_route_stanza);
35                         return;
36                 end
37         end
38         _core_route_stanza(origin, stanza);
39 end
40
41 local function select_top_resources(user)
42         local priority = 0;
43         local recipients = {};
44         for _, session in pairs(user.sessions) do -- find resource with greatest priority
45                 if session.presence then
46                         -- TODO check active privacy list for session
47                         local p = session.priority;
48                         if p > priority then
49                                 priority = p;
50                                 recipients = {session};
51                         elseif p == priority then
52                                 t_insert(recipients, session);
53                         end
54                 end
55         end
56         return recipients;
57 end
58 local function recalc_resource_map(origin)
59         local user = hosts[origin.host].sessions[origin.username];
60         user.top_resources = select_top_resources(user);
61         if #user.top_resources == 0 then user.top_resources = nil; end
62 end
63
64 function handle_normal_presence(origin, stanza, core_route_stanza)
65         local roster = origin.roster;
66         local node, host = origin.username, origin.host;
67         local user = bare_sessions[node.."@"..host];
68         for _, res in pairs(user and user.sessions or NULL) do -- broadcast to all resources
69                 if res ~= origin and res.presence then -- to resource
70                         stanza.attr.to = res.full_jid;
71                         core_route_stanza(origin, stanza);
72                 end
73         end
74         for jid, item in pairs(roster) do -- broadcast to all interested contacts
75                 if item.subscription == "both" or item.subscription == "from" then
76                         stanza.attr.to = jid;
77                         core_route_stanza(origin, stanza);
78                 end
79         end
80         if stanza.attr.type == nil and not origin.presence then -- initial presence
81                 origin.presence = stanza; -- FIXME repeated later
82                 local probe = st.presence({from = origin.full_jid, type = "probe"});
83                 for jid, item in pairs(roster) do -- probe all contacts we are subscribed to
84                         if item.subscription == "both" or item.subscription == "to" then
85                                 probe.attr.to = jid;
86                                 core_route_stanza(origin, probe);
87                         end
88                 end
89                 for _, res in pairs(user and user.sessions or NULL) do -- broadcast from all available resources
90                         if res ~= origin and res.presence then
91                                 res.presence.attr.to = origin.full_jid;
92                                 core_route_stanza(res, res.presence);
93                                 res.presence.attr.to = nil;
94                         end
95                 end
96                 if roster.pending then -- resend incoming subscription requests
97                         for jid in pairs(roster.pending) do
98                                 origin.send(st.presence({type="subscribe", from=jid})); -- TODO add to attribute? Use original?
99                         end
100                 end
101                 local request = st.presence({type="subscribe", from=origin.username.."@"..origin.host});
102                 for jid, item in pairs(roster) do -- resend outgoing subscription requests
103                         if item.ask then
104                                 request.attr.to = jid;
105                                 core_route_stanza(origin, request);
106                         end
107                 end
108                 local offline = offlinemanager.load(node, host);
109                 if offline then
110                         for _, msg in ipairs(offline) do
111                                 origin.send(msg); -- FIXME do we need to modify to/from in any way?
112                         end
113                         offlinemanager.deleteAll(node, host);
114                 end
115         end
116         if stanza.attr.type == "unavailable" then
117                 origin.presence = nil;
118                 if origin.priority then
119                         origin.priority = nil;
120                         recalc_resource_map(origin);
121                 end
122                 if origin.directed then
123                         for jid in pairs(origin.directed) do
124                                 stanza.attr.to = jid;
125                                 core_route_stanza(origin, stanza);
126                         end
127                         origin.directed = nil;
128                 end
129         else
130                 origin.presence = stanza;
131                 local priority = stanza:child_with_name("priority");
132                 if priority and #priority > 0 then
133                         priority = t_concat(priority);
134                         if s_find(priority, "^[+-]?[0-9]+$") then
135                                 priority = tonumber(priority);
136                                 if priority < -128 then priority = -128 end
137                                 if priority > 127 then priority = 127 end
138                         else priority = 0; end
139                 else priority = 0; end
140                 if origin.priority ~= priority then
141                         origin.priority = priority;
142                         recalc_resource_map(origin);
143                 end
144         end
145         stanza.attr.to = nil; -- reset it
146 end
147
148 function send_presence_of_available_resources(user, host, jid, recipient_session, core_route_stanza, stanza)
149         local h = hosts[host];
150         local count = 0;
151         if h and h.type == "local" then
152                 local u = h.sessions[user];
153                 if u then
154                         for k, session in pairs(u.sessions) do
155                                 local pres = session.presence;
156                                 if pres then
157                                         if stanza then pres = stanza; pres.attr.from = session.full_jid; end
158                                         pres.attr.to = jid;
159                                         core_route_stanza(session, pres);
160                                         pres.attr.to = nil;
161                                         count = count + 1;
162                                 end
163                         end
164                 end
165         end
166         log("debug", "broadcasted presence of "..count.." resources from "..user.."@"..host.." to "..jid);
167         return count;
168 end
169
170 function handle_outbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare, core_route_stanza)
171         local node, host = jid_split(from_bare);
172         if to_bare == origin.username.."@"..origin.host then return; end -- No self contacts
173         local st_from, st_to = stanza.attr.from, stanza.attr.to;
174         stanza.attr.from, stanza.attr.to = from_bare, to_bare;
175         log("debug", "outbound presence "..stanza.attr.type.." from "..from_bare.." for "..to_bare);
176         if stanza.attr.type == "subscribe" then
177                 -- 1. route stanza
178                 -- 2. roster push (subscription = none, ask = subscribe)
179                 if rostermanager.set_contact_pending_out(node, host, to_bare) then
180                         rostermanager.roster_push(node, host, to_bare);
181                 end -- else file error
182                 core_route_stanza(origin, stanza);
183         elseif stanza.attr.type == "unsubscribe" then
184                 -- 1. route stanza
185                 -- 2. roster push (subscription = none or from)
186                 if rostermanager.unsubscribe(node, host, to_bare) then
187                         rostermanager.roster_push(node, host, to_bare); -- FIXME do roster push when roster has in fact not changed?
188                 end -- else file error
189                 core_route_stanza(origin, stanza);
190         elseif stanza.attr.type == "subscribed" then
191                 -- 1. route stanza
192                 -- 2. roster_push ()
193                 -- 3. send_presence_of_available_resources
194                 if rostermanager.subscribed(node, host, to_bare) then
195                         rostermanager.roster_push(node, host, to_bare);
196                 end
197                 core_route_stanza(origin, stanza);
198                 send_presence_of_available_resources(node, host, to_bare, origin, core_route_stanza);
199         elseif stanza.attr.type == "unsubscribed" then
200                 -- 1. route stanza
201                 -- 2. roster push (subscription = none or to)
202                 if rostermanager.unsubscribed(node, host, to_bare) then
203                         rostermanager.roster_push(node, host, to_bare);
204                 end
205                 core_route_stanza(origin, stanza);
206         end
207         stanza.attr.from, stanza.attr.to = st_from, st_to;
208 end
209
210 function handle_inbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare, core_route_stanza)
211         local node, host = jid_split(to_bare);
212         local st_from, st_to = stanza.attr.from, stanza.attr.to;
213         stanza.attr.from, stanza.attr.to = from_bare, to_bare;
214         log("debug", "inbound presence "..stanza.attr.type.." from "..from_bare.." for "..to_bare);
215         
216         if not node then
217                 log("debug", "dropping presence sent to host or invalid address '%s'", tostring(to_bare));
218         end
219         
220         if stanza.attr.type == "probe" then
221                 if rostermanager.is_contact_subscribed(node, host, from_bare) then
222                         if 0 == send_presence_of_available_resources(node, host, st_from, origin, core_route_stanza) then
223                                 core_route_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"})); -- TODO send last activity
224                         end
225                 else
226                         core_route_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unsubscribed"}));
227                 end
228         elseif stanza.attr.type == "subscribe" then
229                 if rostermanager.is_contact_subscribed(node, host, from_bare) then
230                         core_route_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="subscribed"})); -- already subscribed
231                         -- Sending presence is not clearly stated in the RFC, but it seems appropriate
232                         if 0 == send_presence_of_available_resources(node, host, from_bare, origin, core_route_stanza) then
233                                 core_route_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"})); -- TODO send last activity
234                         end
235                 else
236                         core_route_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"})); -- acknowledging receipt
237                         if not rostermanager.is_contact_pending_in(node, host, from_bare) then
238                                 if rostermanager.set_contact_pending_in(node, host, from_bare) then
239                                         sessionmanager.send_to_available_resources(node, host, stanza);
240                                 end -- TODO else return error, unable to save
241                         end
242                 end
243         elseif stanza.attr.type == "unsubscribe" then
244                 if rostermanager.process_inbound_unsubscribe(node, host, from_bare) then
245                         sessionmanager.send_to_interested_resources(node, host, stanza);
246                         rostermanager.roster_push(node, host, from_bare);
247                 end
248         elseif stanza.attr.type == "subscribed" then
249                 if rostermanager.process_inbound_subscription_approval(node, host, from_bare) then
250                         sessionmanager.send_to_interested_resources(node, host, stanza);
251                         rostermanager.roster_push(node, host, from_bare);
252                 end
253         elseif stanza.attr.type == "unsubscribed" then
254                 if rostermanager.process_inbound_subscription_cancellation(node, host, from_bare) then
255                         sessionmanager.send_to_interested_resources(node, host, stanza);
256                         rostermanager.roster_push(node, host, from_bare);
257                 end
258         end -- discard any other type
259         stanza.attr.from, stanza.attr.to = st_from, st_to;
260 end
261
262 local outbound_presence_handler = function(data)
263         -- outbound presence recieved
264         local origin, stanza = data.origin, data.stanza;
265
266         local to = stanza.attr.to;
267         if to then
268                 local t = stanza.attr.type;
269                 if t ~= nil and t ~= "unavailable" and t ~= "error" then -- check for subscriptions and probes
270                         handle_outbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to), core_route_stanza);
271                         return true;
272                 end
273
274                 local to_bare = jid_bare(to);
275                 if not(origin.roster[to_bare] and (origin.roster[to_bare].subscription == "both" or origin.roster[to_bare].subscription == "from")) then -- directed presence
276                         origin.directed = origin.directed or {};
277                         if t then -- removing from directed presence list on sending an error or unavailable
278                                 origin.directed[to] = nil; -- FIXME does it make more sense to add to_bare rather than to?
279                         else
280                                 origin.directed[to] = true; -- FIXME does it make more sense to add to_bare rather than to?
281                         end
282                 end
283         end -- TODO maybe handle normal presence here, instead of letting it pass to incoming handlers?
284 end
285
286 module:hook("pre-presence/full", outbound_presence_handler);
287 module:hook("pre-presence/bare", outbound_presence_handler);
288 module:hook("pre-presence/host", outbound_presence_handler);
289
290 module:hook("presence/bare", function(data)
291         -- inbound presence to bare JID recieved
292         local origin, stanza = data.origin, data.stanza;
293
294         local to = stanza.attr.to;
295         local t = stanza.attr.type;
296         if to then
297                 if t ~= nil and t ~= "unavailable" and t ~= "error" then -- check for subscriptions and probes sent to bare JID
298                         handle_inbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to), core_route_stanza);
299                         return true;
300                 end
301         
302                 local user = bare_sessions[to];
303                 if user then
304                         for _, session in pairs(user.sessions) do
305                                 if session.presence then -- only send to available resources
306                                         session.send(stanza);
307                                 end
308                         end
309                 end -- no resources not online, discard
310         elseif not t or t == "unavailable" then
311                 handle_normal_presence(origin, stanza, core_route_stanza);
312         end
313         return true;
314 end);
315 module:hook("presence/full", function(data)
316         -- inbound presence to full JID recieved
317         local origin, stanza = data.origin, data.stanza;
318
319         local t = stanza.attr.type;
320         if t ~= nil and t ~= "unavailable" and t ~= "error" then -- check for subscriptions and probes sent to full JID
321                 handle_inbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to), core_route_stanza);
322                 return true;
323         end
324
325         local session = full_sessions[stanza.attr.to];
326         if session then
327                 -- TODO fire post processing event
328                 session.send(stanza);
329         end -- resource not online, discard
330         return true;
331 end);
332 module:hook("presence/host", function(data)
333         -- inbound presence to the host
334         local origin, stanza = data.origin, data.stanza;
335         
336         local from_bare = jid_bare(stanza.attr.from);
337         local t = stanza.attr.type;
338         if t == "probe" then
339                 core_route_stanza(hosts[module.host], st.presence({ from = module.host, to = from_bare, id = stanza.attr.id }));
340         elseif t == "subscribe" then
341                 core_route_stanza(hosts[module.host], st.presence({ from = module.host, to = from_bare, id = stanza.attr.id, type = "subscribed" }));
342                 core_route_stanza(hosts[module.host], st.presence({ from = module.host, to = from_bare, id = stanza.attr.id }));
343         end
344         return true;
345 end);
346
347 module:hook("resource-unbind", function(event)
348         local session, err = event.session, event.error;
349         -- Send unavailable presence
350         if session.presence then
351                 local pres = st.presence{ type = "unavailable" };
352                 if not(err) or err == "closed" then err = "connection closed"; end
353                 pres:tag("status"):text("Disconnected: "..err):up();
354                 session:dispatch_stanza(pres);
355         elseif session.directed then
356                 local pres = st.presence{ type = "unavailable", from = session.full_jid };
357                 if not(err) or err == "closed" then err = "connection closed"; end
358                 pres:tag("status"):text("Disconnected: "..err):up();
359                 for jid in pairs(session.directed) do
360                         pres.attr.to = jid;
361                         core_route_stanza(session, pres);
362                 end
363                 session.directed = nil;
364         end
365 end);