tools/ejabberd2prosody: Fixed private storage export
[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 = tostring;
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         if config.get(host, "core", "modules_enable") == false then
57                 return; -- Only load for hosts, not components, etc.
58         end
59
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(modules_enabled) do
71                         if not disabled_set[module] then
72                                 load(host, module);
73                         end
74                 end
75         end
76
77         -- Load modules from just this host
78         local modules_enabled = config.get(host, "core", "modules_enabled");
79         if modules_enabled then
80                 for _, module in pairs(modules_enabled) do
81                         if not is_loaded(host, module) then
82                                 load(host, module);
83                         end
84                 end
85         end
86 end
87 eventmanager.add_event_hook("host-activated", load_modules_for_host);
88 --
89
90 function load(host, module_name, config)
91         if not (host and module_name) then
92                 return nil, "insufficient-parameters";
93         end
94         
95         if not modulemap[host] then
96                 modulemap[host] = {};
97         end
98         
99         if modulemap[host][module_name] then
100                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
101                 return nil, "module-already-loaded";
102         elseif modulemap["*"][module_name] then
103                 return nil, "global-module-already-loaded";
104         end
105         
106
107         local mod, err = loadfile(get_module_filename(module_name));
108         if not mod then
109                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
110                 return nil, err;
111         end
112
113         local _log = logger.init(host..":"..module_name);
114         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
115
116         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
117         
118         setfenv(mod, pluginenv);
119         if not hosts[host] then hosts[host] = { type = "component", host = host, connected = false, s2sout = {} }; end
120         
121         local success, ret = pcall(mod);
122         if not success then
123                 log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
124                 return nil, ret;
125         end
126         
127         -- Use modified host, if the module set one
128         modulemap[api_instance.host][module_name] = pluginenv;
129         
130         if api_instance.host == "*" and host ~= "*" then
131                 api_instance:set_global();
132         end
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 or "jabber:client";
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 not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
224         if handlers then
225                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
226                 (handlers[1])(origin, stanza);
227                 return true;
228         else
229                 log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns); -- we didn't handle it
230         end
231 end
232
233 function module_has_method(module, method)
234         return type(module.module[method]) == "function";
235 end
236
237 function call_module_method(module, method, ...)
238         if module_has_method(module, method) then       
239                 local f = module.module[method];
240                 return pcall(f, ...);
241         else
242                 return false, "no-such-method";
243         end
244 end
245
246 local _modulepath = { plugin_dir, "mod_", nil, ".lua"};
247 function get_module_filename(name)
248         _modulepath[3] = name;
249         return t_concat(_modulepath);
250 end
251
252 ----- API functions exposed to modules -----------
253 -- Must all be in api.* 
254
255 -- Returns the name of the current module
256 function api:get_name()
257         return self.name;
258 end
259
260 -- Returns the host that the current module is serving
261 function api:get_host()
262         return self.host;
263 end
264
265 function api:get_host_type()
266         return hosts[self.host].type;
267 end
268
269 function api:set_global()
270         self.host = "*";
271         -- Update the logger
272         local _log = logger.init("mod_"..self.name);
273         self.log = function (self, ...) return _log(...); end;
274         self._log = _log;
275 end
276
277 local function _add_handler(module, origin_type, tag, xmlns, handler)
278         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
279         local msg = (tag == "iq") and "namespace" or "payload namespace";
280         if not handlers then
281                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
282                 handler_info[handler] = module;
283                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
284                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
285         else
286                 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);
287         end
288 end
289
290 function api:add_handler(origin_type, tag, xmlns, handler)
291         if not (origin_type and tag and xmlns and handler) then return false; end
292         if type(origin_type) == "table" then
293                 for _, origin_type in ipairs(origin_type) do
294                         _add_handler(self, origin_type, tag, xmlns, handler);
295                 end
296         else
297                 _add_handler(self, origin_type, tag, xmlns, handler);
298         end
299 end
300 function api:add_iq_handler(origin_type, xmlns, handler)
301         self:add_handler(origin_type, "iq", xmlns, handler);
302 end
303
304 addDiscoInfoHandler("*host", function(reply, to, from, node)
305         if #node == 0 then
306                 local done = {};
307                 for module, features in pairs(features_table:get(to) or NULL) do -- for each module
308                         for feature in pairs(features) do
309                                 if not done[feature] then
310                                         reply:tag("feature", {var = feature}):up(); -- TODO cache
311                                         done[feature] = true;
312                                 end
313                         end
314                 end
315                 for module, features in pairs(features_table:get("*") 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                 return next(done) ~= nil;
324         end
325 end);
326
327 function api:add_feature(xmlns)
328         features_table:set(self.host, self.name, xmlns, true);
329 end
330
331 local event_hook = function(host, mod_name, event_name, ...)
332         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
333         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
334                 handler(...);
335         end
336 end;
337 function api:add_event_hook(name, handler)
338         if not hooked:get(self.host, self.name, name) then
339                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
340                 hooked:set(self.host, self.name, name, true);
341         end
342         event_hooks:set(self.host, self.name, name, handler, true);
343 end
344
345 --------------------------------------------------------------------
346
347 local actions = {};
348
349 function actions.load(params)
350         --return true, "Module loaded ("..params.module.." on "..params.host..")";
351         return load(params.host, params.module);
352 end
353
354 function actions.unload(params)
355         return unload(params.host, params.module);
356 end
357
358 register_actions("/modules", actions);
359
360 return _M;