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