Gamespy3.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. /**
  3. * This file is part of GameQ.
  4. *
  5. * GameQ is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU Lesser General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * GameQ is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. namespace GameQ\Protocols;
  19. use GameQ\Protocol;
  20. use GameQ\Buffer;
  21. use GameQ\Result;
  22. /**
  23. * GameSpy3 Protocol class
  24. *
  25. * Given the ability for non utf-8 characters to be used as hostnames, player names, etc... this
  26. * version returns all strings utf-8 encoded (utf8_encode). To access the proper version of a
  27. * string response you must use utf8_decode() on the specific response.
  28. *
  29. * @author Austin Bischoff <[email protected]>
  30. */
  31. class Gamespy3 extends Protocol
  32. {
  33. /**
  34. * Array of packets we want to look up.
  35. * Each key should correspond to a defined method in this or a parent class
  36. *
  37. * @type array
  38. */
  39. protected $packets = [
  40. self::PACKET_CHALLENGE => "\xFE\xFD\x09\x10\x20\x30\x40",
  41. self::PACKET_ALL => "\xFE\xFD\x00\x10\x20\x30\x40%s\xFF\xFF\xFF\x01",
  42. ];
  43. /**
  44. * The query protocol used to make the call
  45. *
  46. * @type string
  47. */
  48. protected $protocol = 'gamespy3';
  49. /**
  50. * String name of this protocol class
  51. *
  52. * @type string
  53. */
  54. protected $name = 'gamespy3';
  55. /**
  56. * Longer string name of this protocol class
  57. *
  58. * @type string
  59. */
  60. protected $name_long = "GameSpy3 Server";
  61. /**
  62. * The client join link
  63. *
  64. * @type string
  65. */
  66. protected $join_link = null;
  67. /**
  68. * This defines the split between the server info and player/team info.
  69. * This value can vary by game. This value is the default split.
  70. *
  71. * @var string
  72. */
  73. protected $packetSplit = "/\\x00\\x00\\x01/m";
  74. /**
  75. * Parse the challenge response and apply it to all the packet types
  76. *
  77. * @param \GameQ\Buffer $challenge_buffer
  78. *
  79. * @return bool
  80. * @throws \GameQ\Exception\Protocol
  81. */
  82. public function challengeParseAndApply(Buffer $challenge_buffer)
  83. {
  84. // Pull out the challenge
  85. $challenge = substr(preg_replace("/[^0-9\-]/si", "", $challenge_buffer->getBuffer()), 1);
  86. // By default, no challenge result (see #197)
  87. $challenge_result = '';
  88. // Check for valid challenge (see #197)
  89. if ($challenge) {
  90. // Encode chellenge result
  91. $challenge_result = sprintf(
  92. "%c%c%c%c",
  93. ($challenge >> 24),
  94. ($challenge >> 16),
  95. ($challenge >> 8),
  96. ($challenge >> 0)
  97. );
  98. }
  99. // Apply the challenge and return
  100. return $this->challengeApply($challenge_result);
  101. }
  102. /**
  103. * Process the response
  104. *
  105. * @return array
  106. */
  107. public function processResponse()
  108. {
  109. // Holds the processed packets
  110. $processed = [];
  111. // Iterate over the packets
  112. foreach ($this->packets_response as $response) {
  113. // Make a buffer
  114. $buffer = new Buffer($response, Buffer::NUMBER_TYPE_BIGENDIAN);
  115. // Packet type = 0
  116. $buffer->readInt8();
  117. // Session Id
  118. $buffer->readInt32();
  119. // We need to burn the splitnum\0 because it is not used
  120. $buffer->skip(9);
  121. // Get the id
  122. $id = $buffer->readInt8();
  123. // Burn next byte not sure what it is used for
  124. $buffer->skip(1);
  125. // Add this packet to the processed
  126. $processed[$id] = $buffer->getBuffer();
  127. unset($buffer, $id);
  128. }
  129. // Sort packets, reset index
  130. ksort($processed);
  131. // Offload cleaning up the packets if they happen to be split
  132. $packets = $this->cleanPackets(array_values($processed));
  133. // Split the packets by type general and the rest (i.e. players & teams)
  134. $split = preg_split($this->packetSplit, implode('', $packets));
  135. // Create a new result
  136. $result = new Result();
  137. // Assign variable due to pass by reference in PHP 7+
  138. $buffer = new Buffer($split[0], Buffer::NUMBER_TYPE_BIGENDIAN);
  139. // First key should be server details and rules
  140. $this->processDetails($buffer, $result);
  141. // The rest should be the player and team information, if it exists
  142. if (array_key_exists(1, $split)) {
  143. $buffer = new Buffer($split[1], Buffer::NUMBER_TYPE_BIGENDIAN);
  144. $this->processPlayersAndTeams($buffer, $result);
  145. }
  146. unset($buffer);
  147. return $result->fetch();
  148. }
  149. /*
  150. * Internal methods
  151. */
  152. /**
  153. * Handles cleaning up packets since the responses can be a bit "dirty"
  154. *
  155. * @param array $packets
  156. *
  157. * @return array
  158. */
  159. protected function cleanPackets(array $packets = [])
  160. {
  161. // Get the number of packets
  162. $packetCount = count($packets);
  163. // Compare last var of current packet with first var of next packet
  164. // On a partial match, remove last var from current packet,
  165. // variable header from next packet
  166. for ($i = 0, $x = $packetCount; $i < $x - 1; $i++) {
  167. // First packet
  168. $fst = substr($packets[$i], 0, -1);
  169. // Second packet
  170. $snd = $packets[$i + 1];
  171. // Get last variable from first packet
  172. $fstvar = substr($fst, strrpos($fst, "\x00") + 1);
  173. // Get first variable from last packet
  174. $snd = substr($snd, strpos($snd, "\x00") + 2);
  175. $sndvar = substr($snd, 0, strpos($snd, "\x00"));
  176. // Check if fstvar is a substring of sndvar
  177. // If so, remove it from the first string
  178. if (!empty($fstvar) && strpos($sndvar, $fstvar) !== false) {
  179. $packets[$i] = preg_replace("#(\\x00[^\\x00]+\\x00)$#", "\x00", $packets[$i]);
  180. }
  181. }
  182. // Now let's loop the return and remove any dupe prefixes
  183. for ($x = 1; $x < $packetCount; $x++) {
  184. $buffer = new Buffer($packets[$x], Buffer::NUMBER_TYPE_BIGENDIAN);
  185. $prefix = $buffer->readString();
  186. // Check to see if the return before has the same prefix present
  187. if ($prefix != null && strstr($packets[($x - 1)], $prefix)) {
  188. // Update the return by removing the prefix plus 2 chars
  189. $packets[$x] = substr(str_replace($prefix, '', $packets[$x]), 2);
  190. }
  191. unset($buffer);
  192. }
  193. unset($x, $i, $snd, $sndvar, $fst, $fstvar);
  194. // Return cleaned packets
  195. return $packets;
  196. }
  197. /**
  198. * Handles processing the details data into a usable format
  199. *
  200. * @param \GameQ\Buffer $buffer
  201. * @param \GameQ\Result $result
  202. */
  203. protected function processDetails(Buffer &$buffer, Result &$result)
  204. {
  205. // We go until we hit an empty key
  206. while ($buffer->getLength()) {
  207. $key = $buffer->readString();
  208. if (strlen($key) == 0) {
  209. break;
  210. }
  211. $result->add($key, utf8_encode($buffer->readString()));
  212. }
  213. }
  214. /**
  215. * Handles processing the player and team data into a usable format
  216. *
  217. * @param \GameQ\Buffer $buffer
  218. * @param \GameQ\Result $result
  219. */
  220. protected function processPlayersAndTeams(Buffer &$buffer, Result &$result)
  221. {
  222. /*
  223. * Explode the data into groups. First is player, next is team (item_t)
  224. * Each group should be as follows:
  225. *
  226. * [0] => item_
  227. * [1] => information for item_
  228. * ...
  229. */
  230. $data = explode("\x00\x00", $buffer->getBuffer());
  231. // By default item_group is blank, this will be set for each loop thru the data
  232. $item_group = '';
  233. // By default the item_type is blank, this will be set on each loop
  234. $item_type = '';
  235. // Save count as variable
  236. $count = count($data);
  237. // Loop through all of the $data for information and pull it out into the result
  238. for ($x = 0; $x < $count - 1; $x++) {
  239. // Pull out the item
  240. $item = $data[$x];
  241. // If this is an empty item, move on
  242. if ($item == '' || $item == "\x00") {
  243. continue;
  244. }
  245. /*
  246. * Left as reference:
  247. *
  248. * Each block of player_ and team_t have preceding junk chars
  249. *
  250. * player_ is actually \x01player_
  251. * team_t is actually \x00\x02team_t
  252. *
  253. * Probably a by-product of the change to exploding the data from the original.
  254. *
  255. * For now we just strip out these characters
  256. */
  257. // Check to see if $item has a _ at the end, this is player info
  258. if (substr($item, -1) == '_') {
  259. // Set the item group
  260. $item_group = 'players';
  261. // Set the item type, rip off any trailing stuff and bad chars
  262. $item_type = rtrim(str_replace("\x01", '', $item), '_');
  263. } elseif (substr($item, -2) == '_t') {
  264. // Check to see if $item has a _t at the end, this is team info
  265. // Set the item group
  266. $item_group = 'teams';
  267. // Set the item type, rip off any trailing stuff and bad chars
  268. $item_type = rtrim(str_replace(["\x00", "\x02"], '', $item), '_t');
  269. } else {
  270. // We can assume it is data belonging to a previously defined item
  271. // Make a temp buffer so we have easier access to the data
  272. $buf_temp = new Buffer($item, Buffer::NUMBER_TYPE_BIGENDIAN);
  273. // Get the values
  274. while ($buf_temp->getLength()) {
  275. // No value so break the loop, end of string
  276. if (($val = $buf_temp->readString()) === '') {
  277. break;
  278. }
  279. // Add the value to the proper item in the correct group
  280. $result->addSub($item_group, $item_type, utf8_encode(trim($val)));
  281. }
  282. // Unset our buffer
  283. unset($buf_temp);
  284. }
  285. }
  286. // Free up some memory
  287. unset($count, $data, $item, $item_group, $item_type, $val);
  288. }
  289. }