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