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