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