mod_iq: Don't hook 'iq/full' on components.
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
10
11 local logger = require "util.logger";
12 local log = logger.init("modulemanager");
13 local config = require "core.configmanager";
14 local multitable_new = require "util.multitable".new;
15 local st = require "util.stanza";
16 local pluginloader = require "util.pluginloader";
17
18 local hosts = hosts;
19 local prosody = prosody;
20 local prosody_events = prosody.events;
21
22 local loadfile, pcall, xpcall = loadfile, pcall, xpcall;
23 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
24 local pairs, ipairs = pairs, ipairs;
25 local t_insert, t_concat = table.insert, table.concat;
26 local type = type;
27 local next = next;
28 local rawget = rawget;
29 local error = error;
30 local tostring, tonumber = tostring, tonumber;
31
32 local debug_traceback = debug.traceback;
33 local unpack, select = unpack, select;
34 pcall = function(f, ...)
35         local n = select("#", ...);
36         local params = {...};
37         return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
38 end
39
40 local array, set = require "util.array", require "util.set";
41
42 local autoload_modules = {"presence", "message", "iq"};
43 local component_inheritable_modules = {"tls", "dialback", "iq"};
44
45 -- We need this to let modules access the real global namespace
46 local _G = _G;
47
48 module "modulemanager"
49
50 api = {};
51 local api = api; -- Module API container
52
53 local modulemap = { ["*"] = {} };
54
55 local modulehelpers = setmetatable({}, { __index = _G });
56
57 local hooks = multitable_new();
58
59 local NULL = {};
60
61 -- Load modules when a host is activated
62 function load_modules_for_host(host)
63         local component = config.get(host, "core", "component_module");
64         
65         local global_modules_enabled = config.get("*", "core", "modules_enabled");
66         local global_modules_disabled = config.get("*", "core", "modules_disabled");
67         local host_modules_enabled = config.get(host, "core", "modules_enabled");
68         local host_modules_disabled = config.get(host, "core", "modules_disabled");
69         
70         if host_modules_enabled == global_modules_enabled then host_modules_enabled = nil; end
71         if host_modules_disabled == global_modules_disabled then host_modules_disabled = nil; end
72         
73         local host_modules = set.new(host_modules_enabled) - set.new(host_modules_disabled);
74         local global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
75         if component then
76                 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
77         end
78         local modules = global_modules + host_modules;
79         
80         if component then
81                 load(host, component);
82         end
83         for module in modules do
84                 load(host, module);
85         end
86 end
87 prosody_events.add_handler("host-activated", load_modules_for_host);
88 --
89
90 function load(host, module_name, config)
91         if not (host and module_name) then
92                 return nil, "insufficient-parameters";
93         elseif not hosts[host] then
94                 return nil, "unknown-host";
95         end
96         
97         if not modulemap[host] then
98                 modulemap[host] = {};
99         end
100         
101         if modulemap[host][module_name] then
102                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
103                 return nil, "module-already-loaded";
104         elseif modulemap["*"][module_name] then
105                 return nil, "global-module-already-loaded";
106         end
107         
108
109         local mod, err = pluginloader.load_code(module_name);
110         if not mod then
111                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
112                 return nil, err;
113         end
114
115         local _log = logger.init(host..":"..module_name);
116         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
117
118         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
119         api_instance.environment = pluginenv;
120         
121         setfenv(mod, pluginenv);
122         hosts[host].modules = modulemap[host];
123         modulemap[host][module_name] = pluginenv;
124         
125         local success, err = pcall(mod);
126         if success then
127                 if module_has_method(pluginenv, "load") then
128                         success, err = call_module_method(pluginenv, "load");
129                         if not success then
130                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
131                         end
132                 end
133
134                 -- Use modified host, if the module set one
135                 if api_instance.host == "*" and host ~= "*" then
136                         modulemap[host][module_name] = nil;
137                         modulemap["*"][module_name] = pluginenv;
138                         api_instance:set_global();
139                 end
140         else
141                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
142         end
143         if success then
144                 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
145                 return true;
146         else -- load failed, unloading
147                 unload(api_instance.host, module_name);
148                 return nil, err;
149         end
150 end
151
152 function get_module(host, name)
153         return modulemap[host] and modulemap[host][name];
154 end
155
156 function is_loaded(host, name)
157         return modulemap[host] and modulemap[host][name] and true;
158 end
159
160 function unload(host, name, ...)
161         local mod = get_module(host, name);
162         if not mod then return nil, "module-not-loaded"; end
163         
164         if module_has_method(mod, "unload") then
165                 local ok, err = call_module_method(mod, "unload");
166                 if (not ok) and err then
167                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
168                 end
169         end
170         -- unhook event handlers hooked by module:hook
171         for event, handlers in pairs(hooks:get(host, name) or NULL) do
172                 for handler in pairs(handlers or NULL) do
173                         (hosts[host] or prosody).events.remove_handler(event, handler);
174                 end
175         end
176         hooks:remove(host, name);
177         if mod.module.items then -- remove items
178                 for key,t in pairs(mod.module.items) do
179                         for i = #t,1,-1 do
180                                 local value = t[i];
181                                 t[i] = nil;
182                                 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
183                         end
184                 end
185         end
186         modulemap[host][name] = nil;
187         (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
188         return true;
189 end
190
191 function reload(host, name, ...)
192         local mod = get_module(host, name);
193         if not mod then return nil, "module-not-loaded"; end
194
195         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
196         if not _mod then
197                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
198                 return nil, err;
199         end
200
201         local saved;
202
203         if module_has_method(mod, "save") then
204                 local ok, ret, err = call_module_method(mod, "save");
205                 if ok then
206                         saved = ret;
207                 else
208                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
209                         if not config.get(host, "core", "force_module_reload") then
210                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
211                                 return nil, "save-state-failed";
212                         else
213                                 log("warn", "Continuing with reload (using the force)");
214                         end
215                 end
216         end
217
218         unload(host, name, ...);
219         local ok, err = load(host, name, ...);
220         if ok then
221                 mod = get_module(host, name);
222                 if module_has_method(mod, "restore") then
223                         local ok, err = call_module_method(mod, "restore", saved or {})
224                         if (not ok) and err then
225                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
226                         end
227                 end
228                 return true;
229         end
230         return ok, err;
231 end
232
233 function module_has_method(module, method)
234         return type(module.module[method]) == "function";
235 end
236
237 function call_module_method(module, method, ...)
238         if module_has_method(module, method) then
239                 local f = module.module[method];
240                 return pcall(f, ...);
241         else
242                 return false, "no-such-method";
243         end
244 end
245
246 ----- API functions exposed to modules -----------
247 -- Must all be in api.*
248
249 -- Returns the name of the current module
250 function api:get_name()
251         return self.name;
252 end
253
254 -- Returns the host that the current module is serving
255 function api:get_host()
256         return self.host;
257 end
258
259 function api:get_host_type()
260         return hosts[self.host].type;
261 end
262
263 function api:set_global()
264         self.host = "*";
265         -- Update the logger
266         local _log = logger.init("mod_"..self.name);
267         self.log = function (self, ...) return _log(...); end;
268         self._log = _log;
269 end
270
271 function api:add_feature(xmlns)
272         self:add_item("feature", xmlns);
273 end
274 function api:add_identity(category, type, name)
275         self:add_item("identity", {category = category, type = type, name = name});
276 end
277
278 function api:fire_event(...)
279         return (hosts[self.host] or prosody).events.fire_event(...);
280 end
281
282 function api:hook(event, handler, priority)
283         hooks:set(self.host, self.name, event, handler, true);
284         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
285 end
286
287 function api:hook_stanza(xmlns, name, handler, priority)
288         if not handler and type(name) == "function" then
289                 -- If only 2 options then they specified no xmlns
290                 xmlns, name, handler, priority = nil, xmlns, name, handler;
291         elseif not (handler and name) then
292                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
293                 return;
294         end
295         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
296 end
297
298 function api:require(lib)
299         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
300         if not f then
301                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
302         end
303         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
304         setfenv(f, self.environment);
305         return f();
306 end
307
308 function api:get_option(name, default_value)
309         local value = config.get(self.host, self.name, name);
310         if value == nil then
311                 value = config.get(self.host, "core", name);
312                 if value == nil then
313                         value = default_value;
314                 end
315         end
316         return value;
317 end
318
319 function api:get_option_string(name, default_value)
320         local value = self:get_option(name, default_value);
321         if type(value) == "table" then
322                 if #value > 1 then
323                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
324                 end
325                 value = value[1];
326         end
327         if value == nil then
328                 return nil;
329         end
330         return tostring(value);
331 end
332
333 function api:get_option_number(name, ...)
334         local value = self:get_option(name, ...);
335         if type(value) == "table" then
336                 if #value > 1 then
337                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
338                 end
339                 value = value[1];
340         end
341         local ret = tonumber(value);
342         if value ~= nil and ret == nil then
343                 self:log("error", "Config option '%s' not understood, expecting a number", name);
344         end
345         return ret;
346 end
347
348 function api:get_option_boolean(name, ...)
349         local value = self:get_option(name, ...);
350         if type(value) == "table" then
351                 if #value > 1 then
352                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
353                 end
354                 value = value[1];
355         end
356         if value == nil then
357                 return nil;
358         end
359         local ret = value == true or value == "true" or value == 1 or nil;
360         if ret == nil then
361                 ret = (value == false or value == "false" or value == 0);
362                 if ret then
363                         ret = false;
364                 else
365                         ret = nil;
366                 end
367         end
368         if ret == nil then
369                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
370         end
371         return ret;
372 end
373
374 function api:get_option_array(name, ...)
375         local value = self:get_option(name, ...);
376
377         if value == nil then
378                 return nil;
379         end
380         
381         if type(value) ~= "table" then
382                 return array{ value }; -- Assume any non-list is a single-item list
383         end
384         
385         return array():append(value); -- Clone
386 end
387
388 function api:get_option_set(name, ...)
389         local value = self:get_option_array(name, ...);
390         
391         if value == nil then
392                 return nil;
393         end
394         
395         return set.new(value);
396 end
397
398 local t_remove = _G.table.remove;
399 local module_items = multitable_new();
400 function api:add_item(key, value)
401         self.items = self.items or {};
402         self.items[key] = self.items[key] or {};
403         t_insert(self.items[key], value);
404         self:fire_event("item-added/"..key, {source = self, item = value});
405 end
406 function api:remove_item(key, value)
407         local t = self.items and self.items[key] or NULL;
408         for i = #t,1,-1 do
409                 if t[i] == value then
410                         t_remove(self.items[key], i);
411                         self:fire_event("item-removed/"..key, {source = self, item = value});
412                         return value;
413                 end
414         end
415 end
416
417 function api:get_host_items(key)
418         local result = {};
419         for mod_name, module in pairs(modulemap[self.host]) do
420                 module = module.module;
421                 if module.items then
422                         for _, item in ipairs(module.items[key] or NULL) do
423                                 t_insert(result, item);
424                         end
425                 end
426         end
427         for mod_name, module in pairs(modulemap["*"]) do
428                 module = module.module;
429                 if module.items then
430                         for _, item in ipairs(module.items[key] or NULL) do
431                                 t_insert(result, item);
432                         end
433                 end
434         end
435         return result;
436 end
437
438 return _M;