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