9f90e34ea8688ba123aecf10648c460a1ee13030
[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 multitable_new = require "util.multitable".new;
13 local st = require "util.stanza";
14 local pluginloader = require "util.pluginloader";
15
16 local hosts = hosts;
17 local prosody = prosody;
18
19 local loadfile, pcall, xpcall = loadfile, pcall, xpcall;
20 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
21 local pairs, ipairs = pairs, ipairs;
22 local t_insert, t_concat = table.insert, table.concat;
23 local type = type;
24 local next = next;
25 local rawget = rawget;
26 local error = error;
27 local tostring, tonumber = tostring, tonumber;
28
29 local debug_traceback = debug.traceback;
30 local unpack, select = unpack, select;
31 pcall = function(f, ...)
32         local n = select("#", ...);
33         local params = {...};
34         return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
35 end
36
37 local array, set = require "util.array", require "util.set";
38
39 local autoload_modules = {"presence", "message", "iq", "offline"};
40 local component_inheritable_modules = {"tls", "dialback", "iq"};
41
42 -- We need this to let modules access the real global namespace
43 local _G = _G;
44
45 module "modulemanager"
46
47 local api = _G.require "core.moduleapi"; -- Module API container
48
49 local modulemap = { ["*"] = {} };
50
51 local modulehelpers = setmetatable({}, { __index = _G });
52
53 local hooks = multitable_new();
54
55 local NULL = {};
56
57 -- Load modules when a host is activated
58 function load_modules_for_host(host)
59         local component = config.get(host, "core", "component_module");
60         
61         local global_modules_enabled = config.get("*", "core", "modules_enabled");
62         local global_modules_disabled = config.get("*", "core", "modules_disabled");
63         local host_modules_enabled = config.get(host, "core", "modules_enabled");
64         local host_modules_disabled = config.get(host, "core", "modules_disabled");
65         
66         if host_modules_enabled == global_modules_enabled then host_modules_enabled = nil; end
67         if host_modules_disabled == global_modules_disabled then host_modules_disabled = nil; end
68         
69         local global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
70         if component then
71                 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
72         end
73         local modules = (global_modules + set.new(host_modules_enabled)) - set.new(host_modules_disabled);
74         
75         -- COMPAT w/ pre 0.8
76         if modules:contains("console") then
77                 log("error", "The mod_console plugin has been renamed to mod_admin_telnet. Please update your config.");
78                 modules:remove("console");
79                 modules:add("admin_telnet");
80         end
81         
82         if component then
83                 load(host, component);
84         end
85         for module in modules do
86                 load(host, module);
87         end
88 end
89 prosody.events.add_handler("host-activated", load_modules_for_host);
90
91 --- Private helpers ---
92
93 local function do_unload_module(host, name)
94         local mod = get_module(host, name);
95         if not mod then return nil, "module-not-loaded"; end
96         
97         if module_has_method(mod, "unload") then
98                 local ok, err = call_module_method(mod, "unload");
99                 if (not ok) and err then
100                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
101                 end
102         end
103         -- unhook event handlers hooked by module:hook
104         for event, handlers in pairs(hooks:get(host, name) or NULL) do
105                 for handler in pairs(handlers or NULL) do
106                         (hosts[host] or prosody).events.remove_handler(event, handler);
107                 end
108         end
109         -- unhook event handlers hooked by module:hook_global
110         for event, handlers in pairs(hooks:get("*", name) or NULL) do
111                 for handler in pairs(handlers or NULL) do
112                         prosody.events.remove_handler(event, handler);
113                 end
114         end
115         hooks:remove(host, name);
116         if mod.module.items then -- remove items
117                 for key,t in pairs(mod.module.items) do
118                         for i = #t,1,-1 do
119                                 local value = t[i];
120                                 t[i] = nil;
121                                 hosts[host].events.fire_event("item-removed/"..key, {source = mod.module, item = value});
122                         end
123                 end
124         end
125         modulemap[host][name] = nil;
126         return true;
127 end
128
129 local function do_load_module(host, module_name)
130         if not (host and module_name) then
131                 return nil, "insufficient-parameters";
132         elseif not hosts[host] then
133                 return nil, "unknown-host";
134         end
135         
136         if not modulemap[host] then
137                 modulemap[host] = {};
138         end
139         
140         if modulemap[host][module_name] then
141                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
142                 return nil, "module-already-loaded";
143         elseif modulemap["*"][module_name] then
144                 return nil, "global-module-already-loaded";
145         end
146         
147
148         local mod, err = pluginloader.load_code(module_name);
149         if not mod then
150                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
151                 return nil, err;
152         end
153
154         local _log = logger.init(host..":"..module_name);
155         local api_instance = setmetatable({ name = module_name, host = host, path = err,
156                 _log = _log, log = function (self, ...) return _log(...); end }
157                 , { __index = api });
158
159         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
160         api_instance.environment = pluginenv;
161         
162         setfenv(mod, pluginenv);
163         hosts[host].modules = modulemap[host];
164         modulemap[host][module_name] = pluginenv;
165         
166         local ok, err = pcall(mod);
167         if ok then
168                 -- Call module's "load"
169                 if module_has_method(pluginenv, "load") then
170                         ok, err = call_module_method(pluginenv, "load");
171                         if not ok then
172                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
173                         end
174                 end
175
176                 -- Use modified host, if the module set one
177                 if api_instance.host == "*" and host ~= "*" then
178                         modulemap[host][module_name] = nil;
179                         modulemap["*"][module_name] = pluginenv;
180                         api_instance:set_global();
181                 end
182         else
183                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
184                 do_unload_module(api_instance.host, module_name); -- Ignore error, module may be partially-loaded
185         end
186         return ok and mod, err;
187 end
188
189 local function do_reload_module(host, name)
190         local mod = get_module(host, name);
191         if not mod then return nil, "module-not-loaded"; end
192
193         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
194         if not _mod then
195                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
196                 return nil, err;
197         end
198
199         local saved;
200
201         if module_has_method(mod, "save") then
202                 local ok, ret, err = call_module_method(mod, "save");
203                 if ok then
204                         saved = ret;
205                 else
206                         log("warn", "Error saving module '%s:%s' state: %s", host, name, 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";
210                         else
211                                 log("warn", "Continuing with reload (using the force)");
212                         end
213                 end
214         end
215
216         do_unload_module(host, name);
217         local ok, err = do_load_module(host, name);
218         if ok then
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);
224                         end
225                 end
226         end
227         return ok and mod, err;
228 end
229
230 --- Public API ---
231
232 -- Load a module and fire module-loaded event
233 function load(host, name)
234         local mod, err = do_load_module(host, name);
235         if mod then
236                 (hosts[mod.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
237         end
238         return mod, err;
239 end
240
241 -- Unload a module and fire module-unloaded
242 function unload(host, name)
243         local ok, err = do_unload_module(host, name);
244         if ok then
245                 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
246         end
247         return ok, err;
248 end
249
250 function reload(host, name)
251         local ok, err = do_reload_module(host, name);
252         if ok then
253                 (hosts[host] or prosody).events.fire_event("module-reloaded", { module = name, host = host });
254         elseif not is_loaded(host, name) then
255                 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
256         end
257         return ok, err;
258 end
259
260 function get_module(host, name)
261         return modulemap[host] and modulemap[host][name];
262 end
263
264 function get_modules(host)
265         return modulemap[host];
266 end
267
268 function is_loaded(host, name)
269         return modulemap[host] and modulemap[host][name] and true;
270 end
271
272 function module_has_method(module, method)
273         return type(module.module[method]) == "function";
274 end
275
276 function call_module_method(module, method, ...)
277         if module_has_method(module, method) then
278                 local f = module.module[method];
279                 return pcall(f, ...);
280         else
281                 return false, "no-such-method";
282         end
283 end
284
285 return _M;