2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
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";
19 local prosody = prosody;
20 local prosody_events = prosody.events;
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;
28 local rawget = rawget;
30 local tostring, tonumber = tostring, tonumber;
32 local debug_traceback = debug.traceback;
33 local unpack, select = unpack, select;
34 pcall = function(f, ...)
35 local n = select("#", ...);
37 return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
40 local array, set = require "util.array", require "util.set";
42 local autoload_modules = {"presence", "message", "iq", "offline"};
43 local component_inheritable_modules = {"tls", "dialback", "iq"};
45 -- We need this to let modules access the real global namespace
48 module "modulemanager"
51 local api = api; -- Module API container
53 local modulemap = { ["*"] = {} };
55 local modulehelpers = setmetatable({}, { __index = _G });
57 local hooks = multitable_new();
61 -- Load modules when a host is activated
62 function load_modules_for_host(host)
63 local component = config.get(host, "core", "component_module");
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");
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
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);
76 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
78 local modules = global_modules + host_modules;
81 if modules:contains("console") then
82 log("error", "The mod_console plugin has been renamed to mod_admin_telnet. Please update your config.");
83 modules:remove("console");
84 modules:add("admin_telnet");
88 load(host, component);
90 for module in modules do
94 prosody_events.add_handler("host-activated", load_modules_for_host);
97 function load(host, module_name, config)
98 if not (host and module_name) then
99 return nil, "insufficient-parameters";
100 elseif not hosts[host] then
101 return nil, "unknown-host";
104 if not modulemap[host] then
105 modulemap[host] = {};
108 if modulemap[host][module_name] then
109 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
110 return nil, "module-already-loaded";
111 elseif modulemap["*"][module_name] then
112 return nil, "global-module-already-loaded";
116 local mod, err = pluginloader.load_code(module_name);
118 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
122 local _log = logger.init(host..":"..module_name);
123 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
125 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
126 api_instance.environment = pluginenv;
128 setfenv(mod, pluginenv);
129 hosts[host].modules = modulemap[host];
130 modulemap[host][module_name] = pluginenv;
132 local success, err = pcall(mod);
134 if module_has_method(pluginenv, "load") then
135 success, err = call_module_method(pluginenv, "load");
137 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
141 -- Use modified host, if the module set one
142 if api_instance.host == "*" and host ~= "*" then
143 modulemap[host][module_name] = nil;
144 modulemap["*"][module_name] = pluginenv;
145 api_instance:set_global();
148 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
151 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
153 else -- load failed, unloading
154 unload(api_instance.host, module_name);
159 function get_module(host, name)
160 return modulemap[host] and modulemap[host][name];
163 function is_loaded(host, name)
164 return modulemap[host] and modulemap[host][name] and true;
167 function unload(host, name, ...)
168 local mod = get_module(host, name);
169 if not mod then return nil, "module-not-loaded"; end
171 if module_has_method(mod, "unload") then
172 local ok, err = call_module_method(mod, "unload");
173 if (not ok) and err then
174 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
177 -- unhook event handlers hooked by module:hook
178 for event, handlers in pairs(hooks:get(host, name) or NULL) do
179 for handler in pairs(handlers or NULL) do
180 (hosts[host] or prosody).events.remove_handler(event, handler);
183 hooks:remove(host, name);
184 if mod.module.items then -- remove items
185 for key,t in pairs(mod.module.items) do
189 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
193 modulemap[host][name] = nil;
194 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
198 function reload(host, name, ...)
199 local mod = get_module(host, name);
200 if not mod then return nil, "module-not-loaded"; end
202 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
204 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
210 if module_has_method(mod, "save") then
211 local ok, ret, err = call_module_method(mod, "save");
215 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
216 if not config.get(host, "core", "force_module_reload") then
217 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
218 return nil, "save-state-failed";
220 log("warn", "Continuing with reload (using the force)");
225 unload(host, name, ...);
226 local ok, err = load(host, name, ...);
228 mod = get_module(host, name);
229 if module_has_method(mod, "restore") then
230 local ok, err = call_module_method(mod, "restore", saved or {})
231 if (not ok) and err then
232 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
240 function module_has_method(module, method)
241 return type(module.module[method]) == "function";
244 function call_module_method(module, method, ...)
245 if module_has_method(module, method) then
246 local f = module.module[method];
247 return pcall(f, ...);
249 return false, "no-such-method";
253 ----- API functions exposed to modules -----------
254 -- Must all be in api.*
256 -- Returns the name of the current module
257 function api:get_name()
261 -- Returns the host that the current module is serving
262 function api:get_host()
266 function api:get_host_type()
267 return hosts[self.host].type;
270 function api:set_global()
273 local _log = logger.init("mod_"..self.name);
274 self.log = function (self, ...) return _log(...); end;
278 function api:add_feature(xmlns)
279 self:add_item("feature", xmlns);
281 function api:add_identity(category, type, name)
282 self:add_item("identity", {category = category, type = type, name = name});
285 function api:fire_event(...)
286 return (hosts[self.host] or prosody).events.fire_event(...);
289 function api:hook(event, handler, priority)
290 hooks:set(self.host, self.name, event, handler, true);
291 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
294 function api:hook_stanza(xmlns, name, handler, priority)
295 if not handler and type(name) == "function" then
296 -- If only 2 options then they specified no xmlns
297 xmlns, name, handler, priority = nil, xmlns, name, handler;
298 elseif not (handler and name) then
299 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
302 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
305 function api:require(lib)
306 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
308 f, n = pluginloader.load_code(lib, lib..".lib.lua");
310 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
311 setfenv(f, self.environment);
315 function api:get_option(name, default_value)
316 local value = config.get(self.host, self.name, name);
318 value = config.get(self.host, "core", name);
320 value = default_value;
326 function api:get_option_string(name, default_value)
327 local value = self:get_option(name, default_value);
328 if type(value) == "table" then
330 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
337 return tostring(value);
340 function api:get_option_number(name, ...)
341 local value = self:get_option(name, ...);
342 if type(value) == "table" then
344 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
348 local ret = tonumber(value);
349 if value ~= nil and ret == nil then
350 self:log("error", "Config option '%s' not understood, expecting a number", name);
355 function api:get_option_boolean(name, ...)
356 local value = self:get_option(name, ...);
357 if type(value) == "table" then
359 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
366 local ret = value == true or value == "true" or value == 1 or nil;
368 ret = (value == false or value == "false" or value == 0);
376 self:log("error", "Config option '%s' not understood, expecting true/false", name);
381 function api:get_option_array(name, ...)
382 local value = self:get_option(name, ...);
388 if type(value) ~= "table" then
389 return array{ value }; -- Assume any non-list is a single-item list
392 return array():append(value); -- Clone
395 function api:get_option_set(name, ...)
396 local value = self:get_option_array(name, ...);
402 return set.new(value);
405 local t_remove = _G.table.remove;
406 local module_items = multitable_new();
407 function api:add_item(key, value)
408 self.items = self.items or {};
409 self.items[key] = self.items[key] or {};
410 t_insert(self.items[key], value);
411 self:fire_event("item-added/"..key, {source = self, item = value});
413 function api:remove_item(key, value)
414 local t = self.items and self.items[key] or NULL;
416 if t[i] == value then
417 t_remove(self.items[key], i);
418 self:fire_event("item-removed/"..key, {source = self, item = value});
424 function api:get_host_items(key)
426 for mod_name, module in pairs(modulemap[self.host]) do
427 module = module.module;
429 for _, item in ipairs(module.items[key] or NULL) do
430 t_insert(result, item);
434 for mod_name, module in pairs(modulemap["*"]) do
435 module = module.module;
437 for _, item in ipairs(module.items[key] or NULL) do
438 t_insert(result, item);