modulemanager: Module API functions add_item and add_feature updated to use the add_i...
[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 --
100
101 function load(host, module_name, config)
102         if not (host and module_name) then
103                 return nil, "insufficient-parameters";
104         end
105         
106         if not modulemap[host] then
107                 modulemap[host] = {};
108         end
109         
110         if modulemap[host][module_name] then
111                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
112                 return nil, "module-already-loaded";
113         elseif modulemap["*"][module_name] then
114                 return nil, "global-module-already-loaded";
115         end
116         
117
118         local mod, err = pluginloader.load_code(module_name);
119         if not mod then
120                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
121                 return nil, err;
122         end
123
124         local _log = logger.init(host..":"..module_name);
125         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
126
127         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
128         
129         setfenv(mod, pluginenv);
130         if not hosts[host] then hosts[host] = { type = "component", host = host, connected = false, s2sout = {} }; end
131         
132         local success, ret = pcall(mod);
133         if not success then
134                 log("error", "Error initialising module '%s': %s", module_name or "nil", ret or "nil");
135                 return nil, ret;
136         end
137         
138         if module_has_method(pluginenv, "load") then
139                 local ok, err = call_module_method(pluginenv, "load");
140                 if (not ok) and err then
141                         log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err);
142                 end
143         end
144
145         -- Use modified host, if the module set one
146         modulemap[api_instance.host][module_name] = pluginenv;
147         
148         if api_instance.host == "*" and host ~= "*" then
149                 api_instance:set_global();
150         end
151                 
152         return true;
153 end
154
155 function get_module(host, name)
156         return modulemap[host] and modulemap[host][name];
157 end
158
159 function is_loaded(host, name)
160         return modulemap[host] and modulemap[host][name] and true;
161 end
162
163 function unload(host, name, ...)
164         local mod = get_module(host, name); 
165         if not mod then return nil, "module-not-loaded"; end
166         
167         if module_has_method(mod, "unload") then
168                 local ok, err = call_module_method(mod, "unload");
169                 if (not ok) and err then
170                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
171                 end
172         end
173         modulemap[host][name] = nil;
174         features_table:remove(host, name);
175         identities_table:remove(host, name);
176         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
177         for _, param in pairs(params or NULL) do
178                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
179                 if handlers then
180                         handler_info[handlers[1]] = nil;
181                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
182                 end
183         end
184         event_hooks:remove(host, name);
185         -- unhook event handlers hooked by module:hook
186         for event, handlers in pairs(hooks:get(host, name) or NULL) do
187                 for handler in pairs(handlers or NULL) do
188                         (hosts[host] or prosody).events.remove_handler(event, handler);
189                 end
190         end
191         hooks:remove(host, name);
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, 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                 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
256                 if stanza.attr.xmlns == "jabber:client" then
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                         origin:close("unsupported-stanza-type");
262                 end
263         end
264 end
265
266 function module_has_method(module, method)
267         return type(module.module[method]) == "function";
268 end
269
270 function call_module_method(module, method, ...)
271         if module_has_method(module, method) then       
272                 local f = module.module[method];
273                 return pcall(f, ...);
274         else
275                 return false, "no-such-method";
276         end
277 end
278
279 ----- API functions exposed to modules -----------
280 -- Must all be in api.* 
281
282 -- Returns the name of the current module
283 function api:get_name()
284         return self.name;
285 end
286
287 -- Returns the host that the current module is serving
288 function api:get_host()
289         return self.host;
290 end
291
292 function api:get_host_type()
293         return hosts[self.host].type;
294 end
295
296 function api:set_global()
297         self.host = "*";
298         -- Update the logger
299         local _log = logger.init("mod_"..self.name);
300         self.log = function (self, ...) return _log(...); end;
301         self._log = _log;
302 end
303
304 local function _add_handler(module, origin_type, tag, xmlns, handler)
305         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
306         local msg = (tag == "iq") and "namespace" or "payload namespace";
307         if not handlers then
308                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
309                 handler_info[handler] = module;
310                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
311                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
312         else
313                 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);
314         end
315 end
316
317 function api:add_handler(origin_type, tag, xmlns, handler)
318         if not (origin_type and tag and xmlns and handler) then return false; end
319         if type(origin_type) == "table" then
320                 for _, origin_type in ipairs(origin_type) do
321                         _add_handler(self, origin_type, tag, xmlns, handler);
322                 end
323         else
324                 _add_handler(self, origin_type, tag, xmlns, handler);
325         end
326 end
327 function api:add_iq_handler(origin_type, xmlns, handler)
328         self:add_handler(origin_type, "iq", xmlns, handler);
329 end
330
331 addDiscoInfoHandler("*host", function(reply, to, from, node)
332         if #node == 0 then
333                 local done = {};
334                 for module, identities in pairs(identities_table:get(to) or NULL) do -- for each module
335                         for identity, attr in pairs(identities) do
336                                 if not done[identity] then
337                                         reply:tag("identity", attr):up(); -- TODO cache
338                                         done[identity] = true;
339                                 end
340                         end
341                 end
342                 for module, identities in pairs(identities_table:get("*") or NULL) do -- for each module
343                         for identity, attr in pairs(identities) do
344                                 if not done[identity] then
345                                         reply:tag("identity", attr):up(); -- TODO cache
346                                         done[identity] = true;
347                                 end
348                         end
349                 end
350                 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
351                         for feature in pairs(features) do
352                                 if not done[feature] then
353                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
354                                         done[feature] = true;
355                                 end
356                         end
357                 end
358                 for module, features in pairs(features_table:get("*") or NULL) do -- for each module
359                         for feature in pairs(features) do
360                                 if not done[feature] then
361                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
362                                         done[feature] = true;
363                                 end
364                         end
365                 end
366                 return next(done) ~= nil;
367         end
368 end);
369
370 function api:add_feature(xmlns)
371         self:add_item("feature", xmlns);
372         features_table:set(self.host, self.name, xmlns, true);
373 end
374 function api:add_identity(category, type, name)
375         self:add_item("identity", {category = category, type = type, name = name});
376         identities_table:set(self.host, self.name, category.."\0"..type, {category = category, type = type, name = name});
377 end
378
379 local event_hook = function(host, mod_name, event_name, ...)
380         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
381         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
382                 handler(...);
383         end
384 end;
385 function api:add_event_hook(name, handler)
386         if not hooked:get(self.host, self.name, name) then
387                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
388                 hooked:set(self.host, self.name, name, true);
389         end
390         event_hooks:set(self.host, self.name, name, handler, true);
391 end
392
393 function api:fire_event(...)
394         return (hosts[self.host] or prosody).events.fire_event(...);
395 end
396
397 function api:hook(event, handler, priority)
398         hooks:set(self.host, self.name, event, handler, true);
399         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
400 end
401
402 function api:hook_stanza(xmlns, name, handler, priority)
403         if not handler and type(name) == "function" then
404                 -- If only 2 options then they specified no xmlns
405                 xmlns, name, handler, priority = nil, xmlns, name, handler;
406         elseif not (handler and name) then
407                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
408                 return;
409         end
410         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
411 end
412
413 function api:require(lib)
414         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
415         if not f then
416                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
417         end
418         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
419         setfenv(f, setmetatable({ module = self }, { __index = _G }));
420         return f();
421 end
422
423 function api:get_option(name, default_value)
424         return config.get(self.host, self.name, name) or config.get(self.host, "core", name) or default_value;
425 end
426
427 local t_remove = _G.table.remove;
428 local module_items = multitable_new();
429 function api:add_item(key, value)
430         self.items = self.items or {};
431         self.items[key] = self.items[key] or {};
432         t_insert(self.items[key], value);
433         self:fire_event("item-added/"..key, {source = self, item = value});
434 end
435 function api:remove_item(key, value)
436         local t = self.items and self.items[key] or NULL;
437         for i = #t,1,-1 do
438                 if t[i] == value then
439                         t_remove(self.items[key], i);
440                         self:fire_event("item-removed/"..key, {source = self, item = value});
441                         return value;
442                 end
443         end
444 end
445
446 --------------------------------------------------------------------
447
448 local actions = {};
449
450 function actions.load(params)
451         --return true, "Module loaded ("..params.module.." on "..params.host..")";
452         return load(params.host, params.module);
453 end
454
455 function actions.unload(params)
456         return unload(params.host, params.module);
457 end
458
459 register_actions("/modules", actions);
460
461 return _M;