Merge with sasl branch.
[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
42                         log("error", "Error while loading listener '%s': %s", tostring(name), tostring(ret));
43                         return nil, ret;
44                 end
45                 h = listeners[name];
46         end
47         return h;
48 end
49
50 function start(name, udata)
51         local h, err = get(name);
52         if not h then
53                 error("No such connection module: "..name.. (err and (" ("..err..")") or ""), 0);
54         end
55         
56         if udata then
57                 if (udata.type == "ssl" or udata.type == "tls") and not udata.ssl then
58                         error("No SSL context supplied for a "..tostring(udata.type):upper().." connection!", 0);
59                 elseif udata.ssl and udata.type == "tcp" then
60                         error("SSL context supplied for a TCP connection!", 0);
61                 end
62         end
63         
64         return server.addserver(h, 
65                         (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), 
66                                 (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");
67 end
68
69 return _M;