Gs2Status.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.Sockets;
  7. using System.Net;
  8. //https://github.com/opengsq/opengsq-dotnet/blob/main/OpenGSQ/Protocols/GameSpy2.cs
  9. //https://github.com/opengsq/opengsq-dotnet/blob/main/OpenGSQ/ProtocolBase.cs
  10. /*
  11. MIT License
  12. Copyright (c) 2021 OpenGSQ
  13. Permission is hereby granted, free of charge, to any person obtaining a copy
  14. of this software and associated documentation files (the "Software"), to deal
  15. in the Software without restriction, including without limitation the rights
  16. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. copies of the Software, and to permit persons to whom the Software is
  18. furnished to do so, subject to the following conditions:
  19. The above copyright notice and this permission notice shall be included in all
  20. copies or substantial portions of the Software.
  21. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  27. SOFTWARE.
  28. */
  29. namespace VeloeMonitorDataCollector.Dependencies
  30. {
  31. /// <summary>
  32. /// Gamespy Query Protocol version 2
  33. /// </summary>
  34. public class Gs2Status
  35. {
  36. /// <summary>
  37. /// Represents a network endpoint as an IP address and a port number.
  38. /// </summary>
  39. protected IPEndPoint _EndPoint;
  40. /// <summary>
  41. /// Timeout in millisecond
  42. /// </summary>
  43. protected int _Timeout;
  44. /// <summary>
  45. /// Cached challenge bytes
  46. /// </summary>
  47. protected byte[] _Challenge = new byte[0];
  48. /// <summary>
  49. /// ProtocolBase
  50. /// </summary>
  51. /// <param name="address"></param>
  52. /// <param name="port"></param>
  53. /// <param name="timeout"></param>
  54. public Gs2Status(string address, int port, int timeout = 5000)
  55. {
  56. if (IPAddress.TryParse(address, out var ipAddress))
  57. {
  58. _EndPoint = new IPEndPoint(ipAddress, port);
  59. }
  60. else
  61. {
  62. _EndPoint = new IPEndPoint(Dns.GetHostAddresses(address)[0], port);
  63. }
  64. _Timeout = timeout;
  65. }
  66. /// <summary>
  67. /// Gamespy Query Protocol version 2
  68. /// </summary>
  69. /// <param name="address"></param>
  70. /// <param name="port"></param>
  71. /// <param name="timeout"></param>
  72. /// <summary>
  73. /// Retrieves information about the server including, Info, Players, and Teams.
  74. /// </summary>
  75. /// <param name="request"></param>
  76. /// <returns></returns>
  77. /// <exception cref="SocketException"></exception>
  78. public Status GetStatus(Request request = Request.Info | Request.Players | Request.Teams)
  79. {
  80. using (var udpClient = new UdpClient())
  81. {
  82. var responseData = ConnectAndSend(udpClient, request);
  83. using (var br = new BinaryReader(new MemoryStream(responseData), Encoding.UTF8))
  84. {
  85. var status = new Status();
  86. // Save Response Info
  87. if (request.HasFlag(Request.Info))
  88. {
  89. status.Info = GetInfo(br);
  90. }
  91. // Save Response Players
  92. if (request.HasFlag(Request.Players))
  93. {
  94. status.Players = GetPlayers(br);
  95. }
  96. // Save Response Teams
  97. if (request.HasFlag(Request.Teams))
  98. {
  99. status.Teams = GetTeams(br);
  100. }
  101. return status;
  102. }
  103. }
  104. }
  105. private byte[] ConnectAndSend(UdpClient udpClient, Request request)
  106. {
  107. // Connect to remote host
  108. udpClient.Connect(_EndPoint);
  109. udpClient.Client.SendTimeout = _Timeout;
  110. udpClient.Client.ReceiveTimeout = _Timeout;
  111. // Send Request
  112. var requestData = new byte[] { 0xFE, 0xFD, 0x00, 0x04, 0x05, 0x06, 0x07 }.Concat(GetRequestBytes(request)).ToArray();
  113. udpClient.Send(requestData, requestData.Length);
  114. // Server response
  115. var responseData = udpClient.Receive(ref _EndPoint);
  116. // Remove the first 5 bytes { 0x00, 0x04, 0x05, 0x06, 0x07 }
  117. return responseData.Skip(5).ToArray();
  118. }
  119. private byte[] GetRequestBytes(Request request)
  120. {
  121. return new byte[] {
  122. (byte)(request.HasFlag(Request.Info) ? 0xFF : 0x00),
  123. (byte)(request.HasFlag(Request.Players) ? 0xFF : 0x00),
  124. (byte)(request.HasFlag(Request.Teams) ? 0xFF : 0x00),
  125. };
  126. }
  127. private Dictionary<string, string> GetInfo(BinaryReader br)
  128. {
  129. var info = new Dictionary<string, string>();
  130. // Read all key values
  131. while (br.TryReadStringEx(out var key))
  132. {
  133. info[key] = br.ReadStringEx().Trim();
  134. }
  135. return info;
  136. }
  137. private List<Dictionary<string, string>> GetPlayers(BinaryReader br)
  138. {
  139. var players = new List<Dictionary<string, string>>();
  140. // Skip a byte
  141. br.ReadByte();
  142. // Get player count
  143. var playerCount = br.ReadByte();
  144. // Get all keys
  145. var keys = new List<string>();
  146. while (br.TryReadStringEx(out var key))
  147. {
  148. keys.Add(key.TrimEnd('_'));
  149. }
  150. // Set all keys and values
  151. for (int i = 0; i < playerCount; i++)
  152. {
  153. players.Add(new Dictionary<string, string>());
  154. foreach (var key in keys)
  155. {
  156. players[i][key] = br.ReadStringEx().Trim();
  157. }
  158. }
  159. return players;
  160. }
  161. private List<Dictionary<string, string>> GetTeams(BinaryReader br)
  162. {
  163. var teams = new List<Dictionary<string, string>>();
  164. // Skip a byte
  165. br.ReadByte();
  166. // Get team count
  167. var teamCount = br.ReadByte();
  168. // Get all keys
  169. var keys = new List<string>();
  170. while (br.TryReadStringEx(out var key))
  171. {
  172. keys.Add(key.TrimEnd('t').TrimEnd('_'));
  173. }
  174. // Set all keys and values
  175. for (int i = 0; i < teamCount; i++)
  176. {
  177. teams.Add(new Dictionary<string, string>());
  178. foreach (var key in keys)
  179. {
  180. teams[i][key] = br.ReadStringEx().Trim();
  181. }
  182. }
  183. return teams;
  184. }
  185. /// <summary>
  186. /// Request Flag
  187. /// </summary>
  188. [Flags]
  189. public enum Request : short
  190. {
  191. #pragma warning disable 1591
  192. Info = 1,
  193. Players = 2,
  194. Teams = 4,
  195. }
  196. public class Status
  197. {
  198. public Dictionary<string, string> Info { get; set; }
  199. public List<Dictionary<string, string>> Players { get; set; }
  200. public List<Dictionary<string, string>> Teams { get; set; }
  201. }
  202. }
  203. }