net.connlisteners: Allow listeners to specify default interface
[prosody.git] / net / connlisteners.lua
1 -- Prosody IM v0.4
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
10
11 local listeners_dir = (CFG_SOURCEDIR or ".").."/net/";
12 local server = require "net.server";
13 local log = require "util.logger".init("connlisteners");
14
15 local dofile, pcall, error = 
16         dofile, pcall, error
17
18 module "connlisteners"
19
20 local listeners = {};
21
22 function register(name, listener)
23         if listeners[name] and listeners[name] ~= listener then
24                 log("warn", "Listener %s is already registered, not registering any more", name);
25                 return false;
26         end
27         listeners[name] = listener;
28         log("info", "Registered connection listener %s", name);
29         return true;
30 end
31
32 function deregister(name)
33         listeners[name] = nil;
34 end
35
36 function get(name)
37         local h = listeners[name];
38         if not h then
39                 local ok, ret = pcall(dofile, listeners_dir..name:gsub("[^%w%-]", "_").."_listener.lua");
40                 if not ok then return nil, ret; end
41                 h = listeners[name];
42         end
43         return h;
44 end
45
46 function start(name, udata)
47         local h, err = get(name);
48         if not h then
49                 error("No such connection module: "..name.. (err and (" ("..err..")") or ""), 0);
50         end
51         
52         if udata then
53                 if (udata.type == "ssl" or udata.type == "tls") and not udata.ssl then
54                         error("No SSL context supplied for a "..tostring(udata.type):upper().." connection!", 0);
55                 elseif udata.ssl and udata.type == "tcp" then
56                         error("SSL context supplied for a TCP connection!", 0);
57                 end
58         end
59         
60         return server.addserver(h, 
61                         (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), 
62                                 (udata and udata.interface) or h.default_interface or "*", (udata and udata.mode) or h.default_mode or 1, (udata and udata.ssl) or nil, 99999999, udata and udata.type == "ssl");
63 end
64
65 return _M;