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);
94 eventmanager.add_event_hook("component-activated", load_modules_for_host);
97 function load(host, module_name, config)
98 if not (host and module_name) then
99 return nil, "insufficient-parameters";
102 if not modulemap[host] then
103 modulemap[host] = {};
106 if modulemap[host][module_name] then
107 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
108 return nil, "module-already-loaded";
109 elseif modulemap["*"][module_name] then
110 return nil, "global-module-already-loaded";
114 local mod, err = pluginloader.load_code(module_name);
116 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
120 local _log = logger.init(host..":"..module_name);
121 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
123 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
125 setfenv(mod, pluginenv);
126 if not hosts[host] then hosts[host] = { type = "component", host = host, connected = false, s2sout = {} }; end
128 local success, ret = pcall(mod);
130 log("error", "Error initialising module '%s': %s", module_name or "nil", ret or "nil");
134 if module_has_method(pluginenv, "load") then
135 local ok, err = call_module_method(pluginenv, "load");
136 if (not ok) and err then
137 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err);
141 -- Use modified host, if the module set one
142 modulemap[api_instance.host][module_name] = pluginenv;
144 if api_instance.host == "*" and host ~= "*" then
145 api_instance:set_global();
151 function get_module(host, name)
152 return modulemap[host] and modulemap[host][name];
155 function is_loaded(host, name)
156 return modulemap[host] and modulemap[host][name] and true;
159 function unload(host, name, ...)
160 local mod = get_module(host, name);
161 if not mod then return nil, "module-not-loaded"; end
163 if module_has_method(mod, "unload") then
164 local ok, err = call_module_method(mod, "unload");
165 if (not ok) and err then
166 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
169 modulemap[host][name] = nil;
170 local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
171 for _, param in pairs(params or NULL) do
172 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
174 handler_info[handlers[1]] = nil;
175 stanza_handlers:remove(param[1], param[2], param[3], param[4]);
178 event_hooks:remove(host, name);
179 -- unhook event handlers hooked by module:hook
180 for event, handlers in pairs(hooks:get(host, name) or NULL) do
181 for handler in pairs(handlers or NULL) do
182 (hosts[host] or prosody).events.remove_handler(event, handler);
185 hooks:remove(host, name);
189 function reload(host, name, ...)
190 local mod = get_module(host, name);
191 if not mod then return nil, "module-not-loaded"; end
193 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
195 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
201 if module_has_method(mod, "save") then
202 local ok, ret, err = call_module_method(mod, "save");
206 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
207 if not config.get(host, "core", "force_module_reload") then
208 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
209 return nil, "save-state-failed";
211 log("warn", "Continuing with reload (using the force)");
216 unload(host, name, ...);
217 local ok, err = load(host, name, ...);
219 mod = get_module(host, name);
220 if module_has_method(mod, "restore") then
221 local ok, err = call_module_method(mod, "restore", saved or {})
222 if (not ok) and err then
223 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
231 function handle_stanza(host, origin, stanza)
232 local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
233 if name == "iq" and xmlns == "jabber:client" then
234 if stanza.attr.type == "get" or stanza.attr.type == "set" then
235 xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
236 log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
238 log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
242 local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
243 if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
245 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
246 (handlers[1])(origin, stanza);
249 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
250 if stanza.attr.xmlns == "jabber:client" then
251 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
252 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
254 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
255 origin:close("unsupported-stanza-type");
260 function module_has_method(module, method)
261 return type(module.module[method]) == "function";
264 function call_module_method(module, method, ...)
265 if module_has_method(module, method) then
266 local f = module.module[method];
267 return pcall(f, ...);
269 return false, "no-such-method";
273 ----- API functions exposed to modules -----------
274 -- Must all be in api.*
276 -- Returns the name of the current module
277 function api:get_name()
281 -- Returns the host that the current module is serving
282 function api:get_host()
286 function api:get_host_type()
287 return hosts[self.host].type;
290 function api:set_global()
293 local _log = logger.init("mod_"..self.name);
294 self.log = function (self, ...) return _log(...); end;
298 local function _add_handler(module, origin_type, tag, xmlns, handler)
299 local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
300 local msg = (tag == "iq") and "namespace" or "payload namespace";
302 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
303 handler_info[handler] = module;
304 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
305 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
307 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);
311 function api:add_handler(origin_type, tag, xmlns, handler)
312 if not (origin_type and tag and xmlns and handler) then return false; end
313 if type(origin_type) == "table" then
314 for _, origin_type in ipairs(origin_type) do
315 _add_handler(self, origin_type, tag, xmlns, handler);
318 _add_handler(self, origin_type, tag, xmlns, handler);
321 function api:add_iq_handler(origin_type, xmlns, handler)
322 self:add_handler(origin_type, "iq", xmlns, handler);
325 function api:add_feature(xmlns)
326 self:add_item("feature", xmlns);
328 function api:add_identity(category, type, name)
329 self:add_item("identity", {category = category, type = type, name = name});
332 local event_hook = function(host, mod_name, event_name, ...)
333 if type((...)) == "table" and (...).host and (...).host ~= host then return; end
334 for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
338 function api:add_event_hook(name, handler)
339 if not hooked:get(self.host, self.name, name) then
340 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
341 hooked:set(self.host, self.name, name, true);
343 event_hooks:set(self.host, self.name, name, handler, true);
346 function api:fire_event(...)
347 return (hosts[self.host] or prosody).events.fire_event(...);
350 function api:hook(event, handler, priority)
351 hooks:set(self.host, self.name, event, handler, true);
352 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
355 function api:hook_stanza(xmlns, name, handler, priority)
356 if not handler and type(name) == "function" then
357 -- If only 2 options then they specified no xmlns
358 xmlns, name, handler, priority = nil, xmlns, name, handler;
359 elseif not (handler and name) then
360 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
363 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
366 function api:require(lib)
367 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
369 f, n = pluginloader.load_code(lib, lib..".lib.lua");
371 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
372 setfenv(f, setmetatable({ module = self }, { __index = _G }));
376 function api:get_option(name, default_value)
377 return config.get(self.host, self.name, name) or config.get(self.host, "core", name) or default_value;
380 local t_remove = _G.table.remove;
381 local module_items = multitable_new();
382 function api:add_item(key, value)
383 self.items = self.items or {};
384 self.items[key] = self.items[key] or {};
385 t_insert(self.items[key], value);
386 self:fire_event("item-added/"..key, {source = self, item = value});
388 function api:remove_item(key, value)
389 local t = self.items and self.items[key] or NULL;
391 if t[i] == value then
392 t_remove(self.items[key], i);
393 self:fire_event("item-removed/"..key, {source = self, item = value});
399 function api:get_host_items(key)
401 for mod_name, module in pairs(modulemap[self.host]) do
402 module = module.module;
404 for _, item in ipairs(module.items[key] or NULL) do
405 t_insert(result, item);
412 --------------------------------------------------------------------
416 function actions.load(params)
417 --return true, "Module loaded ("..params.module.." on "..params.host..")";
418 return load(params.host, params.module);
421 function actions.unload(params)
422 return unload(params.host, params.module);
425 register_actions("/modules", actions);