-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathServer.cs
399 lines (344 loc) · 13.1 KB
/
Server.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace TelnetServer
{
public class Server
{
/// <summary>
/// Telnet's default port.
/// </summary>
private const int PORT = 23;
/// <summary>
/// End of line constant.
/// </summary>
public const string END_LINE = "\r\n";
public const string CURSOR = " > ";
/// <summary>
/// Server's main socket.
/// </summary>
private Socket serverSocket;
/// <summary>
/// The IP on which to listen.
/// </summary>
private IPAddress ip;
/// <summary>
/// The default data size for received data.
/// </summary>
private readonly int dataSize;
/// <summary>
/// Contains the received data.
/// </summary>
private byte[] data;
/// <summary>
/// True for allowing incoming connections;
/// false otherwise.
/// </summary>
private bool acceptIncomingConnections;
/// <summary>
/// Contains all connected clients indexed
/// by their socket.
/// </summary>
private Dictionary<Socket, Client> clients;
public delegate void ConnectionEventHandler(Client c);
/// <summary>
/// Occurs when a client is connected.
/// </summary>
public event ConnectionEventHandler ClientConnected;
/// <summary>
/// Occurs when a client is disconnected.
/// </summary>
public event ConnectionEventHandler ClientDisconnected;
public delegate void ConnectionBlockedEventHandler(IPEndPoint endPoint);
/// <summary>
/// Occurs when an incoming connection is blocked.
/// </summary>
public event ConnectionBlockedEventHandler ConnectionBlocked;
public delegate void MessageReceivedEventHandler(Client c, string message);
/// <summary>
/// Occurs when a message is received.
/// </summary>
public event MessageReceivedEventHandler MessageReceived;
/// <summary>
/// Initializes a new instance of the <see cref="Server"/> class.
/// </summary>
/// <param name="ip">The IP on which to listen to.</param>
/// <param name="dataSize">Data size for received data.</param>
public Server(IPAddress ip, int dataSize = 1024)
{
this.ip = ip;
this.dataSize = dataSize;
this.data = new byte[dataSize];
this.clients = new Dictionary<Socket, Client>();
this.acceptIncomingConnections = true;
this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// Starts the server.
/// </summary>
public void start()
{
serverSocket.Bind(new IPEndPoint(ip, PORT));
serverSocket.Listen(0);
serverSocket.BeginAccept(new AsyncCallback(handleIncomingConnection), serverSocket);
}
/// <summary>
/// Stops the server.
/// </summary>
public void stop()
{
serverSocket.Close();
}
/// <summary>
/// Returns whether incoming connections
/// are allowed.
/// </summary>
/// <returns>True is connections are allowed;
/// false otherwise.</returns>
public bool incomingConnectionsAllowed()
{
return acceptIncomingConnections;
}
/// <summary>
/// Denies the incoming connections.
/// </summary>
public void denyIncomingConnections()
{
this.acceptIncomingConnections = false;
}
/// <summary>
/// Allows the incoming connections.
/// </summary>
public void allowIncomingConnections()
{
this.acceptIncomingConnections = true;
}
/// <summary>
/// Clears the screen for the specified
/// client.
/// </summary>
/// <param name="c">The client on which
/// to clear the screen.</param>
public void clearClientScreen(Client c)
{
sendMessageToClient(c, "\u001B[1J\u001B[H");
}
/// <summary>
/// Sends a text message to the specified
/// client.
/// </summary>
/// <param name="c">The client.</param>
/// <param name="message">The message.</param>
public void sendMessageToClient(Client c, string message)
{
Socket clientSocket = getSocketByClient(c);
sendMessageToSocket(clientSocket, message);
}
/// <summary>
/// Sends a text message to the specified
/// socket.
/// </summary>
/// <param name="s">The socket.</param>
/// <param name="message">The message.</param>
private void sendMessageToSocket(Socket s, string message)
{
byte[] data = Encoding.ASCII.GetBytes(message);
sendBytesToSocket(s, data);
}
/// <summary>
/// Sends bytes to the specified socket.
/// </summary>
/// <param name="s">The socket.</param>
/// <param name="data">The bytes.</param>
private void sendBytesToSocket(Socket s, byte[] data)
{
s.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendData), s);
}
/// <summary>
/// Sends a message to all connected clients.
/// </summary>
/// <param name="message">The message.</param>
public void sendMessageToAll(string message)
{
foreach (Socket s in clients.Keys)
{
try
{
Client c = clients[s];
if (c.getCurrentStatus() == EClientStatus.LoggedIn)
{
sendMessageToSocket(s, END_LINE + message + END_LINE + CURSOR);
c.resetReceivedData();
}
}
catch
{
clients.Remove(s);
}
}
}
/// <summary>
/// Gets the client by socket.
/// </summary>
/// <param name="clientSocket">The client's socket.</param>
/// <returns>If the socket is found, the client instance
/// is returned; otherwise null is returned.</returns>
private Client getClientBySocket(Socket clientSocket)
{
Client c;
if (!clients.TryGetValue(clientSocket, out c))
c = null;
return c;
}
/// <summary>
/// Gets the socket by client.
/// </summary>
/// <param name="client">The client instance.</param>
/// <returns>If the client is found, the socket is
/// returned; otherwise null is returned.</returns>
private Socket getSocketByClient(Client client)
{
Socket s;
s = clients.FirstOrDefault(x => x.Value.getClientID() == client.getClientID()).Key;
return s;
}
/// <summary>
/// Kicks the specified client from the server.
/// </summary>
/// <param name="client">The client.</param>
public void kickClient(Client client)
{
closeSocket(getSocketByClient(client));
ClientDisconnected(client);
}
/// <summary>
/// Closes the socket and removes the client from
/// the clients list.
/// </summary>
/// <param name="clientSocket">The client socket.</param>
private void closeSocket(Socket clientSocket)
{
clientSocket.Close();
clients.Remove(clientSocket);
}
/// <summary>
/// Handles an incoming connection.
/// If incoming connections are allowed,
/// the client is added to the clients list
/// and triggers the client connected event.
/// Else, the connection blocked event is
/// triggered.
/// </summary>
private void handleIncomingConnection(IAsyncResult result)
{
try
{
Socket oldSocket = (Socket)result.AsyncState;
if (acceptIncomingConnections)
{
Socket newSocket = oldSocket.EndAccept(result);
uint clientID = (uint)clients.Count + 1;
Client client = new Client(clientID, (IPEndPoint)newSocket.RemoteEndPoint);
clients.Add(newSocket, client);
sendBytesToSocket(
newSocket,
new byte[] {
0xff, 0xfd, 0x01, // Do Echo
0xff, 0xfd, 0x21, // Do Remote Flow Control
0xff, 0xfb, 0x01, // Will Echo
0xff, 0xfb, 0x03 // Will Supress Go Ahead
}
);
client.resetReceivedData();
ClientConnected(client);
serverSocket.BeginAccept(new AsyncCallback(handleIncomingConnection), serverSocket);
}
else
{
ConnectionBlocked((IPEndPoint)oldSocket.RemoteEndPoint);
}
}
catch { }
}
/// <summary>
/// Sends data to a socket.
/// </summary>
private void sendData(IAsyncResult result)
{
try
{
Socket clientSocket = (Socket)result.AsyncState;
clientSocket.EndSend(result);
clientSocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(receiveData), clientSocket);
}
catch { }
}
/// <summary>
/// Receives and processes data from a socket.
/// It triggers the message received event in
/// case the client pressed the return key.
/// </summary>
private void receiveData(IAsyncResult result)
{
try
{
Socket clientSocket = (Socket)result.AsyncState;
Client client = getClientBySocket(clientSocket);
int bytesReceived = clientSocket.EndReceive(result);
if (bytesReceived == 0)
{
closeSocket(clientSocket);
serverSocket.BeginAccept(new AsyncCallback(handleIncomingConnection), serverSocket);
}
else if (data[0] < 0xF0)
{
string receivedData = client.getReceivedData();
// 0x2E = '.', 0x0D = carriage return, 0x0A = new line
if ((data[0] == 0x2E && data[1] == 0x0D && receivedData.Length == 0) ||
(data[0] == 0x0D && data[1] == 0x0A))
{
//sendMessageToSocket(clientSocket, "\u001B[1J\u001B[H");
MessageReceived(client, client.getReceivedData());
client.resetReceivedData();
}
else
{
// 0x08 => backspace character
if (data[0] == 0x08)
{
if (receivedData.Length > 0)
{
client.removeLastCharacterReceived();
sendBytesToSocket(clientSocket, new byte[] { 0x08, 0x20, 0x08 });
}
else
clientSocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(receiveData), clientSocket);
}
// 0x7F => delete character
else if (data[0] == 0x7F)
clientSocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(receiveData), clientSocket);
else
{
client.appendReceivedData(Encoding.ASCII.GetString(data, 0, bytesReceived));
// Echo back the received character
// if client is not writing any password
if (client.getCurrentStatus() != EClientStatus.Authenticating)
sendBytesToSocket(clientSocket, new byte[] { data[0] });
// Echo back asterisks if client is
// writing a password
else
sendMessageToSocket(clientSocket, "*");
clientSocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(receiveData), clientSocket);
}
}
}
else
clientSocket.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(receiveData), clientSocket);
}
catch { }
}
}
}