modulemanager: Add get_host_type() API method, and fix up call_module_method to work...
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM v0.2
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21
22 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
23
24 local logger = require "util.logger";
25 local log = logger.init("modulemanager");
26 local addDiscoInfoHandler = require "core.discomanager".addDiscoInfoHandler;
27 local eventmanager = require "core.eventmanager";
28 local config = require "core.configmanager";
29 local multitable_new = require "util.multitable".new;
30 local register_actions = require "core.actions".register;
31
32 local hosts = hosts;
33
34 local loadfile, pcall = loadfile, pcall;
35 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
36 local pairs, ipairs = pairs, ipairs;
37 local t_insert, t_concat = table.insert, table.concat;
38 local type = type;
39 local next = next;
40 local rawget = rawget;
41
42 local tostring, print = tostring, print;
43
44 -- We need this to let modules access the real global namespace
45 local _G = _G;
46
47 module "modulemanager"
48
49 local api = {}; -- Module API container
50
51 local modulemap = { ["*"] = {} };
52
53 local stanza_handlers = multitable_new();
54 local handler_info = {};
55
56 local modulehelpers = setmetatable({}, { __index = _G });
57
58 local features_table = multitable_new();
59 local handler_table = multitable_new();
60 local hooked = multitable_new();
61 local event_hooks = multitable_new();
62
63 local NULL = {};
64
65 -- Load modules when a host is activated
66 function load_modules_for_host(host)
67         -- Load modules from global section
68         local modules_enabled = config.get("*", "core", "modules_enabled");
69         local modules_disabled = config.get(host, "core", "modules_disabled");
70         local disabled_set = {};
71         if modules_enabled then
72                 if modules_disabled then
73                         for _, module in ipairs(modules_disabled) do
74                                 disabled_set[module] = true;
75                         end
76                 end
77                 for _, module in ipairs(modules_enabled) do
78                         if not disabled_set[module] then
79                                 load(host, module);
80                         end
81                 end
82         end
83
84         -- Load modules from just this host
85         local modules_enabled = config.get(host, "core", "modules_enabled");
86         if modules_enabled then
87                 for _, module in pairs(modules_enabled) do
88                         if not is_loaded(host, module) then
89                                 load(host, module);
90                         end
91                 end
92         end
93 end
94 eventmanager.add_event_hook("host-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         elseif modulemap[host][module_name] then
105                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
106                 return nil, "module-already-loaded";
107         elseif modulemap["*"][module_name] then
108                 return nil, "global-module-already-loaded";
109         end
110         
111
112         local mod, err = loadfile(get_module_filename(module_name));
113         if not mod then
114                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
115                 return nil, err;
116         end
117
118         local _log = logger.init(host..":"..module_name);
119         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
120
121         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
122         
123         setfenv(mod, pluginenv);
124         
125         local success, ret = pcall(mod);
126         if not success then
127                 log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
128                 return nil, ret;
129         end
130         
131         -- Use modified host, if the module set one
132         modulemap[api_instance.host][module_name] = pluginenv;
133         
134         return true;
135 end
136
137 function get_module(host, name)
138         return modulemap[host] and modulemap[host][name];
139 end
140
141 function is_loaded(host, name)
142         return modulemap[host] and modulemap[host][name] and true;
143 end
144
145 function unload(host, name, ...)
146         local mod = get_module(host, name); 
147         if not mod then return nil, "module-not-loaded"; end
148         
149         if module_has_method(mod, "unload") then
150                 local ok, err = call_module_method(mod, "unload");
151                 if (not ok) and err then
152                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
153                 end
154         end
155         modulemap[host][name] = nil;
156         features_table:remove(host, name);
157         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
158         for _, param in pairs(params or NULL) do
159                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
160                 if handlers then
161                         handler_info[handlers[1]] = nil;
162                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
163                 end
164         end
165         event_hooks:remove(host, name);
166         return true;
167 end
168
169 function reload(host, name, ...)
170         local mod = get_module(host, name);
171         if not mod then return nil, "module-not-loaded"; end
172
173         local _mod, err = loadfile(get_module_filename(name)); -- checking for syntax errors
174         if not _mod then
175                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
176                 return nil, err;
177         end
178
179         local saved;
180
181         if module_has_method(mod, "save") then
182                 local ok, ret, err = call_module_method(mod, "save");
183                 if ok then
184                         saved = ret;
185                 else
186                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
187                         if not config.get(host, "core", "force_module_reload") then
188                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
189                                 return nil, "save-state-failed";
190                         else
191                                 log("warn", "Continuing with reload (using the force)");
192                         end
193                 end
194         end
195
196         unload(host, name, ...);
197         local ok, err = load(host, name, ...);
198         if ok then
199                 mod = get_module(host, name);
200                 if module_has_method(mod, "restore") then
201                         local ok, err = call_module_method(mod, "restore", saved or {})
202                         if (not ok) and err then
203                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
204                         end
205                 end
206                 return true;
207         end
208         return ok, err;
209 end
210
211 function handle_stanza(host, origin, stanza)
212         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
213         if name == "iq" and xmlns == "jabber:client" then
214                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
215                         xmlns = stanza.tags[1].attr.xmlns;
216                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
217                 else
218                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
219                         return true;
220                 end
221         end
222         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
223         if handlers then
224                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
225                 (handlers[1])(origin, stanza);
226                 return true;
227         else
228                 log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns); -- we didn't handle it
229         end
230 end
231
232 function module_has_method(module, method)
233         return type(module.module[method]) == "function";
234 end
235
236 function call_module_method(module, method, ...)
237         if module_has_method(module, method) then       
238                 local f = module.module[func];
239                 return pcall(f, ...);
240         else
241                 return false, "no-such-method";
242         end
243 end
244
245 local _modulepath = { plugin_dir, "mod_", nil, ".lua"};
246 function get_module_filename(name)
247         _modulepath[3] = name;
248         return t_concat(_modulepath);
249 end
250
251 ----- API functions exposed to modules -----------
252 -- Must all be in api.* 
253
254 -- Returns the name of the current module
255 function api:get_name()
256         return self.name;
257 end
258
259 -- Returns the host that the current module is serving
260 function api:get_host()
261         return self.host;
262 end
263
264 function api:get_host_type()
265         return hosts[self.host].type;
266 end
267
268 function api:set_global()
269         self.host = "*";
270 end
271
272 local function _add_handler(module, origin_type, tag, xmlns, handler)
273         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
274         local msg = (tag == "iq") and "namespace" or "payload namespace";
275         if not handlers then
276                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
277                 handler_info[handler] = module;
278                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
279                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
280         else
281                 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);
282         end
283 end
284
285 function api:add_handler(origin_type, tag, xmlns, handler)
286         if not (origin_type and tag and xmlns and handler) then return false; end
287         if type(origin_type) == "table" then
288                 for _, origin_type in ipairs(origin_type) do
289                         _add_handler(self, origin_type, tag, xmlns, handler);
290                 end
291         else
292                 _add_handler(self, origin_type, tag, xmlns, handler);
293         end
294 end
295 function api:add_iq_handler(origin_type, xmlns, handler)
296         self:add_handler(origin_type, "iq", xmlns, handler);
297 end
298
299 addDiscoInfoHandler("*host", function(reply, to, from, node)
300         if #node == 0 then
301                 local done = {};
302                 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
303                         for feature in pairs(features) do
304                                 if not done[feature] then
305                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
306                                         done[feature] = true;
307                                 end
308                         end
309                 end
310                 return next(done) ~= nil;
311         end
312 end);
313
314 function api:add_feature(xmlns)
315         features_table:set(self.host, self.name, xmlns, true);
316 end
317
318 local event_hook = function(host, mod_name, event_name, ...)
319         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
320         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
321                 handler(...);
322         end
323 end;
324 function api:add_event_hook(name, handler)
325         if not hooked:get(self.host, self.name, name) then
326                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
327                 hooked:set(self.host, self.name, name, true);
328         end
329         event_hooks:set(self.host, self.name, name, handler, true);
330 end
331
332 --------------------------------------------------------------------
333
334 local actions = {};
335
336 function actions.load(params)
337         --return true, "Module loaded ("..params.module.." on "..params.host..")";
338         return load(params.host, params.module);
339 end
340
341 function actions.unload(params)
342         return unload(params.host, params.module);
343 end
344
345 register_actions("/modules", actions);
346
347 return _M;