6440f8b82e389a3f701708b87cbec9ac52ccfa47
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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 eventmanager = require "core.eventmanager";
14 local config = require "core.configmanager";
15 local multitable_new = require "util.multitable".new;
16 local register_actions = require "core.actions".register;
17 local st = require "util.stanza";
18 local pluginloader = require "util.pluginloader";
19
20 local hosts = hosts;
21 local prosody = prosody;
22
23 local loadfile, pcall = loadfile, pcall;
24 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
25 local pairs, ipairs = pairs, ipairs;
26 local t_insert, t_concat = table.insert, table.concat;
27 local type = type;
28 local next = next;
29 local rawget = rawget;
30 local error = error;
31 local tostring, tonumber = tostring, tonumber;
32
33 local array, set = require "util.array", require "util.set";
34
35 local autoload_modules = {"presence", "message", "iq"};
36
37 -- We need this to let modules access the real global namespace
38 local _G = _G;
39
40 module "modulemanager"
41
42 api = {};
43 local api = api; -- Module API container
44
45 local modulemap = { ["*"] = {} };
46
47 local stanza_handlers = multitable_new();
48 local handler_info = {};
49
50 local modulehelpers = setmetatable({}, { __index = _G });
51
52 local handler_table = multitable_new();
53 local hooked = multitable_new();
54 local hooks = multitable_new();
55 local event_hooks = multitable_new();
56
57 local NULL = {};
58
59 -- Load modules when a host is activated
60 function load_modules_for_host(host)
61         local disabled_set = {};
62         local modules_disabled = config.get(host, "core", "modules_disabled");
63         if modules_disabled then
64                 for _, module in ipairs(modules_disabled) do
65                         disabled_set[module] = true;
66                 end
67         end
68
69         -- Load auto-loaded modules for this host
70         if hosts[host].type == "local" then
71                 for _, module in ipairs(autoload_modules) do
72                         if not disabled_set[module] then
73                                 load(host, module);
74                         end
75                 end
76         end
77
78         -- Load modules from global section
79         if config.get(host, "core", "load_global_modules") ~= false then
80                 local modules_enabled = config.get("*", "core", "modules_enabled");
81                 if modules_enabled then
82                         for _, module in ipairs(modules_enabled) do
83                                 if not disabled_set[module] and not is_loaded(host, module) then
84                                         load(host, module);
85                                 end
86                         end
87                 end
88         end
89         
90         -- Load modules from just this host
91         local modules_enabled = config.get(host, "core", "modules_enabled");
92         if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
93                 for _, module in pairs(modules_enabled) do
94                         if not is_loaded(host, module) then
95                                 load(host, module);
96                         end
97                 end
98         end
99 end
100 eventmanager.add_event_hook("host-activated", load_modules_for_host);
101 eventmanager.add_event_hook("component-activated", load_modules_for_host);
102 --
103
104 function load(host, module_name, config)
105         if not (host and module_name) then
106                 return nil, "insufficient-parameters";
107         end
108         
109         if not modulemap[host] then
110                 modulemap[host] = {};
111         end
112         
113         if modulemap[host][module_name] then
114                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
115                 return nil, "module-already-loaded";
116         elseif modulemap["*"][module_name] then
117                 return nil, "global-module-already-loaded";
118         end
119         
120
121         local mod, err = pluginloader.load_code(module_name);
122         if not mod then
123                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
124                 return nil, err;
125         end
126
127         local _log = logger.init(host..":"..module_name);
128         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
129
130         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
131         
132         setfenv(mod, pluginenv);
133         if not hosts[host] then
134                 local create_component = _G.require "core.componentmanager".create_component;
135                 hosts[host] = create_component(host);
136                 hosts[host].connected = false;
137                 log("debug", "Created new component: %s", host);
138         end
139         hosts[host].modules = modulemap[host];
140         modulemap[host][module_name] = pluginenv;
141         
142         local success, err = pcall(mod);
143         if success then
144                 if module_has_method(pluginenv, "load") then
145                         success, err = call_module_method(pluginenv, "load");
146                         if not success then
147                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
148                         end
149                 end
150
151                 -- Use modified host, if the module set one
152                 if api_instance.host == "*" and host ~= "*" then
153                         modulemap[host][module_name] = nil;
154                         modulemap["*"][module_name] = pluginenv;
155                         api_instance:set_global();
156                 end
157         else
158                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
159         end
160         if success then
161                 hosts[host].events.fire_event("module-loaded", { module = module_name, host = host });
162                 return true;
163         else -- load failed, unloading
164                 unload(api_instance.host, module_name);
165                 return nil, err;
166         end
167 end
168
169 function get_module(host, name)
170         return modulemap[host] and modulemap[host][name];
171 end
172
173 function is_loaded(host, name)
174         return modulemap[host] and modulemap[host][name] and true;
175 end
176
177 function unload(host, name, ...)
178         local mod = get_module(host, name); 
179         if not mod then return nil, "module-not-loaded"; end
180         
181         if module_has_method(mod, "unload") then
182                 local ok, err = call_module_method(mod, "unload");
183                 if (not ok) and err then
184                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
185                 end
186         end
187         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
188         for _, param in pairs(params or NULL) do
189                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
190                 if handlers then
191                         handler_info[handlers[1]] = nil;
192                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
193                 end
194         end
195         event_hooks:remove(host, name);
196         -- unhook event handlers hooked by module:hook
197         for event, handlers in pairs(hooks:get(host, name) or NULL) do
198                 for handler in pairs(handlers or NULL) do
199                         (hosts[host] or prosody).events.remove_handler(event, handler);
200                 end
201         end
202         hooks:remove(host, name);
203         modulemap[host][name] = nil;
204         hosts[host].events.fire_event("module-unloaded", { module = name, host = host });
205         return true;
206 end
207
208 function reload(host, name, ...)
209         local mod = get_module(host, name);
210         if not mod then return nil, "module-not-loaded"; end
211
212         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
213         if not _mod then
214                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
215                 return nil, err;
216         end
217
218         local saved;
219
220         if module_has_method(mod, "save") then
221                 local ok, ret, err = call_module_method(mod, "save");
222                 if ok then
223                         saved = ret;
224                 else
225                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
226                         if not config.get(host, "core", "force_module_reload") then
227                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
228                                 return nil, "save-state-failed";
229                         else
230                                 log("warn", "Continuing with reload (using the force)");
231                         end
232                 end
233         end
234
235         unload(host, name, ...);
236         local ok, err = load(host, name, ...);
237         if ok then
238                 mod = get_module(host, name);
239                 if module_has_method(mod, "restore") then
240                         local ok, err = call_module_method(mod, "restore", saved or {})
241                         if (not ok) and err then
242                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
243                         end
244                 end
245                 return true;
246         end
247         return ok, err;
248 end
249
250 function handle_stanza(host, origin, stanza)
251         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
252         if name == "iq" and xmlns == "jabber:client" then
253                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
254                         xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
255                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
256                 else
257                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
258                         return true;
259                 end
260         end
261         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
262         if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
263         if handlers then
264                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
265                 (handlers[1])(origin, stanza);
266                 return true;
267         else
268                 if stanza.attr.xmlns == "jabber:client" then
269                         log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
270                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
271                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
272                         end
273                 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
274                         log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
275                         origin:close("unsupported-stanza-type");
276                 end
277         end
278 end
279
280 function module_has_method(module, method)
281         return type(module.module[method]) == "function";
282 end
283
284 function call_module_method(module, method, ...)
285         if module_has_method(module, method) then       
286                 local f = module.module[method];
287                 return pcall(f, ...);
288         else
289                 return false, "no-such-method";
290         end
291 end
292
293 ----- API functions exposed to modules -----------
294 -- Must all be in api.* 
295
296 -- Returns the name of the current module
297 function api:get_name()
298         return self.name;
299 end
300
301 -- Returns the host that the current module is serving
302 function api:get_host()
303         return self.host;
304 end
305
306 function api:get_host_type()
307         return hosts[self.host].type;
308 end
309
310 function api:set_global()
311         self.host = "*";
312         -- Update the logger
313         local _log = logger.init("mod_"..self.name);
314         self.log = function (self, ...) return _log(...); end;
315         self._log = _log;
316 end
317
318 local function _add_handler(module, origin_type, tag, xmlns, handler)
319         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
320         local msg = (tag == "iq") and "namespace" or "payload namespace";
321         if not handlers then
322                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
323                 handler_info[handler] = module;
324                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
325                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
326         else
327                 module:log("warn", "I wanted to handle tag '%s' [%s] with %s '%s' but mod_%s already handles that", tag, origin_type, msg, xmlns, handler_info[handlers[1]].module.name);
328         end
329 end
330
331 function api:add_handler(origin_type, tag, xmlns, handler)
332         if not (origin_type and tag and xmlns and handler) then return false; end
333         if type(origin_type) == "table" then
334                 for _, origin_type in ipairs(origin_type) do
335                         _add_handler(self, origin_type, tag, xmlns, handler);
336                 end
337         else
338                 _add_handler(self, origin_type, tag, xmlns, handler);
339         end
340 end
341 function api:add_iq_handler(origin_type, xmlns, handler)
342         self:add_handler(origin_type, "iq", xmlns, handler);
343 end
344
345 function api:add_feature(xmlns)
346         self:add_item("feature", xmlns);
347 end
348 function api:add_identity(category, type, name)
349         self:add_item("identity", {category = category, type = type, name = name});
350 end
351
352 local event_hook = function(host, mod_name, event_name, ...)
353         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
354         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
355                 handler(...);
356         end
357 end;
358 function api:add_event_hook(name, handler)
359         if not hooked:get(self.host, self.name, name) then
360                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
361                 hooked:set(self.host, self.name, name, true);
362         end
363         event_hooks:set(self.host, self.name, name, handler, true);
364 end
365
366 function api:fire_event(...)
367         return (hosts[self.host] or prosody).events.fire_event(...);
368 end
369
370 function api:hook(event, handler, priority)
371         hooks:set(self.host, self.name, event, handler, true);
372         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
373 end
374
375 function api:hook_stanza(xmlns, name, handler, priority)
376         if not handler and type(name) == "function" then
377                 -- If only 2 options then they specified no xmlns
378                 xmlns, name, handler, priority = nil, xmlns, name, handler;
379         elseif not (handler and name) then
380                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
381                 return;
382         end
383         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
384 end
385
386 function api:require(lib)
387         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
388         if not f then
389                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
390         end
391         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
392         setfenv(f, setmetatable({ module = self }, { __index = _G }));
393         return f();
394 end
395
396 function api:get_option(name, default_value)
397         local value = config.get(self.host, self.name, name);
398         if value == nil then
399                 value = config.get(self.host, "core", name);
400                 if value == nil then
401                         value = default_value;
402                 end
403         end
404         return value;
405 end
406
407 function api:get_option_string(...)
408         local value = self:get_option(...);
409         if type(value) == "table" then
410                 if #value > 1 then
411                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
412                 end
413                 value = value[1];
414         end
415         if value == nil then
416                 return nil;
417         end
418         return tostring(value);
419 end
420
421 function api:get_option_number(name, ...)
422         local value = self:get_option(name, ...);
423         if type(value) == "table" then
424                 if #value > 1 then
425                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
426                 end
427                 value = value[1];
428         end
429         local ret = tonumber(value);
430         if value ~= nil and ret == nil then
431                 self:log("error", "Config option '%s' not understood, expecting a number", name);
432         end
433         return ret;
434 end
435
436 function api:get_option_boolean(name, ...)
437         local value = self:get_option(name, ...);
438         if type(value) == "table" then
439                 if #value > 1 then
440                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
441                 end
442                 value = value[1];
443         end
444         if value == nil then
445                 return nil;
446         end
447         local ret = value == true or value == "true" or value == 1 or nil;
448         if ret == nil then
449                 ret = (value == false or value == "false" or value == 0);
450                 if ret then
451                         ret = false;
452                 else
453                         ret = nil;
454                 end
455         end
456         if ret == nil then
457                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
458         end
459         return ret;
460 end
461
462 function api:get_option_array(name, ...)
463         local value = self:get_option(name, ...);
464
465         if value == nil then
466                 return nil;
467         end
468         
469         if type(value) ~= "table" then
470                 return array{ value }; -- Assume any non-list is a single-item list
471         end
472         
473         return array():append(value); -- Clone
474 end
475
476 function api:get_option_set(name, ...)
477         local value = self:get_option_array(name, ...);
478         
479         if value == nil then
480                 return nil;
481         end
482         
483         return set.new(value);
484 end
485
486 local t_remove = _G.table.remove;
487 local module_items = multitable_new();
488 function api:add_item(key, value)
489         self.items = self.items or {};
490         self.items[key] = self.items[key] or {};
491         t_insert(self.items[key], value);
492         self:fire_event("item-added/"..key, {source = self, item = value});
493 end
494 function api:remove_item(key, value)
495         local t = self.items and self.items[key] or NULL;
496         for i = #t,1,-1 do
497                 if t[i] == value then
498                         t_remove(self.items[key], i);
499                         self:fire_event("item-removed/"..key, {source = self, item = value});
500                         return value;
501                 end
502         end
503 end
504
505 function api:get_host_items(key)
506         local result = {};
507         for mod_name, module in pairs(modulemap[self.host]) do
508                 module = module.module;
509                 if module.items then
510                         for _, item in ipairs(module.items[key] or NULL) do
511                                 t_insert(result, item);
512                         end
513                 end
514         end
515         for mod_name, module in pairs(modulemap["*"]) do
516                 module = module.module;
517                 if module.items then
518                         for _, item in ipairs(module.items[key] or NULL) do
519                                 t_insert(result, item);
520                         end
521                 end
522         end
523         return result;
524 end
525
526 --------------------------------------------------------------------
527
528 local actions = {};
529
530 function actions.load(params)
531         --return true, "Module loaded ("..params.module.." on "..params.host..")";
532         return load(params.host, params.module);
533 end
534
535 function actions.unload(params)
536         return unload(params.host, params.module);
537 end
538
539 register_actions("/modules", actions);
540
541 return _M;