mod_privacy: Don't store the privacy lists as an array, but as a map... faster and...
[prosody.git] / plugins / mod_privacy.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- Copyright (C) 2009 Thilo Cestonaro
5 -- 
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 local prosody = prosody;
11 local st = require "util.stanza";
12 local datamanager = require "util.datamanager";
13 local bare_sessions, full_sessions = bare_sessions, full_sessions;
14 local util_Jid = require "util.jid";
15 local jid_bare = util_Jid.bare;
16 local jid_split = util_Jid.split;
17 local load_roster = require "core.rostermanager".load_roster;
18 local to_number = tonumber;
19
20 function isListUsed(origin, name, privacy_lists)
21         local user = bare_sessions[origin.username.."@"..origin.host];
22         if user then
23                 for resource, session in pairs(user.sessions) do
24                         if resource ~= origin.resource then
25                                 if session.activePrivacyList == name then
26                                         return true;
27                                 elseif session.activePrivacyList == nil and privacy_lists.default == name then
28                                         return true;
29                                 end
30                         end
31                 end
32         end
33 end
34
35 function isAnotherSessionUsingDefaultList(origin)
36         local user = bare_sessions[origin.username.."@"..origin.host];
37         if user then
38                 for resource, session in pairs(user.sessions) do
39                         if resource ~= origin.resource and session.activePrivacyList == nil then
40                                 return true;
41                         end
42                 end
43         end
44 end
45
46 function sendUnavailable(origin, to, from)
47 --[[ example unavailable presence stanza
48 <presence from="node@host/resource" type="unavailable" to="node@host" >
49         <status>Logged out</status>
50 </presence>
51 ]]--
52         local presence = st.presence({from=from, type="unavailable"});
53         presence:tag("status"):text("Logged out");
54
55         local node, host = jid_bare(to);
56         local bare = node .. "@" .. host;
57         
58         local user = bare_sessions[bare];
59         if user then
60                 for resource, session in pairs(user.sessions) do
61                         presence.attr.to = session.full_jid;
62                         module:log("debug", "send unavailable to: %s; from: %s", tostring(presence.attr.to), tostring(presence.attr.from));
63                         origin.send(presence);
64                 end
65         end
66 end
67
68 function sendNeededUnavailablePersences(origin, listnameOrItem) -- TODO implement it correctly!
69         if type(listnameOrItem) == "string" then
70                 local listname = listnameOrItem;
71                 for _,list in ipairs(privacy_lists.lists) do
72                         if list.name == listname then
73                                 for _,item in ipairs(list.items) do
74                                         sendNeededUnavailablePersences(origin, item);
75                                 end
76                         end
77                 end
78         elseif type(listnameOrItem) == "table" then
79                 module:log("debug", "got an item, check whether to send unavailable presence stanza or not");
80                 local item = listnameOrItem;
81
82                 if item["presence-out"] == true then
83                         if item.type == "jid" then
84                                 sendUnavailable(origin, item.value, origin.full_jid);
85                         elseif item.type == "group" then
86                         elseif item.type == "subscription" then
87                         elseif item.type == nil then
88                         end
89                 elseif item["presence-in"] == true then
90                         if item.type == "jid" then
91                                 sendUnavailable(origin, origin.full_jid, item.value);
92                         elseif item.type == "group" then
93                         elseif item.type == "subscription" then
94                         elseif item.type == nil then
95                         end
96                 end
97         else
98                 module:log("debug", "got unknown type: %s", type(listnameOrItem));
99         end
100 end
101
102 function declineList(privacy_lists, origin, stanza, which)
103         if which == "default" then
104                 if isAnotherSessionUsingDefaultList(origin) then
105                         return { "cancel", "conflict", "Another session is online and using the default list."};
106                 end
107                 privacy_lists.default = nil;
108                 origin.send(st.reply(stanza));
109         elseif which == "active" then
110                 origin.activePrivacyList = nil;
111                 origin.send(st.reply(stanza));
112         else
113                 return {"modify", "bad-request", "Neither default nor active list specifed to decline."};
114         end
115         return true;
116 end
117
118 function activateList(privacy_lists, origin, stanza, which, name)
119         local list = privacy_lists.lists[name];
120
121         if privacy_lists.default == nil then
122                 privacy_lists.default = "";
123         end
124         if origin.activePrivacyList == nil then
125                 origin.activePrivacyList = "";
126         end
127         
128         if which == "default" and list then
129                 if isAnotherSessionUsingDefaultList(origin) then
130                         return {"cancel", "conflict", "Another session is online and using the default list."};
131                 end
132                 privacy_lists.default = name;
133                 origin.send(st.reply(stanza));
134 --[[
135                 if origin.activePrivacyList == nil then
136                         sendNeededUnavailablePersences(origin, name);
137                 end
138 ]]--
139         elseif which == "active" and list then
140                 origin.activePrivacyList = name;
141                 origin.send(st.reply(stanza));
142                 -- sendNeededUnavailablePersences(origin, name);
143         else
144                 return {"modify", "bad-request", "Either not active or default given or unknown list name specified."};
145         end
146         return true;
147 end
148
149 function deleteList(privacy_lists, origin, stanza, name)
150         local list = privacy_lists.lists[name];
151
152         if list then
153                 if isListUsed(origin, name, privacy_lists) then
154                         return {"cancel", "conflict", "Another session is online and using the list which should be deleted."};
155                 end
156                 if privacy_lists.default == name then
157                         privacy_lists.default = "";
158                 end
159                 if origin.activePrivacyList == name then
160                         origin.activePrivacyList = "";
161                 end
162                 privacy_lists.lists[name] = nil;
163                 origin.send(st.reply(stanza));
164                 return true;
165         end
166         return {"modify", "bad-request", "Not existing list specifed to be deleted."};
167 end
168
169 function createOrReplaceList (privacy_lists, origin, stanza, name, entries, roster)
170         local bare_jid = origin.username.."@"..origin.host;
171         
172         if privacy_lists.lists == nil then
173                 privacy_lists.lists = {};
174         end
175
176         local list = {};
177         privacy_lists.lists[name] = list;
178
179         local orderCheck = {};
180         list.name = name;
181         list.items = {};
182
183         for _,item in ipairs(entries) do
184                 if to_number(item.attr.order) == nil or to_number(item.attr.order) < 0 or orderCheck[item.attr.order] ~= nil then
185                         return {"modify", "bad-request", "Order attribute not valid."};
186                 end
187                 
188                 if item.attr.type ~= nil and item.attr.type ~= "jid" and item.attr.type ~= "subscription" and item.attr.type ~= "group" then
189                         return {"modify", "bad-request", "Type attribute not valid."};
190                 end
191                 
192                 local tmp = {};
193                 orderCheck[item.attr.order] = true;
194                 
195                 tmp["type"] = item.attr.type;
196                 tmp["value"] = item.attr.value;
197                 tmp["action"] = item.attr.action;
198                 tmp["order"] = to_number(item.attr.order);
199                 tmp["presence-in"] = false;
200                 tmp["presence-out"] = false;
201                 tmp["message"] = false;
202                 tmp["iq"] = false;
203                 
204                 if #item.tags > 0 then
205                         for _,tag in ipairs(item.tags) do
206                                 tmp[tag.name] = true;
207                         end
208                 end
209                 
210                 if tmp.type == "group" then
211                         local found = false;
212                         local roster = load_roster(origin.username, origin.host);
213                         for jid,item in pairs(roster) do
214                                 if item.groups ~= nil then
215                                         for group in pairs(item.groups) do
216                                                 if group == tmp.value then
217                                                         found = true;
218                                                         break;
219                                                 end
220                                         end
221                                         if found == true then
222                                                 break;
223                                         end
224                                 end
225                         end
226                         if found == false then
227                                 return {"cancel", "item-not-found", "Specifed roster group not existing."};
228                         end
229                 elseif tmp.type == "subscription" then
230                         if      tmp.value ~= "both" and
231                                 tmp.value ~= "to" and
232                                 tmp.value ~= "from" and
233                                 tmp.value ~= "none" then
234                                 return {"cancel", "bad-request", "Subscription value must be both, to, from or none."};
235                         end
236                 end
237                 
238                 if tmp.action ~= "deny" and tmp.action ~= "allow" then
239                         return {"cancel", "bad-request", "Action must be either deny or allow."};
240                 end
241                 
242 --[[
243                 if (privacy_lists.default == name and origin.activePrivacyList == nil) or origin.activePrivacyList == name then
244                         module:log("debug", "calling sendNeededUnavailablePresences!");
245                         -- item is valid and list is active, so send needed unavailable stanzas
246                         sendNeededUnavailablePersences(origin, tmp);
247                 end
248 ]]--
249                 list.items[#list.items + 1] = tmp;
250         end
251         
252         table.sort(list, function(a, b) return a.order < b.order; end);
253
254         origin.send(st.reply(stanza));
255         if bare_sessions[bare_jid] ~= nil then
256                 local iq = st.iq ( { type = "set", id="push1" } );
257                 iq:tag ("query", { xmlns = "jabber:iq:privacy" } );
258                 iq:tag ("list", { name = list.name } ):up();
259                 iq:up();
260                 for resource, session in pairs(bare_sessions[bare_jid].sessions) do
261                         iq.attr.to = bare_jid.."/"..resource
262                         session.send(iq);
263                 end
264         else
265                 return {"cancel", "bad-request", "internal error."};
266         end
267         return true;
268 end
269
270 function getList(privacy_lists, origin, stanza, name)
271         local reply = st.reply(stanza);
272         reply:tag("query", {xmlns="jabber:iq:privacy"});
273
274         if name == nil then
275                 reply:tag("active", {name=origin.activePrivacyList or ""}):up();
276                 reply:tag("default", {name=privacy_lists.default or ""}):up();
277                 if privacy_lists.lists then
278                         for _,list in ipairs(privacy_lists.lists) do
279                                 reply:tag("list", {name=list.name}):up();
280                         end
281                 end
282         else
283                 local list = privacy_lists.lists[name];
284                 if list then
285                         reply = reply:tag("list", {name=list.name});
286                         for _,item in ipairs(list.items) do
287                                 reply:tag("item", {type=item.type, value=item.value, action=item.action, order=item.order});
288                                 if item["message"] then reply:tag("message"):up(); end
289                                 if item["iq"] then reply:tag("iq"):up(); end
290                                 if item["presence-in"] then reply:tag("presence-in"):up(); end
291                                 if item["presence-out"] then reply:tag("presence-out"):up(); end
292                                 reply:up();
293                         end
294                 else
295                         return {"cancel", "item-not-found", "Unknown list specified."};
296                 end
297         end
298         
299         origin.send(reply);
300         return true;
301 end
302
303 module:hook("iq/bare/jabber:iq:privacy:query", function(data)
304         local origin, stanza = data.origin, data.stanza;
305         
306         if stanza.attr.to == nil then -- only service requests to own bare JID
307                 local query = stanza.tags[1]; -- the query element
308                 local valid = false;
309                 local privacy_lists = datamanager.load(origin.username, origin.host, "privacy") or {};
310
311                 if stanza.attr.type == "set" then
312                         if #query.tags == 1 then --  the <query/> element MUST NOT include more than one child element
313                                 for _,tag in ipairs(query.tags) do
314                                         if tag.name == "active" or tag.name == "default" then
315                                                 if tag.attr.name == nil then -- Client declines the use of active / default list
316                                                         valid = declineList(privacy_lists, origin, stanza, tag.name);
317                                                 else -- Client requests change of active / default list
318                                                         valid = activateList(privacy_lists, origin, stanza, tag.name, tag.attr.name);
319                                                 end
320                                         elseif tag.name == "list" and tag.attr.name then -- Client adds / edits a privacy list
321                                                 if #tag.tags == 0 then -- Client removes a privacy list
322                                                         valid = deleteList(privacy_lists, origin, stanza, tag.attr.name);
323                                                 else -- Client edits a privacy list
324                                                         valid = createOrReplaceList(privacy_lists, origin, stanza, tag.attr.name, tag.tags);
325                                                 end
326                                         end
327                                 end
328                         end
329                 elseif stanza.attr.type == "get" then
330                         local name = nil;
331                         local listsToRetrieve = 0;
332                         if #query.tags >= 1 then
333                                 for _,tag in ipairs(query.tags) do
334                                         if tag.name == "list" then -- Client requests a privacy list from server
335                                                 name = tag.attr.name;
336                                                 listsToRetrieve = listsToRetrieve + 1;
337                                         end
338                                 end
339                         end
340                         if listsToRetrieve == 0 or listsToRetrieve == 1 then
341                                 valid = getList(privacy_lists, origin, stanza, name);
342                         end
343                 end
344
345                 if valid ~= true then
346                         if valid[0] == nil then
347                                 valid[0] = "cancel";
348                         end
349                         if valid[1] == nil then
350                                 valid[1] = "bad-request";
351                         end
352                         origin.send(st.error_reply(stanza, valid[0], valid[1], valid[2]));
353                 else
354                         datamanager.store(origin.username, origin.host, "privacy", privacy_lists);
355                 end
356                 return true;
357         end
358 end);
359
360 function checkIfNeedToBeBlocked(e, session)
361         local origin, stanza = e.origin, e.stanza;
362         local privacy_lists = datamanager.load(session.username, session.host, "privacy") or {};
363         local bare_jid = session.username.."@"..session.host;
364         local to = stanza.attr.to;
365         local from = stanza.attr.from;
366         
367         local is_to_user = bare_jid == jid_bare(to);
368         local is_from_user = bare_jid == jid_bare(from);
369         
370         module:log("debug", "stanza: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
371         
372         if privacy_lists.lists == nil or
373                 (session.activePrivacyList == nil or session.activePrivacyList == "") and
374                 (privacy_lists.default == nil     or privacy_lists.default == "")
375         then
376                 return; -- Nothing to block, default is Allow all
377         end
378         if is_from_user and is_to_user then
379                 module:log("debug", "Not blocking communications between user's resources");
380                 return; -- from one of a user's resource to another => HANDS OFF!
381         end
382         
383         local item;
384         local listname = session.activePrivacyList;
385         if listname == nil or listname == "" then
386                 listname = privacy_lists.default; -- no active list selected, use default list
387         end
388         local list = privacy_lists.lists[listname];
389         if not list then
390                 module:log("debug", "given privacy list not found. name: %s", listname);
391                 return;
392         end
393         for _,item in ipairs(list.items) do
394                 local apply = false;
395                 local block = false;
396                 if (
397                         (stanza.name == "message" and item.message) or
398                         (stanza.name == "iq" and item.iq) or
399                         (stanza.name == "presence" and is_to_user and item["presence-in"]) or
400                         (stanza.name == "presence" and is_from_user and item["presence-out"]) or
401                         (item.message == false and item.iq == false and item["presence-in"] == false and item["presence-out"] == false)
402                 ) then
403                         apply = true;
404                 end
405                 if apply then
406                         local evilJid = {};
407                         apply = false;
408                         if is_to_user then
409                                 module:log("debug", "evil jid is (from): %s", from);
410                                 evilJid.node, evilJid.host, evilJid.resource = jid_split(from);
411                         else
412                                 module:log("debug", "evil jid is (to): %s", to);
413                                 evilJid.node, evilJid.host, evilJid.resource = jid_split(to);
414                         end
415                         if      item.type == "jid" and
416                                 (evilJid.node and evilJid.host and evilJid.resource and item.value == evilJid.node.."@"..evilJid.host.."/"..evilJid.resource) or
417                                 (evilJid.node and evilJid.host and item.value == evilJid.node.."@"..evilJid.host) or
418                                 (evilJid.host and evilJid.resource and item.value == evilJid.host.."/"..evilJid.resource) or
419                                 (evilJid.host and item.value == evilJid.host) then
420                                 apply = true;
421                                 block = (item.action == "deny");
422                         elseif item.type == "group" then
423                                 local roster = load_roster(session.username, session.host);
424                                 local groups = roster[evilJid.node .. "@" .. evilJid.host].groups;
425                                 for group in pairs(groups) do
426                                         if group == item.value then
427                                                 apply = true;
428                                                 block = (item.action == "deny");
429                                                 break;
430                                         end
431                                 end
432                         elseif item.type == "subscription" and evilJid.node ~= nil and evilJid.host ~= nil then -- we need a valid bare evil jid
433                                 local roster = load_roster(session.username, session.host);
434                                 if roster[evilJid.node .. "@" .. evilJid.host].subscription == item.value then
435                                         apply = true;
436                                         block = (item.action == "deny");
437                                 end
438                         elseif item.type == nil then
439                                 apply = true;
440                                 block = (item.action == "deny");
441                         end
442                 end
443                 if apply then
444                         if block then
445                                 module:log("debug", "stanza blocked: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
446                                 if stanza.name == "message" then
447                                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
448                                 elseif stanza.name == "iq" and (stanza.attr.type == "get" or stanza.attr.type == "set") then
449                                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
450                                 end
451                                 return true; -- stanza blocked !
452                         else
453                                 module:log("debug", "stanza explicitly allowed!")
454                                 return;
455                         end
456                 end
457         end
458 end
459
460 function preCheckIncoming(e)
461         local session;
462         if e.stanza.attr.to ~= nil then
463                 local node, host, resource = jid_split(e.stanza.attr.to);
464                 if node == nil or host == nil then
465                         return;
466                 end
467                 if resource == nil then
468                         local prio = 0;
469                         local session_;
470                         if bare_sessions[node.."@"..host] ~= nil then
471                                 for resource, session_ in pairs(bare_sessions[node.."@"..host].sessions) do
472                                         if session_.priority ~= nil and session_.priority > prio then
473                                                 session = session_;
474                                                 prio = session_.priority;
475                                         end
476                                 end
477                         end
478                 else
479                         session = full_sessions[node.."@"..host.."/"..resource];
480                 end
481                 if session ~= nil then
482                         return checkIfNeedToBeBlocked(e, session);
483                 else
484                         module:log("debug", "preCheckIncoming: Couldn't get session for jid: %s@%s/%s", tostring(node), tostring(host), tostring(resource));
485                 end
486         end
487 end
488
489 function preCheckOutgoing(e)
490         local session = e.origin;
491         if e.stanza.attr.from == nil then
492                 e.stanza.attr.from = session.username .. "@" .. session.host;
493                 if session.resource ~= nil then
494                         e.stanza.attr.from = e.stanza.attr.from .. "/" .. session.resource;
495                 end
496         end
497         return checkIfNeedToBeBlocked(e, session);
498 end
499
500 module:hook("pre-message/full", preCheckOutgoing, 500);
501 module:hook("pre-message/bare", preCheckOutgoing, 500);
502 module:hook("pre-message/host", preCheckOutgoing, 500);
503 module:hook("pre-iq/full", preCheckOutgoing, 500);
504 module:hook("pre-iq/bare", preCheckOutgoing, 500);
505 module:hook("pre-iq/host", preCheckOutgoing, 500);
506 module:hook("pre-presence/full", preCheckOutgoing, 500);
507 module:hook("pre-presence/bare", preCheckOutgoing, 500);
508 module:hook("pre-presence/host", preCheckOutgoing, 500);
509
510 module:hook("message/full", preCheckIncoming, 500);
511 module:hook("message/bare", preCheckIncoming, 500);
512 module:hook("message/host", preCheckIncoming, 500);
513 module:hook("iq/full", preCheckIncoming, 500);
514 module:hook("iq/bare", preCheckIncoming, 500);
515 module:hook("iq/host", preCheckIncoming, 500);
516 module:hook("presence/full", preCheckIncoming, 500);
517 module:hook("presence/bare", preCheckIncoming, 500);
518 module:hook("presence/host", preCheckIncoming, 500);