2018-04-08 02:44:42 -04:00
|
|
|
|
using SharedLibraryCore.Exceptions;
|
|
|
|
|
using SharedLibraryCore.Interfaces;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
using System;
|
2018-05-03 01:25:49 -04:00
|
|
|
|
using System.Collections.Concurrent;
|
2018-04-07 15:49:00 -04:00
|
|
|
|
using System.Linq;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
using System.Net;
|
|
|
|
|
using System.Net.Sockets;
|
2019-02-06 21:12:35 -05:00
|
|
|
|
using System.Text;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2018-04-08 02:44:42 -04:00
|
|
|
|
namespace SharedLibraryCore.RCon
|
2018-04-02 01:25:06 -04:00
|
|
|
|
{
|
|
|
|
|
class ConnectionState
|
|
|
|
|
{
|
2019-09-09 18:37:57 -04:00
|
|
|
|
~ConnectionState()
|
|
|
|
|
{
|
|
|
|
|
OnComplete.Dispose();
|
|
|
|
|
OnSentData.Dispose();
|
|
|
|
|
OnReceivedData.Dispose();
|
|
|
|
|
}
|
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
public int ConnectionAttempts { get; set; }
|
|
|
|
|
const int BufferSize = 4096;
|
|
|
|
|
public readonly byte[] ReceiveBuffer = new byte[BufferSize];
|
|
|
|
|
public readonly SemaphoreSlim OnComplete = new SemaphoreSlim(1, 1);
|
2018-10-02 13:39:08 -04:00
|
|
|
|
public readonly ManualResetEventSlim OnSentData = new ManualResetEventSlim(false);
|
|
|
|
|
public readonly ManualResetEventSlim OnReceivedData = new ManualResetEventSlim(false);
|
|
|
|
|
public SocketAsyncEventArgs SendEventArgs { get; set; } = new SocketAsyncEventArgs();
|
|
|
|
|
public SocketAsyncEventArgs ReceiveEventArgs { get; set; } = new SocketAsyncEventArgs();
|
2018-09-29 22:49:12 -04:00
|
|
|
|
public DateTime LastQuery { get; set; } = DateTime.Now;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class Connection
|
|
|
|
|
{
|
2018-09-29 15:52:22 -04:00
|
|
|
|
static readonly ConcurrentDictionary<EndPoint, ConnectionState> ActiveQueries = new ConcurrentDictionary<EndPoint, ConnectionState>();
|
2018-04-15 21:27:43 -04:00
|
|
|
|
public IPEndPoint Endpoint { get; private set; }
|
|
|
|
|
public string RConPassword { get; private set; }
|
2018-12-03 20:21:13 -05:00
|
|
|
|
|
|
|
|
|
private readonly ILogger Log;
|
2019-02-01 20:49:25 -05:00
|
|
|
|
private IRConParserConfiguration Config;
|
2019-02-10 21:05:50 -05:00
|
|
|
|
private readonly Encoding defaultEncoding;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2019-02-01 20:49:25 -05:00
|
|
|
|
public Connection(string ipAddress, int port, string password, ILogger log, IRConParserConfiguration config)
|
2018-04-02 01:25:06 -04:00
|
|
|
|
{
|
|
|
|
|
Endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
|
2019-02-10 21:05:50 -05:00
|
|
|
|
defaultEncoding = Encoding.GetEncoding("windows-1252");
|
2018-04-02 01:25:06 -04:00
|
|
|
|
RConPassword = password;
|
|
|
|
|
Log = log;
|
2019-02-01 20:49:25 -05:00
|
|
|
|
Config = config;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void SetConfiguration(IRConParserConfiguration config)
|
|
|
|
|
{
|
|
|
|
|
Config = config;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
}
|
|
|
|
|
|
2019-02-03 21:47:05 -05:00
|
|
|
|
public async Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "")
|
2018-04-02 01:25:06 -04:00
|
|
|
|
{
|
2018-09-29 15:52:22 -04:00
|
|
|
|
if (!ActiveQueries.ContainsKey(this.Endpoint))
|
2018-04-02 01:25:06 -04:00
|
|
|
|
{
|
2018-09-29 15:52:22 -04:00
|
|
|
|
ActiveQueries.TryAdd(this.Endpoint, new ConnectionState());
|
2018-04-02 01:25:06 -04:00
|
|
|
|
}
|
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
var connectionState = ActiveQueries[this.Endpoint];
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
#if DEBUG == true
|
|
|
|
|
Log.WriteDebug($"Waiting for semaphore to be released [{this.Endpoint}]");
|
|
|
|
|
#endif
|
|
|
|
|
// enter the semaphore so only one query is sent at a time per server.
|
|
|
|
|
await connectionState.OnComplete.WaitAsync();
|
|
|
|
|
|
|
|
|
|
var timeSinceLastQuery = (DateTime.Now - connectionState.LastQuery).TotalMilliseconds;
|
2018-09-29 22:49:12 -04:00
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
if (timeSinceLastQuery < StaticHelpers.FloodProtectionInterval)
|
2018-09-29 22:49:12 -04:00
|
|
|
|
{
|
2018-10-02 13:39:08 -04:00
|
|
|
|
await Task.Delay(StaticHelpers.FloodProtectionInterval - (int)timeSinceLastQuery);
|
2018-09-29 22:49:12 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
connectionState.LastQuery = DateTime.Now;
|
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
#if DEBUG == true
|
2018-10-02 13:39:08 -04:00
|
|
|
|
Log.WriteDebug($"Semaphore has been released [{this.Endpoint}]");
|
|
|
|
|
Log.WriteDebug($"Query [{this.Endpoint},{type.ToString()},{parameters}]");
|
2018-04-02 01:25:06 -04:00
|
|
|
|
#endif
|
2018-04-09 15:17:10 -04:00
|
|
|
|
|
2018-04-23 01:43:48 -04:00
|
|
|
|
byte[] payload = null;
|
2019-02-03 21:47:05 -05:00
|
|
|
|
bool waitForResponse = Config.WaitForResponse;
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2019-02-09 16:35:13 -05:00
|
|
|
|
string convertEncoding(string text)
|
2019-09-09 18:37:57 -04:00
|
|
|
|
{
|
2019-02-09 16:35:13 -05:00
|
|
|
|
byte[] convertedBytes = Utilities.EncodingType.GetBytes(text);
|
2019-02-10 21:05:50 -05:00
|
|
|
|
return defaultEncoding.GetString(convertedBytes);
|
2019-02-06 21:12:35 -05:00
|
|
|
|
}
|
|
|
|
|
|
2019-08-30 18:24:44 -04:00
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
string convertedRConPassword = convertEncoding(RConPassword);
|
|
|
|
|
string convertedParameters = convertEncoding(parameters);
|
|
|
|
|
|
|
|
|
|
switch (type)
|
|
|
|
|
{
|
|
|
|
|
case StaticHelpers.QueryType.GET_DVAR:
|
|
|
|
|
waitForResponse |= true;
|
|
|
|
|
payload = string.Format(Config.CommandPrefixes.RConGetDvar, convertedRConPassword, convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
|
|
|
|
break;
|
|
|
|
|
case StaticHelpers.QueryType.SET_DVAR:
|
|
|
|
|
payload = string.Format(Config.CommandPrefixes.RConSetDvar, convertedRConPassword, convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
|
|
|
|
break;
|
|
|
|
|
case StaticHelpers.QueryType.COMMAND:
|
|
|
|
|
payload = string.Format(Config.CommandPrefixes.RConCommand, convertedRConPassword, convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
|
|
|
|
break;
|
|
|
|
|
case StaticHelpers.QueryType.GET_STATUS:
|
|
|
|
|
waitForResponse |= true;
|
|
|
|
|
payload = (Config.CommandPrefixes.RConGetStatus + '\0').Select(Convert.ToByte).ToArray();
|
|
|
|
|
break;
|
|
|
|
|
case StaticHelpers.QueryType.GET_INFO:
|
|
|
|
|
waitForResponse |= true;
|
|
|
|
|
payload = (Config.CommandPrefixes.RConGetInfo + '\0').Select(Convert.ToByte).ToArray();
|
|
|
|
|
break;
|
|
|
|
|
case StaticHelpers.QueryType.COMMAND_STATUS:
|
|
|
|
|
waitForResponse |= true;
|
|
|
|
|
payload = string.Format(Config.CommandPrefixes.RConCommand, convertedRConPassword, "status\0").Select(Convert.ToByte).ToArray();
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-02-06 21:12:35 -05:00
|
|
|
|
|
2019-08-30 18:24:44 -04:00
|
|
|
|
// this happens when someone tries to send something that can't be converted into a 7 bit character set
|
|
|
|
|
// e.g: emoji -> windows-1252
|
|
|
|
|
catch (OverflowException)
|
2018-04-02 01:25:06 -04:00
|
|
|
|
{
|
2019-08-30 18:24:44 -04:00
|
|
|
|
connectionState.OnComplete.Release(1);
|
2019-09-09 18:37:57 -04:00
|
|
|
|
throw new NetworkException($"Invalid character encountered when converting encodings - {parameters}");
|
2018-04-02 01:25:06 -04:00
|
|
|
|
}
|
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
byte[] response = null;
|
2018-10-02 13:39:08 -04:00
|
|
|
|
|
2018-12-03 20:21:13 -05:00
|
|
|
|
retrySend:
|
2018-10-25 09:14:39 -04:00
|
|
|
|
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
|
2018-10-02 13:39:08 -04:00
|
|
|
|
{
|
2019-04-23 18:27:20 -04:00
|
|
|
|
DontFragment = true,
|
2018-10-25 09:14:39 -04:00
|
|
|
|
Ttl = 100,
|
2018-10-02 13:39:08 -04:00
|
|
|
|
ExclusiveAddressUse = true,
|
2018-10-25 09:14:39 -04:00
|
|
|
|
})
|
|
|
|
|
{
|
|
|
|
|
connectionState.SendEventArgs.UserToken = socket;
|
|
|
|
|
connectionState.OnSentData.Reset();
|
|
|
|
|
connectionState.OnReceivedData.Reset();
|
|
|
|
|
connectionState.ConnectionAttempts++;
|
2018-09-29 15:52:22 -04:00
|
|
|
|
#if DEBUG == true
|
2018-10-25 09:14:39 -04:00
|
|
|
|
Log.WriteDebug($"Sending {payload.Length} bytes to [{this.Endpoint}] ({connectionState.ConnectionAttempts}/{StaticHelpers.AllowedConnectionFails})");
|
2018-09-29 15:52:22 -04:00
|
|
|
|
#endif
|
2018-10-25 09:14:39 -04:00
|
|
|
|
try
|
2018-04-02 23:11:19 -04:00
|
|
|
|
{
|
2018-10-25 09:14:39 -04:00
|
|
|
|
response = await SendPayloadAsync(payload, waitForResponse);
|
2018-11-07 21:30:11 -05:00
|
|
|
|
|
2018-12-03 20:21:13 -05:00
|
|
|
|
if (response.Length == 0 && waitForResponse)
|
2018-11-07 21:30:11 -05:00
|
|
|
|
{
|
2019-04-23 18:27:20 -04:00
|
|
|
|
throw new NetworkException("Expected response but got 0 bytes back");
|
2018-11-07 21:30:11 -05:00
|
|
|
|
}
|
|
|
|
|
|
2018-10-25 09:14:39 -04:00
|
|
|
|
connectionState.ConnectionAttempts = 0;
|
2018-04-02 23:11:19 -04:00
|
|
|
|
}
|
2018-09-29 22:49:12 -04:00
|
|
|
|
|
2018-11-07 21:30:11 -05:00
|
|
|
|
catch
|
2018-10-25 09:14:39 -04:00
|
|
|
|
{
|
|
|
|
|
if (connectionState.ConnectionAttempts < StaticHelpers.AllowedConnectionFails)
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(StaticHelpers.FloodProtectionInterval);
|
|
|
|
|
goto retrySend;
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-21 17:28:13 -04:00
|
|
|
|
throw new NetworkException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_COMMUNICATION"].FormatExt(Endpoint));
|
2018-10-25 09:14:39 -04:00
|
|
|
|
}
|
2019-09-09 18:37:57 -04:00
|
|
|
|
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
if (connectionState.OnComplete.CurrentCount == 0)
|
|
|
|
|
{
|
|
|
|
|
connectionState.OnComplete.Release(1);
|
|
|
|
|
}
|
|
|
|
|
}
|
2018-09-29 15:52:22 -04:00
|
|
|
|
}
|
2018-04-02 23:11:19 -04:00
|
|
|
|
|
2019-04-23 18:27:20 -04:00
|
|
|
|
string responseString = defaultEncoding.GetString(response, 0, response.Length) + '\n';
|
2018-04-11 18:24:21 -04:00
|
|
|
|
|
2019-06-13 20:10:08 -04:00
|
|
|
|
if (responseString.Contains("Invalid password") || responseString.Contains("rconpassword"))
|
2018-09-29 15:52:22 -04:00
|
|
|
|
{
|
2018-09-29 22:49:12 -04:00
|
|
|
|
throw new NetworkException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_RCON_INVALID"]);
|
2018-09-29 15:52:22 -04:00
|
|
|
|
}
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
if (responseString.ToString().Contains("rcon_password"))
|
|
|
|
|
{
|
2018-09-29 22:49:12 -04:00
|
|
|
|
throw new NetworkException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_RCON_NOTSET"]);
|
2018-09-29 15:52:22 -04:00
|
|
|
|
}
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
string[] splitResponse = responseString.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
|
2019-02-06 21:12:35 -05:00
|
|
|
|
.Select(line => line.Trim())
|
|
|
|
|
.ToArray();
|
2018-09-29 15:52:22 -04:00
|
|
|
|
return splitResponse;
|
|
|
|
|
}
|
2018-04-10 20:25:44 -04:00
|
|
|
|
|
2018-10-08 22:15:59 -04:00
|
|
|
|
private async Task<byte[]> SendPayloadAsync(byte[] payload, bool waitForResponse)
|
2018-09-29 15:52:22 -04:00
|
|
|
|
{
|
|
|
|
|
var connectionState = ActiveQueries[this.Endpoint];
|
2018-10-02 13:39:08 -04:00
|
|
|
|
var rconSocket = (Socket)connectionState.SendEventArgs.UserToken;
|
2018-05-03 01:25:49 -04:00
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
if (connectionState.ReceiveEventArgs.RemoteEndPoint == null &&
|
|
|
|
|
connectionState.SendEventArgs.RemoteEndPoint == null)
|
2018-09-29 15:52:22 -04:00
|
|
|
|
{
|
2018-10-02 13:39:08 -04:00
|
|
|
|
// setup the event handlers only once because we're reusing the event args
|
|
|
|
|
connectionState.SendEventArgs.Completed += OnDataSent;
|
|
|
|
|
connectionState.ReceiveEventArgs.Completed += OnDataReceived;
|
|
|
|
|
connectionState.SendEventArgs.RemoteEndPoint = this.Endpoint;
|
|
|
|
|
connectionState.ReceiveEventArgs.RemoteEndPoint = this.Endpoint;
|
|
|
|
|
connectionState.ReceiveEventArgs.DisconnectReuseSocket = true;
|
|
|
|
|
connectionState.SendEventArgs.DisconnectReuseSocket = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
connectionState.SendEventArgs.SetBuffer(payload);
|
2018-04-04 15:38:34 -04:00
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
// send the data to the server
|
2018-10-02 13:39:08 -04:00
|
|
|
|
bool sendDataPending = rconSocket.SendToAsync(connectionState.SendEventArgs);
|
2018-04-04 15:38:34 -04:00
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
if (sendDataPending)
|
2018-09-29 15:52:22 -04:00
|
|
|
|
{
|
2018-10-02 13:39:08 -04:00
|
|
|
|
// the send has not been completed asyncronously
|
|
|
|
|
if (!await Task.Run(() => connectionState.OnSentData.Wait(StaticHelpers.SocketTimeout)))
|
|
|
|
|
{
|
|
|
|
|
rconSocket.Close();
|
|
|
|
|
throw new NetworkException("Timed out sending data", rconSocket);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-10-08 22:15:59 -04:00
|
|
|
|
if (!waitForResponse)
|
|
|
|
|
{
|
|
|
|
|
return new byte[0];
|
|
|
|
|
}
|
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
connectionState.ReceiveEventArgs.SetBuffer(connectionState.ReceiveBuffer);
|
2018-04-02 23:11:19 -04:00
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
// get our response back
|
2018-10-02 13:39:08 -04:00
|
|
|
|
bool receiveDataPending = rconSocket.ReceiveFromAsync(connectionState.ReceiveEventArgs);
|
2018-04-04 15:38:34 -04:00
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
if (receiveDataPending)
|
2018-09-29 15:52:22 -04:00
|
|
|
|
{
|
2018-10-02 13:39:08 -04:00
|
|
|
|
if (!await Task.Run(() => connectionState.OnReceivedData.Wait(StaticHelpers.SocketTimeout)))
|
|
|
|
|
{
|
|
|
|
|
rconSocket.Close();
|
|
|
|
|
throw new NetworkException("Timed out waiting for response", rconSocket);
|
|
|
|
|
}
|
2018-09-29 15:52:22 -04:00
|
|
|
|
}
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2019-04-23 18:27:20 -04:00
|
|
|
|
rconSocket.Close();
|
|
|
|
|
|
2018-10-02 13:39:08 -04:00
|
|
|
|
byte[] response = connectionState.ReceiveBuffer
|
|
|
|
|
.Take(connectionState.ReceiveEventArgs.BytesTransferred)
|
|
|
|
|
.ToArray();
|
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
return response;
|
|
|
|
|
}
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
private void OnDataReceived(object sender, SocketAsyncEventArgs e)
|
|
|
|
|
{
|
|
|
|
|
#if DEBUG == true
|
|
|
|
|
Log.WriteDebug($"Read {e.BytesTransferred} bytes from {e.RemoteEndPoint.ToString()}");
|
|
|
|
|
#endif
|
2018-10-02 13:39:08 -04:00
|
|
|
|
ActiveQueries[this.Endpoint].OnReceivedData.Set();
|
2018-09-29 15:52:22 -04:00
|
|
|
|
}
|
2018-04-02 01:25:06 -04:00
|
|
|
|
|
2018-09-29 15:52:22 -04:00
|
|
|
|
private void OnDataSent(object sender, SocketAsyncEventArgs e)
|
|
|
|
|
{
|
|
|
|
|
#if DEBUG == true
|
2019-09-09 18:37:57 -04:00
|
|
|
|
Log.WriteDebug($"Sent {e.Buffer?.Length} bytes to {e.ConnectSocket?.RemoteEndPoint?.ToString()}");
|
2018-09-29 15:52:22 -04:00
|
|
|
|
#endif
|
2018-10-02 13:39:08 -04:00
|
|
|
|
ActiveQueries[this.Endpoint].OnSentData.Set();
|
2018-04-02 01:25:06 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|