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 register_actions = require "core.actions".register;
17 local st = require "util.stanza";
18 local pluginloader = require "util.pluginloader";
21 local prosody = prosody;
23 local loadfile, pcall = loadfile, pcall;
24 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
25 local pairs, ipairs = pairs, ipairs;
26 local t_insert, t_concat = table.insert, table.concat;
29 local rawget = rawget;
31 local tostring, tonumber = tostring, tonumber;
33 local array, set = require "util.array", require "util.set";
35 local autoload_modules = {"presence", "message", "iq"};
37 -- We need this to let modules access the real global namespace
40 module "modulemanager"
43 local api = api; -- Module API container
45 local modulemap = { ["*"] = {} };
47 local stanza_handlers = multitable_new();
48 local handler_info = {};
50 local modulehelpers = setmetatable({}, { __index = _G });
52 local handler_table = multitable_new();
53 local hooked = multitable_new();
54 local hooks = multitable_new();
55 local event_hooks = multitable_new();
59 -- Load modules when a host is activated
60 function load_modules_for_host(host)
61 local disabled_set = {};
62 local modules_disabled = config.get(host, "core", "modules_disabled");
63 if modules_disabled then
64 for _, module in ipairs(modules_disabled) do
65 disabled_set[module] = true;
69 -- Load auto-loaded modules for this host
70 if hosts[host].type == "local" then
71 for _, module in ipairs(autoload_modules) do
72 if not disabled_set[module] then
78 -- Load modules from global section
79 if config.get(host, "core", "load_global_modules") ~= false then
80 local modules_enabled = config.get("*", "core", "modules_enabled");
81 if modules_enabled then
82 for _, module in ipairs(modules_enabled) do
83 if not disabled_set[module] and not is_loaded(host, module) then
90 -- Load modules from just this host
91 local modules_enabled = config.get(host, "core", "modules_enabled");
92 if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
93 for _, module in pairs(modules_enabled) do
94 if not is_loaded(host, module) then
100 eventmanager.add_event_hook("host-activated", load_modules_for_host);
101 eventmanager.add_event_hook("component-activated", load_modules_for_host);
104 function load(host, module_name, config)
105 if not (host and module_name) then
106 return nil, "insufficient-parameters";
109 if not modulemap[host] then
110 modulemap[host] = {};
113 if modulemap[host][module_name] then
114 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
115 return nil, "module-already-loaded";
116 elseif modulemap["*"][module_name] then
117 return nil, "global-module-already-loaded";
121 local mod, err = pluginloader.load_code(module_name);
123 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
127 local _log = logger.init(host..":"..module_name);
128 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
130 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
132 setfenv(mod, pluginenv);
133 if not hosts[host] then
134 local create_component = _G.require "core.componentmanager".create_component;
135 hosts[host] = create_component(host);
136 hosts[host].connected = false;
137 log("debug", "Created new component: %s", host);
139 hosts[host].modules = modulemap[host];
140 modulemap[host][module_name] = pluginenv;
142 local success, err = pcall(mod);
144 if module_has_method(pluginenv, "load") then
145 success, err = call_module_method(pluginenv, "load");
147 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
151 -- Use modified host, if the module set one
152 if api_instance.host == "*" and host ~= "*" then
153 modulemap[host][module_name] = nil;
154 modulemap["*"][module_name] = pluginenv;
155 api_instance:set_global();
158 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
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 modulemap[host][name] = nil;
206 function reload(host, name, ...)
207 local mod = get_module(host, name);
208 if not mod then return nil, "module-not-loaded"; end
210 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
212 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
218 if module_has_method(mod, "save") then
219 local ok, ret, err = call_module_method(mod, "save");
223 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
224 if not config.get(host, "core", "force_module_reload") then
225 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
226 return nil, "save-state-failed";
228 log("warn", "Continuing with reload (using the force)");
233 unload(host, name, ...);
234 local ok, err = load(host, name, ...);
236 mod = get_module(host, name);
237 if module_has_method(mod, "restore") then
238 local ok, err = call_module_method(mod, "restore", saved or {})
239 if (not ok) and err then
240 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
248 function handle_stanza(host, origin, stanza)
249 local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
250 if name == "iq" and xmlns == "jabber:client" then
251 if stanza.attr.type == "get" or stanza.attr.type == "set" then
252 xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
253 log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
255 log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
259 local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
260 if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
262 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
263 (handlers[1])(origin, stanza);
266 if stanza.attr.xmlns == "jabber:client" then
267 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
268 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
269 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
271 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
272 log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
273 origin:close("unsupported-stanza-type");
278 function module_has_method(module, method)
279 return type(module.module[method]) == "function";
282 function call_module_method(module, method, ...)
283 if module_has_method(module, method) then
284 local f = module.module[method];
285 return pcall(f, ...);
287 return false, "no-such-method";
291 ----- API functions exposed to modules -----------
292 -- Must all be in api.*
294 -- Returns the name of the current module
295 function api:get_name()
299 -- Returns the host that the current module is serving
300 function api:get_host()
304 function api:get_host_type()
305 return hosts[self.host].type;
308 function api:set_global()
311 local _log = logger.init("mod_"..self.name);
312 self.log = function (self, ...) return _log(...); end;
316 local function _add_handler(module, origin_type, tag, xmlns, handler)
317 local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
318 local msg = (tag == "iq") and "namespace" or "payload namespace";
320 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
321 handler_info[handler] = module;
322 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
323 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
325 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);
329 function api:add_handler(origin_type, tag, xmlns, handler)
330 if not (origin_type and tag and xmlns and handler) then return false; end
331 if type(origin_type) == "table" then
332 for _, origin_type in ipairs(origin_type) do
333 _add_handler(self, origin_type, tag, xmlns, handler);
336 _add_handler(self, origin_type, tag, xmlns, handler);
339 function api:add_iq_handler(origin_type, xmlns, handler)
340 self:add_handler(origin_type, "iq", xmlns, handler);
343 function api:add_feature(xmlns)
344 self:add_item("feature", xmlns);
346 function api:add_identity(category, type, name)
347 self:add_item("identity", {category = category, type = type, name = name});
350 local event_hook = function(host, mod_name, event_name, ...)
351 if type((...)) == "table" and (...).host and (...).host ~= host then return; end
352 for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
356 function api:add_event_hook(name, handler)
357 if not hooked:get(self.host, self.name, name) then
358 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
359 hooked:set(self.host, self.name, name, true);
361 event_hooks:set(self.host, self.name, name, handler, true);
364 function api:fire_event(...)
365 return (hosts[self.host] or prosody).events.fire_event(...);
368 function api:hook(event, handler, priority)
369 hooks:set(self.host, self.name, event, handler, true);
370 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
373 function api:hook_stanza(xmlns, name, handler, priority)
374 if not handler and type(name) == "function" then
375 -- If only 2 options then they specified no xmlns
376 xmlns, name, handler, priority = nil, xmlns, name, handler;
377 elseif not (handler and name) then
378 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
381 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
384 function api:require(lib)
385 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
387 f, n = pluginloader.load_code(lib, lib..".lib.lua");
389 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
390 setfenv(f, setmetatable({ module = self }, { __index = _G }));
394 function api:get_option(name, default_value)
395 local value = config.get(self.host, self.name, name);
397 value = config.get(self.host, "core", name);
399 value = default_value;
405 function api:get_option_string(...)
406 local value = self:get_option(...);
407 if type(value) == "table" then
409 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
416 return tostring(value);
419 function api:get_option_number(name, ...)
420 local value = self:get_option(name, ...);
421 if type(value) == "table" then
423 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
427 local ret = tonumber(value);
428 if value ~= nil and ret == nil then
429 self:log("error", "Config option '%s' not understood, expecting a number", name);
434 function api:get_option_boolean(name, ...)
435 local value = self:get_option(name, ...);
436 if type(value) == "table" then
438 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
445 local ret = value == true or value == "true" or value == 1 or nil;
447 ret = (value == false or value == "false" or value == 0);
455 self:log("error", "Config option '%s' not understood, expecting true/false", name);
460 function api:get_option_array(name, ...)
461 local value = self:get_option(name, ...);
467 if type(value) ~= "table" then
468 return array{ value }; -- Assume any non-list is a single-item list
471 return array():append(value); -- Clone
474 function api:get_option_set(name, ...)
475 local value = self:get_option_array(name, ...);
481 return set.new(value);
484 local t_remove = _G.table.remove;
485 local module_items = multitable_new();
486 function api:add_item(key, value)
487 self.items = self.items or {};
488 self.items[key] = self.items[key] or {};
489 t_insert(self.items[key], value);
490 self:fire_event("item-added/"..key, {source = self, item = value});
492 function api:remove_item(key, value)
493 local t = self.items and self.items[key] or NULL;
495 if t[i] == value then
496 t_remove(self.items[key], i);
497 self:fire_event("item-removed/"..key, {source = self, item = value});
503 function api:get_host_items(key)
505 for mod_name, module in pairs(modulemap[self.host]) do
506 module = module.module;
508 for _, item in ipairs(module.items[key] or NULL) do
509 t_insert(result, item);
513 for mod_name, module in pairs(modulemap["*"]) do
514 module = module.module;
516 for _, item in ipairs(module.items[key] or NULL) do
517 t_insert(result, item);
524 --------------------------------------------------------------------
528 function actions.load(params)
529 --return true, "Module loaded ("..params.module.." on "..params.host..")";
530 return load(params.host, params.module);
533 function actions.unload(params)
534 return unload(params.host, params.module);
537 register_actions("/modules", actions);