mod_blocklist: Expand comments on caching of blocklists
[prosody.git] / plugins / mod_blocklist.lua
1 -- Prosody IM
2 -- Copyright (C) 2009-2010 Matthew Wild
3 -- Copyright (C) 2009-2010 Waqas Hussain
4 -- Copyright (C) 2014 Kim Alvefur
5 --
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9 -- This module implements XEP-0191: Blocking Command
10 --
11
12 local user_exists = require"core.usermanager".user_exists;
13 local is_contact_subscribed = require"core.rostermanager".is_contact_subscribed;
14 local st = require"util.stanza";
15 local st_error_reply = st.error_reply;
16 local jid_prep = require"util.jid".prep;
17 local jid_split = require"util.jid".split;
18
19 local storage = module:open_store();
20 local sessions = prosody.hosts[module.host].sessions;
21
22 -- First level cache of blocklists by username.
23 -- Weak table so may randomly expire at any time.
24 local cache = setmetatable({}, { __mode = "v" });
25
26 -- Second level of caching, keeps a fixed number of items, also anchors
27 -- items in the above cache.
28 --
29 -- The size of this affects how often we will need to load a blocklist from
30 -- disk, which we want to avoid during routing. On the other hand, we don't
31 -- want to use too much memory either, so this can be tuned by advanced
32 -- users. TODO use science to figure out a better default, 64 is just a guess.
33 local cache_size = module:get_option_number("blocklist_cache_size", 64);
34 local cache2 = require"util.cache".new(cache_size);
35
36 local null_blocklist = {};
37
38 module:add_feature("urn:xmpp:blocking");
39
40 local function set_blocklist(username, blocklist)
41         local ok, err = storage:set(username, blocklist);
42         if not ok then
43                 return ok, err;
44         end
45         -- Successful save, update the cache
46         cache2:set(username, blocklist);
47         cache[username] = blocklist;
48         return true;
49 end
50
51 -- Migrates from the old mod_privacy storage
52 local function migrate_privacy_list(username)
53         local migrated_data = { [false] = "not empty" };
54         local legacy_data = module:open_store("privacy"):get(username);
55         if legacy_data and legacy_data.lists and legacy_data.default then
56                 legacy_data = legacy_data.lists[legacy_data.default];
57                 legacy_data = legacy_data and legacy_data.items;
58         else
59                 return migrated_data;
60         end
61         if legacy_data then
62                 module:log("info", "Migrating blocklist from mod_privacy storage for user '%s'", username);
63                 local item, jid;
64                 for i = 1, #legacy_data do
65                         item = legacy_data[i];
66                         if item.type == "jid" and item.action == "deny" then
67                                 jid = jid_prep(item.value);
68                                 if not jid then
69                                         module:log("warn", "Invalid JID in privacy store for user '%s' not migrated: %s", username, tostring(item.value));
70                                 else
71                                         migrated_data[jid] = true;
72                                 end
73                         end
74                 end
75         end
76         set_blocklist(username, migrated_data);
77         return migrated_data;
78 end
79
80 local function get_blocklist(username)
81         local blocklist = cache[username];
82         if not blocklist then
83                 blocklist = cache2:get(username);
84         end
85         if not blocklist then
86                 if not user_exists(username, module.host) then
87                         return null_blocklist;
88                 end
89                 blocklist = storage:get(username);
90                 if not blocklist then
91                         blocklist = migrate_privacy_list(username);
92                 end
93                 cache2:set(username, blocklist);
94         end
95         cache[username] = blocklist;
96         return blocklist;
97 end
98
99 module:hook("iq-get/self/urn:xmpp:blocking:blocklist", function (event)
100         local origin, stanza = event.origin, event.stanza;
101         local username = origin.username;
102         local reply = st.reply(stanza):tag("blocklist", { xmlns = "urn:xmpp:blocking" });
103         local blocklist = get_blocklist(username);
104         for jid in pairs(blocklist) do
105                 if jid then
106                         reply:tag("item", { jid = jid }):up();
107                 end
108         end
109         origin.interested_blocklist = true; -- Gets notified about changes
110         origin.send(reply);
111         return true;
112 end);
113
114 -- Add or remove some jid(s) from the blocklist
115 -- We want this to be atomic and not do a partial update
116 local function edit_blocklist(event)
117         local origin, stanza = event.origin, event.stanza;
118         local username = origin.username;
119         local action = stanza.tags[1];
120         local new = {};
121
122         for item in action:childtags("item") do
123                 local jid = jid_prep(item.attr.jid);
124                 if not jid then
125                         origin.send(st_error_reply(stanza, "modify", "jid-malformed"));
126                         return true;
127                 end
128                 item.attr.jid = jid; -- echo back prepped
129                 new[jid] = is_contact_subscribed(username, module.host, jid) or false;
130         end
131
132         local is_blocking = action.name == "block" or nil; -- nil if unblocking
133
134         if is_blocking and not next(new) then
135                 -- <block/> element does not contain at least one <item/> child element
136                 origin.send(st_error_reply(stanza, "modify", "bad-request"));
137                 return true;
138         end
139
140         local blocklist = get_blocklist(username);
141
142         local new_blocklist = {};
143
144         if is_blocking or next(new) then
145                 for jid in pairs(blocklist) do
146                         new_blocklist[jid] = true;
147                 end
148                 for jid in pairs(new) do
149                         new_blocklist[jid] = is_blocking;
150                 end
151                 -- else empty the blocklist
152         end
153         new_blocklist[false] = "not empty"; -- In order to avoid doing the migration thing twice
154
155         local ok, err = set_blocklist(username, new_blocklist);
156         if ok then
157                 origin.send(st.reply(stanza));
158         else
159                 origin.send(st_error_reply(stanza, "wait", "internal-server-error", err));
160                 return true;
161         end
162
163         if is_blocking then
164                 for jid, in_roster in pairs(new) do
165                         if not blocklist[jid] and in_roster and sessions[username] then
166                                 for _, session in pairs(sessions[username].sessions) do
167                                         if session.presence then
168                                                 module:send(st.presence({ type = "unavailable", to = jid, from = session.full_jid }));
169                                         end
170                                 end
171                         end
172                 end
173         end
174         if sessions[username] then
175                 local blocklist_push = st.iq({ type = "set", id = "blocklist-push" })
176                         :add_child(action); -- I am lazy
177
178                 for _, session in pairs(sessions[username].sessions) do
179                         if session.interested_blocklist then
180                                 blocklist_push.attr.to = session.full_jid;
181                                 session.send(blocklist_push);
182                         end
183                 end
184         end
185
186         return true;
187 end
188
189 module:hook("iq-set/self/urn:xmpp:blocking:block", edit_blocklist);
190 module:hook("iq-set/self/urn:xmpp:blocking:unblock", edit_blocklist);
191
192 -- Cache invalidation, solved!
193 module:hook_global("user-deleted", function (event)
194         if event.host == module.host then
195                 cache:set(event.username, nil);
196                 cache[event.username] = nil;
197         end
198 end);
199
200 -- Buggy clients
201 module:hook("iq-error/self/blocklist-push", function (event)
202         local _, condition, text = event.stanza:get_error();
203         (event.origin.log or module._log)("warn", "Client returned an error in response to notification from mod_%s: %s%s%s", module.name, condition, text and ": " or "", text or "");
204         return true;
205 end);
206
207 local function is_blocked(user, jid)
208         local blocklist = cache[user] or get_blocklist(user);
209         if blocklist[jid] then return true; end
210         local node, host = jid_split(jid);
211         return blocklist[host] or node and blocklist[node..'@'..host];
212 end
213
214 -- Event handlers for bouncing or dropping stanzas
215 local function drop_stanza(event)
216         local stanza = event.stanza;
217         local attr = stanza.attr;
218         local to, from = attr.to, attr.from;
219         to = to and jid_split(to);
220         if to and from then
221                 return is_blocked(to, from);
222         end
223 end
224
225 local function bounce_stanza(event)
226         local origin, stanza = event.origin, event.stanza;
227         if drop_stanza(event) then
228                 origin.send(st_error_reply(stanza, "cancel", "service-unavailable"));
229                 return true;
230         end
231 end
232
233 local function bounce_iq(event)
234         local type = event.stanza.attr.type;
235         if type == "set" or type == "get" then
236                 return bounce_stanza(event);
237         end
238         return drop_stanza(event); -- result or error
239 end
240
241 local function bounce_message(event)
242         local type = event.stanza.attr.type;
243         if type == "chat" or not type or type == "normal" then
244                 return bounce_stanza(event);
245         end
246         return drop_stanza(event); -- drop headlines, groupchats etc
247 end
248
249 local function drop_outgoing(event)
250         local origin, stanza = event.origin, event.stanza;
251         local username = origin.username or jid_split(stanza.attr.from);
252         if not username then return end
253         local to = stanza.attr.to;
254         if to then return is_blocked(username, to); end
255         -- nil 'to' means a self event, don't bock those
256 end
257
258 local function bounce_outgoing(event)
259         local origin, stanza = event.origin, event.stanza;
260         local type = stanza.attr.type;
261         if type == "error" or stanza.name == "iq" and type == "result" then
262                 return drop_outgoing(event);
263         end
264         if drop_outgoing(event) then
265                 origin.send(st_error_reply(stanza, "cancel", "not-acceptable", "You have blocked this JID")
266                         :tag("blocked", { xmlns = "urn:xmpp:blocking:errors" }));
267                 return true;
268         end
269 end
270
271 -- Hook all the events!
272 local prio_in, prio_out = 100, 100;
273 module:hook("presence/bare", drop_stanza, prio_in);
274 module:hook("presence/full", drop_stanza, prio_in);
275
276 module:hook("message/bare", bounce_message, prio_in);
277 module:hook("message/full", bounce_message, prio_in);
278
279 module:hook("iq/bare", bounce_iq, prio_in);
280 module:hook("iq/full", bounce_iq, prio_in);
281
282 module:hook("pre-message/bare", bounce_outgoing, prio_out);
283 module:hook("pre-message/full", bounce_outgoing, prio_out);
284 module:hook("pre-message/host", bounce_outgoing, prio_out);
285
286 -- Note: MUST bounce these, but we don't because this would produce
287 -- lots of error replies due to server-generated presence.
288 -- FIXME some day, likely needing changes to mod_presence
289 module:hook("pre-presence/bare", drop_outgoing, prio_out);
290 module:hook("pre-presence/full", drop_outgoing, prio_out);
291 module:hook("pre-presence/host", drop_outgoing, prio_out);
292
293 module:hook("pre-iq/bare", bounce_outgoing, prio_out);
294 module:hook("pre-iq/full", bounce_outgoing, prio_out);
295 module:hook("pre-iq/host", bounce_outgoing, prio_out);
296