modulemanager: Allow setting priority of stanza handlers
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM v0.4
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
22 local hosts = hosts;
23 local prosody = prosody;
24
25 local loadfile, pcall = loadfile, pcall;
26 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
27 local pairs, ipairs = pairs, ipairs;
28 local t_insert, t_concat = table.insert, table.concat;
29 local type = type;
30 local next = next;
31 local rawget = rawget;
32
33 local tostring = tostring;
34
35 -- We need this to let modules access the real global namespace
36 local _G = _G;
37
38 module "modulemanager"
39
40 local api = {}; -- Module API container
41
42 local modulemap = { ["*"] = {} };
43
44 local stanza_handlers = multitable_new();
45 local handler_info = {};
46
47 local modulehelpers = setmetatable({}, { __index = _G });
48
49 local features_table = multitable_new();
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", "modules_enable") == false then
60                 return; -- Only load for hosts, not components, etc.
61         end
62
63         -- Load modules from global section
64         local modules_enabled = config.get("*", "core", "modules_enabled");
65         local modules_disabled = config.get(host, "core", "modules_disabled");
66         local disabled_set = {};
67         if modules_enabled then
68                 if modules_disabled then
69                         for _, module in ipairs(modules_disabled) do
70                                 disabled_set[module] = true;
71                         end
72                 end
73                 for _, module in ipairs({"presence", "message", "iq"}) do
74                         if not disabled_set[module] then
75                                 load(host, module);
76                         end
77                 end
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
85         -- Load modules from just this host
86         local modules_enabled = config.get(host, "core", "modules_enabled");
87         if modules_enabled then
88                 for _, module in pairs(modules_enabled) do
89                         if not is_loaded(host, module) then
90                                 load(host, module);
91                         end
92                 end
93         end
94 end
95 eventmanager.add_event_hook("host-activated", load_modules_for_host);
96 --
97
98 function load(host, module_name, config)
99         if not (host and module_name) then
100                 return nil, "insufficient-parameters";
101         end
102         
103         if not modulemap[host] then
104                 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 = loadfile(get_module_filename(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", name or "nil", ret or "nil");
132                 return nil, ret;
133         end
134         
135         -- Use modified host, if the module set one
136         modulemap[api_instance.host][module_name] = pluginenv;
137         
138         if api_instance.host == "*" and host ~= "*" then
139                 api_instance:set_global();
140         end
141                 
142         return true;
143 end
144
145 function get_module(host, name)
146         return modulemap[host] and modulemap[host][name];
147 end
148
149 function is_loaded(host, name)
150         return modulemap[host] and modulemap[host][name] and true;
151 end
152
153 function unload(host, name, ...)
154         local mod = get_module(host, name); 
155         if not mod then return nil, "module-not-loaded"; end
156         
157         if module_has_method(mod, "unload") then
158                 local ok, err = call_module_method(mod, "unload");
159                 if (not ok) and err then
160                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
161                 end
162         end
163         modulemap[host][name] = nil;
164         features_table:remove(host, name);
165         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
166         for _, param in pairs(params or NULL) do
167                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
168                 if handlers then
169                         handler_info[handlers[1]] = nil;
170                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
171                 end
172         end
173         event_hooks:remove(host, name);
174         -- unhook event handlers hooked by module:hook
175         for event, handlers in pairs(hooks:get(host, name) or NULL) do
176                 for handler in pairs(handlers or NULL) do
177                         (hosts[host] or prosody).events.remove_handler(event, handler);
178                 end
179         end
180         hooks:remove(host, name);
181         return true;
182 end
183
184 function reload(host, name, ...)
185         local mod = get_module(host, name);
186         if not mod then return nil, "module-not-loaded"; end
187
188         local _mod, err = loadfile(get_module_filename(name)); -- checking for syntax errors
189         if not _mod then
190                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
191                 return nil, err;
192         end
193
194         local saved;
195
196         if module_has_method(mod, "save") then
197                 local ok, ret, err = call_module_method(mod, "save");
198                 if ok then
199                         saved = ret;
200                 else
201                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
202                         if not config.get(host, "core", "force_module_reload") then
203                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
204                                 return nil, "save-state-failed";
205                         else
206                                 log("warn", "Continuing with reload (using the force)");
207                         end
208                 end
209         end
210
211         unload(host, name, ...);
212         local ok, err = load(host, name, ...);
213         if ok then
214                 mod = get_module(host, name);
215                 if module_has_method(mod, "restore") then
216                         local ok, err = call_module_method(mod, "restore", saved or {})
217                         if (not ok) and err then
218                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
219                         end
220                 end
221                 return true;
222         end
223         return ok, err;
224 end
225
226 function handle_stanza(host, origin, stanza)
227         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
228         if name == "iq" and xmlns == "jabber:client" then
229                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
230                         xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
231                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
232                 else
233                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
234                         return true;
235                 end
236         end
237         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
238         if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
239         if handlers then
240                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
241                 (handlers[1])(origin, stanza);
242                 return true;
243         else
244                 log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
245                 if stanza.attr.xmlns == "jabber:client" then
246                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
247                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
248                         end
249                 elseif not(name == "features" and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
250                         origin:close("unsupported-stanza-type");
251                 end
252         end
253 end
254
255 function module_has_method(module, method)
256         return type(module.module[method]) == "function";
257 end
258
259 function call_module_method(module, method, ...)
260         if module_has_method(module, method) then       
261                 local f = module.module[method];
262                 return pcall(f, ...);
263         else
264                 return false, "no-such-method";
265         end
266 end
267
268 local _modulepath = { plugin_dir, "mod_", nil, ".lua"};
269 function get_module_filename(name)
270         _modulepath[3] = name;
271         return t_concat(_modulepath);
272 end
273
274 ----- API functions exposed to modules -----------
275 -- Must all be in api.* 
276
277 -- Returns the name of the current module
278 function api:get_name()
279         return self.name;
280 end
281
282 -- Returns the host that the current module is serving
283 function api:get_host()
284         return self.host;
285 end
286
287 function api:get_host_type()
288         return hosts[self.host].type;
289 end
290
291 function api:set_global()
292         self.host = "*";
293         -- Update the logger
294         local _log = logger.init("mod_"..self.name);
295         self.log = function (self, ...) return _log(...); end;
296         self._log = _log;
297 end
298
299 local function _add_handler(module, origin_type, tag, xmlns, handler)
300         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
301         local msg = (tag == "iq") and "namespace" or "payload namespace";
302         if not handlers then
303                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
304                 handler_info[handler] = module;
305                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
306                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
307         else
308                 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);
309         end
310 end
311
312 function api:add_handler(origin_type, tag, xmlns, handler)
313         if not (origin_type and tag and xmlns and handler) then return false; end
314         if type(origin_type) == "table" then
315                 for _, origin_type in ipairs(origin_type) do
316                         _add_handler(self, origin_type, tag, xmlns, handler);
317                 end
318         else
319                 _add_handler(self, origin_type, tag, xmlns, handler);
320         end
321 end
322 function api:add_iq_handler(origin_type, xmlns, handler)
323         self:add_handler(origin_type, "iq", xmlns, handler);
324 end
325
326 addDiscoInfoHandler("*host", function(reply, to, from, node)
327         if #node == 0 then
328                 local done = {};
329                 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
330                         for feature in pairs(features) do
331                                 if not done[feature] then
332                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
333                                         done[feature] = true;
334                                 end
335                         end
336                 end
337                 for module, features in pairs(features_table:get("*") or NULL) do -- for each module
338                         for feature in pairs(features) do
339                                 if not done[feature] then
340                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
341                                         done[feature] = true;
342                                 end
343                         end
344                 end
345                 return next(done) ~= nil;
346         end
347 end);
348
349 function api:add_feature(xmlns)
350         features_table:set(self.host, self.name, xmlns, true);
351 end
352
353 local event_hook = function(host, mod_name, event_name, ...)
354         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
355         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
356                 handler(...);
357         end
358 end;
359 function api:add_event_hook(name, handler)
360         if not hooked:get(self.host, self.name, name) then
361                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
362                 hooked:set(self.host, self.name, name, true);
363         end
364         event_hooks:set(self.host, self.name, name, handler, true);
365 end
366
367 function api:fire_event(...)
368         return (hosts[self.host] or prosody).events.fire_event(...);
369 end
370
371 function api:hook(event, handler, priority)
372         hooks:set(self.host, self.name, event, handler, true);
373         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
374 end
375
376 function api:hook_stanza(xmlns, name, handler, priority)
377         if not handler and type(name) == "function" then
378                 -- If only 2 options then they specified no xmlns
379                 xmlns, name, handler, priority = nil, xmlns, name, handler;
380         elseif not (handler and name and xmlns) then
381                 module:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
382                 return;
383         end
384         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
385 end
386
387 --------------------------------------------------------------------
388
389 local actions = {};
390
391 function actions.load(params)
392         --return true, "Module loaded ("..params.module.." on "..params.host..")";
393         return load(params.host, params.module);
394 end
395
396 function actions.unload(params)
397         return unload(params.host, params.module);
398 end
399
400 register_actions("/modules", actions);
401
402 return _M;