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