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 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";
17 local prosody = prosody;
18 local prosody_events = prosody.events;
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;
26 local rawget = rawget;
28 local tostring, tonumber = tostring, tonumber;
30 local debug_traceback = debug.traceback;
31 local unpack, select = unpack, select;
32 pcall = function(f, ...)
33 local n = select("#", ...);
35 return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
38 local array, set = require "util.array", require "util.set";
40 local autoload_modules = {"presence", "message", "iq", "offline"};
41 local component_inheritable_modules = {"tls", "dialback", "iq"};
43 -- We need this to let modules access the real global namespace
46 module "modulemanager"
49 local api = api; -- Module API container
51 local modulemap = { ["*"] = {} };
53 local modulehelpers = setmetatable({}, { __index = _G });
55 local hooks = multitable_new();
59 -- Load modules when a host is activated
60 function load_modules_for_host(host)
61 local component = config.get(host, "core", "component_module");
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");
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
71 local host_modules = set.new(host_modules_enabled) - set.new(host_modules_disabled);
72 local global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
74 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
76 local modules = global_modules + host_modules;
79 if modules:contains("console") then
80 log("error", "The mod_console plugin has been renamed to mod_admin_telnet. Please update your config.");
81 modules:remove("console");
82 modules:add("admin_telnet");
86 load(host, component);
88 for module in modules do
92 prosody_events.add_handler("host-activated", load_modules_for_host);
95 function load(host, module_name, config)
96 if not (host and module_name) then
97 return nil, "insufficient-parameters";
98 elseif not hosts[host] then
99 return nil, "unknown-host";
102 if not modulemap[host] then
103 modulemap[host] = {};
106 if modulemap[host][module_name] then
107 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
108 return nil, "module-already-loaded";
109 elseif modulemap["*"][module_name] then
110 return nil, "global-module-already-loaded";
114 local mod, err = pluginloader.load_code(module_name);
116 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
120 local _log = logger.init(host..":"..module_name);
121 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
123 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
124 api_instance.environment = pluginenv;
126 setfenv(mod, pluginenv);
127 hosts[host].modules = modulemap[host];
128 modulemap[host][module_name] = pluginenv;
130 local success, err = pcall(mod);
132 if module_has_method(pluginenv, "load") then
133 success, err = call_module_method(pluginenv, "load");
135 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
139 -- Use modified host, if the module set one
140 if api_instance.host == "*" and host ~= "*" then
141 modulemap[host][module_name] = nil;
142 modulemap["*"][module_name] = pluginenv;
143 api_instance:set_global();
146 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
149 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
151 else -- load failed, unloading
152 unload(api_instance.host, module_name);
157 function get_module(host, name)
158 return modulemap[host] and modulemap[host][name];
161 function is_loaded(host, name)
162 return modulemap[host] and modulemap[host][name] and true;
165 function unload(host, name, ...)
166 local mod = get_module(host, name);
167 if not mod then return nil, "module-not-loaded"; end
169 if module_has_method(mod, "unload") then
170 local ok, err = call_module_method(mod, "unload");
171 if (not ok) and err then
172 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
175 -- unhook event handlers hooked by module:hook
176 for event, handlers in pairs(hooks:get(host, name) or NULL) do
177 for handler in pairs(handlers or NULL) do
178 (hosts[host] or prosody).events.remove_handler(event, handler);
181 hooks:remove(host, name);
182 if mod.module.items then -- remove items
183 for key,t in pairs(mod.module.items) do
187 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
191 modulemap[host][name] = nil;
192 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
196 function reload(host, name, ...)
197 local mod = get_module(host, name);
198 if not mod then return nil, "module-not-loaded"; end
200 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
202 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
208 if module_has_method(mod, "save") then
209 local ok, ret, err = call_module_method(mod, "save");
213 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
214 if not config.get(host, "core", "force_module_reload") then
215 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
216 return nil, "save-state-failed";
218 log("warn", "Continuing with reload (using the force)");
223 unload(host, name, ...);
224 local ok, err = load(host, name, ...);
226 mod = get_module(host, name);
227 if module_has_method(mod, "restore") then
228 local ok, err = call_module_method(mod, "restore", saved or {})
229 if (not ok) and err then
230 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
238 function module_has_method(module, method)
239 return type(module.module[method]) == "function";
242 function call_module_method(module, method, ...)
243 if module_has_method(module, method) then
244 local f = module.module[method];
245 return pcall(f, ...);
247 return false, "no-such-method";
251 ----- API functions exposed to modules -----------
252 -- Must all be in api.*
254 -- Returns the name of the current module
255 function api:get_name()
259 -- Returns the host that the current module is serving
260 function api:get_host()
264 function api:get_host_type()
265 return hosts[self.host].type;
268 function api:set_global()
271 local _log = logger.init("mod_"..self.name);
272 self.log = function (self, ...) return _log(...); end;
276 function api:add_feature(xmlns)
277 self:add_item("feature", xmlns);
279 function api:add_identity(category, type, name)
280 self:add_item("identity", {category = category, type = type, name = name});
283 function api:fire_event(...)
284 return (hosts[self.host] or prosody).events.fire_event(...);
287 function api:hook(event, handler, priority)
288 hooks:set(self.host, self.name, event, handler, true);
289 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
292 function api:hook_stanza(xmlns, name, handler, priority)
293 if not handler and type(name) == "function" then
294 -- If only 2 options then they specified no xmlns
295 xmlns, name, handler, priority = nil, xmlns, name, handler;
296 elseif not (handler and name) then
297 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
300 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
303 function api:require(lib)
304 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
306 f, n = pluginloader.load_code(lib, lib..".lib.lua");
308 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
309 setfenv(f, self.environment);
313 function api:get_option(name, default_value)
314 local value = config.get(self.host, self.name, name);
316 value = config.get(self.host, "core", name);
318 value = default_value;
324 function api:get_option_string(name, default_value)
325 local value = self:get_option(name, default_value);
326 if type(value) == "table" then
328 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
335 return tostring(value);
338 function api:get_option_number(name, ...)
339 local value = self:get_option(name, ...);
340 if type(value) == "table" then
342 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
346 local ret = tonumber(value);
347 if value ~= nil and ret == nil then
348 self:log("error", "Config option '%s' not understood, expecting a number", name);
353 function api:get_option_boolean(name, ...)
354 local value = self:get_option(name, ...);
355 if type(value) == "table" then
357 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
364 local ret = value == true or value == "true" or value == 1 or nil;
366 ret = (value == false or value == "false" or value == 0);
374 self:log("error", "Config option '%s' not understood, expecting true/false", name);
379 function api:get_option_array(name, ...)
380 local value = self:get_option(name, ...);
386 if type(value) ~= "table" then
387 return array{ value }; -- Assume any non-list is a single-item list
390 return array():append(value); -- Clone
393 function api:get_option_set(name, ...)
394 local value = self:get_option_array(name, ...);
400 return set.new(value);
403 local t_remove = _G.table.remove;
404 local module_items = multitable_new();
405 function api:add_item(key, value)
406 self.items = self.items or {};
407 self.items[key] = self.items[key] or {};
408 t_insert(self.items[key], value);
409 self:fire_event("item-added/"..key, {source = self, item = value});
411 function api:remove_item(key, value)
412 local t = self.items and self.items[key] or NULL;
414 if t[i] == value then
415 t_remove(self.items[key], i);
416 self:fire_event("item-removed/"..key, {source = self, item = value});
422 function api:get_host_items(key)
424 for mod_name, module in pairs(modulemap[self.host]) do
425 module = module.module;
427 for _, item in ipairs(module.items[key] or NULL) do
428 t_insert(result, item);
432 for mod_name, module in pairs(modulemap["*"]) do
433 module = module.module;
435 for _, item in ipairs(module.items[key] or NULL) do
436 t_insert(result, item);