util.pposix: Ask for shared file descriptor table using rfork() on *BSD (fixes #412)
[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 array = require "util.array";
11 local set = require "util.set";
12 local it = require "util.iterators";
13 local logger = require "util.logger";
14 local pluginloader = require "util.pluginloader";
15 local timer = require "util.timer";
16 local resolve_relative_path = require"util.paths".resolve_relative_path;
17 local measure = require "core.statsmanager".measure;
18 local st = require "util.stanza";
19
20 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
21 local error, setmetatable, type = error, setmetatable, type;
22 local ipairs, pairs, select = ipairs, pairs, select;
23 local unpack = table.unpack or unpack; --luacheck: ignore 113
24 local tonumber, tostring = tonumber, tostring;
25 local require = require;
26
27 local prosody = prosody;
28 local hosts = prosody.hosts;
29
30 -- FIXME: This assert() is to try and catch an obscure bug (2013-04-05)
31 local core_post_stanza = assert(prosody.core_post_stanza,
32         "prosody.core_post_stanza is nil, please report this as a bug");
33
34 -- Registry of shared module data
35 local shared_data = setmetatable({}, { __mode = "v" });
36
37 local NULL = {};
38
39 local api = {};
40
41 -- Returns the name of the current module
42 function api:get_name()
43         return self.name;
44 end
45
46 -- Returns the host that the current module is serving
47 function api:get_host()
48         return self.host;
49 end
50
51 function api:get_host_type()
52         return (self.host == "*" and "global") or hosts[self.host].type or "local";
53 end
54
55 function api:set_global()
56         self.host = "*";
57         -- Update the logger
58         local _log = logger.init("mod_"..self.name);
59         self.log = function (self, ...) return _log(...); end; --luacheck: ignore self
60         self._log = _log;
61         self.global = true;
62 end
63
64 function api:add_feature(xmlns)
65         self:add_item("feature", xmlns);
66 end
67 function api:add_identity(category, identity_type, name)
68         self:add_item("identity", {category = category, type = identity_type, name = name});
69 end
70 function api:add_extension(data)
71         self:add_item("extension", data);
72 end
73 function api:has_feature(xmlns)
74         for _, feature in ipairs(self:get_host_items("feature")) do
75                 if feature == xmlns then return true; end
76         end
77         return false;
78 end
79 function api:has_identity(category, identity_type, name)
80         for _, id in ipairs(self:get_host_items("identity")) do
81                 if id.category == category and id.type == identity_type and id.name == name then
82                         return true;
83                 end
84         end
85         return false;
86 end
87
88 function api:fire_event(...)
89         return (hosts[self.host] or prosody).events.fire_event(...);
90 end
91
92 function api:hook_object_event(object, event, handler, priority)
93         self.event_handlers:set(object, event, handler, true);
94         return object.add_handler(event, handler, priority);
95 end
96
97 function api:unhook_object_event(object, event, handler)
98         self.event_handlers:set(object, event, handler, nil);
99         return object.remove_handler(event, handler);
100 end
101
102 function api:hook(event, handler, priority)
103         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
104 end
105
106 function api:hook_global(event, handler, priority)
107         return self:hook_object_event(prosody.events, event, handler, priority);
108 end
109
110 function api:hook_tag(xmlns, name, handler, priority)
111         if not handler and type(name) == "function" then
112                 -- If only 2 options then they specified no xmlns
113                 xmlns, name, handler, priority = nil, xmlns, name, handler;
114         elseif not (handler and name) then
115                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
116                 return;
117         end
118         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
119 end
120 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
121
122 function api:unhook(event, handler)
123         return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
124 end
125
126 function api:wrap_object_event(events_object, event, handler)
127         return self:hook_object_event(assert(events_object.wrappers, "no wrappers"), event, handler);
128 end
129
130 function api:wrap_event(event, handler)
131         return self:wrap_object_event((hosts[self.host] or prosody).events, event, handler);
132 end
133
134 function api:wrap_global(event, handler)
135         return self:hook_object_event(prosody.events, event, handler);
136 end
137
138 function api:require(lib)
139         local f, n = pluginloader.load_code_ext(self.name, lib, "lib.lua", self.environment);
140         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
141         return f();
142 end
143
144 function api:depends(name)
145         local modulemanager = require"core.modulemanager";
146         if not self.dependencies then
147                 self.dependencies = {};
148                 self:hook("module-reloaded", function (event)
149                         if self.dependencies[event.module] and not self.reloading then
150                                 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
151                                 modulemanager.reload(self.host, self.name);
152                                 return;
153                         end
154                 end);
155                 self:hook("module-unloaded", function (event)
156                         if self.dependencies[event.module] then
157                                 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
158                                 modulemanager.unload(self.host, self.name);
159                         end
160                 end);
161         end
162         local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
163         if mod and mod.module.host == "*" and self.host ~= "*"
164         and modulemanager.module_has_method(mod, "add_host") then
165                 mod = nil; -- Target is a shared module, so we still want to load it on our host
166         end
167         if not mod then
168                 local err;
169                 mod, err = modulemanager.load(self.host, name);
170                 if not mod then
171                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
172                 end
173         end
174         self.dependencies[name] = true;
175         return mod;
176 end
177
178 -- Returns one or more shared tables at the specified virtual paths
179 -- Intentionally does not allow the table at a path to be _set_, it
180 -- is auto-created if it does not exist.
181 function api:shared(...)
182         if not self.shared_data then self.shared_data = {}; end
183         local paths = { n = select("#", ...), ... };
184         local data_array = {};
185         local default_path_components = { self.host, self.name };
186         for i = 1, paths.n do
187                 local path = paths[i];
188                 if path:sub(1,1) ~= "/" then -- Prepend default components
189                         local n_components = select(2, path:gsub("/", "%1"));
190                         path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
191                 end
192                 local shared = shared_data[path];
193                 if not shared then
194                         shared = {};
195                         if path:match("%-cache$") then
196                                 setmetatable(shared, { __mode = "kv" });
197                         end
198                         shared_data[path] = shared;
199                 end
200                 t_insert(data_array, shared);
201                 self.shared_data[path] = shared;
202         end
203         return unpack(data_array);
204 end
205
206 function api:get_option(name, default_value)
207         local value = config.get(self.host, name);
208         if value == nil then
209                 value = default_value;
210         end
211         return value;
212 end
213
214 function api:get_option_string(name, default_value)
215         local value = self:get_option(name, default_value);
216         if type(value) == "table" then
217                 if #value > 1 then
218                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
219                 end
220                 value = value[1];
221         end
222         if value == nil then
223                 return nil;
224         end
225         return tostring(value);
226 end
227
228 function api:get_option_number(name, ...)
229         local value = self:get_option(name, ...);
230         if type(value) == "table" then
231                 if #value > 1 then
232                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
233                 end
234                 value = value[1];
235         end
236         local ret = tonumber(value);
237         if value ~= nil and ret == nil then
238                 self:log("error", "Config option '%s' not understood, expecting a number", name);
239         end
240         return ret;
241 end
242
243 function api:get_option_boolean(name, ...)
244         local value = self:get_option(name, ...);
245         if type(value) == "table" then
246                 if #value > 1 then
247                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
248                 end
249                 value = value[1];
250         end
251         if value == nil then
252                 return nil;
253         end
254         local ret = value == true or value == "true" or value == 1 or nil;
255         if ret == nil then
256                 ret = (value == false or value == "false" or value == 0);
257                 if ret then
258                         ret = false;
259                 else
260                         ret = nil;
261                 end
262         end
263         if ret == nil then
264                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
265         end
266         return ret;
267 end
268
269 function api:get_option_array(name, ...)
270         local value = self:get_option(name, ...);
271
272         if value == nil then
273                 return nil;
274         end
275
276         if type(value) ~= "table" then
277                 return array{ value }; -- Assume any non-list is a single-item list
278         end
279
280         return array():append(value); -- Clone
281 end
282
283 function api:get_option_set(name, ...)
284         local value = self:get_option_array(name, ...);
285
286         if value == nil then
287                 return nil;
288         end
289
290         return set.new(value);
291 end
292
293 function api:get_option_inherited_set(name, ...)
294         local value = self:get_option_set(name, ...);
295         local global_value = self:context("*"):get_option_set(name, ...);
296         if not value then
297                 return global_value;
298         elseif not global_value then
299                 return value;
300         end
301         value:include(global_value);
302         return value;
303 end
304
305 function api:get_option_path(name, default, parent)
306         if parent == nil then
307                 parent = parent or self:get_directory();
308         elseif prosody.paths[parent] then
309                 parent = prosody.paths[parent];
310         end
311         local value = self:get_option_string(name, default);
312         if value == nil then
313                 return nil;
314         end
315         return resolve_relative_path(parent, value);
316 end
317
318
319 function api:context(host)
320         return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
321 end
322
323 function api:add_item(key, value)
324         self.items = self.items or {};
325         self.items[key] = self.items[key] or {};
326         t_insert(self.items[key], value);
327         self:fire_event("item-added/"..key, {source = self, item = value});
328 end
329 function api:remove_item(key, value)
330         local t = self.items and self.items[key] or NULL;
331         for i = #t,1,-1 do
332                 if t[i] == value then
333                         t_remove(self.items[key], i);
334                         self:fire_event("item-removed/"..key, {source = self, item = value});
335                         return value;
336                 end
337         end
338 end
339
340 function api:get_host_items(key)
341         local modulemanager = require"core.modulemanager";
342         local result = modulemanager.get_items(key, self.host) or {};
343         return result;
344 end
345
346 function api:handle_items(item_type, added_cb, removed_cb, existing)
347         self:hook("item-added/"..item_type, added_cb);
348         self:hook("item-removed/"..item_type, removed_cb);
349         if existing ~= false then
350                 for _, item in ipairs(self:get_host_items(item_type)) do
351                         added_cb({ item = item });
352                 end
353         end
354 end
355
356 function api:provides(name, item)
357         -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
358         if not item then
359                 item = {}
360                 for k,v in pairs(self.environment) do
361                         if k ~= "module" then item[k] = v; end
362                 end
363         end
364         if not item.name then
365                 local item_name = self.name;
366                 -- Strip a provider prefix to find the item name
367                 -- (e.g. "auth_foo" -> "foo" for an auth provider)
368                 if item_name:find(name.."_", 1, true) == 1 then
369                         item_name = item_name:sub(#name+2);
370                 end
371                 item.name = item_name;
372         end
373         item._provided_by = self.name;
374         self:add_item(name.."-provider", item);
375 end
376
377 function api:send(stanza, origin)
378         return core_post_stanza(origin or hosts[self.host], stanza);
379 end
380
381 function api:broadcast(jids, stanza, iter)
382         for jid in (iter or it.values)(jids) do
383                 local new_stanza = st.clone(stanza);
384                 new_stanza.attr.to = jid;
385                 core_post_stanza(hosts[self.host], new_stanza);
386         end
387 end
388
389 function api:add_timer(delay, callback)
390         return timer.add_task(delay, function (t)
391                 if self.loaded == false then return; end
392                 return callback(t);
393         end);
394 end
395
396 local path_sep = package.config:sub(1,1);
397 function api:get_directory()
398         return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
399 end
400
401 function api:load_resource(path, mode)
402         path = resolve_relative_path(self:get_directory(), path);
403         return io.open(path, mode);
404 end
405
406 function api:open_store(name, store_type)
407         return require"core.storagemanager".open(self.host, name or self.name, store_type);
408 end
409
410 function api:measure(name, stat_type)
411         return measure(stat_type, "/"..self.host.."/mod_"..self.name.."/"..name);
412 end
413
414 function api:measure_object_event(events_object, event_name, stat_name)
415         local m = self:measure(stat_name or event_name, "duration");
416         local function handler(handlers, _event_name, _event_data)
417                 local finished = m();
418                 local ret = handlers(_event_name, _event_data);
419                 finished();
420                 return ret;
421         end
422         return self:hook_object_event(events_object, event_name, handler);
423 end
424
425 function api:measure_event(event_name, stat_name)
426         return self:measure_object_event((hosts[self.host] or prosody).events.wrappers, event_name, stat_name);
427 end
428
429 function api:measure_global_event(event_name, stat_name)
430         return self:measure_object_event(prosody.events.wrappers, event_name, stat_name);
431 end
432
433 return api;