1 module server.listeners;
2 
3 import core.thread : Thread;
4 import server.listener : ButterflyListener;
5 import std.socket : Socket, Address, SocketType, ProtocolType, parseAddress, AddressFamily;
6 import std.json : JSONValue;
7 import client.client;
8 import std.conv : to;
9 
10 
11 /* TODO: Enforce IPv4 on address */
12 public class IPv4Listener : ButterflyListener
13 {
14 
15     private Socket serverSocket;
16 
17     this(string name, JSONValue config)
18     {
19         super(name, config["domain"].str(), config);
20 
21         Address bindAddress = parseAddress(config["address"].str(), to!(ushort)(config["port"].str()));
22 
23 		/* TODO: Throw an exception if not IPv4 */
24 		if(bindAddress.addressFamily() == AddressFamily.INET)
25 		{
26 			/**
27 			* Instantiate a new Socket for the given Address
28 			* `bindAddress` of which it will bind to.
29 			*/
30 			serverSocket = new Socket(AddressFamily.INET, SocketType.STREAM, ProtocolType.TCP);
31 			serverSocket.bind(bindAddress);
32 		}	
33 		else
34 		{
35 			/* TODO: Throw an exception if not IPv4 */
36 		}
37             
38     }
39 
40     public override void run()
41     {
42         serverSocket.listen(1); //TODO: backlog
43 
44         while(true)
45         {
46             /* Accept the queued connection */
47             Socket clientConnection = serverSocket.accept();
48 
49 
50             ButterflyClient client = new ButterflyClient(this, clientConnection);
51 
52             /* Start the client handler */
53             client.start();
54         }
55     }
56 }
57 
58 /* TODO: Enforce IPv6 on address */
59 public class IPv6Listener : ButterflyListener
60 {
61 
62     private Socket serverSocket;
63 
64     this(string name, JSONValue config)
65     {
66         super(name, config["domain"].str(), config);
67 
68         Address bindAddress = parseAddress(config["address"].str(), to!(ushort)(config["port"].str()));
69 
70 		/* TODO: Throw an exception if not IPv6 */
71 		if(bindAddress.addressFamily() == AddressFamily.INET6)
72 		{
73 			/**
74 			* Instantiate a new Socket for the given Address
75 			* `bindAddress` of which it will bind to.
76 			*/
77 			serverSocket = new Socket(AddressFamily.INET6, SocketType.STREAM, ProtocolType.TCP);
78 			serverSocket.bind(bindAddress);
79 		}	
80 		else
81 		{
82 			/* TODO: Throw an exception if not IPv6 */
83 		} 
84     }
85 
86     public override void run()
87     {
88         serverSocket.listen(1); //TODO: backlog
89 
90         while(true)
91         {
92             /* Accept the queued connection */
93             Socket clientConnection = serverSocket.accept();
94 
95 
96             ButterflyClient client = new ButterflyClient(this, clientConnection);
97 
98             /* Start the client handler */
99             client.start();
100         }
101     }
102 }