Merged with 0.6.
[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                 return true;
162         else -- load failed, unloading
163                 unload(api_instance.host, module_name);
164                 return nil, err;
165         end
166 end
167
168 function get_module(host, name)
169         return modulemap[host] and modulemap[host][name];
170 end
171
172 function is_loaded(host, name)
173         return modulemap[host] and modulemap[host][name] and true;
174 end
175
176 function unload(host, name, ...)
177         local mod = get_module(host, name); 
178         if not mod then return nil, "module-not-loaded"; end
179         
180         if module_has_method(mod, "unload") then
181                 local ok, err = call_module_method(mod, "unload");
182                 if (not ok) and err then
183                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
184                 end
185         end
186         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
187         for _, param in pairs(params or NULL) do
188                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
189                 if handlers then
190                         handler_info[handlers[1]] = nil;
191                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
192                 end
193         end
194         event_hooks:remove(host, name);
195         -- unhook event handlers hooked by module:hook
196         for event, handlers in pairs(hooks:get(host, name) or NULL) do
197                 for handler in pairs(handlers or NULL) do
198                         (hosts[host] or prosody).events.remove_handler(event, handler);
199                 end
200         end
201         hooks:remove(host, name);
202         modulemap[host][name] = nil;
203         return true;
204 end
205
206 function reload(host, name, ...)
207         local mod = get_module(host, name);
208         if not mod then return nil, "module-not-loaded"; end
209
210         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
211         if not _mod then
212                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
213                 return nil, err;
214         end
215
216         local saved;
217
218         if module_has_method(mod, "save") then
219                 local ok, ret, err = call_module_method(mod, "save");
220                 if ok then
221                         saved = ret;
222                 else
223                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
224                         if not config.get(host, "core", "force_module_reload") then
225                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
226                                 return nil, "save-state-failed";
227                         else
228                                 log("warn", "Continuing with reload (using the force)");
229                         end
230                 end
231         end
232
233         unload(host, name, ...);
234         local ok, err = load(host, name, ...);
235         if ok then
236                 mod = get_module(host, name);
237                 if module_has_method(mod, "restore") then
238                         local ok, err = call_module_method(mod, "restore", saved or {})
239                         if (not ok) and err then
240                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
241                         end
242                 end
243                 return true;
244         end
245         return ok, err;
246 end
247
248 function handle_stanza(host, origin, stanza)
249         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
250         if name == "iq" and xmlns == "jabber:client" then
251                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
252                         xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
253                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
254                 else
255                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
256                         return true;
257                 end
258         end
259         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
260         if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
261         if handlers then
262                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
263                 (handlers[1])(origin, stanza);
264                 return true;
265         else
266                 if stanza.attr.xmlns == "jabber:client" then
267                         log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
268                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
269                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
270                         end
271                 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
272                         log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
273                         origin:close("unsupported-stanza-type");
274                 end
275         end
276 end
277
278 function module_has_method(module, method)
279         return type(module.module[method]) == "function";
280 end
281
282 function call_module_method(module, method, ...)
283         if module_has_method(module, method) then       
284                 local f = module.module[method];
285                 return pcall(f, ...);
286         else
287                 return false, "no-such-method";
288         end
289 end
290
291 ----- API functions exposed to modules -----------
292 -- Must all be in api.* 
293
294 -- Returns the name of the current module
295 function api:get_name()
296         return self.name;
297 end
298
299 -- Returns the host that the current module is serving
300 function api:get_host()
301         return self.host;
302 end
303
304 function api:get_host_type()
305         return hosts[self.host].type;
306 end
307
308 function api:set_global()
309         self.host = "*";
310         -- Update the logger
311         local _log = logger.init("mod_"..self.name);
312         self.log = function (self, ...) return _log(...); end;
313         self._log = _log;
314 end
315
316 local function _add_handler(module, origin_type, tag, xmlns, handler)
317         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
318         local msg = (tag == "iq") and "namespace" or "payload namespace";
319         if not handlers then
320                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
321                 handler_info[handler] = module;
322                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
323                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
324         else
325                 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);
326         end
327 end
328
329 function api:add_handler(origin_type, tag, xmlns, handler)
330         if not (origin_type and tag and xmlns and handler) then return false; end
331         if type(origin_type) == "table" then
332                 for _, origin_type in ipairs(origin_type) do
333                         _add_handler(self, origin_type, tag, xmlns, handler);
334                 end
335         else
336                 _add_handler(self, origin_type, tag, xmlns, handler);
337         end
338 end
339 function api:add_iq_handler(origin_type, xmlns, handler)
340         self:add_handler(origin_type, "iq", xmlns, handler);
341 end
342
343 function api:add_feature(xmlns)
344         self:add_item("feature", xmlns);
345 end
346 function api:add_identity(category, type, name)
347         self:add_item("identity", {category = category, type = type, name = name});
348 end
349
350 local event_hook = function(host, mod_name, event_name, ...)
351         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
352         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
353                 handler(...);
354         end
355 end;
356 function api:add_event_hook(name, handler)
357         if not hooked:get(self.host, self.name, name) then
358                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
359                 hooked:set(self.host, self.name, name, true);
360         end
361         event_hooks:set(self.host, self.name, name, handler, true);
362 end
363
364 function api:fire_event(...)
365         return (hosts[self.host] or prosody).events.fire_event(...);
366 end
367
368 function api:hook(event, handler, priority)
369         hooks:set(self.host, self.name, event, handler, true);
370         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
371 end
372
373 function api:hook_stanza(xmlns, name, handler, priority)
374         if not handler and type(name) == "function" then
375                 -- If only 2 options then they specified no xmlns
376                 xmlns, name, handler, priority = nil, xmlns, name, handler;
377         elseif not (handler and name) then
378                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
379                 return;
380         end
381         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
382 end
383
384 function api:require(lib)
385         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
386         if not f then
387                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
388         end
389         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
390         setfenv(f, setmetatable({ module = self }, { __index = _G }));
391         return f();
392 end
393
394 function api:get_option(name, default_value)
395         local value = config.get(self.host, self.name, name);
396         if value == nil then
397                 value = config.get(self.host, "core", name);
398                 if value == nil then
399                         value = default_value;
400                 end
401         end
402         return value;
403 end
404
405 function api:get_option_string(...)
406         local value = self:get_option(...);
407         if type(value) == "table" then
408                 if #value > 1 then
409                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
410                 end
411                 value = value[1];
412         end
413         if value == nil then
414                 return nil;
415         end
416         return tostring(value);
417 end
418
419 function api:get_option_number(name, ...)
420         local value = self:get_option(name, ...);
421         if type(value) == "table" then
422                 if #value > 1 then
423                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
424                 end
425                 value = value[1];
426         end
427         local ret = tonumber(value);
428         if value ~= nil and ret == nil then
429                 self:log("error", "Config option '%s' not understood, expecting a number", name);
430         end
431         return ret;
432 end
433
434 function api:get_option_boolean(name, ...)
435         local value = self:get_option(name, ...);
436         if type(value) == "table" then
437                 if #value > 1 then
438                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
439                 end
440                 value = value[1];
441         end
442         if value == nil then
443                 return nil;
444         end
445         local ret = value == true or value == "true" or value == 1 or nil;
446         if ret == nil then
447                 ret = (value == false or value == "false" or value == 0);
448                 if ret then
449                         ret = false;
450                 else
451                         ret = nil;
452                 end
453         end
454         if ret == nil then
455                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
456         end
457         return ret;
458 end
459
460 function api:get_option_array(name, ...)
461         local value = self:get_option(name, ...);
462
463         if value == nil then
464                 return nil;
465         end
466         
467         if type(value) ~= "table" then
468                 return array{ value }; -- Assume any non-list is a single-item list
469         end
470         
471         return array():append(value); -- Clone
472 end
473
474 function api:get_option_set(name, ...)
475         local value = self:get_option_array(name, ...);
476         
477         if value == nil then
478                 return nil;
479         end
480         
481         return set.new(value);
482 end
483
484 local t_remove = _G.table.remove;
485 local module_items = multitable_new();
486 function api:add_item(key, value)
487         self.items = self.items or {};
488         self.items[key] = self.items[key] or {};
489         t_insert(self.items[key], value);
490         self:fire_event("item-added/"..key, {source = self, item = value});
491 end
492 function api:remove_item(key, value)
493         local t = self.items and self.items[key] or NULL;
494         for i = #t,1,-1 do
495                 if t[i] == value then
496                         t_remove(self.items[key], i);
497                         self:fire_event("item-removed/"..key, {source = self, item = value});
498                         return value;
499                 end
500         end
501 end
502
503 function api:get_host_items(key)
504         local result = {};
505         for mod_name, module in pairs(modulemap[self.host]) do
506                 module = module.module;
507                 if module.items then
508                         for _, item in ipairs(module.items[key] or NULL) do
509                                 t_insert(result, item);
510                         end
511                 end
512         end
513         for mod_name, module in pairs(modulemap["*"]) do
514                 module = module.module;
515                 if module.items then
516                         for _, item in ipairs(module.items[key] or NULL) do
517                                 t_insert(result, item);
518                         end
519                 end
520         end
521         return result;
522 end
523
524 --------------------------------------------------------------------
525
526 local actions = {};
527
528 function actions.load(params)
529         --return true, "Module loaded ("..params.module.." on "..params.host..")";
530         return load(params.host, params.module);
531 end
532
533 function actions.unload(params)
534         return unload(params.host, params.module);
535 end
536
537 register_actions("/modules", actions);
538
539 return _M;