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