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"};
43 local component_inheritable_modules = {"tls", "dialback"};
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 load(host, component);
83 for module in modules do
87 prosody_events.add_handler("host-activated", load_modules_for_host);
88 prosody_events.add_handler("component-activated", load_modules_for_host);
91 function load(host, module_name, config)
92 if not (host and module_name) then
93 return nil, "insufficient-parameters";
94 elseif not hosts[host] then
95 return nil, "unknown-host";
98 if not modulemap[host] then
102 if modulemap[host][module_name] then
103 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
104 return nil, "module-already-loaded";
105 elseif modulemap["*"][module_name] then
106 return nil, "global-module-already-loaded";
110 local mod, err = pluginloader.load_code(module_name);
112 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
116 local _log = logger.init(host..":"..module_name);
117 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
119 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
120 api_instance.environment = pluginenv;
122 setfenv(mod, pluginenv);
123 hosts[host].modules = modulemap[host];
124 modulemap[host][module_name] = pluginenv;
126 local success, err = pcall(mod);
128 if module_has_method(pluginenv, "load") then
129 success, err = call_module_method(pluginenv, "load");
131 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
135 -- Use modified host, if the module set one
136 if api_instance.host == "*" and host ~= "*" then
137 modulemap[host][module_name] = nil;
138 modulemap["*"][module_name] = pluginenv;
139 api_instance:set_global();
142 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
145 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
147 else -- load failed, unloading
148 unload(api_instance.host, module_name);
153 function get_module(host, name)
154 return modulemap[host] and modulemap[host][name];
157 function is_loaded(host, name)
158 return modulemap[host] and modulemap[host][name] and true;
161 function unload(host, name, ...)
162 local mod = get_module(host, name);
163 if not mod then return nil, "module-not-loaded"; end
165 if module_has_method(mod, "unload") then
166 local ok, err = call_module_method(mod, "unload");
167 if (not ok) and err then
168 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
171 -- unhook event handlers hooked by module:hook
172 for event, handlers in pairs(hooks:get(host, name) or NULL) do
173 for handler in pairs(handlers or NULL) do
174 (hosts[host] or prosody).events.remove_handler(event, handler);
177 hooks:remove(host, name);
178 if mod.module.items then -- remove items
179 for key,t in pairs(mod.module.items) do
183 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
187 modulemap[host][name] = nil;
188 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
192 function reload(host, name, ...)
193 local mod = get_module(host, name);
194 if not mod then return nil, "module-not-loaded"; end
196 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
198 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
204 if module_has_method(mod, "save") then
205 local ok, ret, err = call_module_method(mod, "save");
209 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
210 if not config.get(host, "core", "force_module_reload") then
211 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
212 return nil, "save-state-failed";
214 log("warn", "Continuing with reload (using the force)");
219 unload(host, name, ...);
220 local ok, err = load(host, name, ...);
222 mod = get_module(host, name);
223 if module_has_method(mod, "restore") then
224 local ok, err = call_module_method(mod, "restore", saved or {})
225 if (not ok) and err then
226 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
234 function module_has_method(module, method)
235 return type(module.module[method]) == "function";
238 function call_module_method(module, method, ...)
239 if module_has_method(module, method) then
240 local f = module.module[method];
241 return pcall(f, ...);
243 return false, "no-such-method";
247 ----- API functions exposed to modules -----------
248 -- Must all be in api.*
250 -- Returns the name of the current module
251 function api:get_name()
255 -- Returns the host that the current module is serving
256 function api:get_host()
260 function api:get_host_type()
261 return hosts[self.host].type;
264 function api:set_global()
267 local _log = logger.init("mod_"..self.name);
268 self.log = function (self, ...) return _log(...); end;
272 function api:add_feature(xmlns)
273 self:add_item("feature", xmlns);
275 function api:add_identity(category, type, name)
276 self:add_item("identity", {category = category, type = type, name = name});
279 function api:fire_event(...)
280 return (hosts[self.host] or prosody).events.fire_event(...);
283 function api:hook(event, handler, priority)
284 hooks:set(self.host, self.name, event, handler, true);
285 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
288 function api:hook_stanza(xmlns, name, handler, priority)
289 if not handler and type(name) == "function" then
290 -- If only 2 options then they specified no xmlns
291 xmlns, name, handler, priority = nil, xmlns, name, handler;
292 elseif not (handler and name) then
293 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
296 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
299 function api:require(lib)
300 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
302 f, n = pluginloader.load_code(lib, lib..".lib.lua");
304 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
305 setfenv(f, self.environment);
309 function api:get_option(name, default_value)
310 local value = config.get(self.host, self.name, name);
312 value = config.get(self.host, "core", name);
314 value = default_value;
320 function api:get_option_string(name, default_value)
321 local value = self:get_option(name, default_value);
322 if type(value) == "table" then
324 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
331 return tostring(value);
334 function api:get_option_number(name, ...)
335 local value = self:get_option(name, ...);
336 if type(value) == "table" then
338 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
342 local ret = tonumber(value);
343 if value ~= nil and ret == nil then
344 self:log("error", "Config option '%s' not understood, expecting a number", name);
349 function api:get_option_boolean(name, ...)
350 local value = self:get_option(name, ...);
351 if type(value) == "table" then
353 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
360 local ret = value == true or value == "true" or value == 1 or nil;
362 ret = (value == false or value == "false" or value == 0);
370 self:log("error", "Config option '%s' not understood, expecting true/false", name);
375 function api:get_option_array(name, ...)
376 local value = self:get_option(name, ...);
382 if type(value) ~= "table" then
383 return array{ value }; -- Assume any non-list is a single-item list
386 return array():append(value); -- Clone
389 function api:get_option_set(name, ...)
390 local value = self:get_option_array(name, ...);
396 return set.new(value);
399 local t_remove = _G.table.remove;
400 local module_items = multitable_new();
401 function api:add_item(key, value)
402 self.items = self.items or {};
403 self.items[key] = self.items[key] or {};
404 t_insert(self.items[key], value);
405 self:fire_event("item-added/"..key, {source = self, item = value});
407 function api:remove_item(key, value)
408 local t = self.items and self.items[key] or NULL;
410 if t[i] == value then
411 t_remove(self.items[key], i);
412 self:fire_event("item-removed/"..key, {source = self, item = value});
418 function api:get_host_items(key)
420 for mod_name, module in pairs(modulemap[self.host]) do
421 module = module.module;
423 for _, item in ipairs(module.items[key] or NULL) do
424 t_insert(result, item);
428 for mod_name, module in pairs(modulemap["*"]) do
429 module = module.module;
431 for _, item in ipairs(module.items[key] or NULL) do
432 t_insert(result, item);