modulemanager: Fixed: Stanza modules were being auto-loaded for components (regressio...
[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 = tostring;
32
33 local autoload_modules = {"presence", "message", "iq"};
34
35 -- We need this to let modules access the real global namespace
36 local _G = _G;
37
38 module "modulemanager"
39
40 api = {};
41 local api = api; -- Module API container
42
43 local modulemap = { ["*"] = {} };
44
45 local stanza_handlers = multitable_new();
46 local handler_info = {};
47
48 local modulehelpers = setmetatable({}, { __index = _G });
49
50 local handler_table = multitable_new();
51 local hooked = multitable_new();
52 local hooks = multitable_new();
53 local event_hooks = multitable_new();
54
55 local NULL = {};
56
57 -- Load modules when a host is activated
58 function load_modules_for_host(host)
59         local disabled_set = {};
60         local modules_disabled = config.get(host, "core", "modules_disabled");
61         if modules_disabled then
62                 for _, module in ipairs(modules_disabled) do
63                         disabled_set[module] = true;
64                 end
65         end
66
67         -- Load auto-loaded modules for this host
68         if hosts[host].type == "local" then
69                 for _, module in ipairs(autoload_modules) do
70                         if not disabled_set[module] then
71                                 load(host, module);
72                         end
73                 end
74         end
75
76         -- Load modules from global section
77         if config.get(host, "core", "load_global_modules") ~= false then
78                 local modules_enabled = config.get("*", "core", "modules_enabled");
79                 if modules_enabled then
80                         for _, module in ipairs(modules_enabled) do
81                                 if not disabled_set[module] and not is_loaded(host, module) then
82                                         load(host, module);
83                                 end
84                         end
85                 end
86         end
87         
88         -- Load modules from just this host
89         local modules_enabled = config.get(host, "core", "modules_enabled");
90         if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
91                 for _, module in pairs(modules_enabled) do
92                         if not is_loaded(host, module) then
93                                 load(host, module);
94                         end
95                 end
96         end
97 end
98 eventmanager.add_event_hook("host-activated", load_modules_for_host);
99 eventmanager.add_event_hook("component-activated", load_modules_for_host);
100 --
101
102 function load(host, module_name, config)
103         if not (host and module_name) then
104                 return nil, "insufficient-parameters";
105         end
106         
107         if not modulemap[host] then
108                 modulemap[host] = {};
109         end
110         
111         if modulemap[host][module_name] then
112                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
113                 return nil, "module-already-loaded";
114         elseif modulemap["*"][module_name] then
115                 return nil, "global-module-already-loaded";
116         end
117         
118
119         local mod, err = pluginloader.load_code(module_name);
120         if not mod then
121                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
122                 return nil, err;
123         end
124
125         local _log = logger.init(host..":"..module_name);
126         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
127
128         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
129         
130         setfenv(mod, pluginenv);
131         if not hosts[host] then hosts[host] = { type = "component", host = host, connected = false, s2sout = {} }; end
132         hosts[host].modules = modulemap[host];
133         
134         local success, ret = pcall(mod);
135         if not success then
136                 log("error", "Error initialising module '%s': %s", module_name or "nil", ret or "nil");
137                 return nil, ret;
138         end
139         
140         if module_has_method(pluginenv, "load") then
141                 local ok, err = call_module_method(pluginenv, "load");
142                 if (not ok) and err then
143                         log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err);
144                 end
145         end
146
147         -- Use modified host, if the module set one
148         modulemap[api_instance.host][module_name] = pluginenv;
149         
150         if api_instance.host == "*" and host ~= "*" then
151                 api_instance:set_global();
152         end
153                 
154         return true;
155 end
156
157 function get_module(host, name)
158         return modulemap[host] and modulemap[host][name];
159 end
160
161 function is_loaded(host, name)
162         return modulemap[host] and modulemap[host][name] and true;
163 end
164
165 function unload(host, name, ...)
166         local mod = get_module(host, name); 
167         if not mod then return nil, "module-not-loaded"; end
168         
169         if module_has_method(mod, "unload") then
170                 local ok, err = call_module_method(mod, "unload");
171                 if (not ok) and err then
172                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
173                 end
174         end
175         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
176         for _, param in pairs(params or NULL) do
177                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
178                 if handlers then
179                         handler_info[handlers[1]] = nil;
180                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
181                 end
182         end
183         event_hooks:remove(host, name);
184         -- unhook event handlers hooked by module:hook
185         for event, handlers in pairs(hooks:get(host, name) or NULL) do
186                 for handler in pairs(handlers or NULL) do
187                         (hosts[host] or prosody).events.remove_handler(event, handler);
188                 end
189         end
190         hooks:remove(host, name);
191         modulemap[host][name] = nil;
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 handle_stanza(host, origin, stanza)
238         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
239         if name == "iq" and xmlns == "jabber:client" then
240                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
241                         xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
242                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
243                 else
244                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
245                         return true;
246                 end
247         end
248         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
249         if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
250         if handlers then
251                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
252                 (handlers[1])(origin, stanza);
253                 return true;
254         else
255                 if stanza.attr.xmlns == "jabber:client" then
256                         log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
257                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
258                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
259                         end
260                 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
261                         log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
262                         origin:close("unsupported-stanza-type");
263                 end
264         end
265 end
266
267 function module_has_method(module, method)
268         return type(module.module[method]) == "function";
269 end
270
271 function call_module_method(module, method, ...)
272         if module_has_method(module, method) then       
273                 local f = module.module[method];
274                 return pcall(f, ...);
275         else
276                 return false, "no-such-method";
277         end
278 end
279
280 ----- API functions exposed to modules -----------
281 -- Must all be in api.* 
282
283 -- Returns the name of the current module
284 function api:get_name()
285         return self.name;
286 end
287
288 -- Returns the host that the current module is serving
289 function api:get_host()
290         return self.host;
291 end
292
293 function api:get_host_type()
294         return hosts[self.host].type;
295 end
296
297 function api:set_global()
298         self.host = "*";
299         -- Update the logger
300         local _log = logger.init("mod_"..self.name);
301         self.log = function (self, ...) return _log(...); end;
302         self._log = _log;
303 end
304
305 local function _add_handler(module, origin_type, tag, xmlns, handler)
306         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
307         local msg = (tag == "iq") and "namespace" or "payload namespace";
308         if not handlers then
309                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
310                 handler_info[handler] = module;
311                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
312                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
313         else
314                 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);
315         end
316 end
317
318 function api:add_handler(origin_type, tag, xmlns, handler)
319         if not (origin_type and tag and xmlns and handler) then return false; end
320         if type(origin_type) == "table" then
321                 for _, origin_type in ipairs(origin_type) do
322                         _add_handler(self, origin_type, tag, xmlns, handler);
323                 end
324         else
325                 _add_handler(self, origin_type, tag, xmlns, handler);
326         end
327 end
328 function api:add_iq_handler(origin_type, xmlns, handler)
329         self:add_handler(origin_type, "iq", xmlns, handler);
330 end
331
332 function api:add_feature(xmlns)
333         self:add_item("feature", xmlns);
334 end
335 function api:add_identity(category, type, name)
336         self:add_item("identity", {category = category, type = type, name = name});
337 end
338
339 local event_hook = function(host, mod_name, event_name, ...)
340         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
341         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
342                 handler(...);
343         end
344 end;
345 function api:add_event_hook(name, handler)
346         if not hooked:get(self.host, self.name, name) then
347                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
348                 hooked:set(self.host, self.name, name, true);
349         end
350         event_hooks:set(self.host, self.name, name, handler, true);
351 end
352
353 function api:fire_event(...)
354         return (hosts[self.host] or prosody).events.fire_event(...);
355 end
356
357 function api:hook(event, handler, priority)
358         hooks:set(self.host, self.name, event, handler, true);
359         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
360 end
361
362 function api:hook_stanza(xmlns, name, handler, priority)
363         if not handler and type(name) == "function" then
364                 -- If only 2 options then they specified no xmlns
365                 xmlns, name, handler, priority = nil, xmlns, name, handler;
366         elseif not (handler and name) then
367                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
368                 return;
369         end
370         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
371 end
372
373 function api:require(lib)
374         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
375         if not f then
376                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
377         end
378         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
379         setfenv(f, setmetatable({ module = self }, { __index = _G }));
380         return f();
381 end
382
383 function api:get_option(name, default_value)
384         return config.get(self.host, self.name, name) or config.get(self.host, "core", name) or default_value;
385 end
386
387 local t_remove = _G.table.remove;
388 local module_items = multitable_new();
389 function api:add_item(key, value)
390         self.items = self.items or {};
391         self.items[key] = self.items[key] or {};
392         t_insert(self.items[key], value);
393         self:fire_event("item-added/"..key, {source = self, item = value});
394 end
395 function api:remove_item(key, value)
396         local t = self.items and self.items[key] or NULL;
397         for i = #t,1,-1 do
398                 if t[i] == value then
399                         t_remove(self.items[key], i);
400                         self:fire_event("item-removed/"..key, {source = self, item = value});
401                         return value;
402                 end
403         end
404 end
405
406 function api:get_host_items(key)
407         local result = {};
408         for mod_name, module in pairs(modulemap[self.host]) do
409                 module = module.module;
410                 if module.items then
411                         for _, item in ipairs(module.items[key] or NULL) do
412                                 t_insert(result, item);
413                         end
414                 end
415         end
416         for mod_name, module in pairs(modulemap["*"]) do
417                 module = module.module;
418                 if module.items then
419                         for _, item in ipairs(module.items[key] or NULL) do
420                                 t_insert(result, item);
421                         end
422                 end
423         end
424         return result;
425 end
426
427 --------------------------------------------------------------------
428
429 local actions = {};
430
431 function actions.load(params)
432         --return true, "Module loaded ("..params.module.." on "..params.host..")";
433         return load(params.host, params.module);
434 end
435
436 function actions.unload(params)
437         return unload(params.host, params.module);
438 end
439
440 register_actions("/modules", actions);
441
442 return _M;