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