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 global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
73 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
75 local modules = (global_modules + set.new(host_modules_enabled)) - set.new(host_modules_disabled);
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");
85 load(host, component);
87 for module in modules do
91 prosody_events.add_handler("host-activated", load_modules_for_host);
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";
101 if not modulemap[host] then
102 modulemap[host] = {};
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";
113 local mod, err = pluginloader.load_code(module_name);
115 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
119 local _log = logger.init(host..":"..module_name);
120 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
122 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
123 api_instance.environment = pluginenv;
125 setfenv(mod, pluginenv);
126 hosts[host].modules = modulemap[host];
127 modulemap[host][module_name] = pluginenv;
129 local success, err = pcall(mod);
131 if module_has_method(pluginenv, "load") then
132 success, err = call_module_method(pluginenv, "load");
134 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
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();
145 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
148 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
150 else -- load failed, unloading
151 unload(api_instance.host, module_name);
156 function get_module(host, name)
157 return modulemap[host] and modulemap[host][name];
160 function is_loaded(host, name)
161 return modulemap[host] and modulemap[host][name] and true;
164 function unload(host, name, ...)
165 local mod = get_module(host, name);
166 if not mod then return nil, "module-not-loaded"; end
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);
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);
180 hooks:remove(host, name);
181 if mod.module.items then -- remove items
182 for key,t in pairs(mod.module.items) do
186 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
190 modulemap[host][name] = nil;
191 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
195 function reload(host, name, ...)
196 local mod = get_module(host, name);
197 if not mod then return nil, "module-not-loaded"; end
199 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
201 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
207 if module_has_method(mod, "save") then
208 local ok, ret, err = call_module_method(mod, "save");
212 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
213 if not config.get(host, "core", "force_module_reload") then
214 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
215 return nil, "save-state-failed";
217 log("warn", "Continuing with reload (using the force)");
222 unload(host, name, ...);
223 local ok, err = load(host, name, ...);
225 mod = get_module(host, name);
226 if module_has_method(mod, "restore") then
227 local ok, err = call_module_method(mod, "restore", saved or {})
228 if (not ok) and err then
229 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
237 function module_has_method(module, method)
238 return type(module.module[method]) == "function";
241 function call_module_method(module, method, ...)
242 if module_has_method(module, method) then
243 local f = module.module[method];
244 return pcall(f, ...);
246 return false, "no-such-method";
250 ----- API functions exposed to modules -----------
251 -- Must all be in api.*
253 -- Returns the name of the current module
254 function api:get_name()
258 -- Returns the host that the current module is serving
259 function api:get_host()
263 function api:get_host_type()
264 return hosts[self.host].type;
267 function api:set_global()
270 local _log = logger.init("mod_"..self.name);
271 self.log = function (self, ...) return _log(...); end;
275 function api:add_feature(xmlns)
276 self:add_item("feature", xmlns);
278 function api:add_identity(category, type, name)
279 self:add_item("identity", {category = category, type = type, name = name});
282 function api:fire_event(...)
283 return (hosts[self.host] or prosody).events.fire_event(...);
286 function api:hook(event, handler, priority)
287 hooks:set(self.host, self.name, event, handler, true);
288 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
291 function api:hook_stanza(xmlns, name, handler, priority)
292 if not handler and type(name) == "function" then
293 -- If only 2 options then they specified no xmlns
294 xmlns, name, handler, priority = nil, xmlns, name, handler;
295 elseif not (handler and name) then
296 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
299 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
302 function api:require(lib)
303 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
305 f, n = pluginloader.load_code(lib, lib..".lib.lua");
307 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
308 setfenv(f, self.environment);
312 function api:get_option(name, default_value)
313 local value = config.get(self.host, self.name, name);
315 value = config.get(self.host, "core", name);
317 value = default_value;
323 function api:get_option_string(name, default_value)
324 local value = self:get_option(name, default_value);
325 if type(value) == "table" then
327 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
334 return tostring(value);
337 function api:get_option_number(name, ...)
338 local value = self:get_option(name, ...);
339 if type(value) == "table" then
341 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
345 local ret = tonumber(value);
346 if value ~= nil and ret == nil then
347 self:log("error", "Config option '%s' not understood, expecting a number", name);
352 function api:get_option_boolean(name, ...)
353 local value = self:get_option(name, ...);
354 if type(value) == "table" then
356 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
363 local ret = value == true or value == "true" or value == 1 or nil;
365 ret = (value == false or value == "false" or value == 0);
373 self:log("error", "Config option '%s' not understood, expecting true/false", name);
378 function api:get_option_array(name, ...)
379 local value = self:get_option(name, ...);
385 if type(value) ~= "table" then
386 return array{ value }; -- Assume any non-list is a single-item list
389 return array():append(value); -- Clone
392 function api:get_option_set(name, ...)
393 local value = self:get_option_array(name, ...);
399 return set.new(value);
402 local t_remove = _G.table.remove;
403 local module_items = multitable_new();
404 function api:add_item(key, value)
405 self.items = self.items or {};
406 self.items[key] = self.items[key] or {};
407 t_insert(self.items[key], value);
408 self:fire_event("item-added/"..key, {source = self, item = value});
410 function api:remove_item(key, value)
411 local t = self.items and self.items[key] or NULL;
413 if t[i] == value then
414 t_remove(self.items[key], i);
415 self:fire_event("item-removed/"..key, {source = self, item = value});
421 function api:get_host_items(key)
423 for mod_name, module in pairs(modulemap[self.host]) do
424 module = module.module;
426 for _, item in ipairs(module.items[key] or NULL) do
427 t_insert(result, item);
431 for mod_name, module in pairs(modulemap["*"]) do
432 module = module.module;
434 for _, item in ipairs(module.items[key] or NULL) do
435 t_insert(result, item);