12cf9ce8c6eb78131ef98fb0f733b69dc309a656
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM v0.3
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         
116         local success, ret = pcall(mod);
117         if not success then
118                 log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
119                 return nil, ret;
120         end
121         
122         -- Use modified host, if the module set one
123         modulemap[api_instance.host][module_name] = pluginenv;
124         
125         return true;
126 end
127
128 function get_module(host, name)
129         return modulemap[host] and modulemap[host][name];
130 end
131
132 function is_loaded(host, name)
133         return modulemap[host] and modulemap[host][name] and true;
134 end
135
136 function unload(host, name, ...)
137         local mod = get_module(host, name); 
138         if not mod then return nil, "module-not-loaded"; end
139         
140         if module_has_method(mod, "unload") then
141                 local ok, err = call_module_method(mod, "unload");
142                 if (not ok) and err then
143                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
144                 end
145         end
146         modulemap[host][name] = nil;
147         features_table:remove(host, name);
148         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
149         for _, param in pairs(params or NULL) do
150                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
151                 if handlers then
152                         handler_info[handlers[1]] = nil;
153                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
154                 end
155         end
156         event_hooks:remove(host, name);
157         return true;
158 end
159
160 function reload(host, name, ...)
161         local mod = get_module(host, name);
162         if not mod then return nil, "module-not-loaded"; end
163
164         local _mod, err = loadfile(get_module_filename(name)); -- checking for syntax errors
165         if not _mod then
166                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
167                 return nil, err;
168         end
169
170         local saved;
171
172         if module_has_method(mod, "save") then
173                 local ok, ret, err = call_module_method(mod, "save");
174                 if ok then
175                         saved = ret;
176                 else
177                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
178                         if not config.get(host, "core", "force_module_reload") then
179                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
180                                 return nil, "save-state-failed";
181                         else
182                                 log("warn", "Continuing with reload (using the force)");
183                         end
184                 end
185         end
186
187         unload(host, name, ...);
188         local ok, err = load(host, name, ...);
189         if ok then
190                 mod = get_module(host, name);
191                 if module_has_method(mod, "restore") then
192                         local ok, err = call_module_method(mod, "restore", saved or {})
193                         if (not ok) and err then
194                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
195                         end
196                 end
197                 return true;
198         end
199         return ok, err;
200 end
201
202 function handle_stanza(host, origin, stanza)
203         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
204         if name == "iq" and xmlns == "jabber:client" then
205                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
206                         xmlns = stanza.tags[1].attr.xmlns;
207                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
208                 else
209                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
210                         return true;
211                 end
212         end
213         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
214         if handlers then
215                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
216                 (handlers[1])(origin, stanza);
217                 return true;
218         else
219                 log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns); -- we didn't handle it
220         end
221 end
222
223 function module_has_method(module, method)
224         return type(module.module[method]) == "function";
225 end
226
227 function call_module_method(module, method, ...)
228         if module_has_method(module, method) then       
229                 local f = module.module[method];
230                 return pcall(f, ...);
231         else
232                 return false, "no-such-method";
233         end
234 end
235
236 local _modulepath = { plugin_dir, "mod_", nil, ".lua"};
237 function get_module_filename(name)
238         _modulepath[3] = name;
239         return t_concat(_modulepath);
240 end
241
242 ----- API functions exposed to modules -----------
243 -- Must all be in api.* 
244
245 -- Returns the name of the current module
246 function api:get_name()
247         return self.name;
248 end
249
250 -- Returns the host that the current module is serving
251 function api:get_host()
252         return self.host;
253 end
254
255 function api:get_host_type()
256         return hosts[self.host].type;
257 end
258
259 function api:set_global()
260         self.host = "*";
261 end
262
263 local function _add_handler(module, origin_type, tag, xmlns, handler)
264         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
265         local msg = (tag == "iq") and "namespace" or "payload namespace";
266         if not handlers then
267                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
268                 handler_info[handler] = module;
269                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
270                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
271         else
272                 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);
273         end
274 end
275
276 function api:add_handler(origin_type, tag, xmlns, handler)
277         if not (origin_type and tag and xmlns and handler) then return false; end
278         if type(origin_type) == "table" then
279                 for _, origin_type in ipairs(origin_type) do
280                         _add_handler(self, origin_type, tag, xmlns, handler);
281                 end
282         else
283                 _add_handler(self, origin_type, tag, xmlns, handler);
284         end
285 end
286 function api:add_iq_handler(origin_type, xmlns, handler)
287         self:add_handler(origin_type, "iq", xmlns, handler);
288 end
289
290 addDiscoInfoHandler("*host", function(reply, to, from, node)
291         if #node == 0 then
292                 local done = {};
293                 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
294                         for feature in pairs(features) do
295                                 if not done[feature] then
296                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
297                                         done[feature] = true;
298                                 end
299                         end
300                 end
301                 return next(done) ~= nil;
302         end
303 end);
304
305 function api:add_feature(xmlns)
306         features_table:set(self.host, self.name, xmlns, true);
307 end
308
309 local event_hook = function(host, mod_name, event_name, ...)
310         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
311         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
312                 handler(...);
313         end
314 end;
315 function api:add_event_hook(name, handler)
316         if not hooked:get(self.host, self.name, name) then
317                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
318                 hooked:set(self.host, self.name, name, true);
319         end
320         event_hooks:set(self.host, self.name, name, handler, true);
321 end
322
323 --------------------------------------------------------------------
324
325 local actions = {};
326
327 function actions.load(params)
328         --return true, "Module loaded ("..params.module.." on "..params.host..")";
329         return load(params.host, params.module);
330 end
331
332 function actions.unload(params)
333         return unload(params.host, params.module);
334 end
335
336 register_actions("/modules", actions);
337
338 return _M;