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 = tostring;
33 local autoload_modules = {"presence", "message", "iq"};
35 -- We need this to let modules access the real global namespace
38 module "modulemanager"
41 local api = api; -- Module API container
43 local modulemap = { ["*"] = {} };
45 local stanza_handlers = multitable_new();
46 local handler_info = {};
48 local modulehelpers = setmetatable({}, { __index = _G });
50 local handler_table = multitable_new();
51 local hooked = multitable_new();
52 local hooks = multitable_new();
53 local event_hooks = multitable_new();
57 -- Load modules when a host is activated
58 function load_modules_for_host(host)
59 if config.get(host, "core", "load_global_modules") ~= false then
60 -- Load modules from global section
61 local modules_enabled = config.get("*", "core", "modules_enabled");
62 local modules_disabled = config.get(host, "core", "modules_disabled");
63 local disabled_set = {};
64 if modules_enabled then
65 if modules_disabled then
66 for _, module in ipairs(modules_disabled) do
67 disabled_set[module] = true;
70 for _, module in ipairs(autoload_modules) do
71 if not disabled_set[module] then
75 for _, module in ipairs(modules_enabled) do
76 if not disabled_set[module] and not is_loaded(host, module) then
83 -- Load modules from just this host
84 local modules_enabled = config.get(host, "core", "modules_enabled");
85 if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
86 for _, module in pairs(modules_enabled) do
87 if not is_loaded(host, module) then
93 eventmanager.add_event_hook("host-activated", load_modules_for_host);
96 function load(host, module_name, config)
97 if not (host and module_name) then
98 return nil, "insufficient-parameters";
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 });
124 setfenv(mod, pluginenv);
125 if not hosts[host] then hosts[host] = { type = "component", host = host, connected = false, s2sout = {} }; end
127 local success, ret = pcall(mod);
129 log("error", "Error initialising module '%s': %s", module_name or "nil", ret or "nil");
133 if module_has_method(pluginenv, "load") then
134 local ok, err = call_module_method(pluginenv, "load");
135 if (not ok) and err then
136 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err);
140 -- Use modified host, if the module set one
141 modulemap[api_instance.host][module_name] = pluginenv;
143 if api_instance.host == "*" and host ~= "*" then
144 api_instance:set_global();
150 function get_module(host, name)
151 return modulemap[host] and modulemap[host][name];
154 function is_loaded(host, name)
155 return modulemap[host] and modulemap[host][name] and true;
158 function unload(host, name, ...)
159 local mod = get_module(host, name);
160 if not mod then return nil, "module-not-loaded"; end
162 if module_has_method(mod, "unload") then
163 local ok, err = call_module_method(mod, "unload");
164 if (not ok) and err then
165 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
168 modulemap[host][name] = nil;
169 local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
170 for _, param in pairs(params or NULL) do
171 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
173 handler_info[handlers[1]] = nil;
174 stanza_handlers:remove(param[1], param[2], param[3], param[4]);
177 event_hooks:remove(host, name);
178 -- unhook event handlers hooked by module:hook
179 for event, handlers in pairs(hooks:get(host, name) or NULL) do
180 for handler in pairs(handlers or NULL) do
181 (hosts[host] or prosody).events.remove_handler(event, handler);
184 hooks:remove(host, name);
188 function reload(host, name, ...)
189 local mod = get_module(host, name);
190 if not mod then return nil, "module-not-loaded"; end
192 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
194 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
200 if module_has_method(mod, "save") then
201 local ok, ret, err = call_module_method(mod, "save");
205 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
206 if not config.get(host, "core", "force_module_reload") then
207 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
208 return nil, "save-state-failed";
210 log("warn", "Continuing with reload (using the force)");
215 unload(host, name, ...);
216 local ok, err = load(host, name, ...);
218 mod = get_module(host, name);
219 if module_has_method(mod, "restore") then
220 local ok, err = call_module_method(mod, "restore", saved or {})
221 if (not ok) and err then
222 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
230 function handle_stanza(host, origin, stanza)
231 local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
232 if name == "iq" and xmlns == "jabber:client" then
233 if stanza.attr.type == "get" or stanza.attr.type == "set" then
234 xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
235 log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
237 log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
241 local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
242 if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
244 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
245 (handlers[1])(origin, stanza);
248 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
249 if stanza.attr.xmlns == "jabber:client" then
250 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
251 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
253 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
254 origin:close("unsupported-stanza-type");
259 function module_has_method(module, method)
260 return type(module.module[method]) == "function";
263 function call_module_method(module, method, ...)
264 if module_has_method(module, method) then
265 local f = module.module[method];
266 return pcall(f, ...);
268 return false, "no-such-method";
272 ----- API functions exposed to modules -----------
273 -- Must all be in api.*
275 -- Returns the name of the current module
276 function api:get_name()
280 -- Returns the host that the current module is serving
281 function api:get_host()
285 function api:get_host_type()
286 return hosts[self.host].type;
289 function api:set_global()
292 local _log = logger.init("mod_"..self.name);
293 self.log = function (self, ...) return _log(...); end;
297 local function _add_handler(module, origin_type, tag, xmlns, handler)
298 local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
299 local msg = (tag == "iq") and "namespace" or "payload namespace";
301 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
302 handler_info[handler] = module;
303 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
304 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
306 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);
310 function api:add_handler(origin_type, tag, xmlns, handler)
311 if not (origin_type and tag and xmlns and handler) then return false; end
312 if type(origin_type) == "table" then
313 for _, origin_type in ipairs(origin_type) do
314 _add_handler(self, origin_type, tag, xmlns, handler);
317 _add_handler(self, origin_type, tag, xmlns, handler);
320 function api:add_iq_handler(origin_type, xmlns, handler)
321 self:add_handler(origin_type, "iq", xmlns, handler);
324 function api:add_feature(xmlns)
325 self:add_item("feature", xmlns);
327 function api:add_identity(category, type, name)
328 self:add_item("identity", {category = category, type = type, name = name});
331 local event_hook = function(host, mod_name, event_name, ...)
332 if type((...)) == "table" and (...).host and (...).host ~= host then return; end
333 for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
337 function api:add_event_hook(name, handler)
338 if not hooked:get(self.host, self.name, name) then
339 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
340 hooked:set(self.host, self.name, name, true);
342 event_hooks:set(self.host, self.name, name, handler, true);
345 function api:fire_event(...)
346 return (hosts[self.host] or prosody).events.fire_event(...);
349 function api:hook(event, handler, priority)
350 hooks:set(self.host, self.name, event, handler, true);
351 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
354 function api:hook_stanza(xmlns, name, handler, priority)
355 if not handler and type(name) == "function" then
356 -- If only 2 options then they specified no xmlns
357 xmlns, name, handler, priority = nil, xmlns, name, handler;
358 elseif not (handler and name) then
359 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
362 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
365 function api:require(lib)
366 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
368 f, n = pluginloader.load_code(lib, lib..".lib.lua");
370 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
371 setfenv(f, setmetatable({ module = self }, { __index = _G }));
375 function api:get_option(name, default_value)
376 return config.get(self.host, self.name, name) or config.get(self.host, "core", name) or default_value;
379 local t_remove = _G.table.remove;
380 local module_items = multitable_new();
381 function api:add_item(key, value)
382 self.items = self.items or {};
383 self.items[key] = self.items[key] or {};
384 t_insert(self.items[key], value);
385 self:fire_event("item-added/"..key, {source = self, item = value});
387 function api:remove_item(key, value)
388 local t = self.items and self.items[key] or NULL;
390 if t[i] == value then
391 t_remove(self.items[key], i);
392 self:fire_event("item-removed/"..key, {source = self, item = value});
398 function api:get_host_items(key)
400 for mod_name, module in pairs(modulemap[self.host]) do
401 module = module.module;
403 for _, item in ipairs(module.items[key] or NULL) do
404 t_insert(result, item);
411 --------------------------------------------------------------------
415 function actions.load(params)
416 --return true, "Module loaded ("..params.module.." on "..params.host..")";
417 return load(params.host, params.module);
420 function actions.unload(params)
421 return unload(params.host, params.module);
424 register_actions("/modules", actions);