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