123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458 |
- 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
- {
- /// <summary>
- /// Represents a network endpoint as an IP address and a port number.
- /// </summary>
- protected IPEndPoint _EndPoint;
- /// <summary>
- /// Timeout in millisecond
- /// </summary>
- protected int _Timeout;
- /// <summary>
- /// Cached challenge bytes
- /// </summary>
- //protected byte[] _Challenge = new byte[0];
- /// <summary>
- /// Gamespy Query Protocol version 3
- /// </summary>
- /// <param name="address"></param>
- /// <param name="port"></param>
- /// <param name="timeout"></param>
- 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
- /// <summary>
- /// Retrieves information about the server including, Info, Players, and Teams.
- /// </summary>
- /// <returns></returns>
- /// <exception cref="SocketException"></exception>
- 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<int, byte[]>();
- 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;
- }
- /// <summary>
- /// Remove the last trash string on the payload
- /// </summary>
- /// <param name="payload"></param>
- /// <returns></returns>
- private byte[] TrimPayload(byte[] payload)
- {
- int i = payload.Length;
- while (payload[--i] != 0) ;
- return payload.Take(i).ToArray();
- }
- private Dictionary<string, string> GetInfo(BinaryReader br)
- {
- var info = new Dictionary<string, string>();
- // Read all key values
- while (br.TryReadStringEx(out var key))
- {
- info[key] = br.ReadStringEx().Trim();
- }
- return info;
- }
- private List<Dictionary<string, string>> GetPlayers(BinaryReader br)
- {
- var players = new List<Dictionary<string, string>>();
- // 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<string, string>());
- }
- // 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<Dictionary<string, string>> GetTeams(BinaryReader br)
- {
- var teams = new List<Dictionary<string, string>>();
- // 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<string, string>());
- }
- // 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;
- }
- /// <summary>
- /// Status object
- /// </summary>
- public class Status
- {
- /// <summary>
- /// Status Info
- /// </summary>
- public Dictionary<string, string> Info { get; set; }
- /// <summary>
- /// Status Players
- /// </summary>
- public List<Dictionary<string, string>> Players { get; set; }
- /// <summary>
- /// Status Teams
- /// </summary>
- public List<Dictionary<string, string>> Teams { get; set; }
- }
- }
- /// <summary>
- /// BinaryReader Extensions
- /// </summary>
- public static class BinaryReaderExtensions
- {
- /// <summary>
- /// Reads a string from the current stream until charByte.
- /// </summary>
- /// <param name="br"></param>
- /// <param name="charBytes"></param>
- /// <returns>The string being read.</returns>
- /// <exception cref="EndOfStreamException">The end of the stream is reached.</exception>
- /// <exception cref="ObjectDisposedException">The stream is closed.</exception>
- /// <exception cref="IOException">An I/O error occurs.</exception>
- public static string ReadStringEx(this BinaryReader br, byte[] charBytes)
- {
- charBytes = charBytes ?? new byte[] { 0 };
- var bytes = new List<byte>();
- byte streamByte;
- while (Array.IndexOf(charBytes, streamByte = br.ReadByte()) == -1)
- {
- bytes.Add(streamByte);
- }
- return Encoding.UTF8.GetString(bytes.ToArray());
- }
- /// <summary>
- /// Reads a string from the current stream until charByte.
- /// </summary>
- /// <param name="br"></param>
- /// <param name="charByte"></param>
- /// <returns>The string being read.</returns>
- /// <exception cref="EndOfStreamException">The end of the stream is reached.</exception>
- /// <exception cref="ObjectDisposedException">The stream is closed.</exception>
- /// <exception cref="IOException">An I/O error occurs.</exception>
- public static string ReadStringEx(this BinaryReader br, byte charByte = 0)
- {
- return br.ReadStringEx(new byte[] { charByte });
- }
- /// <summary>
- /// Reads a string from the current stream until charByte. Return true if is not null and empty.
- /// </summary>
- /// <param name="br"></param>
- /// <param name="outString"></param>
- /// <param name="charBytes"></param>
- /// <returns></returns>
- public static bool TryReadStringEx(this BinaryReader br, out string outString, byte[] charBytes)
- {
- outString = br.ReadStringEx(charBytes);
- return !string.IsNullOrEmpty(outString);
- }
- /// <summary>
- /// Reads a string from the current stream until charByte. Return true if is not null and empty.
- /// </summary>
- /// <param name="br"></param>
- /// <param name="outString"></param>
- /// <param name="charByte"></param>
- /// <returns></returns>
- public static bool TryReadStringEx(this BinaryReader br, out string outString, byte charByte = 0)
- {
- return br.TryReadStringEx(out outString, new byte[] { charByte });
- }
- }
- }
|