2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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 eventmanager = require "core.eventmanager";
14 local config = require "core.configmanager";
15 local multitable_new = require "util.multitable".new;
16 local st = require "util.stanza";
17 local pluginloader = require "util.pluginloader";
20 local prosody = prosody;
22 local loadfile, pcall = loadfile, pcall;
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 array, set = require "util.array", require "util.set";
34 local autoload_modules = {"presence", "message", "iq"};
36 -- We need this to let modules access the real global namespace
39 module "modulemanager"
42 local api = api; -- Module API container
44 local modulemap = { ["*"] = {} };
46 local stanza_handlers = multitable_new();
47 local handler_info = {};
49 local modulehelpers = setmetatable({}, { __index = _G });
51 local handler_table = multitable_new();
52 local hooked = multitable_new();
53 local hooks = multitable_new();
54 local event_hooks = multitable_new();
58 -- Load modules when a host is activated
59 function load_modules_for_host(host)
60 local disabled_set = {};
61 local modules_disabled = config.get(host, "core", "modules_disabled");
62 if modules_disabled then
63 for _, module in ipairs(modules_disabled) do
64 disabled_set[module] = true;
68 -- Load auto-loaded modules for this host
69 if hosts[host].type == "local" then
70 for _, module in ipairs(autoload_modules) do
71 if not disabled_set[module] then
77 -- Load modules from global section
78 if config.get(host, "core", "load_global_modules") ~= false then
79 local modules_enabled = config.get("*", "core", "modules_enabled");
80 if modules_enabled then
81 for _, module in ipairs(modules_enabled) do
82 if not disabled_set[module] and not is_loaded(host, module) then
89 -- Load modules from just this host
90 local modules_enabled = config.get(host, "core", "modules_enabled");
91 if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
92 for _, module in pairs(modules_enabled) do
93 if not is_loaded(host, module) then
99 eventmanager.add_event_hook("host-activated", load_modules_for_host);
100 eventmanager.add_event_hook("component-activated", load_modules_for_host);
103 function load(host, module_name, config)
104 if not (host and module_name) then
105 return nil, "insufficient-parameters";
108 if not modulemap[host] then
109 modulemap[host] = {};
112 if modulemap[host][module_name] then
113 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
114 return nil, "module-already-loaded";
115 elseif modulemap["*"][module_name] then
116 return nil, "global-module-already-loaded";
120 local mod, err = pluginloader.load_code(module_name);
122 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
126 local _log = logger.init(host..":"..module_name);
127 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
129 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
131 setfenv(mod, pluginenv);
132 if not hosts[host] then
133 local create_component = _G.require "core.componentmanager".create_component;
134 hosts[host] = create_component(host);
135 hosts[host].connected = false;
136 log("debug", "Created new component: %s", host);
138 hosts[host].modules = modulemap[host];
139 modulemap[host][module_name] = pluginenv;
141 local success, err = pcall(mod);
143 if module_has_method(pluginenv, "load") then
144 success, err = call_module_method(pluginenv, "load");
146 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
150 -- Use modified host, if the module set one
151 if api_instance.host == "*" and host ~= "*" then
152 modulemap[host][module_name] = nil;
153 modulemap["*"][module_name] = pluginenv;
154 api_instance:set_global();
157 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
160 hosts[host].events.fire_event("module-loaded", { module = module_name, host = host });
162 else -- load failed, unloading
163 unload(api_instance.host, module_name);
168 function get_module(host, name)
169 return modulemap[host] and modulemap[host][name];
172 function is_loaded(host, name)
173 return modulemap[host] and modulemap[host][name] and true;
176 function unload(host, name, ...)
177 local mod = get_module(host, name);
178 if not mod then return nil, "module-not-loaded"; end
180 if module_has_method(mod, "unload") then
181 local ok, err = call_module_method(mod, "unload");
182 if (not ok) and err then
183 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
186 local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
187 for _, param in pairs(params or NULL) do
188 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
190 handler_info[handlers[1]] = nil;
191 stanza_handlers:remove(param[1], param[2], param[3], param[4]);
194 event_hooks:remove(host, name);
195 -- unhook event handlers hooked by module:hook
196 for event, handlers in pairs(hooks:get(host, name) or NULL) do
197 for handler in pairs(handlers or NULL) do
198 (hosts[host] or prosody).events.remove_handler(event, handler);
201 hooks:remove(host, name);
202 if mod.module.items then -- remove items
203 for key,t in pairs(mod.module.items) do
207 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
211 modulemap[host][name] = nil;
212 hosts[host].events.fire_event("module-unloaded", { module = name, host = host });
216 function reload(host, name, ...)
217 local mod = get_module(host, name);
218 if not mod then return nil, "module-not-loaded"; end
220 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
222 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
228 if module_has_method(mod, "save") then
229 local ok, ret, err = call_module_method(mod, "save");
233 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
234 if not config.get(host, "core", "force_module_reload") then
235 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
236 return nil, "save-state-failed";
238 log("warn", "Continuing with reload (using the force)");
243 unload(host, name, ...);
244 local ok, err = load(host, name, ...);
246 mod = get_module(host, name);
247 if module_has_method(mod, "restore") then
248 local ok, err = call_module_method(mod, "restore", saved or {})
249 if (not ok) and err then
250 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
258 function handle_stanza(host, origin, stanza)
259 local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
260 if name == "iq" and xmlns == "jabber:client" then
261 if stanza.attr.type == "get" or stanza.attr.type == "set" then
262 xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
263 log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
265 log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
269 local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
270 if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
272 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
273 (handlers[1])(origin, stanza);
276 if stanza.attr.xmlns == "jabber:client" then
277 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
278 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
279 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
281 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
282 log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
283 origin:close("unsupported-stanza-type");
288 function module_has_method(module, method)
289 return type(module.module[method]) == "function";
292 function call_module_method(module, method, ...)
293 if module_has_method(module, method) then
294 local f = module.module[method];
295 return pcall(f, ...);
297 return false, "no-such-method";
301 ----- API functions exposed to modules -----------
302 -- Must all be in api.*
304 -- Returns the name of the current module
305 function api:get_name()
309 -- Returns the host that the current module is serving
310 function api:get_host()
314 function api:get_host_type()
315 return hosts[self.host].type;
318 function api:set_global()
321 local _log = logger.init("mod_"..self.name);
322 self.log = function (self, ...) return _log(...); end;
326 local function _add_handler(module, origin_type, tag, xmlns, handler)
327 local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
328 local msg = (tag == "iq") and "namespace" or "payload namespace";
330 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
331 handler_info[handler] = module;
332 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
333 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
335 module:log("warn", "I wanted to handle tag '%s' [%s] with %s '%s' but mod_%s already handles that", tag, origin_type, msg, xmlns, handler_info[handlers[1]].module.name);
339 function api:add_handler(origin_type, tag, xmlns, handler)
340 if not (origin_type and tag and xmlns and handler) then return false; end
341 if type(origin_type) == "table" then
342 for _, origin_type in ipairs(origin_type) do
343 _add_handler(self, origin_type, tag, xmlns, handler);
346 _add_handler(self, origin_type, tag, xmlns, handler);
349 function api:add_iq_handler(origin_type, xmlns, handler)
350 self:add_handler(origin_type, "iq", xmlns, handler);
353 function api:add_feature(xmlns)
354 self:add_item("feature", xmlns);
356 function api:add_identity(category, type, name)
357 self:add_item("identity", {category = category, type = type, name = name});
360 local event_hook = function(host, mod_name, event_name, ...)
361 if type((...)) == "table" and (...).host and (...).host ~= host then return; end
362 for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
366 function api:add_event_hook(name, handler)
367 if not hooked:get(self.host, self.name, name) then
368 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
369 hooked:set(self.host, self.name, name, true);
371 event_hooks:set(self.host, self.name, name, handler, true);
374 function api:fire_event(...)
375 return (hosts[self.host] or prosody).events.fire_event(...);
378 function api:hook(event, handler, priority)
379 hooks:set(self.host, self.name, event, handler, true);
380 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
383 function api:hook_stanza(xmlns, name, handler, priority)
384 if not handler and type(name) == "function" then
385 -- If only 2 options then they specified no xmlns
386 xmlns, name, handler, priority = nil, xmlns, name, handler;
387 elseif not (handler and name) then
388 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
391 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
394 function api:require(lib)
395 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
397 f, n = pluginloader.load_code(lib, lib..".lib.lua");
399 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
400 setfenv(f, setmetatable({ module = self }, { __index = _G }));
404 function api:get_option(name, default_value)
405 local value = config.get(self.host, self.name, name);
407 value = config.get(self.host, "core", name);
409 value = default_value;
415 function api:get_option_string(name, default_value)
416 local value = self:get_option(name, default_value);
417 if type(value) == "table" then
419 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
426 return tostring(value);
429 function api:get_option_number(name, ...)
430 local value = self:get_option(name, ...);
431 if type(value) == "table" then
433 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
437 local ret = tonumber(value);
438 if value ~= nil and ret == nil then
439 self:log("error", "Config option '%s' not understood, expecting a number", name);
444 function api:get_option_boolean(name, ...)
445 local value = self:get_option(name, ...);
446 if type(value) == "table" then
448 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
455 local ret = value == true or value == "true" or value == 1 or nil;
457 ret = (value == false or value == "false" or value == 0);
465 self:log("error", "Config option '%s' not understood, expecting true/false", name);
470 function api:get_option_array(name, ...)
471 local value = self:get_option(name, ...);
477 if type(value) ~= "table" then
478 return array{ value }; -- Assume any non-list is a single-item list
481 return array():append(value); -- Clone
484 function api:get_option_set(name, ...)
485 local value = self:get_option_array(name, ...);
491 return set.new(value);
494 local t_remove = _G.table.remove;
495 local module_items = multitable_new();
496 function api:add_item(key, value)
497 self.items = self.items or {};
498 self.items[key] = self.items[key] or {};
499 t_insert(self.items[key], value);
500 self:fire_event("item-added/"..key, {source = self, item = value});
502 function api:remove_item(key, value)
503 local t = self.items and self.items[key] or NULL;
505 if t[i] == value then
506 t_remove(self.items[key], i);
507 self:fire_event("item-removed/"..key, {source = self, item = value});
513 function api:get_host_items(key)
515 for mod_name, module in pairs(modulemap[self.host]) do
516 module = module.module;
518 for _, item in ipairs(module.items[key] or NULL) do
519 t_insert(result, item);
523 for mod_name, module in pairs(modulemap["*"]) do
524 module = module.module;
526 for _, item in ipairs(module.items[key] or NULL) do
527 t_insert(result, item);