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 local disabled_set = {};
60 local modules_disabled = config.get(host, "core", "modules_disabled");
61 if modules_disabled then
62 for _, module in ipairs(modules_disabled) do
63 disabled_set[module] = true;
67 -- Load auto-loaded modules for this host
68 if hosts[host].type == "local" then
69 for _, module in ipairs(autoload_modules) do
70 if not disabled_set[module] then
76 -- Load modules from global section
77 if config.get(host, "core", "load_global_modules") ~= false then
78 local modules_enabled = config.get("*", "core", "modules_enabled");
79 if modules_enabled 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] = {};
111 if modulemap[host][module_name] then
112 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
113 return nil, "module-already-loaded";
114 elseif modulemap["*"][module_name] then
115 return nil, "global-module-already-loaded";
119 local mod, err = pluginloader.load_code(module_name);
121 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
125 local _log = logger.init(host..":"..module_name);
126 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
128 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
130 setfenv(mod, pluginenv);
131 if not hosts[host] then
132 local create_component = _G.require "core.componentmanager".create_component;
133 hosts[host] = create_component(host);
134 hosts[host].connected = false;
135 log("debug", "Created new component: %s", host);
137 hosts[host].modules = modulemap[host];
138 modulemap[host][module_name] = pluginenv;
140 local success, err = pcall(mod);
142 if module_has_method(pluginenv, "load") then
143 success, err = call_module_method(pluginenv, "load");
145 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
149 -- Use modified host, if the module set one
150 if api_instance.host == "*" and host ~= "*" then
151 modulemap[host][module_name] = nil;
152 modulemap["*"][module_name] = pluginenv;
153 api_instance:set_global();
156 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
160 else -- load failed, unloading
161 unload(api_instance.host, module_name);
166 function get_module(host, name)
167 return modulemap[host] and modulemap[host][name];
170 function is_loaded(host, name)
171 return modulemap[host] and modulemap[host][name] and true;
174 function unload(host, name, ...)
175 local mod = get_module(host, name);
176 if not mod then return nil, "module-not-loaded"; end
178 if module_has_method(mod, "unload") then
179 local ok, err = call_module_method(mod, "unload");
180 if (not ok) and err then
181 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
184 local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
185 for _, param in pairs(params or NULL) do
186 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
188 handler_info[handlers[1]] = nil;
189 stanza_handlers:remove(param[1], param[2], param[3], param[4]);
192 event_hooks:remove(host, name);
193 -- unhook event handlers hooked by module:hook
194 for event, handlers in pairs(hooks:get(host, name) or NULL) do
195 for handler in pairs(handlers or NULL) do
196 (hosts[host] or prosody).events.remove_handler(event, handler);
199 hooks:remove(host, name);
200 modulemap[host][name] = nil;
204 function reload(host, name, ...)
205 local mod = get_module(host, name);
206 if not mod then return nil, "module-not-loaded"; end
208 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
210 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
216 if module_has_method(mod, "save") then
217 local ok, ret, err = call_module_method(mod, "save");
221 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
222 if not config.get(host, "core", "force_module_reload") then
223 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
224 return nil, "save-state-failed";
226 log("warn", "Continuing with reload (using the force)");
231 unload(host, name, ...);
232 local ok, err = load(host, name, ...);
234 mod = get_module(host, name);
235 if module_has_method(mod, "restore") then
236 local ok, err = call_module_method(mod, "restore", saved or {})
237 if (not ok) and err then
238 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
246 function handle_stanza(host, origin, stanza)
247 local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
248 if name == "iq" and xmlns == "jabber:client" then
249 if stanza.attr.type == "get" or stanza.attr.type == "set" then
250 xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
251 log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
253 log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
257 local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
258 if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
260 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
261 (handlers[1])(origin, stanza);
264 if stanza.attr.xmlns == "jabber:client" then
265 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
266 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
267 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
269 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
270 log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
271 origin:close("unsupported-stanza-type");
276 function module_has_method(module, method)
277 return type(module.module[method]) == "function";
280 function call_module_method(module, method, ...)
281 if module_has_method(module, method) then
282 local f = module.module[method];
283 return pcall(f, ...);
285 return false, "no-such-method";
289 ----- API functions exposed to modules -----------
290 -- Must all be in api.*
292 -- Returns the name of the current module
293 function api:get_name()
297 -- Returns the host that the current module is serving
298 function api:get_host()
302 function api:get_host_type()
303 return hosts[self.host].type;
306 function api:set_global()
309 local _log = logger.init("mod_"..self.name);
310 self.log = function (self, ...) return _log(...); end;
314 local function _add_handler(module, origin_type, tag, xmlns, handler)
315 local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
316 local msg = (tag == "iq") and "namespace" or "payload namespace";
318 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
319 handler_info[handler] = module;
320 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
321 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
323 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);
327 function api:add_handler(origin_type, tag, xmlns, handler)
328 if not (origin_type and tag and xmlns and handler) then return false; end
329 if type(origin_type) == "table" then
330 for _, origin_type in ipairs(origin_type) do
331 _add_handler(self, origin_type, tag, xmlns, handler);
334 _add_handler(self, origin_type, tag, xmlns, handler);
337 function api:add_iq_handler(origin_type, xmlns, handler)
338 self:add_handler(origin_type, "iq", xmlns, handler);
341 function api:add_feature(xmlns)
342 self:add_item("feature", xmlns);
344 function api:add_identity(category, type, name)
345 self:add_item("identity", {category = category, type = type, name = name});
348 local event_hook = function(host, mod_name, event_name, ...)
349 if type((...)) == "table" and (...).host and (...).host ~= host then return; end
350 for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
354 function api:add_event_hook(name, handler)
355 if not hooked:get(self.host, self.name, name) then
356 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
357 hooked:set(self.host, self.name, name, true);
359 event_hooks:set(self.host, self.name, name, handler, true);
362 function api:fire_event(...)
363 return (hosts[self.host] or prosody).events.fire_event(...);
366 function api:hook(event, handler, priority)
367 hooks:set(self.host, self.name, event, handler, true);
368 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
371 function api:hook_stanza(xmlns, name, handler, priority)
372 if not handler and type(name) == "function" then
373 -- If only 2 options then they specified no xmlns
374 xmlns, name, handler, priority = nil, xmlns, name, handler;
375 elseif not (handler and name) then
376 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
379 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
382 function api:require(lib)
383 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
385 f, n = pluginloader.load_code(lib, lib..".lib.lua");
387 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
388 setfenv(f, setmetatable({ module = self }, { __index = _G }));
392 function api:get_option(name, default_value)
393 return config.get(self.host, self.name, name) or config.get(self.host, "core", name) or default_value;
396 local t_remove = _G.table.remove;
397 local module_items = multitable_new();
398 function api:add_item(key, value)
399 self.items = self.items or {};
400 self.items[key] = self.items[key] or {};
401 t_insert(self.items[key], value);
402 self:fire_event("item-added/"..key, {source = self, item = value});
404 function api:remove_item(key, value)
405 local t = self.items and self.items[key] or NULL;
407 if t[i] == value then
408 t_remove(self.items[key], i);
409 self:fire_event("item-removed/"..key, {source = self, item = value});
415 function api:get_host_items(key)
417 for mod_name, module in pairs(modulemap[self.host]) do
418 module = module.module;
420 for _, item in ipairs(module.items[key] or NULL) do
421 t_insert(result, item);
425 for mod_name, module in pairs(modulemap["*"]) do
426 module = module.module;
428 for _, item in ipairs(module.items[key] or NULL) do
429 t_insert(result, item);
436 --------------------------------------------------------------------
440 function actions.load(params)
441 --return true, "Module loaded ("..params.module.." on "..params.host..")";
442 return load(params.host, params.module);
445 function actions.unload(params)
446 return unload(params.host, params.module);
449 register_actions("/modules", actions);