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