using System.Net;
using System.Net.Sockets;
using System.Text;
//https://github.com/opengsq/opengsq-dotnet/blob/main/OpenGSQ/Protocols/GameSpy3.cs
//https://github.com/opengsq/opengsq-dotnet/blob/main/OpenGSQ/ProtocolBase.cs
//https://github.com/opengsq/opengsq-dotnet/blob/main/OpenGSQ/BinaryReaderExtensions.cs
/*
MIT License
Copyright (c) 2021 OpenGSQ
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
namespace VeloeMonitorDataCollector.Dependencies
{
public class Gs3Status
{
///
/// Represents a network endpoint as an IP address and a port number.
///
protected IPEndPoint _EndPoint;
///
/// Timeout in millisecond
///
protected int _Timeout;
///
/// Cached challenge bytes
///
//protected byte[] _Challenge = new byte[0];
///
/// Gamespy Query Protocol version 3
///
///
///
///
public Gs3Status(string address, int port, int timeout = 5000)
{
if (IPAddress.TryParse(address, out var ipAddress))
{
_EndPoint = new IPEndPoint(ipAddress, port);
}
else
{
_EndPoint = new IPEndPoint(Dns.GetHostAddresses(address)[0], port);
}
_Timeout = timeout;
}
#pragma warning disable 1591
protected bool _Challenge;
#pragma warning restore 1591
///
/// Retrieves information about the server including, Info, Players, and Teams.
///
///
///
public Status GetStatus()
{
using (var udpClient = new UdpClient())
{
var responseData = ConnectAndSendPackets(udpClient);
using (var br = new BinaryReader(new MemoryStream(responseData), Encoding.UTF8))
{
return new Status
{
// Save Status Info
Info = GetInfo(br),
// Save Status Players
Players = GetPlayers(br),
// Save Status Teams
Teams = GetTeams(br)
};
}
}
}
private byte[] ConnectAndSendPackets(UdpClient udpClient)
{
// Connect to remote host
udpClient.Connect(_EndPoint);
udpClient.Client.SendTimeout = _Timeout;
udpClient.Client.ReceiveTimeout = _Timeout;
// Packet 1: Initial request
byte[] responseData, challenge = new byte[] { }, requestData = new byte[] { 0xFE, 0xFD, 0x09, 0x04, 0x05, 0x06, 0x07 };
if (_Challenge)
{
udpClient.Send(requestData, requestData.Length);
// Packet 2: First response
responseData = udpClient.Receive(ref _EndPoint);
// Get challenge
if (int.TryParse(Encoding.ASCII.GetString(responseData.Skip(5).ToArray()).Trim(), out int result) && result != 0)
{
challenge = BitConverter.GetBytes(result);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(challenge);
}
}
}
// Packet 3: Second request
requestData[2] = 0x00;
requestData = requestData.Concat(challenge).Concat(new byte[] { 0xFF, 0xFF, 0xFF, 0x01 }).ToArray();
udpClient.Send(requestData, requestData.Length);
// Packet 4: Server response
responseData = Receive(udpClient);
return responseData;
}
private byte[] Receive(UdpClient udpClient)
{
int totalPackets = -1;
var payloads = new SortedDictionary();
do
{
var responseData = udpClient.Receive(ref _EndPoint);
using (var br = new BinaryReader(new MemoryStream(responseData), Encoding.UTF8))
{
var header = br.ReadByte();
if (header != 0)
{
throw new Exception($"Packet header mismatch. Received: {header}. Expected: 0.");
}
// Skip the timestamp and splitnum
br.ReadBytes(13);
// The 'numPackets' byte
var numPackets = br.ReadByte();
// The low 7 bits are the packet index (starting at zero)
var number = numPackets & 0x7F;
// The high bit is whether or not this is the last packet
var isLastPacket = numPackets >> 7 == 1;
// Save totalPackets as packet number + 1
if (isLastPacket)
{
totalPackets = number + 1;
}
// The object id. Example: \x01
var objectId = br.ReadByte();
// The object header
byte[] objectHeader = new byte[] { };
if (objectId >= 1)
{
// The object name. Example: "player_"
string objectName = br.ReadStringEx();
// The object items appear count
int count = br.ReadByte();
// If the object item doesn't appear before, set the header back
if (count == 0)
{
// Set the header. Example: \x00\x01player_\x00\x00
objectHeader = new byte[] { 0x00, objectId }.Concat(Encoding.UTF8.GetBytes(objectName)).Concat(new byte[] { 0x00, 0x00 }).ToArray();
}
}
// Save the payload
byte[] payload = objectHeader.Concat(responseData.Skip((int)br.BaseStream.Position)).ToArray();
payloads.Add(number, TrimPayload(payload));
}
} while (totalPackets == -1 || payloads.Count < totalPackets);
// Combine the payloads
var combinedPayload = payloads.Values.Aggregate((a, b) => a.Concat(b).ToArray());
return combinedPayload;
}
///
/// Remove the last trash string on the payload
///
///
///
private byte[] TrimPayload(byte[] payload)
{
int i = payload.Length;
while (payload[--i] != 0) ;
return payload.Take(i).ToArray();
}
private Dictionary GetInfo(BinaryReader br)
{
var info = new Dictionary();
// Read all key values
while (br.TryReadStringEx(out var key))
{
info[key] = br.ReadStringEx().Trim();
}
return info;
}
private List> GetPlayers(BinaryReader br)
{
var players = new List>();
// Return if BaseStream is end
if (br.BaseStream.Position == br.BaseStream.Length)
{
return players;
}
// Skip \x01player_\x00\x00
br.ReadByte();
string key = br.ReadStringEx().TrimEnd('_');
br.ReadByte();
// Team index
int i = 0;
// Loop all values and save
while (br.BaseStream.Position < br.BaseStream.Length)
{
if (br.TryReadStringEx(out var value))
{
// Add a Dictionary object if not exists
if (players.Count < i + 1)
{
players.Add(new Dictionary());
}
// Save the value
players[i++][key] = value.Trim();
}
else
{
// Return if no player
if (br.BaseStream.Position == br.BaseStream.Length)
{
break;
}
// Set new key
if (br.TryReadStringEx(out key))
{
// Remove the trailing "_"
key = key.TrimEnd('_');
}
else
{
break;
}
// Reset the team index
i = br.ReadByte();
}
}
return players;
}
private List> GetTeams(BinaryReader br)
{
var teams = new List>();
// Return if BaseStream is end
if (br.BaseStream.Position == br.BaseStream.Length)
{
return teams;
}
// Skip \x00\x02team_t\x00\x00
br.ReadBytes(2);
string key = br.ReadStringEx().TrimEnd('t').TrimEnd('_');
br.ReadByte();
// Player index
int i = 0;
// Loop all values and save
while (br.BaseStream.Position < br.BaseStream.Length)
{
if (br.TryReadStringEx(out var value))
{
// Add a Dictionary object if not exists
if (teams.Count < i + 1)
{
teams.Add(new Dictionary());
}
// Save the value
teams[i++][key] = value.Trim();
}
else
{
// Return if no team
if (br.BaseStream.Position == br.BaseStream.Length)
{
break;
}
// Set new key
if (br.TryReadStringEx(out key))
{
// Remove the trailing "_t"
key = key.TrimEnd('t').TrimEnd('_');
}
else
{
break;
}
// Reset the team index
i = br.ReadByte();
}
}
return teams;
}
///
/// Status object
///
public class Status
{
///
/// Status Info
///
public Dictionary Info { get; set; }
///
/// Status Players
///
public List> Players { get; set; }
///
/// Status Teams
///
public List> Teams { get; set; }
}
}
///
/// BinaryReader Extensions
///
public static class BinaryReaderExtensions
{
///
/// Reads a string from the current stream until charByte.
///
///
///
/// The string being read.
/// The end of the stream is reached.
/// The stream is closed.
/// An I/O error occurs.
public static string ReadStringEx(this BinaryReader br, byte[] charBytes)
{
charBytes = charBytes ?? new byte[] { 0 };
var bytes = new List();
byte streamByte;
while (Array.IndexOf(charBytes, streamByte = br.ReadByte()) == -1)
{
bytes.Add(streamByte);
}
return Encoding.UTF8.GetString(bytes.ToArray());
}
///
/// Reads a string from the current stream until charByte.
///
///
///
/// The string being read.
/// The end of the stream is reached.
/// The stream is closed.
/// An I/O error occurs.
public static string ReadStringEx(this BinaryReader br, byte charByte = 0)
{
return br.ReadStringEx(new byte[] { charByte });
}
///
/// Reads a string from the current stream until charByte. Return true if is not null and empty.
///
///
///
///
///
public static bool TryReadStringEx(this BinaryReader br, out string outString, byte[] charBytes)
{
outString = br.ReadStringEx(charBytes);
return !string.IsNullOrEmpty(outString);
}
///
/// Reads a string from the current stream until charByte. Return true if is not null and empty.
///
///
///
///
///
public static bool TryReadStringEx(this BinaryReader br, out string outString, byte charByte = 0)
{
return br.TryReadStringEx(out outString, new byte[] { charByte });
}
}
}