Merge 0.6.2/waqas with 0.6.2/MattJ
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM
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 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
10
11 local logger = require "util.logger";
12 local log = logger.init("modulemanager");
13 local eventmanager = require "core.eventmanager";
14 local config = require "core.configmanager";
15 local multitable_new = require "util.multitable".new;
16 local register_actions = require "core.actions".register;
17 local st = require "util.stanza";
18 local pluginloader = require "util.pluginloader";
19
20 local hosts = hosts;
21 local prosody = prosody;
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 local error = error;
31 local tostring = tostring;
32
33 local autoload_modules = {"presence", "message", "iq"};
34
35 -- We need this to let modules access the real global namespace
36 local _G = _G;
37
38 module "modulemanager"
39
40 api = {};
41 local api = api; -- Module API container
42
43 local modulemap = { ["*"] = {} };
44
45 local stanza_handlers = multitable_new();
46 local handler_info = {};
47
48 local modulehelpers = setmetatable({}, { __index = _G });
49
50 local handler_table = multitable_new();
51 local hooked = multitable_new();
52 local hooks = multitable_new();
53 local event_hooks = multitable_new();
54
55 local NULL = {};
56
57 -- Load modules when a host is activated
58 function load_modules_for_host(host)
59         local disabled_set = {};
60         local modules_disabled = config.get(host, "core", "modules_disabled");
61         if modules_disabled then
62                 for _, module in ipairs(modules_disabled) do
63                         disabled_set[module] = true;
64                 end
65         end
66
67         -- Load auto-loaded modules for this host
68         if hosts[host].type == "local" then
69                 for _, module in ipairs(autoload_modules) do
70                         if not disabled_set[module] then
71                                 load(host, module);
72                         end
73                 end
74         end
75
76         -- Load modules from global section
77         if config.get(host, "core", "load_global_modules") ~= false then
78                 local modules_enabled = config.get("*", "core", "modules_enabled");
79                 if modules_enabled then
80                         for _, module in ipairs(modules_enabled) do
81                                 if not disabled_set[module] and not is_loaded(host, module) then
82                                         load(host, module);
83                                 end
84                         end
85                 end
86         end
87         
88         -- Load modules from just this host
89         local modules_enabled = config.get(host, "core", "modules_enabled");
90         if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
91                 for _, module in pairs(modules_enabled) do
92                         if not is_loaded(host, module) then
93                                 load(host, module);
94                         end
95                 end
96         end
97 end
98 eventmanager.add_event_hook("host-activated", load_modules_for_host);
99 eventmanager.add_event_hook("component-activated", load_modules_for_host);
100 --
101
102 function load(host, module_name, config)
103         if not (host and module_name) then
104                 return nil, "insufficient-parameters";
105         end
106         
107         if not modulemap[host] then
108                 modulemap[host] = {};
109         end
110         
111         if modulemap[host][module_name] then
112                 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
113                 return nil, "module-already-loaded";
114         elseif modulemap["*"][module_name] then
115                 return nil, "global-module-already-loaded";
116         end
117         
118
119         local mod, err = pluginloader.load_code(module_name);
120         if not mod then
121                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
122                 return nil, err;
123         end
124
125         local _log = logger.init(host..":"..module_name);
126         local api_instance = setmetatable({ name = module_name, host = host, config = config,  _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
127
128         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
129         
130         setfenv(mod, pluginenv);
131         if not hosts[host] then
132                 local create_component = _G.require "core.componentmanager".create_component;
133                 hosts[host] = create_component(host);
134                 hosts[host].connected = false;
135                 log("debug", "Created new component: %s", host);
136         end
137         hosts[host].modules = modulemap[host];
138         modulemap[host][module_name] = pluginenv;
139         
140         local success, err = pcall(mod);
141         if success then
142                 if module_has_method(pluginenv, "load") then
143                         success, err = call_module_method(pluginenv, "load");
144                         if not success then
145                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
146                         end
147                 end
148
149                 -- Use modified host, if the module set one
150                 if api_instance.host == "*" and host ~= "*" then
151                         modulemap[host][module_name] = nil;
152                         modulemap["*"][module_name] = pluginenv;
153                         api_instance:set_global();
154                 end
155         else
156                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
157         end
158         if success then
159                 return true;
160         else -- load failed, unloading
161                 unload(api_instance.host, module_name);
162                 return nil, err;
163         end
164 end
165
166 function get_module(host, name)
167         return modulemap[host] and modulemap[host][name];
168 end
169
170 function is_loaded(host, name)
171         return modulemap[host] and modulemap[host][name] and true;
172 end
173
174 function unload(host, name, ...)
175         local mod = get_module(host, name); 
176         if not mod then return nil, "module-not-loaded"; end
177         
178         if module_has_method(mod, "unload") then
179                 local ok, err = call_module_method(mod, "unload");
180                 if (not ok) and err then
181                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
182                 end
183         end
184         local params = handler_table:get(host, name); -- , {module.host, origin_type, tag, xmlns}
185         for _, param in pairs(params or NULL) do
186                 local handlers = stanza_handlers:get(param[1], param[2], param[3], param[4]);
187                 if handlers then
188                         handler_info[handlers[1]] = nil;
189                         stanza_handlers:remove(param[1], param[2], param[3], param[4]);
190                 end
191         end
192         event_hooks:remove(host, name);
193         -- unhook event handlers hooked by module:hook
194         for event, handlers in pairs(hooks:get(host, name) or NULL) do
195                 for handler in pairs(handlers or NULL) do
196                         (hosts[host] or prosody).events.remove_handler(event, handler);
197                 end
198         end
199         hooks:remove(host, name);
200         if mod.module.items then -- remove items
201                 for key,t in pairs(mod.module.items) do
202                         for i = #t,1,-1 do
203                                 local value = t[i];
204                                 t[i] = nil;
205                                 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
206                         end
207                 end
208         end
209         modulemap[host][name] = nil;
210         return true;
211 end
212
213 function reload(host, name, ...)
214         local mod = get_module(host, name);
215         if not mod then return nil, "module-not-loaded"; end
216
217         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
218         if not _mod then
219                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
220                 return nil, err;
221         end
222
223         local saved;
224
225         if module_has_method(mod, "save") then
226                 local ok, ret, err = call_module_method(mod, "save");
227                 if ok then
228                         saved = ret;
229                 else
230                         log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
231                         if not config.get(host, "core", "force_module_reload") then
232                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
233                                 return nil, "save-state-failed";
234                         else
235                                 log("warn", "Continuing with reload (using the force)");
236                         end
237                 end
238         end
239
240         unload(host, name, ...);
241         local ok, err = load(host, name, ...);
242         if ok then
243                 mod = get_module(host, name);
244                 if module_has_method(mod, "restore") then
245                         local ok, err = call_module_method(mod, "restore", saved or {})
246                         if (not ok) and err then
247                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
248                         end
249                 end
250                 return true;
251         end
252         return ok, err;
253 end
254
255 function handle_stanza(host, origin, stanza)
256         local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
257         if name == "iq" and xmlns == "jabber:client" then
258                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
259                         xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
260                         log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
261                 else
262                         log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
263                         return true;
264                 end
265         end
266         local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
267         if not handlers then handlers = stanza_handlers:get("*", origin_type, name, xmlns); end
268         if handlers then
269                 log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
270                 (handlers[1])(origin, stanza);
271                 return true;
272         else
273                 if stanza.attr.xmlns == "jabber:client" then
274                         log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
275                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
276                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
277                         end
278                 elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
279                         log("warn", "Unhandled %s stream element: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
280                         origin:close("unsupported-stanza-type");
281                 end
282         end
283 end
284
285 function module_has_method(module, method)
286         return type(module.module[method]) == "function";
287 end
288
289 function call_module_method(module, method, ...)
290         if module_has_method(module, method) then       
291                 local f = module.module[method];
292                 return pcall(f, ...);
293         else
294                 return false, "no-such-method";
295         end
296 end
297
298 ----- API functions exposed to modules -----------
299 -- Must all be in api.* 
300
301 -- Returns the name of the current module
302 function api:get_name()
303         return self.name;
304 end
305
306 -- Returns the host that the current module is serving
307 function api:get_host()
308         return self.host;
309 end
310
311 function api:get_host_type()
312         return hosts[self.host].type;
313 end
314
315 function api:set_global()
316         self.host = "*";
317         -- Update the logger
318         local _log = logger.init("mod_"..self.name);
319         self.log = function (self, ...) return _log(...); end;
320         self._log = _log;
321 end
322
323 local function _add_handler(module, origin_type, tag, xmlns, handler)
324         local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
325         local msg = (tag == "iq") and "namespace" or "payload namespace";
326         if not handlers then
327                 stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
328                 handler_info[handler] = module;
329                 handler_table:add(module.host, module.name, {module.host, origin_type, tag, xmlns});
330                 --module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
331         else
332                 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);
333         end
334 end
335
336 function api:add_handler(origin_type, tag, xmlns, handler)
337         if not (origin_type and tag and xmlns and handler) then return false; end
338         if type(origin_type) == "table" then
339                 for _, origin_type in ipairs(origin_type) do
340                         _add_handler(self, origin_type, tag, xmlns, handler);
341                 end
342         else
343                 _add_handler(self, origin_type, tag, xmlns, handler);
344         end
345 end
346 function api:add_iq_handler(origin_type, xmlns, handler)
347         self:add_handler(origin_type, "iq", xmlns, handler);
348 end
349
350 function api:add_feature(xmlns)
351         self:add_item("feature", xmlns);
352 end
353 function api:add_identity(category, type, name)
354         self:add_item("identity", {category = category, type = type, name = name});
355 end
356
357 local event_hook = function(host, mod_name, event_name, ...)
358         if type((...)) == "table" and (...).host and (...).host ~= host then return; end
359         for handler in pairs(event_hooks:get(host, mod_name, event_name) or NULL) do
360                 handler(...);
361         end
362 end;
363 function api:add_event_hook(name, handler)
364         if not hooked:get(self.host, self.name, name) then
365                 eventmanager.add_event_hook(name, function(...) event_hook(self.host, self.name, name, ...); end);
366                 hooked:set(self.host, self.name, name, true);
367         end
368         event_hooks:set(self.host, self.name, name, handler, true);
369 end
370
371 function api:fire_event(...)
372         return (hosts[self.host] or prosody).events.fire_event(...);
373 end
374
375 function api:hook(event, handler, priority)
376         hooks:set(self.host, self.name, event, handler, true);
377         (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
378 end
379
380 function api:hook_stanza(xmlns, name, handler, priority)
381         if not handler and type(name) == "function" then
382                 -- If only 2 options then they specified no xmlns
383                 xmlns, name, handler, priority = nil, xmlns, name, handler;
384         elseif not (handler and name) then
385                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
386                 return;
387         end
388         return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
389 end
390
391 function api:require(lib)
392         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
393         if not f then
394                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
395         end
396         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
397         setfenv(f, setmetatable({ module = self }, { __index = _G }));
398         return f();
399 end
400
401 function api:get_option(name, default_value)
402         local value = config.get(self.host, self.name, name);
403         if value == nil then
404                 value = config.get(self.host, "core", name);
405                 if value == nil then
406                         value = default_value;
407                 end
408         end
409         return value;
410 end
411
412 local t_remove = _G.table.remove;
413 local module_items = multitable_new();
414 function api:add_item(key, value)
415         self.items = self.items or {};
416         self.items[key] = self.items[key] or {};
417         t_insert(self.items[key], value);
418         self:fire_event("item-added/"..key, {source = self, item = value});
419 end
420 function api:remove_item(key, value)
421         local t = self.items and self.items[key] or NULL;
422         for i = #t,1,-1 do
423                 if t[i] == value then
424                         t_remove(self.items[key], i);
425                         self:fire_event("item-removed/"..key, {source = self, item = value});
426                         return value;
427                 end
428         end
429 end
430
431 function api:get_host_items(key)
432         local result = {};
433         for mod_name, module in pairs(modulemap[self.host]) do
434                 module = module.module;
435                 if module.items then
436                         for _, item in ipairs(module.items[key] or NULL) do
437                                 t_insert(result, item);
438                         end
439                 end
440         end
441         for mod_name, module in pairs(modulemap["*"]) do
442                 module = module.module;
443                 if module.items then
444                         for _, item in ipairs(module.items[key] or NULL) do
445                                 t_insert(result, item);
446                         end
447                 end
448         end
449         return result;
450 end
451
452 --------------------------------------------------------------------
453
454 local actions = {};
455
456 function actions.load(params)
457         --return true, "Module loaded ("..params.module.." on "..params.host..")";
458         return load(params.host, params.module);
459 end
460
461 function actions.unload(params)
462         return unload(params.host, params.module);
463 end
464
465 register_actions("/modules", actions);
466
467 return _M;