Merge 0.8->trunk.
[prosody.git] / net / connlisteners.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 listeners_dir = (CFG_SOURCEDIR or ".").."/net/";
12 local server = require "net.server";
13 local log = require "util.logger".init("connlisteners");
14 local tostring = tostring;
15
16 local dofile, xpcall, error =
17       dofile, xpcall, error
18
19 local debug_traceback = debug.traceback;
20
21 module "connlisteners"
22
23 local listeners = {};
24
25 function register(name, listener)
26         if listeners[name] and listeners[name] ~= listener then
27                 log("debug", "Listener %s is already registered, not registering any more", name);
28                 return false;
29         end
30         listeners[name] = listener;
31         log("debug", "Registered connection listener %s", name);
32         return true;
33 end
34
35 function deregister(name)
36         listeners[name] = nil;
37 end
38
39 function get(name)
40         local h = listeners[name];
41         if not h then
42                 local ok, ret = xpcall(function() dofile(listeners_dir..name:gsub("[^%w%-]", "_").."_listener.lua") end, debug_traceback);
43                 if not ok then
44                         log("error", "Error while loading listener '%s': %s", tostring(name), tostring(ret));
45                         return nil, ret;
46                 end
47                 h = listeners[name];
48         end
49         return h;
50 end
51
52 function start(name, udata)
53         local h, err = get(name);
54         if not h then
55                 error("No such connection module: "..name.. (err and (" ("..err..")") or ""), 0);
56         end
57         
58         local interface = (udata and udata.interface) or h.default_interface or "*";
59         local port = (udata and udata.port) or h.default_port or error("Can't start listener "..name.." because no port was specified, and it has no default port", 0);
60         local mode = (udata and udata.mode) or h.default_mode or 1;
61         local ssl = (udata and udata.ssl) or nil;
62         local autossl = udata and udata.type == "ssl";
63         
64         if autossl and not ssl then
65                 return nil, "no ssl context";
66         end
67         
68         return server.addserver(interface, port, h, mode, autossl and ssl or nil);
69 end
70
71 return _M;