Merge 0.9->0.10
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local logger = require "util.logger";
10 local log = logger.init("modulemanager");
11 local config = require "core.configmanager";
12 local pluginloader = require "util.pluginloader";
13 local set = require "util.set";
14
15 local new_multitable = require "util.multitable".new;
16
17 local hosts = hosts;
18 local prosody = prosody;
19
20 local xpcall = xpcall;
21 local setmetatable, rawget = setmetatable, rawget;
22 local ipairs, pairs, type, tostring, t_insert = ipairs, pairs, type, tostring, table.insert;
23
24 local debug_traceback = debug.traceback;
25 local unpack, select = unpack, select;
26 local pcall = function(f, ...)
27         local n = select("#", ...);
28         local params = {...};
29         return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
30 end
31
32 local autoload_modules = {prosody.platform, "presence", "message", "iq", "offline", "c2s", "s2s", "s2s_auth_certs"};
33 local component_inheritable_modules = {"tls", "saslauth", "dialback", "iq", "s2s"};
34
35 -- We need this to let modules access the real global namespace
36 local _G = _G;
37
38 module "modulemanager"
39
40 local api = _G.require "core.moduleapi".init(_M); -- Module API container
41
42 -- [host] = { [module] = module_env }
43 local modulemap = { ["*"] = {} };
44
45 -- Load modules when a host is activated
46 function load_modules_for_host(host)
47         local component = config.get(host, "component_module");
48
49         local global_modules_enabled = config.get("*", "modules_enabled");
50         local global_modules_disabled = config.get("*", "modules_disabled");
51         local host_modules_enabled = config.get(host, "modules_enabled");
52         local host_modules_disabled = config.get(host, "modules_disabled");
53
54         if host_modules_enabled == global_modules_enabled then host_modules_enabled = nil; end
55         if host_modules_disabled == global_modules_disabled then host_modules_disabled = nil; end
56
57         local global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
58         if component then
59                 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
60         end
61         local modules = (global_modules + set.new(host_modules_enabled)) - set.new(host_modules_disabled);
62
63         -- COMPAT w/ pre 0.8
64         if modules:contains("console") then
65                 log("error", "The mod_console plugin has been renamed to mod_admin_telnet. Please update your config.");
66                 modules:remove("console");
67                 modules:add("admin_telnet");
68         end
69
70         if component then
71                 load(host, component);
72         end
73         for module in modules do
74                 load(host, module);
75         end
76 end
77 prosody.events.add_handler("host-activated", load_modules_for_host);
78 prosody.events.add_handler("host-deactivated", function (host)
79         modulemap[host] = nil;
80 end);
81
82 --- Private helpers ---
83
84 local function do_unload_module(host, name)
85         local mod = get_module(host, name);
86         if not mod then return nil, "module-not-loaded"; end
87
88         if module_has_method(mod, "unload") then
89                 local ok, err = call_module_method(mod, "unload");
90                 if (not ok) and err then
91                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
92                 end
93         end
94
95         for object, event, handler in mod.module.event_handlers:iter(nil, nil, nil) do
96                 object.remove_handler(event, handler);
97         end
98
99         if mod.module.items then -- remove items
100                 local events = (host == "*" and prosody.events) or hosts[host].events;
101                 for key,t in pairs(mod.module.items) do
102                         for i = #t,1,-1 do
103                                 local value = t[i];
104                                 t[i] = nil;
105                                 events.fire_event("item-removed/"..key, {source = mod.module, item = value});
106                         end
107                 end
108         end
109         mod.module.loaded = false;
110         modulemap[host][name] = nil;
111         return true;
112 end
113
114 local function do_load_module(host, module_name, state)
115         if not (host and module_name) then
116                 return nil, "insufficient-parameters";
117         elseif not hosts[host] and host ~= "*"then
118                 return nil, "unknown-host";
119         end
120
121         if not modulemap[host] then
122                 modulemap[host] = hosts[host].modules;
123         end
124
125         if modulemap[host][module_name] then
126                 log("debug", "%s is already loaded for %s, so not loading again", module_name, host);
127                 return nil, "module-already-loaded";
128         elseif modulemap["*"][module_name] then
129                 local mod = modulemap["*"][module_name];
130                 if module_has_method(mod, "add_host") then
131                         local _log = logger.init(host..":"..module_name);
132                         local host_module_api = setmetatable({
133                                 host = host, event_handlers = new_multitable(), items = {};
134                                 _log = _log, log = function (self, ...) return _log(...); end; --luacheck: ignore 212/self
135                         },{
136                                 __index = modulemap["*"][module_name].module;
137                         });
138                         local host_module = setmetatable({ module = host_module_api }, { __index = mod });
139                         host_module_api.environment = host_module;
140                         modulemap[host][module_name] = host_module;
141                         local ok, result, module_err = call_module_method(mod, "add_host", host_module_api);
142                         if not ok or result == false then
143                                 modulemap[host][module_name] = nil;
144                                 return nil, ok and module_err or result;
145                         end
146                         return host_module;
147                 end
148                 return nil, "global-module-already-loaded";
149         end
150
151
152
153         local _log = logger.init(host..":"..module_name);
154         local api_instance = setmetatable({ name = module_name, host = host,
155                 _log = _log, log = function (self, ...) return _log(...); end, --luacheck: ignore 212/self
156                 event_handlers = new_multitable(), reloading = not not state,
157                 saved_state = state~=true and state or nil }
158                 , { __index = api });
159
160         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
161         api_instance.environment = pluginenv;
162
163         local mod, err = pluginloader.load_code(module_name, nil, pluginenv);
164         if not mod then
165                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
166                 return nil, err;
167         end
168
169         api_instance.path = err;
170
171         modulemap[host][module_name] = pluginenv;
172         local ok, err = pcall(mod);
173         if ok then
174                 -- Call module's "load"
175                 if module_has_method(pluginenv, "load") then
176                         ok, err = call_module_method(pluginenv, "load");
177                         if not ok then
178                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
179                         end
180                 end
181                 api_instance.reloading, api_instance.saved_state = nil, nil;
182
183                 if api_instance.host == "*" then
184                         if not api_instance.global then -- COMPAT w/pre-0.9
185                                 if host ~= "*" then
186                                         log("warn", "mod_%s: Setting module.host = '*' deprecated, call module:set_global() instead", module_name);
187                                 end
188                                 api_instance:set_global();
189                         end
190                         modulemap[host][module_name] = nil;
191                         modulemap[api_instance.host][module_name] = pluginenv;
192                         if host ~= api_instance.host and module_has_method(pluginenv, "add_host") then
193                                 -- Now load the module again onto the host it was originally being loaded on
194                                 ok, err = do_load_module(host, module_name);
195                         end
196                 end
197         end
198         if not ok then
199                 modulemap[api_instance.host][module_name] = nil;
200                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
201         end
202         return ok and pluginenv, err;
203 end
204
205 local function do_reload_module(host, name)
206         local mod = get_module(host, name);
207         if not mod then return nil, "module-not-loaded"; end
208
209         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
210         if not _mod then
211                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
212                 return nil, err;
213         end
214
215         local saved;
216         if module_has_method(mod, "save") then
217                 local ok, ret, err = call_module_method(mod, "save");
218                 if ok then
219                         saved = ret;
220                 else
221                         log("warn", "Error saving module '%s:%s' state: %s", host, name, ret);
222                         if not config.get(host, "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";
225                         else
226                                 log("warn", "Continuing with reload (using the force)");
227                         end
228                 end
229         end
230
231         mod.module.reloading = true;
232         do_unload_module(host, name);
233         local ok, err = do_load_module(host, name, saved or true);
234         if ok then
235                 mod = get_module(host, name);
236                 if module_has_method(mod, "restore") then
237                         local ok, err = call_module_method(mod, "restore", saved or {})
238                         if (not ok) and err then
239                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
240                         end
241                 end
242         end
243         return ok and mod, err;
244 end
245
246 --- Public API ---
247
248 -- Load a module and fire module-loaded event
249 function load(host, name)
250         local mod, err = do_load_module(host, name);
251         if mod then
252                 (hosts[mod.module.host] or prosody).events.fire_event("module-loaded", { module = name, host = mod.module.host });
253         end
254         return mod, err;
255 end
256
257 -- Unload a module and fire module-unloaded
258 function unload(host, name)
259         local ok, err = do_unload_module(host, name);
260         if ok then
261                 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
262         end
263         return ok, err;
264 end
265
266 function reload(host, name)
267         local mod, err = do_reload_module(host, name);
268         if mod then
269                 modulemap[host][name].module.reloading = true;
270                 (hosts[host] or prosody).events.fire_event("module-reloaded", { module = name, host = host });
271                 mod.module.reloading = nil;
272         elseif not is_loaded(host, name) then
273                 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
274         end
275         return mod, err;
276 end
277
278 function get_module(host, name)
279         return modulemap[host] and modulemap[host][name];
280 end
281
282 function get_items(key, host)
283         local result = {};
284         local modules = modulemap[host];
285         if not key or not host or not modules then return nil; end
286
287         for _, module in pairs(modules) do
288                 local mod = module.module;
289                 if mod.items and mod.items[key] then
290                         for _, value in ipairs(mod.items[key]) do
291                                 t_insert(result, value);
292                         end
293                 end
294         end
295
296         return result;
297 end
298
299 function get_modules(host)
300         return modulemap[host];
301 end
302
303 function is_loaded(host, name)
304         return modulemap[host] and modulemap[host][name] and true;
305 end
306
307 function module_has_method(module, method)
308         return type(rawget(module.module, method)) == "function";
309 end
310
311 function call_module_method(module, method, ...)
312         local f = rawget(module.module, method);
313         if type(f) == "function" then
314                 return pcall(f, ...);
315         else
316                 return false, "no-such-method";
317         end
318 end
319
320 return _M;