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