mod_privacy: Fix to correctly iterate over lists stored in new format
[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 which == "default" and list then
122                 if isAnotherSessionUsingDefaultList(origin) then
123                         return {"cancel", "conflict", "Another session is online and using the default list."};
124                 end
125                 privacy_lists.default = name;
126                 origin.send(st.reply(stanza));
127 --[[
128                 if origin.activePrivacyList == nil then
129                         sendNeededUnavailablePersences(origin, name);
130                 end
131 ]]--
132         elseif which == "active" and list then
133                 origin.activePrivacyList = name;
134                 origin.send(st.reply(stanza));
135                 -- sendNeededUnavailablePersences(origin, name);
136         else
137                 return {"modify", "bad-request", "Either not active or default given or unknown list name specified."};
138         end
139         return true;
140 end
141
142 function deleteList(privacy_lists, origin, stanza, name)
143         local list = privacy_lists.lists[name];
144
145         if list then
146                 if isListUsed(origin, name, privacy_lists) then
147                         return {"cancel", "conflict", "Another session is online and using the list which should be deleted."};
148                 end
149                 if privacy_lists.default == name then
150                         privacy_lists.default = nil;
151                 end
152                 if origin.activePrivacyList == name then
153                         origin.activePrivacyList = nil;
154                 end
155                 privacy_lists.lists[name] = nil;
156                 origin.send(st.reply(stanza));
157                 return true;
158         end
159         return {"modify", "bad-request", "Not existing list specifed to be deleted."};
160 end
161
162 function createOrReplaceList (privacy_lists, origin, stanza, name, entries, roster)
163         local bare_jid = origin.username.."@"..origin.host;
164         
165         if privacy_lists.lists == nil then
166                 privacy_lists.lists = {};
167         end
168
169         local list = {};
170         privacy_lists.lists[name] = list;
171
172         local orderCheck = {};
173         list.name = name;
174         list.items = {};
175
176         for _,item in ipairs(entries) do
177                 if to_number(item.attr.order) == nil or to_number(item.attr.order) < 0 or orderCheck[item.attr.order] ~= nil then
178                         return {"modify", "bad-request", "Order attribute not valid."};
179                 end
180                 
181                 if item.attr.type ~= nil and item.attr.type ~= "jid" and item.attr.type ~= "subscription" and item.attr.type ~= "group" then
182                         return {"modify", "bad-request", "Type attribute not valid."};
183                 end
184                 
185                 local tmp = {};
186                 orderCheck[item.attr.order] = true;
187                 
188                 tmp["type"] = item.attr.type;
189                 tmp["value"] = item.attr.value;
190                 tmp["action"] = item.attr.action;
191                 tmp["order"] = to_number(item.attr.order);
192                 tmp["presence-in"] = false;
193                 tmp["presence-out"] = false;
194                 tmp["message"] = false;
195                 tmp["iq"] = false;
196                 
197                 if #item.tags > 0 then
198                         for _,tag in ipairs(item.tags) do
199                                 tmp[tag.name] = true;
200                         end
201                 end
202                 
203                 if tmp.type == "group" then
204                         local found = false;
205                         local roster = load_roster(origin.username, origin.host);
206                         for jid,item in pairs(roster) do
207                                 if item.groups ~= nil then
208                                         for group in pairs(item.groups) do
209                                                 if group == tmp.value then
210                                                         found = true;
211                                                         break;
212                                                 end
213                                         end
214                                         if found == true then
215                                                 break;
216                                         end
217                                 end
218                         end
219                         if found == false then
220                                 return {"cancel", "item-not-found", "Specifed roster group not existing."};
221                         end
222                 elseif tmp.type == "subscription" then
223                         if      tmp.value ~= "both" and
224                                 tmp.value ~= "to" and
225                                 tmp.value ~= "from" and
226                                 tmp.value ~= "none" then
227                                 return {"cancel", "bad-request", "Subscription value must be both, to, from or none."};
228                         end
229                 end
230                 
231                 if tmp.action ~= "deny" and tmp.action ~= "allow" then
232                         return {"cancel", "bad-request", "Action must be either deny or allow."};
233                 end
234                 
235 --[[
236                 if (privacy_lists.default == name and origin.activePrivacyList == nil) or origin.activePrivacyList == name then
237                         module:log("debug", "calling sendNeededUnavailablePresences!");
238                         -- item is valid and list is active, so send needed unavailable stanzas
239                         sendNeededUnavailablePersences(origin, tmp);
240                 end
241 ]]--
242                 list.items[#list.items + 1] = tmp;
243         end
244         
245         table.sort(list, function(a, b) return a.order < b.order; end);
246
247         origin.send(st.reply(stanza));
248         if bare_sessions[bare_jid] ~= nil then
249                 local iq = st.iq ( { type = "set", id="push1" } );
250                 iq:tag ("query", { xmlns = "jabber:iq:privacy" } );
251                 iq:tag ("list", { name = list.name } ):up();
252                 iq:up();
253                 for resource, session in pairs(bare_sessions[bare_jid].sessions) do
254                         iq.attr.to = bare_jid.."/"..resource
255                         session.send(iq);
256                 end
257         else
258                 return {"cancel", "bad-request", "internal error."};
259         end
260         return true;
261 end
262
263 function getList(privacy_lists, origin, stanza, name)
264         local reply = st.reply(stanza);
265         reply:tag("query", {xmlns="jabber:iq:privacy"});
266
267         if name == nil then
268                 if privacy_lists.lists then
269                         if origin.ActivePrivacyList then
270                                 reply:tag("active", {name=origin.activePrivacyList}):up();
271                         end
272                         if privacy_lists.default then
273                                 reply:tag("default", {name=privacy_lists.default}):up();
274                         end
275                         for name,list in pairs(privacy_lists.lists) do
276                                 reply:tag("list", {name=name}):up();
277                         end
278                 end
279         else
280                 local list = privacy_lists.lists[name];
281                 if list then
282                         reply = reply:tag("list", {name=list.name});
283                         for _,item in ipairs(list.items) do
284                                 reply:tag("item", {type=item.type, value=item.value, action=item.action, order=item.order});
285                                 if item["message"] then reply:tag("message"):up(); end
286                                 if item["iq"] then reply:tag("iq"):up(); end
287                                 if item["presence-in"] then reply:tag("presence-in"):up(); end
288                                 if item["presence-out"] then reply:tag("presence-out"):up(); end
289                                 reply:up();
290                         end
291                 else
292                         return {"cancel", "item-not-found", "Unknown list specified."};
293                 end
294         end
295         
296         origin.send(reply);
297         return true;
298 end
299
300 module:hook("iq/bare/jabber:iq:privacy:query", function(data)
301         local origin, stanza = data.origin, data.stanza;
302         
303         if stanza.attr.to == nil then -- only service requests to own bare JID
304                 local query = stanza.tags[1]; -- the query element
305                 local valid = false;
306                 local privacy_lists = datamanager.load(origin.username, origin.host, "privacy") or { lists = {} };
307
308                 if privacy_lists.lists[1] then -- Code to migrate from old privacy lists format, remove in 0.8
309                         module:log("info", "Upgrading format of stored privacy lists for %s@%s", origin.username, origin.host);
310                         local lists = privacy_lists.lists;
311                         for idx, list in ipairs(lists) do
312                                 lists[list.name] = list;
313                                 lists[idx] = nil;
314                         end
315                 end
316
317                 if stanza.attr.type == "set" then
318                         if #query.tags == 1 then --  the <query/> element MUST NOT include more than one child element
319                                 for _,tag in ipairs(query.tags) do
320                                         if tag.name == "active" or tag.name == "default" then
321                                                 if tag.attr.name == nil then -- Client declines the use of active / default list
322                                                         valid = declineList(privacy_lists, origin, stanza, tag.name);
323                                                 else -- Client requests change of active / default list
324                                                         valid = activateList(privacy_lists, origin, stanza, tag.name, tag.attr.name);
325                                                 end
326                                         elseif tag.name == "list" and tag.attr.name then -- Client adds / edits a privacy list
327                                                 if #tag.tags == 0 then -- Client removes a privacy list
328                                                         valid = deleteList(privacy_lists, origin, stanza, tag.attr.name);
329                                                 else -- Client edits a privacy list
330                                                         valid = createOrReplaceList(privacy_lists, origin, stanza, tag.attr.name, tag.tags);
331                                                 end
332                                         end
333                                 end
334                         end
335                 elseif stanza.attr.type == "get" then
336                         local name = nil;
337                         local listsToRetrieve = 0;
338                         if #query.tags >= 1 then
339                                 for _,tag in ipairs(query.tags) do
340                                         if tag.name == "list" then -- Client requests a privacy list from server
341                                                 name = tag.attr.name;
342                                                 listsToRetrieve = listsToRetrieve + 1;
343                                         end
344                                 end
345                         end
346                         if listsToRetrieve == 0 or listsToRetrieve == 1 then
347                                 valid = getList(privacy_lists, origin, stanza, name);
348                         end
349                 end
350
351                 if valid ~= true then
352                         valid = valid or { "cancel", "bad-request", "Couldn't understand request" };
353                         if valid[1] == nil then
354                                 valid[1] = "cancel";
355                         end
356                         if valid[2] == nil then
357                                 valid[2] = "bad-request";
358                         end
359                         origin.send(st.error_reply(stanza, valid[1], valid[2], valid[3]));
360                 else
361                         datamanager.store(origin.username, origin.host, "privacy", privacy_lists);
362                 end
363                 return true;
364         end
365 end);
366
367 function checkIfNeedToBeBlocked(e, session)
368         local origin, stanza = e.origin, e.stanza;
369         local privacy_lists = datamanager.load(session.username, session.host, "privacy") or {};
370         local bare_jid = session.username.."@"..session.host;
371         local to = stanza.attr.to;
372         local from = stanza.attr.from;
373         
374         local is_to_user = bare_jid == jid_bare(to);
375         local is_from_user = bare_jid == jid_bare(from);
376         
377         module:log("debug", "stanza: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
378         
379         if privacy_lists.lists == nil or
380                 not (session.activePrivacyList or privacy_lists.default)
381         then
382                 return; -- Nothing to block, default is Allow all
383         end
384         if is_from_user and is_to_user then
385                 module:log("debug", "Not blocking communications between user's resources");
386                 return; -- from one of a user's resource to another => HANDS OFF!
387         end
388         
389         local item;
390         local listname = session.activePrivacyList;
391         if listname == nil then
392                 listname = privacy_lists.default; -- no active list selected, use default list
393         end
394         local list = privacy_lists.lists[listname];
395         if not list then
396                 module:log("debug", "given privacy list not found. name: %s", listname);
397                 return;
398         end
399         for _,item in ipairs(list.items) do
400                 local apply = false;
401                 local block = false;
402                 if (
403                         (stanza.name == "message" and item.message) or
404                         (stanza.name == "iq" and item.iq) or
405                         (stanza.name == "presence" and is_to_user and item["presence-in"]) or
406                         (stanza.name == "presence" and is_from_user and item["presence-out"]) or
407                         (item.message == false and item.iq == false and item["presence-in"] == false and item["presence-out"] == false)
408                 ) then
409                         apply = true;
410                 end
411                 if apply then
412                         local evilJid = {};
413                         apply = false;
414                         if is_to_user then
415                                 module:log("debug", "evil jid is (from): %s", from);
416                                 evilJid.node, evilJid.host, evilJid.resource = jid_split(from);
417                         else
418                                 module:log("debug", "evil jid is (to): %s", to);
419                                 evilJid.node, evilJid.host, evilJid.resource = jid_split(to);
420                         end
421                         if      item.type == "jid" and
422                                 (evilJid.node and evilJid.host and evilJid.resource and item.value == evilJid.node.."@"..evilJid.host.."/"..evilJid.resource) or
423                                 (evilJid.node and evilJid.host and item.value == evilJid.node.."@"..evilJid.host) or
424                                 (evilJid.host and evilJid.resource and item.value == evilJid.host.."/"..evilJid.resource) or
425                                 (evilJid.host and item.value == evilJid.host) then
426                                 apply = true;
427                                 block = (item.action == "deny");
428                         elseif item.type == "group" then
429                                 local roster = load_roster(session.username, session.host);
430                                 local groups = roster[evilJid.node .. "@" .. evilJid.host].groups;
431                                 for group in pairs(groups) do
432                                         if group == item.value then
433                                                 apply = true;
434                                                 block = (item.action == "deny");
435                                                 break;
436                                         end
437                                 end
438                         elseif item.type == "subscription" and evilJid.node ~= nil and evilJid.host ~= nil then -- we need a valid bare evil jid
439                                 local roster = load_roster(session.username, session.host);
440                                 if roster[evilJid.node .. "@" .. evilJid.host].subscription == item.value then
441                                         apply = true;
442                                         block = (item.action == "deny");
443                                 end
444                         elseif item.type == nil then
445                                 apply = true;
446                                 block = (item.action == "deny");
447                         end
448                 end
449                 if apply then
450                         if block then
451                                 module:log("debug", "stanza blocked: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
452                                 if stanza.name == "message" then
453                                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
454                                 elseif stanza.name == "iq" and (stanza.attr.type == "get" or stanza.attr.type == "set") then
455                                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
456                                 end
457                                 return true; -- stanza blocked !
458                         else
459                                 module:log("debug", "stanza explicitly allowed!")
460                                 return;
461                         end
462                 end
463         end
464 end
465
466 function preCheckIncoming(e)
467         local session;
468         if e.stanza.attr.to ~= nil then
469                 local node, host, resource = jid_split(e.stanza.attr.to);
470                 if node == nil or host == nil then
471                         return;
472                 end
473                 if resource == nil then
474                         local prio = 0;
475                         local session_;
476                         if bare_sessions[node.."@"..host] ~= nil then
477                                 for resource, session_ in pairs(bare_sessions[node.."@"..host].sessions) do
478                                         if session_.priority ~= nil and session_.priority > prio then
479                                                 session = session_;
480                                                 prio = session_.priority;
481                                         end
482                                 end
483                         end
484                 else
485                         session = full_sessions[node.."@"..host.."/"..resource];
486                 end
487                 if session ~= nil then
488                         return checkIfNeedToBeBlocked(e, session);
489                 else
490                         module:log("debug", "preCheckIncoming: Couldn't get session for jid: %s@%s/%s", tostring(node), tostring(host), tostring(resource));
491                 end
492         end
493 end
494
495 function preCheckOutgoing(e)
496         local session = e.origin;
497         if e.stanza.attr.from == nil then
498                 e.stanza.attr.from = session.username .. "@" .. session.host;
499                 if session.resource ~= nil then
500                         e.stanza.attr.from = e.stanza.attr.from .. "/" .. session.resource;
501                 end
502         end
503         return checkIfNeedToBeBlocked(e, session);
504 end
505
506 module:hook("pre-message/full", preCheckOutgoing, 500);
507 module:hook("pre-message/bare", preCheckOutgoing, 500);
508 module:hook("pre-message/host", preCheckOutgoing, 500);
509 module:hook("pre-iq/full", preCheckOutgoing, 500);
510 module:hook("pre-iq/bare", preCheckOutgoing, 500);
511 module:hook("pre-iq/host", preCheckOutgoing, 500);
512 module:hook("pre-presence/full", preCheckOutgoing, 500);
513 module:hook("pre-presence/bare", preCheckOutgoing, 500);
514 module:hook("pre-presence/host", preCheckOutgoing, 500);
515
516 module:hook("message/full", preCheckIncoming, 500);
517 module:hook("message/bare", preCheckIncoming, 500);
518 module:hook("message/host", preCheckIncoming, 500);
519 module:hook("iq/full", preCheckIncoming, 500);
520 module:hook("iq/bare", preCheckIncoming, 500);
521 module:hook("iq/host", preCheckIncoming, 500);
522 module:hook("presence/full", preCheckIncoming, 500);
523 module:hook("presence/bare", preCheckIncoming, 500);
524 module:hook("presence/host", preCheckIncoming, 500);