/
TelnetClient.cs
428 lines (370 loc) · 17.3 KB
/
TelnetClient.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
* Avalon Mud Client
*
* @project lead : Blake Pell
* @website : http://www.blakepell.com
* @copyright : Copyright (c), 2018-2023 All rights reserved.
* @license : MIT
*/
using Avalon.Common.Interfaces;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Avalon.Network
{
/// <summary>
/// Telnet client.
/// </summary>
public class TelnetClient : IDisposable, ITelnetClient
{
private readonly int _port;
private readonly string _host;
private readonly TimeSpan _sendRate;
private readonly SemaphoreSlim _sendRateLimit;
private readonly CancellationTokenSource _internalCancellation;
private readonly bool _traceEnabled = true;
private const byte GO_AHEAD_CODE = 0xF9;
private TcpClient _tcpClient;
private StreamReader _tcpReader;
private StreamWriter _tcpWriter;
public EventHandler<string> LineReceived { get; set; }
public EventHandler<string> DataReceived { get; set; }
public EventHandler ConnectionClosed { get; set; }
/// <summary>
/// Simple telnet client
/// </summary>
/// <param name="host">Destination Hostname or IP</param>
/// <param name="port">Destination TCP port number</param>
/// <param name="sendRate">Minimum time span between sends. This is a throttle to prevent flooding the server.</param>
/// <param name="token"></param>
public TelnetClient(string host, int port, TimeSpan sendRate, CancellationToken token)
{
_host = host;
_port = port;
_sendRate = sendRate;
_sendRateLimit = new SemaphoreSlim(1);
_internalCancellation = new CancellationTokenSource();
token.Register(() => _internalCancellation.Cancel());
}
/// <summary>
/// Connect and wait for incoming messages.
/// When this task completes you are connected.
/// You cannot call this method twice; if you need to reconnect, dispose of this instance and create a new one.
/// </summary>
public async Task ConnectAsync()
{
if (_tcpClient != null)
{
throw new NotSupportedException($"{nameof(ConnectAsync)} aborted: Reconnecting is not supported. You must dispose of this instance and instantiate a new TelnetClient");
}
_tcpClient = new TcpClient();
_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
await _tcpClient.ConnectAsync(_host, _port);
_tcpReader = new StreamReader(_tcpClient.GetStream());
_tcpWriter = new StreamWriter(_tcpClient.GetStream()) { AutoFlush = true };
// Fire-and-forget looping task that waits for messages to arrive
WaitForMessageAsync();
}
/// <summary>
/// Connect via SOCKS4 proxy. See http://en.wikipedia.org/wiki/SOCKS#SOCKS4.
/// When this task completes you are connected.
/// You cannot call this method twice; if you need to reconnect, dispose of this instance and create a new one.
/// </summary>
/// <param name="socks4ProxyHost"></param>
/// <param name="socks4ProxyPort"></param>
/// <param name="socks4ProxyUser"></param>
public async Task ConnectAsync(string socks4ProxyHost, int socks4ProxyPort, string socks4ProxyUser)
{
if (_tcpClient != null)
{
throw new NotSupportedException($"{nameof(ConnectAsync)} aborted: Reconnecting is not supported. You must dispose of this instance and instantiate a new TelnetClient");
}
_tcpClient = new TcpClient();
_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
await _tcpClient.ConnectAsync(socks4ProxyHost, socks4ProxyPort);
// Simple implementation of http://en.wikipedia.org/wiki/SOCKS#SOCKS4
// Similar to http://biko.codeplex.com/
byte[] hostAddress = (await Dns.GetHostAddressesAsync(_host)).First().GetAddressBytes();
byte[] hostPort = new byte[2]; // 16-bit number
hostPort[0] = Convert.ToByte(_port / 256);
hostPort[1] = Convert.ToByte(_port % 256);
byte[] proxyUserId = Encoding.ASCII.GetBytes(socks4ProxyUser ?? string.Empty); // Can't pass in null
// Request
// - We build a "please connect me" packet to send to the proxy
byte[] proxyRequest = new byte[9 + proxyUserId.Length];
proxyRequest[0] = 4; // SOCKS4;
proxyRequest[1] = 0x01; // Connect (we don't support Bind);
hostPort.CopyTo(proxyRequest, 2);
hostAddress.CopyTo(proxyRequest, 4);
proxyUserId.CopyTo(proxyRequest, 8);
proxyRequest[8 + proxyUserId.Length] = 0x00; // UserId terminator
// Send proxy request
// - Then we wait for an ack
// - If successful, we can use the TelnetClient directly and traffic will be proxied
await _tcpClient.GetStream().WriteAsync(proxyRequest, 0, proxyRequest.Length, _internalCancellation.Token);
// Response
// - First byte is null
// - Second byte is our result code (we want 0x5a Request granted)
// - Last 6 bytes should be ignored
byte[] proxyResponse = new byte[8];
// Wait for proxy response
await _tcpClient.GetStream().ReadAsync(proxyResponse, 0, proxyResponse.Length, _internalCancellation.Token);
if (proxyResponse[1] != 0x5a) // Request granted
{
switch (proxyResponse[1])
{
case 0x5b:
throw new InvalidOperationException("Proxy connect request rejected or failed");
case 0x5c:
throw new InvalidOperationException("Proxy connect request failed because client is not running identd (or not reachable from the server)");
case 0x5d:
throw new InvalidOperationException("Proxy connect request failed because client's identd could not confirm the user ID string in the request");
default:
throw new InvalidOperationException("Proxy connect request failed, unknown error occurred");
}
}
_tcpReader = new StreamReader(_tcpClient.GetStream());
_tcpWriter = new StreamWriter(_tcpClient.GetStream()) { AutoFlush = true };
// Fire-and-forget looping task that waits for messages to arrive
WaitForMessageAsync();
}
public async Task SendAsync(string message)
{
try
{
// Wait for any previous send commands to finish and release the semaphore
// This throttles our commands
await _sendRateLimit.WaitAsync(_internalCancellation.Token);
// Send command + params
await _tcpWriter.WriteLineAsync(message);
// Block other commands until our timeout to prevent flooding
await Task.Delay(_sendRate, _internalCancellation.Token);
}
catch (OperationCanceledException)
{
// We're waiting to release our semaphore, and someone cancelled the task on us (I'm looking at you, WaitForMessages...)
// This happens if we've just sent something and then disconnect immediately
TraceInformation($"{nameof(SendAsync)} aborted: {nameof(_internalCancellation.IsCancellationRequested)} == true");
}
catch (ObjectDisposedException)
{
// This happens during ReadLineAsync() when we call Disconnect() and close the underlying stream
// This is an expected exception during disconnection if we're in the middle of a send
TraceInformation($"{nameof(SendAsync)} failed: {nameof(_tcpWriter)} or {nameof(_tcpWriter.BaseStream)} disposed");
}
catch (IOException)
{
// This happens when we start WriteLineAsync() if the socket is disconnected unexpectedly
TraceError($"{nameof(SendAsync)} failed: Socket disconnected unexpectedly");
throw;
}
catch (Exception error)
{
TraceError($"{nameof(SendAsync)} failed: {error}");
throw;
}
finally
{
// Exit our semaphore
_sendRateLimit.Release();
}
}
public async Task WaitForMessageAsync()
{
// We're going to store the receiveBuffer and it's string value in these variables that will
// be cleared. This is more of a micro optimization. They will need to be cleared each iteration.
var receiveBuffer = new char[4096];
var lineBuffer = new StringBuilder(4096);
var dataBuffer = new StringBuilder(4096);
try
{
while (true)
{
if (_internalCancellation.IsCancellationRequested)
{
TraceInformation($"{nameof(WaitForMessageAsync)} aborted: {nameof(_internalCancellation.IsCancellationRequested)} == true");
break;
}
// Clear out buffers
Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
try
{
if (!_tcpClient.Connected)
{
TraceInformation($"{nameof(WaitForMessageAsync)} aborted: {nameof(_tcpClient)} is not connected");
break;
}
int dataReceivedLength = await _tcpReader.ReadAsync(receiveBuffer, 0, receiveBuffer.Length);
// No data, break!
if (dataReceivedLength == 0)
{
break;
}
// The data buffer will be stored regardless of whether there is a line and will be sent
// out as DataReceived so that the UI can render it. The actual line will be sent separate
// because we don't know when the line terminator will come indicating a full line has
// been sent and can be processed for triggers and whatever else as a complete line.
for (int i = 0; i < receiveBuffer.Length; i++)
{
// If it's a carriage return or a null character ignore it and move on.
if (receiveBuffer[i] == 13 || receiveBuffer[i] == 0)
{
continue;
}
// The dataBuffer being before the check will have the newline or go ahead
// char included which is important since it's written to the screen. This
// is why the lineBuffer isn't appended to until after the \n (char 10) check.
dataBuffer.Append(receiveBuffer[i]);
// This was a newline or a telnetga (telnet go ahead), process it like it's a line.
if (receiveBuffer[i] == 10 || receiveBuffer[i] == GO_AHEAD_CODE)
{
// A complete line was found, send it on to the line handler. Send the real
// time data first to the OnDataReceived so that it renders before any triggers
// that might need to write to the terminal. The actual data needs to render
// first, THEN any triggers (that might render subsequent text) can go. We can't
// reuse the dataBuffer for both because it sends immediately if there's no line
// ending found while the lineBuffer hangs onto everything until then.
this.OnDataReceived(dataBuffer.ToString());
this.OnLineReceived(lineBuffer.ToString());
dataBuffer.Clear();
lineBuffer.Clear();
continue;
}
lineBuffer.Append(receiveBuffer[i]);
}
// We had data, a partial line, go ahead send it so the OnDataReceived event so it can be
// processed in real time if required.
if (dataBuffer.Length > 0)
{
this.OnDataReceived(dataBuffer.ToString());
dataBuffer.Clear();
}
}
catch (ObjectDisposedException)
{
// This happens during ReadLineAsync() when we call Disconnect() and close the underlying stream
// This is an expected exception during disconnection
TraceInformation($"{nameof(WaitForMessageAsync)} aborted: {nameof(_tcpReader)} or {nameof(_tcpReader.BaseStream)} disposed. This is expected after calling Disconnect()");
break;
}
catch (IOException)
{
// This happens when we start ReadLineAsync() if the socket is disconnected unexpectedly
TraceError($"{nameof(WaitForMessageAsync)} aborted: Socket disconnected unexpectedly");
break;
}
catch (Exception error)
{
TraceError($"{nameof(WaitForMessageAsync)} aborted: {error}");
break;
}
}
}
finally
{
TraceInformation($"{nameof(WaitForMessageAsync)} completed");
}
}
/// <summary>
/// Disconnecting will leave TelnetClient in an unusable state.
/// </summary>
public void Disconnect()
{
try
{
// Blow up any outstanding tasks
_internalCancellation.Cancel();
// Both reader and writer use the TcpClient.GetStream(), and closing them will close the underlying stream
// So closing the stream for TcpClient is redundant but it means we're triple sure.
_tcpReader?.Close();
_tcpReader?.Dispose();
_tcpReader = null;
_tcpWriter?.Close();
_tcpWriter?.Dispose();
_tcpWriter = null;
_tcpClient?.Close();
_tcpClient?.Dispose();
_tcpClient = null;
}
catch (Exception ex)
{
TraceError($"{nameof(Disconnect)} error: {ex}");
}
finally
{
OnConnectionClosed();
}
}
/// <summary>
/// A hard check of whether the TCP/IP connection is still open by peeking.
/// </summary>
public bool IsConnected()
{
try
{
if (!_tcpClient.Connected)
{
return false;
}
if (_tcpClient.Client.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (_tcpClient.Client.Receive(buff, SocketFlags.Peek) == 0)
{
// Client disconnected
return false;
}
}
}
catch
{
return false;
}
return true;
}
public void TraceInformation(string text)
{
if (_traceEnabled)
{
Trace.TraceInformation($"{DateTime.Now.ToString()}: {text}");
}
}
public void TraceError(string text)
{
if (_traceEnabled)
{
Trace.TraceError($"{DateTime.Now.ToString()}: {text}");
}
}
public void OnLineReceived(string message)
{
LineReceived?.Invoke(this, message);
}
public void OnDataReceived(string message)
{
DataReceived?.Invoke(this, message);
}
public void OnConnectionClosed()
{
ConnectionClosed?.Invoke(this, new EventArgs());
}
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
Disconnect();
}
_disposed = true;
}
}
}