d64718507709c137b8129e33f9564008b4f268e0
[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 plugin_dir = CFG_PLUGINDIR or "./plugins/";
10
11 local logger = require "util.logger";
12 local log = logger.init("modulemanager");
13 local config = require "core.configmanager";
14 local multitable_new = require "util.multitable".new;
15 local st = require "util.stanza";
16 local pluginloader = require "util.pluginloader";
17
18 local hosts = hosts;
19 local prosody = prosody;
20 local prosody_events = prosody.events;
21
22 local loadfile, pcall, xpcall = loadfile, pcall, xpcall;
23 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
24 local pairs, ipairs = pairs, ipairs;
25 local t_insert, t_concat = table.insert, table.concat;
26 local type = type;
27 local next = next;
28 local rawget = rawget;
29 local error = error;
30 local tostring, tonumber = tostring, tonumber;
31
32 local debug_traceback = debug.traceback;
33 local unpack, select = unpack, select;
34 pcall = function(f, ...)
35         local n = select("#", ...);
36         local params = {...};
37         return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
38 end
39
40 local array, set = require "util.array", require "util.set";
41
42 local autoload_modules = {"presence", "message", "iq"};
43 local component_inheritable_modules = {"tls", "dialback"};
44
45 -- We need this to let modules access the real global namespace
46 local _G = _G;
47
48 module "modulemanager"
49
50 api = {};
51 local api = api; -- Module API container
52
53 local modulemap = { ["*"] = {} };
54
55 local modulehelpers = setmetatable({}, { __index = _G });
56
57 local hooks = multitable_new();
58
59 local NULL = {};
60
61 -- Load modules when a host is activated
62 function load_modules_for_host(host)
63         local component = config.get(host, "core", "component_module");
64         
65         local global_modules_enabled = config.get("*", "core", "modules_enabled");
66         local global_modules_disabled = config.get("*", "core", "modules_disabled");
67         local host_modules_enabled = config.get(host, "core", "modules_enabled");
68         local host_modules_disabled = config.get(host, "core", "modules_disabled");
69         
70         if host_modules_enabled == global_modules_enabled then host_modules_enabled = nil; end
71         if host_modules_disabled == global_modules_disabled then host_modules_disabled = nil; end
72         
73         local host_modules = set.new(host_modules_enabled) - set.new(host_modules_disabled);
74         local global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
75         if component then
76                 global_modules = set.new(component_inheritable_modules) - global_modules;
77         end
78         local modules = global_modules + host_modules;
79         
80         if component then
81                 load(host, component);
82         end
83         for module in modules do
84                 load(host, module);
85         end
86 end
87 prosody_events.add_handler("host-activated", load_modules_for_host);
88 prosody_events.add_handler("component-activated", load_modules_for_host);
89 --
90
91 function load(host, module_name, config)
92         if not (host and module_name) then
93                 return nil, "insufficient-parameters";
94         end
95         
96         if not modulemap[host] then
97                 modulemap[host] = {};
98         end
99         
100         if modulemap[host][module_name] then
101                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
102                 return nil, "module-already-loaded";
103         elseif modulemap["*"][module_name] then
104                 return nil, "global-module-already-loaded";
105         end
106         
107
108         local mod, err = pluginloader.load_code(module_name);
109         if not mod then
110                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
111                 return nil, err;
112         end
113
114         local _log = logger.init(host..":"..module_name);
115         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
116
117         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
118         api_instance.environment = pluginenv;
119         
120         setfenv(mod, pluginenv);
121         if not hosts[host] then
122                 local create_component = _G.require "core.componentmanager".create_component;
123                 hosts[host] = create_component(host);
124                 log("debug", "Created new component: %s", host);
125         end
126         hosts[host].modules = modulemap[host];
127         modulemap[host][module_name] = pluginenv;
128         
129         local success, err = pcall(mod);
130         if success then
131                 if module_has_method(pluginenv, "load") then
132                         success, err = call_module_method(pluginenv, "load");
133                         if not success then
134                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
135                         end
136                 end
137
138                 -- Use modified host, if the module set one
139                 if api_instance.host == "*" and host ~= "*" then
140                         modulemap[host][module_name] = nil;
141                         modulemap["*"][module_name] = pluginenv;
142                         api_instance:set_global();
143                 end
144         else
145                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
146         end
147         if success then
148                 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
149                 return true;
150         else -- load failed, unloading
151                 unload(api_instance.host, module_name);
152                 return nil, err;
153         end
154 end
155
156 function get_module(host, name)
157         return modulemap[host] and modulemap[host][name];
158 end
159
160 function is_loaded(host, name)
161         return modulemap[host] and modulemap[host][name] and true;
162 end
163
164 function unload(host, name, ...)
165         local mod = get_module(host, name);
166         if not mod then return nil, "module-not-loaded"; end
167         
168         if module_has_method(mod, "unload") then
169                 local ok, err = call_module_method(mod, "unload");
170                 if (not ok) and err then
171                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
172                 end
173         end
174         -- unhook event handlers hooked by module:hook
175         for event, handlers in pairs(hooks:get(host, name) or NULL) do
176                 for handler in pairs(handlers or NULL) do
177                         (hosts[host] or prosody).events.remove_handler(event, handler);
178                 end
179         end
180         hooks:remove(host, name);
181         if mod.module.items then -- remove items
182                 for key,t in pairs(mod.module.items) do
183                         for i = #t,1,-1 do
184                                 local value = t[i];
185                                 t[i] = nil;
186                                 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
187                         end
188                 end
189         end
190         modulemap[host][name] = nil;
191         (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
192         return true;
193 end
194
195 function reload(host, name, ...)
196         local mod = get_module(host, name);
197         if not mod then return nil, "module-not-loaded"; end
198
199         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
200         if not _mod then
201                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
202                 return nil, err;
203         end
204
205         local saved;
206
207         if module_has_method(mod, "save") then
208                 local ok, ret, err = call_module_method(mod, "save");
209                 if ok then
210                         saved = ret;
211                 else
212                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
213                         if not config.get(host, "core", "force_module_reload") then
214                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
215                                 return nil, "save-state-failed";
216                         else
217                                 log("warn", "Continuing with reload (using the force)");
218                         end
219                 end
220         end
221
222         unload(host, name, ...);
223         local ok, err = load(host, name, ...);
224         if ok then
225                 mod = get_module(host, name);
226                 if module_has_method(mod, "restore") then
227                         local ok, err = call_module_method(mod, "restore", saved or {})
228                         if (not ok) and err then
229                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
230                         end
231                 end
232                 return true;
233         end
234         return ok, err;
235 end
236
237 function module_has_method(module, method)
238         return type(module.module[method]) == "function";
239 end
240
241 function call_module_method(module, method, ...)
242         if module_has_method(module, method) then
243                 local f = module.module[method];
244                 return pcall(f, ...);
245         else
246                 return false, "no-such-method";
247         end
248 end
249
250 ----- API functions exposed to modules -----------
251 -- Must all be in api.*
252
253 -- Returns the name of the current module
254 function api:get_name()
255         return self.name;
256 end
257
258 -- Returns the host that the current module is serving
259 function api:get_host()
260         return self.host;
261 end
262
263 function api:get_host_type()
264         return hosts[self.host].type;
265 end
266
267 function api:set_global()
268         self.host = "*";
269         -- Update the logger
270         local _log = logger.init("mod_"..self.name);
271         self.log = function (self, ...) return _log(...); end;
272         self._log = _log;
273 end
274
275 function api:add_feature(xmlns)
276         self:add_item("feature", xmlns);
277 end
278 function api:add_identity(category, type, name)
279         self:add_item("identity", {category = category, type = type, name = name});
280 end
281
282 function api:fire_event(...)
283         return (hosts[self.host] or prosody).events.fire_event(...);
284 end
285
286 function api:hook(event, handler, priority)
287         hooks:set(self.host, self.name, event, handler, true);
288         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
289 end
290
291 function api:hook_stanza(xmlns, name, handler, priority)
292         if not handler and type(name) == "function" then
293                 -- If only 2 options then they specified no xmlns
294                 xmlns, name, handler, priority = nil, xmlns, name, handler;
295         elseif not (handler and name) then
296                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
297                 return;
298         end
299         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
300 end
301
302 function api:require(lib)
303         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
304         if not f then
305                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
306         end
307         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
308         setfenv(f, self.environment);
309         return f();
310 end
311
312 function api:get_option(name, default_value)
313         local value = config.get(self.host, self.name, name);
314         if value == nil then
315                 value = config.get(self.host, "core", name);
316                 if value == nil then
317                         value = default_value;
318                 end
319         end
320         return value;
321 end
322
323 function api:get_option_string(name, default_value)
324         local value = self:get_option(name, default_value);
325         if type(value) == "table" then
326                 if #value > 1 then
327                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
328                 end
329                 value = value[1];
330         end
331         if value == nil then
332                 return nil;
333         end
334         return tostring(value);
335 end
336
337 function api:get_option_number(name, ...)
338         local value = self:get_option(name, ...);
339         if type(value) == "table" then
340                 if #value > 1 then
341                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
342                 end
343                 value = value[1];
344         end
345         local ret = tonumber(value);
346         if value ~= nil and ret == nil then
347                 self:log("error", "Config option '%s' not understood, expecting a number", name);
348         end
349         return ret;
350 end
351
352 function api:get_option_boolean(name, ...)
353         local value = self:get_option(name, ...);
354         if type(value) == "table" then
355                 if #value > 1 then
356                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
357                 end
358                 value = value[1];
359         end
360         if value == nil then
361                 return nil;
362         end
363         local ret = value == true or value == "true" or value == 1 or nil;
364         if ret == nil then
365                 ret = (value == false or value == "false" or value == 0);
366                 if ret then
367                         ret = false;
368                 else
369                         ret = nil;
370                 end
371         end
372         if ret == nil then
373                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
374         end
375         return ret;
376 end
377
378 function api:get_option_array(name, ...)
379         local value = self:get_option(name, ...);
380
381         if value == nil then
382                 return nil;
383         end
384         
385         if type(value) ~= "table" then
386                 return array{ value }; -- Assume any non-list is a single-item list
387         end
388         
389         return array():append(value); -- Clone
390 end
391
392 function api:get_option_set(name, ...)
393         local value = self:get_option_array(name, ...);
394         
395         if value == nil then
396                 return nil;
397         end
398         
399         return set.new(value);
400 end
401
402 local t_remove = _G.table.remove;
403 local module_items = multitable_new();
404 function api:add_item(key, value)
405         self.items = self.items or {};
406         self.items[key] = self.items[key] or {};
407         t_insert(self.items[key], value);
408         self:fire_event("item-added/"..key, {source = self, item = value});
409 end
410 function api:remove_item(key, value)
411         local t = self.items and self.items[key] or NULL;
412         for i = #t,1,-1 do
413                 if t[i] == value then
414                         t_remove(self.items[key], i);
415                         self:fire_event("item-removed/"..key, {source = self, item = value});
416                         return value;
417                 end
418         end
419 end
420
421 function api:get_host_items(key)
422         local result = {};
423         for mod_name, module in pairs(modulemap[self.host]) do
424                 module = module.module;
425                 if module.items then
426                         for _, item in ipairs(module.items[key] or NULL) do
427                                 t_insert(result, item);
428                         end
429                 end
430         end
431         for mod_name, module in pairs(modulemap["*"]) do
432                 module = module.module;
433                 if module.items then
434                         for _, item in ipairs(module.items[key] or NULL) do
435                                 t_insert(result, item);
436                         end
437                 end
438         end
439         return result;
440 end
441
442 return _M;