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