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