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