-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathServer.cs
320 lines (262 loc) · 10.8 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SerialToNetDotnet
{
internal enum TelnetCmd : byte
{
IAC = 0xFF,
WILL = 0xFB,
WONT = 0xFC,
DO = 0xFD,
DONT = 0xFE,
}
public enum EchoType
{
none,
device,
server
}
class Server
{
NetServerConfig m_cfg;
private Socket m_serverSocket;
// TODO List<Clients>
private Dictionary<Socket, Client> m_clients;
private const uint m_bufLen = 16;
private byte[] m_rxBuffer;
private readonly string m_portName;
public delegate void DataReceivedHandler(byte[] buffer, int numBytes);
public event DataReceivedHandler DataReceived;
public delegate void ClientConnectEvent();
public event ClientConnectEvent OnFirstClientConnected;
public event ClientConnectEvent OnLastClientDisconnected;
private readonly char m_lineEndChar;
public Server(NetServerConfig config, string comPortName)
{
this.m_portName = comPortName;
this.m_cfg = config;
this.m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.m_clients = new Dictionary<Socket, Client>();
this.m_rxBuffer = new byte[m_bufLen];
// In telnet, "\r\n" is the correct line ending. React only om the last one in signing
if (m_cfg.terminalType == TerminalType.telnet)
this.m_lineEndChar = '\n';
else if (m_cfg.terminalType == TerminalType.raw)
this.m_lineEndChar = '\r';
}
public void Start()
{
m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, m_cfg.tcpPort));
m_serverSocket.Listen(0);
m_serverSocket.BeginAccept(new AsyncCallback(IncomeConnectionCallback), m_serverSocket);
Console.WriteLine("Server started on port {0} ({1})", m_cfg.tcpPort, m_portName);
}
public void Stop()
{
m_serverSocket.Close();
}
private void IncomeConnectionCallback(IAsyncResult result)
{
Socket tmpSocket = (Socket)result.AsyncState;
Socket clientSocket = tmpSocket.EndAccept(result);
ConnectClient(clientSocket);
m_serverSocket.BeginAccept(new AsyncCallback(IncomeConnectionCallback), m_serverSocket);
}
private void OnClientConnectedToUnavailablePort(Socket sock)
{
var msg = "Failed to open serial port " + m_portName + ", please check its status";
byte[] data = Encoding.ASCII.GetBytes(msg);
sock.Send(data, SocketFlags.None);
// Assuming we have not too slow network and client, so message will be delivered in 1 sec
Thread.Sleep(1000);
sock.Close();
}
private void ConnectClient(Socket clientSocket)
{
if (m_clients.Count == 0)
{
try
{
OnFirstClientConnected();
}
catch
{
Task.Run(() => { OnClientConnectedToUnavailablePort(clientSocket); } );
return;
}
}
uint clientID = (uint)m_clients.Count + 1;
IPEndPoint remoteEp = (IPEndPoint)clientSocket.RemoteEndPoint;
Client client = new Client(clientID, remoteEp, this);
SendWelcomeMessage(clientSocket);
m_clients.Add(clientSocket, client);
Console.WriteLine("Server at {0} ({1}): client connected from {2}", m_cfg.tcpPort, m_portName, remoteEp.ToString());
clientSocket.BeginReceive(m_rxBuffer, 0, 1, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), clientSocket);
}
private void SendWelcomeMessage(Socket clientSocket)
{
if (m_cfg.terminalType == TerminalType.telnet)
{
byte[] options = new byte[] {
(byte)TelnetCmd.IAC, (byte)TelnetCmd.DO, 0x01, // Don't Echo
(byte)TelnetCmd.IAC, (byte)TelnetCmd.DO, 0x21, // Do Remote Flow Control
(byte)TelnetCmd.IAC, (byte)TelnetCmd.WILL, 0x01, // Will Echo
(byte)TelnetCmd.IAC, (byte)TelnetCmd.WILL, 0x03 // Will Supress Go Ahead
};
// If echo does not perfrom by server or device - inform client about it
if (m_cfg.echoType == EchoType.none)
options[7] = (byte)TelnetCmd.WONT;
SendBytesToSocket(
clientSocket,
options
);
}
SendStringToSocket(
clientSocket,
"You connected to COM-to-telnet on port " + m_cfg.tcpPort.ToString() + ", COM port " + m_portName + "\r\n"
);
SendStringToSocket(clientSocket, "Already connected clients:\r\n");
SendStringToSocket(clientSocket, getClientsString());
SendStringToSocket(clientSocket, "\r\n");
AskForSignature(clientSocket);
}
private void AskForSignature(Socket sock)
{
SendStringToSocket(sock, "Please enter your short signature: ");
}
public string getClientsString()
{
if (m_clients.Count == 0)
return "No clients connected";
string res = "";
foreach (Socket s in m_clients.Keys)
{
Client c = m_clients[s];
res += String.Format(" {0} from {1}\r\n", c.m_signature, s.RemoteEndPoint.ToString());
}
return res;
}
private IAsyncResult SendBytesToSocket(Socket sock, byte[] data)
{
return sock.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendDataCallback), sock);
}
private void SendByteToSocket(Socket sock, byte data)
{
SendBytesToSocket(sock, new byte[1] { data });
}
private void SendDataCallback(IAsyncResult result)
{
Socket clientSocket = (Socket)result.AsyncState;
clientSocket.EndSend(result);
}
private void ReceiveDataCallback(IAsyncResult result)
{
try
{
Socket clientSocket = (Socket)result.AsyncState;
Client client = GetClientBySocket(clientSocket);
int bytesReceived = clientSocket.EndReceive(result);
if (bytesReceived == 0)
{
DisconnectClient(clientSocket);
}
// received data (byte) is in m_rxBuffer[0];
if (client.m_state == Client.State.iac)
{
client.AddIacByte(m_rxBuffer[0]);
}
else
{
// Process IAC (Interpret as command) symbol in case of telnet
if ((m_rxBuffer[0] == (byte)TelnetCmd.IAC) &&
(m_cfg.terminalType == TerminalType.telnet))
{
client.ToIacState();
}
else
{
// in 'raw' mode, putty sends CR on Enter, in telnet - CR+LF
if (client.m_state == Client.State.signing)
{
// Echo back the input symbol
// Note: in case of telnet if echo is disabled (none), we informed about it, so client
// is expected to do local echo. Do not echo in this case
if (!((m_cfg.terminalType == TerminalType.telnet) && (m_cfg.echoType == EchoType.none)))
SendByteToSocket(clientSocket, m_rxBuffer[0]);
var res = client.AddSignatureChar((char)m_rxBuffer[0], m_lineEndChar);
// If an empty signature provided - ask again
if (res == Client.SignatureAppendResult.empty)
{
AskForSignature(clientSocket);
}
else if (res == Client.SignatureAppendResult.finished)
{
SendStringToSocket(clientSocket, "Thanks\r\n");
}
}
else
{
// Normal byte in normal state
if (!m_cfg.skipChars.Contains((char)m_rxBuffer[0]))
{
// If server is asked for echo, do it
if (m_cfg.echoType == EchoType.server)
SendByteToSocket(clientSocket, m_rxBuffer[0]);
DataReceived(m_rxBuffer, bytesReceived);
}
}
}
}
clientSocket.BeginReceive(m_rxBuffer, 0, 1, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), clientSocket);
}
catch { }
}
private Client GetClientBySocket(Socket clientSocket)
{
if (!m_clients.TryGetValue(clientSocket, out Client c))
c = null;
return c;
}
public void SendBytesToAll(byte[] data)
{
List<Socket> socksToClose = new List<Socket>();
foreach (Socket sock in m_clients.Keys)
{
// Do not broadcast to a signing client
if (m_clients[sock].m_state != Client.State.signing)
{
try
{
SendBytesToSocket(sock, data);
}
catch
{
socksToClose.Add(sock);
}
}
}
// Remove all erroneous sockets after iteration, cause cannot do it inside foreach
foreach (Socket sock in socksToClose)
{
DisconnectClient(sock);
}
}
private IAsyncResult SendStringToSocket(Socket socket, string msg)
{
byte[] data = Encoding.ASCII.GetBytes(msg);
return SendBytesToSocket(socket, data);
}
private void DisconnectClient(Socket sock)
{
sock.Close();
m_clients.Remove(sock);
if (m_clients.Count == 0)
OnLastClientDisconnected();
}
}
}