mod_privacy: Return the correct item-not-found instead of bad-request when a non...
[prosody.git] / plugins / mod_privacy.lua
1 -- Prosody IM
2 -- Copyright (C) 2009-2010 Matthew Wild
3 -- Copyright (C) 2009-2010 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, jid_join = util_Jid.split, util_Jid.join;
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 declineList(privacy_lists, origin, stanza, which)
69         if which == "default" then
70                 if isAnotherSessionUsingDefaultList(origin) then
71                         return { "cancel", "conflict", "Another session is online and using the default list."};
72                 end
73                 privacy_lists.default = nil;
74                 origin.send(st.reply(stanza));
75         elseif which == "active" then
76                 origin.activePrivacyList = nil;
77                 origin.send(st.reply(stanza));
78         else
79                 return {"modify", "bad-request", "Neither default nor active list specifed to decline."};
80         end
81         return true;
82 end
83
84 function activateList(privacy_lists, origin, stanza, which, name)
85         local list = privacy_lists.lists[name];
86
87         if which == "default" and list then
88                 if isAnotherSessionUsingDefaultList(origin) then
89                         return {"cancel", "conflict", "Another session is online and using the default list."};
90                 end
91                 privacy_lists.default = name;
92                 origin.send(st.reply(stanza));
93         elseif which == "active" and list then
94                 origin.activePrivacyList = name;
95                 origin.send(st.reply(stanza));
96         elseif not list then
97                 return {"cancel", "item-not-found", "No such list: "..name};
98         else
99                 return {"modify", "bad-request", "No list chosen to be active or default."};
100         end
101         return true;
102 end
103
104 function deleteList(privacy_lists, origin, stanza, name)
105         local list = privacy_lists.lists[name];
106
107         if list then
108                 if isListUsed(origin, name, privacy_lists) then
109                         return {"cancel", "conflict", "Another session is online and using the list which should be deleted."};
110                 end
111                 if privacy_lists.default == name then
112                         privacy_lists.default = nil;
113                 end
114                 if origin.activePrivacyList == name then
115                         origin.activePrivacyList = nil;
116                 end
117                 privacy_lists.lists[name] = nil;
118                 origin.send(st.reply(stanza));
119                 return true;
120         end
121         return {"modify", "bad-request", "Not existing list specifed to be deleted."};
122 end
123
124 function createOrReplaceList (privacy_lists, origin, stanza, name, entries, roster)
125         local bare_jid = origin.username.."@"..origin.host;
126         
127         if privacy_lists.lists == nil then
128                 privacy_lists.lists = {};
129         end
130
131         local list = {};
132         privacy_lists.lists[name] = list;
133
134         local orderCheck = {};
135         list.name = name;
136         list.items = {};
137
138         for _,item in ipairs(entries) do
139                 if to_number(item.attr.order) == nil or to_number(item.attr.order) < 0 or orderCheck[item.attr.order] ~= nil then
140                         return {"modify", "bad-request", "Order attribute not valid."};
141                 end
142                 
143                 if item.attr.type ~= nil and item.attr.type ~= "jid" and item.attr.type ~= "subscription" and item.attr.type ~= "group" then
144                         return {"modify", "bad-request", "Type attribute not valid."};
145                 end
146                 
147                 local tmp = {};
148                 orderCheck[item.attr.order] = true;
149                 
150                 tmp["type"] = item.attr.type;
151                 tmp["value"] = item.attr.value;
152                 tmp["action"] = item.attr.action;
153                 tmp["order"] = to_number(item.attr.order);
154                 tmp["presence-in"] = false;
155                 tmp["presence-out"] = false;
156                 tmp["message"] = false;
157                 tmp["iq"] = false;
158                 
159                 if #item.tags > 0 then
160                         for _,tag in ipairs(item.tags) do
161                                 tmp[tag.name] = true;
162                         end
163                 end
164                 
165                 if tmp.type == "subscription" then
166                         if      tmp.value ~= "both" and
167                                 tmp.value ~= "to" and
168                                 tmp.value ~= "from" and
169                                 tmp.value ~= "none" then
170                                 return {"cancel", "bad-request", "Subscription value must be both, to, from or none."};
171                         end
172                 end
173                 
174                 if tmp.action ~= "deny" and tmp.action ~= "allow" then
175                         return {"cancel", "bad-request", "Action must be either deny or allow."};
176                 end
177                 list.items[#list.items + 1] = tmp;
178         end
179         
180         table.sort(list, function(a, b) return a.order < b.order; end);
181
182         origin.send(st.reply(stanza));
183         if bare_sessions[bare_jid] ~= nil then
184                 local iq = st.iq ( { type = "set", id="push1" } );
185                 iq:tag ("query", { xmlns = "jabber:iq:privacy" } );
186                 iq:tag ("list", { name = list.name } ):up();
187                 iq:up();
188                 for resource, session in pairs(bare_sessions[bare_jid].sessions) do
189                         iq.attr.to = bare_jid.."/"..resource
190                         session.send(iq);
191                 end
192         else
193                 return {"cancel", "bad-request", "internal error."};
194         end
195         return true;
196 end
197
198 function getList(privacy_lists, origin, stanza, name)
199         local reply = st.reply(stanza);
200         reply:tag("query", {xmlns="jabber:iq:privacy"});
201
202         if name == nil then
203                 if privacy_lists.lists then
204                         if origin.ActivePrivacyList then
205                                 reply:tag("active", {name=origin.activePrivacyList}):up();
206                         end
207                         if privacy_lists.default then
208                                 reply:tag("default", {name=privacy_lists.default}):up();
209                         end
210                         for name,list in pairs(privacy_lists.lists) do
211                                 reply:tag("list", {name=name}):up();
212                         end
213                 end
214         else
215                 local list = privacy_lists.lists[name];
216                 if list then
217                         reply = reply:tag("list", {name=list.name});
218                         for _,item in ipairs(list.items) do
219                                 reply:tag("item", {type=item.type, value=item.value, action=item.action, order=item.order});
220                                 if item["message"] then reply:tag("message"):up(); end
221                                 if item["iq"] then reply:tag("iq"):up(); end
222                                 if item["presence-in"] then reply:tag("presence-in"):up(); end
223                                 if item["presence-out"] then reply:tag("presence-out"):up(); end
224                                 reply:up();
225                         end
226                 else
227                         return {"cancel", "item-not-found", "Unknown list specified."};
228                 end
229         end
230         
231         origin.send(reply);
232         return true;
233 end
234
235 module:hook("iq/bare/jabber:iq:privacy:query", function(data)
236         local origin, stanza = data.origin, data.stanza;
237         
238         if stanza.attr.to == nil then -- only service requests to own bare JID
239                 local query = stanza.tags[1]; -- the query element
240                 local valid = false;
241                 local privacy_lists = datamanager.load(origin.username, origin.host, "privacy") or { lists = {} };
242
243                 if privacy_lists.lists[1] then -- Code to migrate from old privacy lists format, remove in 0.8
244                         module:log("info", "Upgrading format of stored privacy lists for %s@%s", origin.username, origin.host);
245                         local lists = privacy_lists.lists;
246                         for idx, list in ipairs(lists) do
247                                 lists[list.name] = list;
248                                 lists[idx] = nil;
249                         end
250                 end
251
252                 if stanza.attr.type == "set" then
253                         if #query.tags == 1 then --  the <query/> element MUST NOT include more than one child element
254                                 for _,tag in ipairs(query.tags) do
255                                         if tag.name == "active" or tag.name == "default" then
256                                                 if tag.attr.name == nil then -- Client declines the use of active / default list
257                                                         valid = declineList(privacy_lists, origin, stanza, tag.name);
258                                                 else -- Client requests change of active / default list
259                                                         valid = activateList(privacy_lists, origin, stanza, tag.name, tag.attr.name);
260                                                 end
261                                         elseif tag.name == "list" and tag.attr.name then -- Client adds / edits a privacy list
262                                                 if #tag.tags == 0 then -- Client removes a privacy list
263                                                         valid = deleteList(privacy_lists, origin, stanza, tag.attr.name);
264                                                 else -- Client edits a privacy list
265                                                         valid = createOrReplaceList(privacy_lists, origin, stanza, tag.attr.name, tag.tags);
266                                                 end
267                                         end
268                                 end
269                         end
270                 elseif stanza.attr.type == "get" then
271                         local name = nil;
272                         local listsToRetrieve = 0;
273                         if #query.tags >= 1 then
274                                 for _,tag in ipairs(query.tags) do
275                                         if tag.name == "list" then -- Client requests a privacy list from server
276                                                 name = tag.attr.name;
277                                                 listsToRetrieve = listsToRetrieve + 1;
278                                         end
279                                 end
280                         end
281                         if listsToRetrieve == 0 or listsToRetrieve == 1 then
282                                 valid = getList(privacy_lists, origin, stanza, name);
283                         end
284                 end
285
286                 if valid ~= true then
287                         valid = valid or { "cancel", "bad-request", "Couldn't understand request" };
288                         if valid[1] == nil then
289                                 valid[1] = "cancel";
290                         end
291                         if valid[2] == nil then
292                                 valid[2] = "bad-request";
293                         end
294                         origin.send(st.error_reply(stanza, valid[1], valid[2], valid[3]));
295                 else
296                         datamanager.store(origin.username, origin.host, "privacy", privacy_lists);
297                 end
298                 return true;
299         end
300 end);
301
302 function checkIfNeedToBeBlocked(e, session)
303         local origin, stanza = e.origin, e.stanza;
304         local privacy_lists = datamanager.load(session.username, session.host, "privacy") or {};
305         local bare_jid = session.username.."@"..session.host;
306         local to = stanza.attr.to or bare_jid;
307         local from = stanza.attr.from;
308         
309         local is_to_user = bare_jid == jid_bare(to);
310         local is_from_user = bare_jid == jid_bare(from);
311         
312         --module:log("debug", "stanza: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
313         
314         if privacy_lists.lists == nil or
315                 not (session.activePrivacyList or privacy_lists.default)
316         then
317                 return; -- Nothing to block, default is Allow all
318         end
319         if is_from_user and is_to_user then
320                 --module:log("debug", "Not blocking communications between user's resources");
321                 return; -- from one of a user's resource to another => HANDS OFF!
322         end
323         
324         local item;
325         local listname = session.activePrivacyList;
326         if listname == nil then
327                 listname = privacy_lists.default; -- no active list selected, use default list
328         end
329         local list = privacy_lists.lists[listname];
330         if not list then -- should never happen
331                 module:log("warn", "given privacy list not found. name: %s for user %s", listname, bare_jid);
332                 return;
333         end
334         for _,item in ipairs(list.items) do
335                 local apply = false;
336                 local block = false;
337                 if (
338                         (stanza.name == "message" and item.message) or
339                         (stanza.name == "iq" and item.iq) or
340                         (stanza.name == "presence" and is_to_user and item["presence-in"]) or
341                         (stanza.name == "presence" and is_from_user and item["presence-out"]) or
342                         (item.message == false and item.iq == false and item["presence-in"] == false and item["presence-out"] == false)
343                 ) then
344                         apply = true;
345                 end
346                 if apply then
347                         local evilJid = {};
348                         apply = false;
349                         if is_to_user then
350                                 --module:log("debug", "evil jid is (from): %s", from);
351                                 evilJid.node, evilJid.host, evilJid.resource = jid_split(from);
352                         else
353                                 --module:log("debug", "evil jid is (to): %s", to);
354                                 evilJid.node, evilJid.host, evilJid.resource = jid_split(to);
355                         end
356                         if      item.type == "jid" and
357                                 (evilJid.node and evilJid.host and evilJid.resource and item.value == evilJid.node.."@"..evilJid.host.."/"..evilJid.resource) or
358                                 (evilJid.node and evilJid.host and item.value == evilJid.node.."@"..evilJid.host) or
359                                 (evilJid.host and evilJid.resource and item.value == evilJid.host.."/"..evilJid.resource) or
360                                 (evilJid.host and item.value == evilJid.host) then
361                                 apply = true;
362                                 block = (item.action == "deny");
363                         elseif item.type == "group" then
364                                 local roster = load_roster(session.username, session.host);
365                                 local roster_entry = roster[jid_join(evilJid.node, evilJid.host)];
366                                 if roster_entry then
367                                         local groups = roster_entry.groups;
368                                         for group in pairs(groups) do
369                                                 if group == item.value then
370                                                         apply = true;
371                                                         block = (item.action == "deny");
372                                                         break;
373                                                 end
374                                         end
375                                 end
376                         elseif item.type == "subscription" then -- we need a valid bare evil jid
377                                 local roster = load_roster(session.username, session.host);
378                                 local roster_entry = roster[jid_join(evilJid.node, evilJid.host)];
379                                 if (not(roster_entry) and item.value == "none")
380                                    or (roster_entry and roster_entry.subscription == item.value) then
381                                         apply = true;
382                                         block = (item.action == "deny");
383                                 end
384                         elseif item.type == nil then
385                                 apply = true;
386                                 block = (item.action == "deny");
387                         end
388                 end
389                 if apply then
390                         if block then
391                                 module:log("debug", "stanza blocked: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
392                                 if stanza.name == "message" then
393                                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
394                                 elseif stanza.name == "iq" and (stanza.attr.type == "get" or stanza.attr.type == "set") then
395                                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
396                                 end
397                                 return true; -- stanza blocked !
398                         else
399                                 --module:log("debug", "stanza explicitly allowed!")
400                                 return;
401                         end
402                 end
403         end
404 end
405
406 function preCheckIncoming(e)
407         local session;
408         if e.stanza.attr.to ~= nil then
409                 local node, host, resource = jid_split(e.stanza.attr.to);
410                 if node == nil or host == nil then
411                         return;
412                 end
413                 if resource == nil then
414                         local prio = 0;
415                         local session_;
416                         if bare_sessions[node.."@"..host] ~= nil then
417                                 for resource, session_ in pairs(bare_sessions[node.."@"..host].sessions) do
418                                         if session_.priority ~= nil and session_.priority > prio then
419                                                 session = session_;
420                                                 prio = session_.priority;
421                                         end
422                                 end
423                         end
424                 else
425                         session = full_sessions[node.."@"..host.."/"..resource];
426                 end
427                 if session ~= nil then
428                         return checkIfNeedToBeBlocked(e, session);
429                 else
430                         --module:log("debug", "preCheckIncoming: Couldn't get session for jid: %s@%s/%s", tostring(node), tostring(host), tostring(resource));
431                 end
432         end
433 end
434
435 function preCheckOutgoing(e)
436         local session = e.origin;
437         if e.stanza.attr.from == nil then
438                 e.stanza.attr.from = session.username .. "@" .. session.host;
439                 if session.resource ~= nil then
440                         e.stanza.attr.from = e.stanza.attr.from .. "/" .. session.resource;
441                 end
442         end
443         return checkIfNeedToBeBlocked(e, session);
444 end
445
446 module:hook("pre-message/full", preCheckOutgoing, 500);
447 module:hook("pre-message/bare", preCheckOutgoing, 500);
448 module:hook("pre-message/host", preCheckOutgoing, 500);
449 module:hook("pre-iq/full", preCheckOutgoing, 500);
450 module:hook("pre-iq/bare", preCheckOutgoing, 500);
451 module:hook("pre-iq/host", preCheckOutgoing, 500);
452 module:hook("pre-presence/full", preCheckOutgoing, 500);
453 module:hook("pre-presence/bare", preCheckOutgoing, 500);
454 module:hook("pre-presence/host", preCheckOutgoing, 500);
455
456 module:hook("message/full", preCheckIncoming, 500);
457 module:hook("message/bare", preCheckIncoming, 500);
458 module:hook("message/host", preCheckIncoming, 500);
459 module:hook("iq/full", preCheckIncoming, 500);
460 module:hook("iq/bare", preCheckIncoming, 500);
461 module:hook("iq/host", preCheckIncoming, 500);
462 module:hook("presence/full", preCheckIncoming, 500);
463 module:hook("presence/bare", preCheckIncoming, 500);
464 module:hook("presence/host", preCheckIncoming, 500);