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