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.
11 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
13 local logger = require "util.logger";
14 local log = logger.init("modulemanager");
15 local addDiscoInfoHandler = require "core.discomanager".addDiscoInfoHandler;
16 local eventmanager = require "core.eventmanager";
17 local config = require "core.configmanager";
18 local multitable_new = require "util.multitable".new;
19 local register_actions = require "core.actions".register;
20 local st = require "util.stanza";
21 local pluginloader = require "util.pluginloader";
24 local prosody = prosody;
26 local loadfile, pcall = loadfile, pcall;
27 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
28 local pairs, ipairs = pairs, ipairs;
29 local t_insert, t_concat = table.insert, table.concat;
32 local rawget = rawget;
34 local tostring = tostring;
36 local autoload_modules = {"presence", "message", "iq"};
38 -- We need this to let modules access the real global namespace
41 module "modulemanager"
44 local api = api; -- Module API container
46 local modulemap = { ["*"] = {} };
48 local stanza_handlers = multitable_new();
49 local handler_info = {};
51 local modulehelpers = setmetatable({}, { __index = _G });
53 local features_table = multitable_new();
54 local identities_table = multitable_new();
55 local handler_table = multitable_new();
56 local hooked = multitable_new();
57 local hooks = multitable_new();
58 local event_hooks = multitable_new();
62 -- Load modules when a host is activated
63 function load_modules_for_host(host)
64 if config.get(host, "core", "load_global_modules") ~= false then
65 -- Load modules from global section
66 local modules_enabled = config.get("*", "core", "modules_enabled");
67 local modules_disabled = config.get(host, "core", "modules_disabled");
68 local disabled_set = {};
69 if modules_enabled then
70 if modules_disabled then
71 for _, module in ipairs(modules_disabled) do
72 disabled_set[module] = true;
75 for _, module in ipairs(autoload_modules) do
76 if not disabled_set[module] then
80 for _, module in ipairs(modules_enabled) do
81 if not disabled_set[module] and not is_loaded(host, module) then
88 -- Load modules from just this host
89 local modules_enabled = config.get(host, "core", "modules_enabled");
90 if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
91 for _, module in pairs(modules_enabled) do
92 if not is_loaded(host, module) then
98 eventmanager.add_event_hook("host-activated", load_modules_for_host);
99 eventmanager.add_event_hook("component-activated", load_modules_for_host);
102 function load(host, module_name, config)
103 if not (host and module_name) then
104 return nil, "insufficient-parameters";
107 if not modulemap[host] then
108 modulemap[host] = {};
109 hosts[host].modules = 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 hosts[host] = { type = "component", host = host, connected = false, s2sout = {} }; end
134 local success, ret = pcall(mod);
136 log("error", "Error initialising module '%s': %s", module_name or "nil", ret or "nil");
140 if module_has_method(pluginenv, "load") then
141 local ok, err = call_module_method(pluginenv, "load");
142 if (not ok) and err then
143 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err);
147 -- Use modified host, if the module set one
148 modulemap[api_instance.host][module_name] = pluginenv;
150 if api_instance.host == "*" and host ~= "*" then
151 api_instance:set_global();
157 function get_module(host, name)
158 return modulemap[host] and modulemap[host][name];
161 function is_loaded(host, name)
162 return modulemap[host] and modulemap[host][name] and true;
165 function unload(host, name, ...)
166 local mod = get_module(host, name);
167 if not mod then return nil, "module-not-loaded"; end
169 if module_has_method(mod, "unload") then
170 local ok, err = call_module_method(mod, "unload");
171 if (not ok) and err then
172 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
175 modulemap[host][name] = nil;
176 features_table:remove(host, name);
177 identities_table:remove(host, name);
178 local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
179 for _, param in pairs(params or NULL) do
180 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
182 handler_info[handlers[1]] = nil;
183 stanza_handlers:remove(param[1], param[2], param[3], param[4]);
186 event_hooks:remove(host, name);
187 -- unhook event handlers hooked by module:hook
188 for event, handlers in pairs(hooks:get(host, name) or NULL) do
189 for handler in pairs(handlers or NULL) do
190 (hosts[host] or prosody).events.remove_handler(event, handler);
193 hooks:remove(host, name);
197 function reload(host, name, ...)
198 local mod = get_module(host, name);
199 if not mod then return nil, "module-not-loaded"; end
201 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
203 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
209 if module_has_method(mod, "save") then
210 local ok, ret, err = call_module_method(mod, "save");
214 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
215 if not config.get(host, "core", "force_module_reload") then
216 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
217 return nil, "save-state-failed";
219 log("warn", "Continuing with reload (using the force)");
224 unload(host, name, ...);
225 local ok, err = load(host, name, ...);
227 mod = get_module(host, name);
228 if module_has_method(mod, "restore") then
229 local ok, err = call_module_method(mod, "restore", saved or {})
230 if (not ok) and err then
231 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
239 function handle_stanza(host, origin, stanza)
240 local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
241 if name == "iq" and xmlns == "jabber:client" then
242 if stanza.attr.type == "get" or stanza.attr.type == "set" then
243 xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
244 log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
246 log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
250 local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
251 if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
253 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
254 (handlers[1])(origin, stanza);
257 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
258 if stanza.attr.xmlns == "jabber:client" then
259 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
260 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
262 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
263 origin:close("unsupported-stanza-type");
268 function module_has_method(module, method)
269 return type(module.module[method]) == "function";
272 function call_module_method(module, method, ...)
273 if module_has_method(module, method) then
274 local f = module.module[method];
275 return pcall(f, ...);
277 return false, "no-such-method";
281 ----- API functions exposed to modules -----------
282 -- Must all be in api.*
284 -- Returns the name of the current module
285 function api:get_name()
289 -- Returns the host that the current module is serving
290 function api:get_host()
294 function api:get_host_type()
295 return hosts[self.host].type;
298 function api:set_global()
301 local _log = logger.init("mod_"..self.name);
302 self.log = function (self, ...) return _log(...); end;
306 local function _add_handler(module, origin_type, tag, xmlns, handler)
307 local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
308 local msg = (tag == "iq") and "namespace" or "payload namespace";
310 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
311 handler_info[handler] = module;
312 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
313 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
315 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);
319 function api:add_handler(origin_type, tag, xmlns, handler)
320 if not (origin_type and tag and xmlns and handler) then return false; end
321 if type(origin_type) == "table" then
322 for _, origin_type in ipairs(origin_type) do
323 _add_handler(self, origin_type, tag, xmlns, handler);
326 _add_handler(self, origin_type, tag, xmlns, handler);
329 function api:add_iq_handler(origin_type, xmlns, handler)
330 self:add_handler(origin_type, "iq", xmlns, handler);
333 addDiscoInfoHandler("*host", function(reply, to, from, node)
336 for module, identities in pairs(identities_table:get(to) or NULL) do -- for each module
337 for identity, attr in pairs(identities) do
338 if not done[identity] then
339 reply:tag("identity", attr):up(); -- TODO cache
340 done[identity] = true;
344 for module, identities in pairs(identities_table:get("*") or NULL) do -- for each module
345 for identity, attr in pairs(identities) do
346 if not done[identity] then
347 reply:tag("identity", attr):up(); -- TODO cache
348 done[identity] = true;
352 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
353 for feature in pairs(features) do
354 if not done[feature] then
355 reply:tag("feature", {var = feature}):up(); -- TODO cache
356 done[feature] = true;
360 for module, features in pairs(features_table:get("*") or NULL) do -- for each module
361 for feature in pairs(features) do
362 if not done[feature] then
363 reply:tag("feature", {var = feature}):up(); -- TODO cache
364 done[feature] = true;
368 return next(done) ~= nil;
372 function api:add_feature(xmlns)
373 features_table:set(self.host, self.name, xmlns, true);
375 function api:add_identity(category, type)
376 identities_table:set(self.host, self.name, category.."\0"..type, {category = category, type = type});
379 local event_hook = function(host, mod_name, event_name, ...)
380 if type((...)) == "table" and (...).host and (...).host ~= host then return; end
381 for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
385 function api:add_event_hook(name, handler)
386 if not hooked:get(self.host, self.name, name) then
387 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
388 hooked:set(self.host, self.name, name, true);
390 event_hooks:set(self.host, self.name, name, handler, true);
393 function api:fire_event(...)
394 return (hosts[self.host] or prosody).events.fire_event(...);
397 function api:hook(event, handler, priority)
398 hooks:set(self.host, self.name, event, handler, true);
399 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
402 function api:hook_stanza(xmlns, name, handler, priority)
403 if not handler and type(name) == "function" then
404 -- If only 2 options then they specified no xmlns
405 xmlns, name, handler, priority = nil, xmlns, name, handler;
406 elseif not (handler and name) then
407 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
410 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
413 function api:require(lib)
414 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
416 f, n = pluginloader.load_code(lib, lib..".lib.lua");
418 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
419 setfenv(f, setmetatable({ module = self }, { __index = _G }));
423 --------------------------------------------------------------------
427 function actions.load(params)
428 --return true, "Module loaded ("..params.module.." on "..params.host..")";
429 return load(params.host, params.module);
432 function actions.unload(params)
433 return unload(params.host, params.module);
436 register_actions("/modules", actions);