portmanager: use_ipv6 defaults to true if luasocket has ipv6 support
[prosody.git] / core / moduleapi.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2012 Matthew Wild
3 -- Copyright (C) 2008-2012 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 config = require "core.configmanager";
10 local modulemanager = require "modulemanager"; -- This is necessary to avoid require loops
11 local array = require "util.array";
12 local set = require "util.set";
13 local logger = require "util.logger";
14 local pluginloader = require "util.pluginloader";
15 local timer = require "util.timer";
16
17 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
18 local error, setmetatable, type = error, setmetatable, type;
19 local ipairs, pairs, select, unpack = ipairs, pairs, select, unpack;
20 local tonumber, tostring = tonumber, tostring;
21
22 local prosody = prosody;
23 local hosts = prosody.hosts;
24 local core_post_stanza = prosody.core_post_stanza;
25
26 -- Registry of shared module data
27 local shared_data = setmetatable({}, { __mode = "v" });
28
29 local NULL = {};
30
31 local api = {};
32
33 -- Returns the name of the current module
34 function api:get_name()
35         return self.name;
36 end
37
38 -- Returns the host that the current module is serving
39 function api:get_host()
40         return self.host;
41 end
42
43 function api:get_host_type()
44         return self.host ~= "*" and hosts[self.host].type or nil;
45 end
46
47 function api:set_global()
48         self.host = "*";
49         -- Update the logger
50         local _log = logger.init("mod_"..self.name);
51         self.log = function (self, ...) return _log(...); end;
52         self._log = _log;
53         self.global = true;
54 end
55
56 function api:add_feature(xmlns)
57         self:add_item("feature", xmlns);
58 end
59 function api:add_identity(category, type, name)
60         self:add_item("identity", {category = category, type = type, name = name});
61 end
62 function api:add_extension(data)
63         self:add_item("extension", data);
64 end
65
66 function api:fire_event(...)
67         return (hosts[self.host] or prosody).events.fire_event(...);
68 end
69
70 function api:hook_object_event(object, event, handler, priority)
71         self.event_handlers:set(object, event, handler, true);
72         return object.add_handler(event, handler, priority);
73 end
74
75 function api:unhook_object_event(object, event, handler)
76         return object.remove_handler(event, handler);
77 end
78
79 function api:hook(event, handler, priority)
80         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
81 end
82
83 function api:hook_global(event, handler, priority)
84         return self:hook_object_event(prosody.events, event, handler, priority);
85 end
86
87 function api:hook_tag(xmlns, name, handler, priority)
88         if not handler and type(name) == "function" then
89                 -- If only 2 options then they specified no xmlns
90                 xmlns, name, handler, priority = nil, xmlns, name, handler;
91         elseif not (handler and name) then
92                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
93                 return;
94         end
95         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
96 end
97 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
98
99 function api:require(lib)
100         local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
101         if not f then
102                 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
103         end
104         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
105         return f();
106 end
107
108 function api:depends(name)
109         if not self.dependencies then
110                 self.dependencies = {};
111                 self:hook("module-reloaded", function (event)
112                         if self.dependencies[event.module] and not self.reloading then
113                                 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
114                                 modulemanager.reload(self.host, self.name);
115                                 return;
116                         end
117                 end);
118                 self:hook("module-unloaded", function (event)
119                         if self.dependencies[event.module] then
120                                 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
121                                 modulemanager.unload(self.host, self.name);
122                         end
123                 end);
124         end
125         local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
126         if mod and mod.module.host == "*" and self.host ~= "*"
127         and modulemanager.module_has_method(mod, "add_host") then
128                 mod = nil; -- Target is a shared module, so we still want to load it on our host
129         end
130         if not mod then
131                 local err;
132                 mod, err = modulemanager.load(self.host, name);
133                 if not mod then
134                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
135                 end
136         end
137         self.dependencies[name] = true;
138         return mod;
139 end
140
141 -- Returns one or more shared tables at the specified virtual paths
142 -- Intentionally does not allow the table at a path to be _set_, it
143 -- is auto-created if it does not exist.
144 function api:shared(...)
145         if not self.shared_data then self.shared_data = {}; end
146         local paths = { n = select("#", ...), ... };
147         local data_array = {};
148         local default_path_components = { self.host, self.name };
149         for i = 1, paths.n do
150                 local path = paths[i];
151                 if path:sub(1,1) ~= "/" then -- Prepend default components
152                         local n_components = select(2, path:gsub("/", "%1"));
153                         path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
154                 end
155                 local shared = shared_data[path];
156                 if not shared then
157                         shared = {};
158                         if path:match("%-cache$") then
159                                 setmetatable(shared, { __mode = "kv" });
160                         end
161                         shared_data[path] = shared;
162                 end
163                 t_insert(data_array, shared);
164                 self.shared_data[path] = shared;
165         end
166         return unpack(data_array);
167 end
168
169 function api:get_option(name, default_value)
170         local value = config.get(self.host, name);
171         if value == nil then
172                 value = default_value;
173         end
174         return value;
175 end
176
177 function api:get_option_string(name, default_value)
178         local value = self:get_option(name, default_value);
179         if type(value) == "table" then
180                 if #value > 1 then
181                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
182                 end
183                 value = value[1];
184         end
185         if value == nil then
186                 return nil;
187         end
188         return tostring(value);
189 end
190
191 function api:get_option_number(name, ...)
192         local value = self:get_option(name, ...);
193         if type(value) == "table" then
194                 if #value > 1 then
195                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
196                 end
197                 value = value[1];
198         end
199         local ret = tonumber(value);
200         if value ~= nil and ret == nil then
201                 self:log("error", "Config option '%s' not understood, expecting a number", name);
202         end
203         return ret;
204 end
205
206 function api:get_option_boolean(name, ...)
207         local value = self:get_option(name, ...);
208         if type(value) == "table" then
209                 if #value > 1 then
210                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
211                 end
212                 value = value[1];
213         end
214         if value == nil then
215                 return nil;
216         end
217         local ret = value == true or value == "true" or value == 1 or nil;
218         if ret == nil then
219                 ret = (value == false or value == "false" or value == 0);
220                 if ret then
221                         ret = false;
222                 else
223                         ret = nil;
224                 end
225         end
226         if ret == nil then
227                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
228         end
229         return ret;
230 end
231
232 function api:get_option_array(name, ...)
233         local value = self:get_option(name, ...);
234
235         if value == nil then
236                 return nil;
237         end
238         
239         if type(value) ~= "table" then
240                 return array{ value }; -- Assume any non-list is a single-item list
241         end
242         
243         return array():append(value); -- Clone
244 end
245
246 function api:get_option_set(name, ...)
247         local value = self:get_option_array(name, ...);
248         
249         if value == nil then
250                 return nil;
251         end
252         
253         return set.new(value);
254 end
255
256 function api:add_item(key, value)
257         self.items = self.items or {};
258         self.items[key] = self.items[key] or {};
259         t_insert(self.items[key], value);
260         self:fire_event("item-added/"..key, {source = self, item = value});
261 end
262 function api:remove_item(key, value)
263         local t = self.items and self.items[key] or NULL;
264         for i = #t,1,-1 do
265                 if t[i] == value then
266                         t_remove(self.items[key], i);
267                         self:fire_event("item-removed/"..key, {source = self, item = value});
268                         return value;
269                 end
270         end
271 end
272
273 function api:get_host_items(key)
274         local result = {};
275         for mod_name, module in pairs(modulemanager.get_modules(self.host)) do
276                 module = module.module;
277                 if module.items then
278                         for _, item in ipairs(module.items[key] or NULL) do
279                                 t_insert(result, item);
280                         end
281                 end
282         end
283         for mod_name, module in pairs(modulemanager.get_modules("*")) do
284                 module = module.module;
285                 if module.items then
286                         for _, item in ipairs(module.items[key] or NULL) do
287                                 t_insert(result, item);
288                         end
289                 end
290         end
291         return result;
292 end
293
294 function api:handle_items(type, added_cb, removed_cb, existing)
295         self:hook("item-added/"..type, added_cb);
296         self:hook("item-removed/"..type, removed_cb);
297         if existing ~= false then
298                 for _, item in ipairs(self:get_host_items(type)) do
299                         added_cb({ item = item });
300                 end
301         end
302 end
303
304 function api:provides(name, item)
305         if not item then item = self.environment; end
306         if not item.name then
307                 local item_name = self.name;
308                 -- Strip a provider prefix to find the item name
309                 -- (e.g. "auth_foo" -> "foo" for an auth provider)
310                 if item_name:find(name.."_", 1, true) == 1 then
311                         item_name = item_name:sub(#name+2);
312                 end
313                 item.name = item_name;
314         end
315         self:add_item(name.."-provider", item);
316 end
317
318 function api:send(stanza)
319         return core_post_stanza(hosts[self.host], stanza);
320 end
321
322 function api:add_timer(delay, callback)
323         return timer.add_task(delay, function (t)
324                 if self.loaded == false then return; end
325                 return callback(t);
326         end);
327 end
328
329 local path_sep = package.config:sub(1,1);
330 function api:get_directory()
331         return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
332 end
333
334 function api:load_resource(path, mode)
335         path = config.resolve_relative_path(self:get_directory(), path);
336         return io.open(path, mode);
337 end
338
339 return api;