a1ed898198e49c0cf3594173646c5f355eccff0d
[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
10
11 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
12
13 local logger = require "util.logger";
14 local log = logger.init("modulemanager");
15 local addDiscoInfoHandler = require "core.discomanager".addDiscoInfoHandler;
16 local eventmanager = require "core.eventmanager";
17 local config = require "core.configmanager";
18 local multitable_new = require "util.multitable".new;
19 local register_actions = require "core.actions".register;
20 local st = require "util.stanza";
21 local pluginloader = require "util.pluginloader";
22
23 local hosts = hosts;
24 local prosody = prosody;
25
26 local loadfile, pcall = loadfile, pcall;
27 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
28 local pairs, ipairs = pairs, ipairs;
29 local t_insert, t_concat = table.insert, table.concat;
30 local type = type;
31 local next = next;
32 local rawget = rawget;
33 local error = error;
34 local tostring = tostring;
35
36 local autoload_modules = {"presence", "message", "iq"};
37
38 -- We need this to let modules access the real global namespace
39 local _G = _G;
40
41 module "modulemanager"
42
43 api = {};
44 local api = api; -- Module API container
45
46 local modulemap = { ["*"] = {} };
47
48 local stanza_handlers = multitable_new();
49 local handler_info = {};
50
51 local modulehelpers = setmetatable({}, { __index = _G });
52
53 local features_table = multitable_new();
54 local identities_table = multitable_new();
55 local handler_table = multitable_new();
56 local hooked = multitable_new();
57 local hooks = multitable_new();
58 local event_hooks = multitable_new();
59
60 local NULL = {};
61
62 -- Load modules when a host is activated
63 function load_modules_for_host(host)
64         if config.get(host, "core", "load_global_modules") ~= false then
65                 -- Load modules from global section
66                 local modules_enabled = config.get("*", "core", "modules_enabled");
67                 local modules_disabled = config.get(host, "core", "modules_disabled");
68                 local disabled_set = {};
69                 if modules_enabled then
70                         if modules_disabled then
71                                 for _, module in ipairs(modules_disabled) do
72                                         disabled_set[module] = true;
73                                 end
74                         end
75                         for _, module in ipairs(autoload_modules) do
76                                 if not disabled_set[module] then
77                                         load(host, module);
78                                 end
79                         end
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         
133         local success, ret = pcall(mod);
134         if not success then
135                 log("error", "Error initialising module '%s': %s", module_name or "nil", ret or "nil");
136                 return nil, ret;
137         end
138         
139         if module_has_method(pluginenv, "load") then
140                 local ok, err = call_module_method(pluginenv, "load");
141                 if (not ok) and err then
142                         log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err);
143                 end
144         end
145
146         -- Use modified host, if the module set one
147         modulemap[api_instance.host][module_name] = pluginenv;
148         
149         if api_instance.host == "*" and host ~= "*" then
150                 api_instance:set_global();
151         end
152                 
153         return true;
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         modulemap[host][name] = nil;
175         features_table:remove(host, name);
176         identities_table:remove(host, name);
177         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
178         for _, param in pairs(params or NULL) do
179                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
180                 if handlers then
181                         handler_info[handlers[1]] = nil;
182                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
183                 end
184         end
185         event_hooks:remove(host, name);
186         -- unhook event handlers hooked by module:hook
187         for event, handlers in pairs(hooks:get(host, name) or NULL) do
188                 for handler in pairs(handlers or NULL) do
189                         (hosts[host] or prosody).events.remove_handler(event, handler);
190                 end
191         end
192         hooks:remove(host, name);
193         return true;
194 end
195
196 function reload(host, name, ...)
197         local mod = get_module(host, name);
198         if not mod then return nil, "module-not-loaded"; end
199
200         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
201         if not _mod then
202                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
203                 return nil, err;
204         end
205
206         local saved;
207
208         if module_has_method(mod, "save") then
209                 local ok, ret, err = call_module_method(mod, "save");
210                 if ok then
211                         saved = ret;
212                 else
213                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
214                         if not config.get(host, "core", "force_module_reload") then
215                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
216                                 return nil, "save-state-failed";
217                         else
218                                 log("warn", "Continuing with reload (using the force)");
219                         end
220                 end
221         end
222
223         unload(host, name, ...);
224         local ok, err = load(host, name, ...);
225         if ok then
226                 mod = get_module(host, name);
227                 if module_has_method(mod, "restore") then
228                         local ok, err = call_module_method(mod, "restore", saved or {})
229                         if (not ok) and err then
230                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
231                         end
232                 end
233                 return true;
234         end
235         return ok, err;
236 end
237
238 function handle_stanza(host, origin, stanza)
239         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
240         if name == "iq" and xmlns == "jabber:client" then
241                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
242                         xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
243                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
244                 else
245                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
246                         return true;
247                 end
248         end
249         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
250         if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
251         if handlers then
252                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
253                 (handlers[1])(origin, stanza);
254                 return true;
255         else
256                 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
257                 if stanza.attr.xmlns == "jabber:client" then
258                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
259                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
260                         end
261                 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
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 addDiscoInfoHandler("*host", function(reply, to, from, node)
333         if #node == 0 then
334                 local done = {};
335                 for module, identities in pairs(identities_table:get(to) or NULL) do -- for each module
336                         for identity, attr in pairs(identities) do
337                                 if not done[identity] then
338                                         reply:tag("identity", attr):up(); -- TODO cache
339                                         done[identity] = true;
340                                 end
341                         end
342                 end
343                 for module, identities in pairs(identities_table:get("*") or NULL) do -- for each module
344                         for identity, attr in pairs(identities) do
345                                 if not done[identity] then
346                                         reply:tag("identity", attr):up(); -- TODO cache
347                                         done[identity] = true;
348                                 end
349                         end
350                 end
351                 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
352                         for feature in pairs(features) do
353                                 if not done[feature] then
354                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
355                                         done[feature] = true;
356                                 end
357                         end
358                 end
359                 for module, features in pairs(features_table:get("*") or NULL) do -- for each module
360                         for feature in pairs(features) do
361                                 if not done[feature] then
362                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
363                                         done[feature] = true;
364                                 end
365                         end
366                 end
367                 return next(done) ~= nil;
368         end
369 end);
370
371 function api:add_feature(xmlns)
372         features_table:set(self.host, self.name, xmlns, true);
373 end
374 function api:add_identity(category, type)
375         identities_table:set(self.host, self.name, category.."\0"..type, {category = category, type = type});
376 end
377
378 local event_hook = function(host, mod_name, event_name, ...)
379         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
380         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
381                 handler(...);
382         end
383 end;
384 function api:add_event_hook(name, handler)
385         if not hooked:get(self.host, self.name, name) then
386                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
387                 hooked:set(self.host, self.name, name, true);
388         end
389         event_hooks:set(self.host, self.name, name, handler, true);
390 end
391
392 function api:fire_event(...)
393         return (hosts[self.host] or prosody).events.fire_event(...);
394 end
395
396 function api:hook(event, handler, priority)
397         hooks:set(self.host, self.name, event, handler, true);
398         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
399 end
400
401 function api:hook_stanza(xmlns, name, handler, priority)
402         if not handler and type(name) == "function" then
403                 -- If only 2 options then they specified no xmlns
404                 xmlns, name, handler, priority = nil, xmlns, name, handler;
405         elseif not (handler and name) then
406                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
407                 return;
408         end
409         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
410 end
411
412 function api:require(lib)
413         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
414         if not f then
415                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
416         end
417         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
418         setfenv(f, setmetatable({ module = self }, { __index = _G }));
419         return f();
420 end
421
422 --------------------------------------------------------------------
423
424 local actions = {};
425
426 function actions.load(params)
427         --return true, "Module loaded ("..params.module.." on "..params.host..")";
428         return load(params.host, params.module);
429 end
430
431 function actions.unload(params)
432         return unload(params.host, params.module);
433 end
434
435 register_actions("/modules", actions);
436
437 return _M;