67a77af65050003f646667bdafeba4cd5a005791
[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.intersection(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         elseif not hosts[host] then
95                 return nil, "unknown-host";
96         end
97         
98         if not modulemap[host] then
99                 modulemap[host] = {};
100         end
101         
102         if modulemap[host][module_name] then
103                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
104                 return nil, "module-already-loaded";
105         elseif modulemap["*"][module_name] then
106                 return nil, "global-module-already-loaded";
107         end
108         
109
110         local mod, err = pluginloader.load_code(module_name);
111         if not mod then
112                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
113                 return nil, err;
114         end
115
116         local _log = logger.init(host..":"..module_name);
117         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
118
119         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
120         api_instance.environment = pluginenv;
121         
122         setfenv(mod, pluginenv);
123         hosts[host].modules = modulemap[host];
124         modulemap[host][module_name] = pluginenv;
125         
126         local success, err = pcall(mod);
127         if success then
128                 if module_has_method(pluginenv, "load") then
129                         success, err = call_module_method(pluginenv, "load");
130                         if not success then
131                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
132                         end
133                 end
134
135                 -- Use modified host, if the module set one
136                 if api_instance.host == "*" and host ~= "*" then
137                         modulemap[host][module_name] = nil;
138                         modulemap["*"][module_name] = pluginenv;
139                         api_instance:set_global();
140                 end
141         else
142                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
143         end
144         if success then
145                 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
146                 return true;
147         else -- load failed, unloading
148                 unload(api_instance.host, module_name);
149                 return nil, err;
150         end
151 end
152
153 function get_module(host, name)
154         return modulemap[host] and modulemap[host][name];
155 end
156
157 function is_loaded(host, name)
158         return modulemap[host] and modulemap[host][name] and true;
159 end
160
161 function unload(host, name, ...)
162         local mod = get_module(host, name);
163         if not mod then return nil, "module-not-loaded"; end
164         
165         if module_has_method(mod, "unload") then
166                 local ok, err = call_module_method(mod, "unload");
167                 if (not ok) and err then
168                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
169                 end
170         end
171         -- unhook event handlers hooked by module:hook
172         for event, handlers in pairs(hooks:get(host, name) or NULL) do
173                 for handler in pairs(handlers or NULL) do
174                         (hosts[host] or prosody).events.remove_handler(event, handler);
175                 end
176         end
177         hooks:remove(host, name);
178         if mod.module.items then -- remove items
179                 for key,t in pairs(mod.module.items) do
180                         for i = #t,1,-1 do
181                                 local value = t[i];
182                                 t[i] = nil;
183                                 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
184                         end
185                 end
186         end
187         modulemap[host][name] = nil;
188         (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
189         return true;
190 end
191
192 function reload(host, name, ...)
193         local mod = get_module(host, name);
194         if not mod then return nil, "module-not-loaded"; end
195
196         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
197         if not _mod then
198                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
199                 return nil, err;
200         end
201
202         local saved;
203
204         if module_has_method(mod, "save") then
205                 local ok, ret, err = call_module_method(mod, "save");
206                 if ok then
207                         saved = ret;
208                 else
209                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
210                         if not config.get(host, "core", "force_module_reload") then
211                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
212                                 return nil, "save-state-failed";
213                         else
214                                 log("warn", "Continuing with reload (using the force)");
215                         end
216                 end
217         end
218
219         unload(host, name, ...);
220         local ok, err = load(host, name, ...);
221         if ok then
222                 mod = get_module(host, name);
223                 if module_has_method(mod, "restore") then
224                         local ok, err = call_module_method(mod, "restore", saved or {})
225                         if (not ok) and err then
226                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
227                         end
228                 end
229                 return true;
230         end
231         return ok, err;
232 end
233
234 function module_has_method(module, method)
235         return type(module.module[method]) == "function";
236 end
237
238 function call_module_method(module, method, ...)
239         if module_has_method(module, method) then
240                 local f = module.module[method];
241                 return pcall(f, ...);
242         else
243                 return false, "no-such-method";
244         end
245 end
246
247 ----- API functions exposed to modules -----------
248 -- Must all be in api.*
249
250 -- Returns the name of the current module
251 function api:get_name()
252         return self.name;
253 end
254
255 -- Returns the host that the current module is serving
256 function api:get_host()
257         return self.host;
258 end
259
260 function api:get_host_type()
261         return hosts[self.host].type;
262 end
263
264 function api:set_global()
265         self.host = "*";
266         -- Update the logger
267         local _log = logger.init("mod_"..self.name);
268         self.log = function (self, ...) return _log(...); end;
269         self._log = _log;
270 end
271
272 function api:add_feature(xmlns)
273         self:add_item("feature", xmlns);
274 end
275 function api:add_identity(category, type, name)
276         self:add_item("identity", {category = category, type = type, name = name});
277 end
278
279 function api:fire_event(...)
280         return (hosts[self.host] or prosody).events.fire_event(...);
281 end
282
283 function api:hook(event, handler, priority)
284         hooks:set(self.host, self.name, event, handler, true);
285         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
286 end
287
288 function api:hook_stanza(xmlns, name, handler, priority)
289         if not handler and type(name) == "function" then
290                 -- If only 2 options then they specified no xmlns
291                 xmlns, name, handler, priority = nil, xmlns, name, handler;
292         elseif not (handler and name) then
293                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
294                 return;
295         end
296         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
297 end
298
299 function api:require(lib)
300         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
301         if not f then
302                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
303         end
304         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
305         setfenv(f, self.environment);
306         return f();
307 end
308
309 function api:get_option(name, default_value)
310         local value = config.get(self.host, self.name, name);
311         if value == nil then
312                 value = config.get(self.host, "core", name);
313                 if value == nil then
314                         value = default_value;
315                 end
316         end
317         return value;
318 end
319
320 function api:get_option_string(name, default_value)
321         local value = self:get_option(name, default_value);
322         if type(value) == "table" then
323                 if #value > 1 then
324                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
325                 end
326                 value = value[1];
327         end
328         if value == nil then
329                 return nil;
330         end
331         return tostring(value);
332 end
333
334 function api:get_option_number(name, ...)
335         local value = self:get_option(name, ...);
336         if type(value) == "table" then
337                 if #value > 1 then
338                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
339                 end
340                 value = value[1];
341         end
342         local ret = tonumber(value);
343         if value ~= nil and ret == nil then
344                 self:log("error", "Config option '%s' not understood, expecting a number", name);
345         end
346         return ret;
347 end
348
349 function api:get_option_boolean(name, ...)
350         local value = self:get_option(name, ...);
351         if type(value) == "table" then
352                 if #value > 1 then
353                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
354                 end
355                 value = value[1];
356         end
357         if value == nil then
358                 return nil;
359         end
360         local ret = value == true or value == "true" or value == 1 or nil;
361         if ret == nil then
362                 ret = (value == false or value == "false" or value == 0);
363                 if ret then
364                         ret = false;
365                 else
366                         ret = nil;
367                 end
368         end
369         if ret == nil then
370                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
371         end
372         return ret;
373 end
374
375 function api:get_option_array(name, ...)
376         local value = self:get_option(name, ...);
377
378         if value == nil then
379                 return nil;
380         end
381         
382         if type(value) ~= "table" then
383                 return array{ value }; -- Assume any non-list is a single-item list
384         end
385         
386         return array():append(value); -- Clone
387 end
388
389 function api:get_option_set(name, ...)
390         local value = self:get_option_array(name, ...);
391         
392         if value == nil then
393                 return nil;
394         end
395         
396         return set.new(value);
397 end
398
399 local t_remove = _G.table.remove;
400 local module_items = multitable_new();
401 function api:add_item(key, value)
402         self.items = self.items or {};
403         self.items[key] = self.items[key] or {};
404         t_insert(self.items[key], value);
405         self:fire_event("item-added/"..key, {source = self, item = value});
406 end
407 function api:remove_item(key, value)
408         local t = self.items and self.items[key] or NULL;
409         for i = #t,1,-1 do
410                 if t[i] == value then
411                         t_remove(self.items[key], i);
412                         self:fire_event("item-removed/"..key, {source = self, item = value});
413                         return value;
414                 end
415         end
416 end
417
418 function api:get_host_items(key)
419         local result = {};
420         for mod_name, module in pairs(modulemap[self.host]) do
421                 module = module.module;
422                 if module.items then
423                         for _, item in ipairs(module.items[key] or NULL) do
424                                 t_insert(result, item);
425                         end
426                 end
427         end
428         for mod_name, module in pairs(modulemap["*"]) do
429                 module = module.module;
430                 if module.items then
431                         for _, item in ipairs(module.items[key] or NULL) do
432                                 t_insert(result, item);
433                         end
434                 end
435         end
436         return result;
437 end
438
439 return _M;