Source.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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\Buffer;
  20. use GameQ\Exception\Protocol as Exception;
  21. use GameQ\Protocol;
  22. use GameQ\Result;
  23. /**
  24. * Valve Source Engine Protocol Class (A2S)
  25. *
  26. * This class is used as the basis for all other source based servers
  27. * that rely on the source protocol for game querying.
  28. *
  29. * @SuppressWarnings(PHPMD.NumberOfChildren)
  30. *
  31. * @author Austin Bischoff <[email protected]>
  32. */
  33. class Source extends Protocol
  34. {
  35. /*
  36. * Source engine type constants
  37. */
  38. const SOURCE_ENGINE = 0,
  39. GOLDSOURCE_ENGINE = 1;
  40. /**
  41. * Array of packets we want to look up.
  42. * Each key should correspond to a defined method in this or a parent class
  43. *
  44. * @type array
  45. */
  46. protected $packets = [
  47. self::PACKET_CHALLENGE => "\xFF\xFF\xFF\xFF\x56\x00\x00\x00\x00",
  48. self::PACKET_DETAILS => "\xFF\xFF\xFF\xFFTSource Engine Query\x00%s",
  49. self::PACKET_PLAYERS => "\xFF\xFF\xFF\xFF\x55%s",
  50. self::PACKET_RULES => "\xFF\xFF\xFF\xFF\x56%s",
  51. ];
  52. /**
  53. * Use the response flag to figure out what method to run
  54. *
  55. * @type array
  56. */
  57. protected $responses = [
  58. "\x49" => "processDetails", // I
  59. "\x6d" => "processDetailsGoldSource", // m, goldsource
  60. "\x44" => "processPlayers", // D
  61. "\x45" => "processRules", // E
  62. ];
  63. /**
  64. * The query protocol used to make the call
  65. *
  66. * @type string
  67. */
  68. protected $protocol = 'source';
  69. /**
  70. * String name of this protocol class
  71. *
  72. * @type string
  73. */
  74. protected $name = 'source';
  75. /**
  76. * Longer string name of this protocol class
  77. *
  78. * @type string
  79. */
  80. protected $name_long = "Source Server";
  81. /**
  82. * Define the Source engine type. By default it is assumed to be Source
  83. *
  84. * @type int
  85. */
  86. protected $source_engine = self::SOURCE_ENGINE;
  87. /**
  88. * The client join link
  89. *
  90. * @type string
  91. */
  92. protected $join_link = "steam://connect/%s:%d/";
  93. /**
  94. * Normalize settings for this protocol
  95. *
  96. * @type array
  97. */
  98. protected $normalize = [
  99. // General
  100. 'general' => [
  101. // target => source
  102. 'dedicated' => 'dedicated',
  103. 'gametype' => 'game_descr',
  104. 'hostname' => 'hostname',
  105. 'mapname' => 'map',
  106. 'maxplayers' => 'max_players',
  107. 'mod' => 'game_dir',
  108. 'numplayers' => 'num_players',
  109. 'password' => 'password',
  110. ],
  111. // Individual
  112. 'player' => [
  113. 'name' => 'name',
  114. 'score' => 'score',
  115. 'time' => 'time',
  116. ],
  117. ];
  118. /**
  119. * Parse the challenge response and apply it to all the packet types
  120. *
  121. * @param \GameQ\Buffer $challenge_buffer
  122. *
  123. * @return bool
  124. * @throws \GameQ\Exception\Protocol
  125. */
  126. public function challengeParseAndApply(Buffer $challenge_buffer)
  127. {
  128. // Skip the header
  129. $challenge_buffer->skip(5);
  130. // Apply the challenge and return
  131. return $this->challengeApply($challenge_buffer->read(4));
  132. }
  133. /**
  134. * Process the response
  135. *
  136. * @return array
  137. * @throws \GameQ\Exception\Protocol
  138. */
  139. public function processResponse()
  140. {
  141. // Will hold the results when complete
  142. $results = [];
  143. // Holds sorted response packets
  144. $packets = [];
  145. // We need to pre-sort these for split packets so we can do extra work where needed
  146. foreach ($this->packets_response as $response) {
  147. $buffer = new Buffer($response);
  148. // Get the header of packet (long)
  149. $header = $buffer->readInt32Signed();
  150. // Single packet
  151. if ($header == -1) {
  152. // We need to peek and see what kind of engine this is for later processing
  153. if ($buffer->lookAhead(1) == "\x6d") {
  154. $this->source_engine = self::GOLDSOURCE_ENGINE;
  155. }
  156. $packets[] = $buffer->getBuffer();
  157. continue;
  158. } else {
  159. // Split packet
  160. // Packet Id (long)
  161. $packet_id = $buffer->readInt32Signed() + 10;
  162. // Add the buffer to the packet as another array
  163. $packets[$packet_id][] = $buffer->getBuffer();
  164. }
  165. }
  166. // Free up memory
  167. unset($response, $packet_id, $buffer, $header);
  168. // Now that we have the packets sorted we need to iterate and process them
  169. foreach ($packets as $packet_id => $packet) {
  170. // We first need to off load split packets to combine them
  171. if (is_array($packet)) {
  172. $buffer = new Buffer($this->processPackets($packet_id, $packet));
  173. } else {
  174. $buffer = new Buffer($packet);
  175. }
  176. // Figure out what packet response this is for
  177. $response_type = $buffer->read(1);
  178. // Figure out which packet response this is
  179. if (!array_key_exists($response_type, $this->responses)) {
  180. throw new Exception(__METHOD__ . " response type '{$response_type}' is not valid");
  181. }
  182. // Now we need to call the proper method
  183. $results = array_merge(
  184. $results,
  185. call_user_func_array([$this, $this->responses[$response_type]], [$buffer])
  186. );
  187. unset($buffer);
  188. }
  189. // Free up memory
  190. unset($packets, $packet, $packet_id, $response_type);
  191. return $results;
  192. }
  193. /*
  194. * Internal methods
  195. */
  196. /**
  197. * Process the split packets and decompress if necessary
  198. *
  199. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  200. *
  201. * @param $packet_id
  202. * @param array $packets
  203. *
  204. * @return string
  205. * @throws \GameQ\Exception\Protocol
  206. */
  207. protected function processPackets($packet_id, array $packets = [])
  208. {
  209. // Init array so we can order
  210. $packs = [];
  211. // We have multiple packets so we need to get them and order them
  212. foreach ($packets as $i => $packet) {
  213. // Make a buffer so we can read this info
  214. $buffer = new Buffer($packet);
  215. // Gold source
  216. if ($this->source_engine == self::GOLDSOURCE_ENGINE) {
  217. // Grab the packet number (byte)
  218. $packet_number = $buffer->readInt8();
  219. // We need to burn the extra header (\xFF\xFF\xFF\xFF) on first loop
  220. if ($i == 0) {
  221. $buffer->read(4);
  222. }
  223. // Now add the rest of the packet to the new array with the packet_number as the id so we can order it
  224. $packs[$packet_number] = $buffer->getBuffer();
  225. } else {
  226. // Number of packets in this set (byte)
  227. $buffer->readInt8();
  228. // The current packet number (byte)
  229. $packet_number = $buffer->readInt8();
  230. // Check to see if this is compressed
  231. // @todo: Check to make sure these decompress correctly, new changes may affect this loop.
  232. if ($packet_id & 0x80000000) {
  233. // Check to see if we have Bzip2 installed
  234. if (!function_exists('bzdecompress')) {
  235. // @codeCoverageIgnoreStart
  236. throw new Exception(
  237. 'Bzip2 is not installed. See http://www.php.net/manual/en/book.bzip2.php for more info.',
  238. 0
  239. );
  240. // @codeCoverageIgnoreEnd
  241. }
  242. // Get the length of the packet (long)
  243. $packet_length = $buffer->readInt32Signed();
  244. // Checksum for the decompressed packet (long), burn it - doesnt work in split responses
  245. $buffer->readInt32Signed();
  246. // Try to decompress
  247. $result = bzdecompress($buffer->getBuffer());
  248. // Now verify the length
  249. if (strlen($result) != $packet_length) {
  250. // @codeCoverageIgnoreStart
  251. throw new Exception(
  252. "Checksum for compressed packet failed! Length expected: {$packet_length}, length
  253. returned: " . strlen($result)
  254. );
  255. // @codeCoverageIgnoreEnd
  256. }
  257. // We need to burn the extra header (\xFF\xFF\xFF\xFF) on first loop
  258. if ($i == 0) {
  259. $result = substr($result, 4);
  260. }
  261. } else {
  262. // Get the packet length (short), burn it
  263. $buffer->readInt16Signed();
  264. // We need to burn the extra header (\xFF\xFF\xFF\xFF) on first loop
  265. if ($i == 0) {
  266. $buffer->read(4);
  267. }
  268. // Grab the rest of the buffer as a result
  269. $result = $buffer->getBuffer();
  270. }
  271. // Add this packet to the list
  272. $packs[$packet_number] = $result;
  273. }
  274. unset($buffer);
  275. }
  276. // Free some memory
  277. unset($packets, $packet);
  278. // Sort the packets by packet number
  279. ksort($packs);
  280. // Now combine the packs into one and return
  281. return implode("", $packs);
  282. }
  283. /**
  284. * Handles processing the details data into a usable format
  285. *
  286. * @param \GameQ\Buffer $buffer
  287. *
  288. * @return mixed
  289. * @throws \GameQ\Exception\Protocol
  290. */
  291. protected function processDetails(Buffer $buffer)
  292. {
  293. // Set the result to a new result instance
  294. $result = new Result();
  295. $result->add('protocol', $buffer->readInt8());
  296. $result->add('hostname', $buffer->readString());
  297. $result->add('map', $buffer->readString());
  298. $result->add('game_dir', $buffer->readString());
  299. $result->add('game_descr', $buffer->readString());
  300. $result->add('steamappid', $buffer->readInt16());
  301. $result->add('num_players', $buffer->readInt8());
  302. $result->add('max_players', $buffer->readInt8());
  303. $result->add('num_bots', $buffer->readInt8());
  304. $result->add('dedicated', $buffer->read());
  305. $result->add('os', $buffer->read());
  306. $result->add('password', $buffer->readInt8());
  307. $result->add('secure', $buffer->readInt8());
  308. // Special result for The Ship only (appid=2400)
  309. if ($result->get('steamappid') == 2400) {
  310. $result->add('game_mode', $buffer->readInt8());
  311. $result->add('witness_count', $buffer->readInt8());
  312. $result->add('witness_time', $buffer->readInt8());
  313. }
  314. $result->add('version', $buffer->readString());
  315. // Because of php 5.4...
  316. $edfCheck = $buffer->lookAhead(1);
  317. // Extra data flag
  318. if (!empty($edfCheck)) {
  319. $edf = $buffer->readInt8();
  320. if ($edf & 0x80) {
  321. $result->add('port', $buffer->readInt16Signed());
  322. }
  323. if ($edf & 0x10) {
  324. $result->add('steam_id', $buffer->readInt64());
  325. }
  326. if ($edf & 0x40) {
  327. $result->add('sourcetv_port', $buffer->readInt16Signed());
  328. $result->add('sourcetv_name', $buffer->readString());
  329. }
  330. if ($edf & 0x20) {
  331. $result->add('keywords', $buffer->readString());
  332. }
  333. if ($edf & 0x01) {
  334. $result->add('game_id', $buffer->readInt64());
  335. }
  336. unset($edf);
  337. }
  338. unset($buffer);
  339. return $result->fetch();
  340. }
  341. /**
  342. * Handles processing the server details from goldsource response
  343. *
  344. * @param \GameQ\Buffer $buffer
  345. *
  346. * @return array
  347. * @throws \GameQ\Exception\Protocol
  348. */
  349. protected function processDetailsGoldSource(Buffer $buffer)
  350. {
  351. // Set the result to a new result instance
  352. $result = new Result();
  353. $result->add('address', $buffer->readString());
  354. $result->add('hostname', $buffer->readString());
  355. $result->add('map', $buffer->readString());
  356. $result->add('game_dir', $buffer->readString());
  357. $result->add('game_descr', $buffer->readString());
  358. $result->add('num_players', $buffer->readInt8());
  359. $result->add('max_players', $buffer->readInt8());
  360. $result->add('version', $buffer->readInt8());
  361. $result->add('dedicated', $buffer->read());
  362. $result->add('os', $buffer->read());
  363. $result->add('password', $buffer->readInt8());
  364. // Mod section
  365. $result->add('ismod', $buffer->readInt8());
  366. // We only run these if ismod is 1 (true)
  367. if ($result->get('ismod') == 1) {
  368. $result->add('mod_urlinfo', $buffer->readString());
  369. $result->add('mod_urldl', $buffer->readString());
  370. $buffer->skip();
  371. $result->add('mod_version', $buffer->readInt32Signed());
  372. $result->add('mod_size', $buffer->readInt32Signed());
  373. $result->add('mod_type', $buffer->readInt8());
  374. $result->add('mod_cldll', $buffer->readInt8());
  375. }
  376. $result->add('secure', $buffer->readInt8());
  377. $result->add('num_bots', $buffer->readInt8());
  378. unset($buffer);
  379. return $result->fetch();
  380. }
  381. /**
  382. * Handles processing the player data into a usable format
  383. *
  384. * @param \GameQ\Buffer $buffer
  385. *
  386. * @return mixed
  387. */
  388. protected function processPlayers(Buffer $buffer)
  389. {
  390. // Set the result to a new result instance
  391. $result = new Result();
  392. // Pull out the number of players
  393. $num_players = $buffer->readInt8();
  394. // Player count
  395. $result->add('num_players', $num_players);
  396. // No players so no need to look any further
  397. if ($num_players == 0) {
  398. return $result->fetch();
  399. }
  400. // Players list
  401. while ($buffer->getLength()) {
  402. $result->addPlayer('id', $buffer->readInt8());
  403. $result->addPlayer('name', $buffer->readString());
  404. $result->addPlayer('score', $buffer->readInt32Signed());
  405. $result->addPlayer('time', $buffer->readFloat32());
  406. }
  407. unset($buffer);
  408. return $result->fetch();
  409. }
  410. /**
  411. * Handles processing the rules data into a usable format
  412. *
  413. * @param \GameQ\Buffer $buffer
  414. *
  415. * @return mixed
  416. */
  417. protected function processRules(Buffer $buffer)
  418. {
  419. // Set the result to a new result instance
  420. $result = new Result();
  421. // Count the number of rules
  422. $num_rules = $buffer->readInt16Signed();
  423. // Add the count of the number of rules this server has
  424. $result->add('num_rules', $num_rules);
  425. // Rules
  426. while ($buffer->getLength()) {
  427. $result->add($buffer->readString(), $buffer->readString());
  428. }
  429. unset($buffer);
  430. return $result->fetch();
  431. }
  432. }