From c83922fa52ccb97a034bee83b1c99a210e5c6ee3 Mon Sep 17 00:00:00 2001 From: Jim Date: Thu, 3 Mar 2022 06:43:23 +0000 Subject: [PATCH] Moving Source Query --- includes/SourceQuery/BaseSocket.php | 139 +++++ includes/SourceQuery/Buffer.php | 177 ++++++ .../Exception/AuthenticationException.php | 19 + .../Exception/InvalidArgumentException.php | 18 + .../Exception/InvalidPacketException.php | 21 + .../SourceQuery/Exception/SocketException.php | 21 + .../Exception/SourceQueryException.php | 18 + includes/SourceQuery/GoldSourceRcon.php | 145 +++++ includes/SourceQuery/Socket.php | 94 +++ includes/SourceQuery/SourceQuery.php | 570 ++++++++++++++++++ includes/SourceQuery/SourceRcon.php | 200 ++++++ includes/SourceQuery/bootstrap.php | 27 + 12 files changed, 1449 insertions(+) create mode 100644 includes/SourceQuery/BaseSocket.php create mode 100644 includes/SourceQuery/Buffer.php create mode 100644 includes/SourceQuery/Exception/AuthenticationException.php create mode 100644 includes/SourceQuery/Exception/InvalidArgumentException.php create mode 100644 includes/SourceQuery/Exception/InvalidPacketException.php create mode 100644 includes/SourceQuery/Exception/SocketException.php create mode 100644 includes/SourceQuery/Exception/SourceQueryException.php create mode 100644 includes/SourceQuery/GoldSourceRcon.php create mode 100644 includes/SourceQuery/Socket.php create mode 100644 includes/SourceQuery/SourceQuery.php create mode 100644 includes/SourceQuery/SourceRcon.php create mode 100644 includes/SourceQuery/bootstrap.php diff --git a/includes/SourceQuery/BaseSocket.php b/includes/SourceQuery/BaseSocket.php new file mode 100644 index 00000000..33fa9c46 --- /dev/null +++ b/includes/SourceQuery/BaseSocket.php @@ -0,0 +1,139 @@ +Close( ); + } + + abstract public function Close( ) : void; + abstract public function Open( string $Address, int $Port, int $Timeout, int $Engine ) : void; + abstract public function Write( int $Header, string $String = '' ) : bool; + abstract public function Read( int $Length = 1400 ) : Buffer; + + protected function ReadInternal( Buffer $Buffer, int $Length, callable $SherlockFunction ) : Buffer + { + if( $Buffer->Remaining( ) === 0 ) + { + throw new InvalidPacketException( 'Failed to read any data from socket', InvalidPacketException::BUFFER_EMPTY ); + } + + $Header = $Buffer->GetLong( ); + + if( $Header === -1 ) // Single packet + { + // We don't have to do anything + } + else if( $Header === -2 ) // Split packet + { + $Packets = []; + $IsCompressed = false; + $ReadMore = false; + $PacketChecksum = null; + + do + { + $RequestID = $Buffer->GetLong( ); + + switch( $this->Engine ) + { + case SourceQuery::GOLDSOURCE: + { + $PacketCountAndNumber = $Buffer->GetByte( ); + $PacketCount = $PacketCountAndNumber & 0xF; + $PacketNumber = $PacketCountAndNumber >> 4; + + break; + } + case SourceQuery::SOURCE: + { + $IsCompressed = ( $RequestID & 0x80000000 ) !== 0; + $PacketCount = $Buffer->GetByte( ); + $PacketNumber = $Buffer->GetByte( ) + 1; + + if( $IsCompressed ) + { + $Buffer->GetLong( ); // Split size + + $PacketChecksum = $Buffer->GetUnsignedLong( ); + } + else + { + $Buffer->GetShort( ); // Split size + } + + break; + } + default: + { + throw new SocketException( 'Unknown engine.', SocketException::INVALID_ENGINE ); + } + } + + $Packets[ $PacketNumber ] = $Buffer->Get( ); + + $ReadMore = $PacketCount > sizeof( $Packets ); + } + while( $ReadMore && $SherlockFunction( $Buffer, $Length ) ); + + $Data = Implode( $Packets ); + + // TODO: Test this + if( $IsCompressed ) + { + // Let's make sure this function exists, it's not included in PHP by default + if( !Function_Exists( 'bzdecompress' ) ) + { + throw new \RuntimeException( 'Received compressed packet, PHP doesn\'t have Bzip2 library installed, can\'t decompress.' ); + } + + $Data = bzdecompress( $Data ); + + if( !is_string( $Data ) || CRC32( $Data ) !== $PacketChecksum ) + { + throw new InvalidPacketException( 'CRC32 checksum mismatch of uncompressed packet data.', InvalidPacketException::CHECKSUM_MISMATCH ); + } + } + + $Buffer->Set( SubStr( $Data, 4 ) ); + } + else + { + throw new InvalidPacketException( 'Socket read: Raw packet header mismatch. (0x' . DecHex( $Header ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + + return $Buffer; + } + } diff --git a/includes/SourceQuery/Buffer.php b/includes/SourceQuery/Buffer.php new file mode 100644 index 00000000..61120167 --- /dev/null +++ b/includes/SourceQuery/Buffer.php @@ -0,0 +1,177 @@ +Buffer = $Buffer; + $this->Length = StrLen( $Buffer ); + $this->Position = 0; + } + + /** + * Get remaining bytes + * + * @return int Remaining bytes in buffer + */ + public function Remaining( ) : int + { + return $this->Length - $this->Position; + } + + /** + * Gets data from buffer + * + * @param int $Length Bytes to read + */ + public function Get( int $Length = -1 ) : string + { + if( $Length === 0 ) + { + return ''; + } + + $Remaining = $this->Remaining( ); + + if( $Length === -1 ) + { + $Length = $Remaining; + } + else if( $Length > $Remaining ) + { + return ''; + } + + $Data = SubStr( $this->Buffer, $this->Position, $Length ); + + $this->Position += $Length; + + return $Data; + } + + /** + * Get byte from buffer + */ + public function GetByte( ) : int + { + return Ord( $this->Get( 1 ) ); + } + + /** + * Get short from buffer + */ + public function GetShort( ) : int + { + if( $this->Remaining( ) < 2 ) + { + throw new InvalidPacketException( 'Not enough data to unpack a short.', InvalidPacketException::BUFFER_EMPTY ); + } + + $Data = UnPack( 'v', $this->Get( 2 ) ); + + return (int)$Data[ 1 ]; + } + + /** + * Get long from buffer + */ + public function GetLong( ) : int + { + if( $this->Remaining( ) < 4 ) + { + throw new InvalidPacketException( 'Not enough data to unpack a long.', InvalidPacketException::BUFFER_EMPTY ); + } + + $Data = UnPack( 'l', $this->Get( 4 ) ); + + return (int)$Data[ 1 ]; + } + + /** + * Get float from buffer + */ + public function GetFloat( ) : float + { + if( $this->Remaining( ) < 4 ) + { + throw new InvalidPacketException( 'Not enough data to unpack a float.', InvalidPacketException::BUFFER_EMPTY ); + } + + $Data = UnPack( 'f', $this->Get( 4 ) ); + + return (float)$Data[ 1 ]; + } + + /** + * Get unsigned long from buffer + */ + public function GetUnsignedLong( ) : int + { + if( $this->Remaining( ) < 4 ) + { + throw new InvalidPacketException( 'Not enough data to unpack an usigned long.', InvalidPacketException::BUFFER_EMPTY ); + } + + $Data = UnPack( 'V', $this->Get( 4 ) ); + + return (int)$Data[ 1 ]; + } + + /** + * Read one string from buffer ending with null byte + */ + public function GetString( ) : string + { + $ZeroBytePosition = StrPos( $this->Buffer, "\0", $this->Position ); + + if( $ZeroBytePosition === false ) + { + return ''; + } + + $String = $this->Get( $ZeroBytePosition - $this->Position ); + + $this->Position++; + + return $String; + } + } diff --git a/includes/SourceQuery/Exception/AuthenticationException.php b/includes/SourceQuery/Exception/AuthenticationException.php new file mode 100644 index 00000000..3e90f6e5 --- /dev/null +++ b/includes/SourceQuery/Exception/AuthenticationException.php @@ -0,0 +1,19 @@ +Socket = $Socket; + } + + public function Close( ) : void + { + $this->RconChallenge = ''; + $this->RconPassword = ''; + } + + public function Open( ) : void + { + // + } + + public function Write( int $Header, string $String = '' ) : bool + { + $Command = Pack( 'cccca*', 0xFF, 0xFF, 0xFF, 0xFF, $String ); + $Length = StrLen( $Command ); + + return $Length === FWrite( $this->Socket->Socket, $Command, $Length ); + } + + /** + * @param int $Length + * @throws AuthenticationException + * @return Buffer + */ + public function Read( int $Length = 1400 ) : Buffer + { + // GoldSource RCON has same structure as Query + $Buffer = $this->Socket->Read( ); + + $StringBuffer = ''; + $ReadMore = false; + + // There is no indentifier of the end, so we just need to continue reading + do + { + $ReadMore = $Buffer->Remaining( ) > 0; + + if( $ReadMore ) + { + if( $Buffer->GetByte( ) !== SourceQuery::S2A_RCON ) + { + throw new InvalidPacketException( 'Invalid rcon response.', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + + $Packet = $Buffer->Get( ); + $StringBuffer .= $Packet; + //$StringBuffer .= SubStr( $Packet, 0, -2 ); + + // Let's assume if this packet is not long enough, there are no more after this one + $ReadMore = StrLen( $Packet ) > 1000; // use 1300? + + if( $ReadMore ) + { + $Buffer = $this->Socket->Read( ); + } + } + } + while( $ReadMore ); + + $Trimmed = trim( $StringBuffer ); + + if( $Trimmed === 'Bad rcon_password.' ) + { + throw new AuthenticationException( $Trimmed, AuthenticationException::BAD_PASSWORD ); + } + else if( $Trimmed === 'You have been banned from this server.' ) + { + throw new AuthenticationException( $Trimmed, AuthenticationException::BANNED ); + } + + $Buffer->Set( $Trimmed ); + + return $Buffer; + } + + public function Command( string $Command ) : string + { + if( !$this->RconChallenge ) + { + throw new AuthenticationException( 'Tried to execute a RCON command before successful authorization.', AuthenticationException::BAD_PASSWORD ); + } + + $this->Write( 0, 'rcon ' . $this->RconChallenge . ' "' . $this->RconPassword . '" ' . $Command . "\0" ); + $Buffer = $this->Read( ); + + return $Buffer->Get( ); + } + + public function Authorize( string $Password ) : void + { + $this->RconPassword = $Password; + + $this->Write( 0, 'challenge rcon' ); + $Buffer = $this->Socket->Read( ); + + if( $Buffer->Get( 14 ) !== 'challenge rcon' ) + { + throw new AuthenticationException( 'Failed to get RCON challenge.', AuthenticationException::BAD_PASSWORD ); + } + + $this->RconChallenge = Trim( $Buffer->Get( ) ); + } + } diff --git a/includes/SourceQuery/Socket.php b/includes/SourceQuery/Socket.php new file mode 100644 index 00000000..4f5cf9fd --- /dev/null +++ b/includes/SourceQuery/Socket.php @@ -0,0 +1,94 @@ +Socket !== null ) + { + FClose( $this->Socket ); + + $this->Socket = null; + } + } + + public function Open( string $Address, int $Port, int $Timeout, int $Engine ) : void + { + $this->Timeout = $Timeout; + $this->Engine = $Engine; + $this->Port = $Port; + $this->Address = $Address; + + $this->Socket = @FSockOpen( 'udp://' . $Address, $Port, $ErrNo, $ErrStr, $Timeout ); + + if( $ErrNo || $this->Socket === false ) + { + throw new SocketException( 'Could not create socket: ' . $ErrStr, SocketException::COULD_NOT_CREATE_SOCKET ); + } + + Stream_Set_Timeout( $this->Socket, $Timeout ); + Stream_Set_Blocking( $this->Socket, true ); + } + + public function Write( int $Header, string $String = '' ) : bool + { + $Command = Pack( 'ccccca*', 0xFF, 0xFF, 0xFF, 0xFF, $Header, $String ); + $Length = StrLen( $Command ); + + return $Length === FWrite( $this->Socket, $Command, $Length ); + } + + /** + * Reads from socket and returns Buffer. + * + * @throws InvalidPacketException + * + * @return Buffer Buffer + */ + public function Read( int $Length = 1400 ) : Buffer + { + $Buffer = new Buffer( ); + $Buffer->Set( FRead( $this->Socket, $Length ) ); + + $this->ReadInternal( $Buffer, $Length, [ $this, 'Sherlock' ] ); + + return $Buffer; + } + + public function Sherlock( Buffer $Buffer, int $Length ) : bool + { + $Data = FRead( $this->Socket, $Length ); + + if( StrLen( $Data ) < 4 ) + { + return false; + } + + $Buffer->Set( $Data ); + + return $Buffer->GetLong( ) === -2; + } + } diff --git a/includes/SourceQuery/SourceQuery.php b/includes/SourceQuery/SourceQuery.php new file mode 100644 index 00000000..b4652fb9 --- /dev/null +++ b/includes/SourceQuery/SourceQuery.php @@ -0,0 +1,570 @@ +Socket = $Socket ?: new Socket( ); + } + + public function __destruct( ) + { + $this->Disconnect( ); + } + + /** + * Opens connection to server + * + * @param string $Address Server ip + * @param int $Port Server port + * @param int $Timeout Timeout period + * @param int $Engine Engine the server runs on (goldsource, source) + * + * @throws InvalidArgumentException + * @throws SocketException + */ + public function Connect( string $Address, int $Port, int $Timeout = 3, int $Engine = self::SOURCE ) : void + { + $this->Disconnect( ); + + if( $Timeout < 0 ) + { + throw new InvalidArgumentException( 'Timeout must be a positive integer.', InvalidArgumentException::TIMEOUT_NOT_INTEGER ); + } + + $this->Socket->Open( $Address, $Port, $Timeout, $Engine ); + + $this->Connected = true; + } + + /** + * Forces GetChallenge to use old method for challenge retrieval because some games use outdated protocol (e.g Starbound) + * + * @param bool $Value Set to true to force old method + * + * @returns bool Previous value + */ + public function SetUseOldGetChallengeMethod( bool $Value ) : bool + { + $Previous = $this->UseOldGetChallengeMethod; + + $this->UseOldGetChallengeMethod = $Value === true; + + return $Previous; + } + + /** + * Closes all open connections + */ + public function Disconnect( ) : void + { + $this->Connected = false; + $this->Challenge = ''; + + $this->Socket->Close( ); + + if( $this->Rcon ) + { + $this->Rcon->Close( ); + + $this->Rcon = null; + } + } + + /** + * Sends ping packet to the server + * NOTE: This may not work on some games (TF2 for example) + * + * @throws InvalidPacketException + * @throws SocketException + * + * @return bool True on success, false on failure + */ + public function Ping( ) : bool + { + if( !$this->Connected ) + { + throw new SocketException( 'Not connected.', SocketException::NOT_CONNECTED ); + } + + $this->Socket->Write( self::A2A_PING ); + $Buffer = $this->Socket->Read( ); + + return $Buffer->GetByte( ) === self::A2A_ACK; + } + + /** + * Get server information + * + * @throws InvalidPacketException + * @throws SocketException + * + * @return array Returns an array with information on success + */ + public function GetInfo( ) : array + { + if( !$this->Connected ) + { + throw new SocketException( 'Not connected.', SocketException::NOT_CONNECTED ); + } + + if( $this->Challenge ) + { + $this->Socket->Write( self::A2S_INFO, "Source Engine Query\0" . $this->Challenge ); + } + else + { + $this->Socket->Write( self::A2S_INFO, "Source Engine Query\0" ); + } + + $Buffer = $this->Socket->Read( ); + $Type = $Buffer->GetByte( ); + $Server = []; + + if( $Type === self::S2C_CHALLENGE ) + { + $this->Challenge = $Buffer->Get( 4 ); + + $this->Socket->Write( self::A2S_INFO, "Source Engine Query\0" . $this->Challenge ); + $Buffer = $this->Socket->Read( ); + $Type = $Buffer->GetByte( ); + } + + // Old GoldSource protocol, HLTV still uses it + if( $Type === self::S2A_INFO_OLD && $this->Socket->Engine === self::GOLDSOURCE ) + { + /** + * If we try to read data again, and we get the result with type S2A_INFO (0x49) + * That means this server is running dproto, + * Because it sends answer for both protocols + */ + + $Server[ 'Address' ] = $Buffer->GetString( ); + $Server[ 'HostName' ] = $Buffer->GetString( ); + $Server[ 'Map' ] = $Buffer->GetString( ); + $Server[ 'ModDir' ] = $Buffer->GetString( ); + $Server[ 'ModDesc' ] = $Buffer->GetString( ); + $Server[ 'Players' ] = $Buffer->GetByte( ); + $Server[ 'MaxPlayers' ] = $Buffer->GetByte( ); + $Server[ 'Protocol' ] = $Buffer->GetByte( ); + $Server[ 'Dedicated' ] = Chr( $Buffer->GetByte( ) ); + $Server[ 'Os' ] = Chr( $Buffer->GetByte( ) ); + $Server[ 'Password' ] = $Buffer->GetByte( ) === 1; + $Server[ 'IsMod' ] = $Buffer->GetByte( ) === 1; + + if( $Server[ 'IsMod' ] ) + { + $Mod = []; + $Mod[ 'Url' ] = $Buffer->GetString( ); + $Mod[ 'Download' ] = $Buffer->GetString( ); + $Buffer->Get( 1 ); // NULL byte + $Mod[ 'Version' ] = $Buffer->GetLong( ); + $Mod[ 'Size' ] = $Buffer->GetLong( ); + $Mod[ 'ServerSide' ] = $Buffer->GetByte( ) === 1; + $Mod[ 'CustomDLL' ] = $Buffer->GetByte( ) === 1; + $Server[ 'Mod' ] = $Mod; + } + + $Server[ 'Secure' ] = $Buffer->GetByte( ) === 1; + $Server[ 'Bots' ] = $Buffer->GetByte( ); + + return $Server; + } + + if( $Type !== self::S2A_INFO_SRC ) + { + throw new InvalidPacketException( 'GetInfo: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + + $Server[ 'Protocol' ] = $Buffer->GetByte( ); + $Server[ 'HostName' ] = $Buffer->GetString( ); + $Server[ 'Map' ] = $Buffer->GetString( ); + $Server[ 'ModDir' ] = $Buffer->GetString( ); + $Server[ 'ModDesc' ] = $Buffer->GetString( ); + $Server[ 'AppID' ] = $Buffer->GetShort( ); + $Server[ 'Players' ] = $Buffer->GetByte( ); + $Server[ 'MaxPlayers' ] = $Buffer->GetByte( ); + $Server[ 'Bots' ] = $Buffer->GetByte( ); + $Server[ 'Dedicated' ] = Chr( $Buffer->GetByte( ) ); + $Server[ 'Os' ] = Chr( $Buffer->GetByte( ) ); + $Server[ 'Password' ] = $Buffer->GetByte( ) === 1; + $Server[ 'Secure' ] = $Buffer->GetByte( ) === 1; + + // The Ship (they violate query protocol spec by modifying the response) + if( $Server[ 'AppID' ] === 2400 ) + { + $Server[ 'GameMode' ] = $Buffer->GetByte( ); + $Server[ 'WitnessCount' ] = $Buffer->GetByte( ); + $Server[ 'WitnessTime' ] = $Buffer->GetByte( ); + } + + $Server[ 'Version' ] = $Buffer->GetString( ); + + // Extra Data Flags + if( $Buffer->Remaining( ) > 0 ) + { + $Server[ 'ExtraDataFlags' ] = $Flags = $Buffer->GetByte( ); + + // S2A_EXTRA_DATA_HAS_GAME_PORT - Next 2 bytes include the game port. + if( $Flags & 0x80 ) + { + $Server[ 'GamePort' ] = $Buffer->GetShort( ); + } + + // S2A_EXTRA_DATA_HAS_STEAMID - Next 8 bytes are the steamID + // Want to play around with this? + // You can use https://github.com/xPaw/SteamID.php + if( $Flags & 0x10 ) + { + $SteamIDLower = $Buffer->GetUnsignedLong( ); + $SteamIDInstance = $Buffer->GetUnsignedLong( ); // This gets shifted by 32 bits, which should be steamid instance + $SteamID = 0; + + if( PHP_INT_SIZE === 4 ) + { + if( extension_loaded( 'gmp' ) ) + { + $SteamIDLower = gmp_abs( $SteamIDLower ); + $SteamIDInstance = gmp_abs( $SteamIDInstance ); + $SteamID = gmp_strval( gmp_or( $SteamIDLower, gmp_mul( $SteamIDInstance, gmp_pow( 2, 32 ) ) ) ); + } + else + { + throw new \RuntimeException( 'Either 64-bit PHP installation or "gmp" module is required to correctly parse server\'s steamid.' ); + } + } + else + { + $SteamID = $SteamIDLower | ( $SteamIDInstance << 32 ); + } + + $Server[ 'SteamID' ] = $SteamID; + + unset( $SteamIDLower, $SteamIDInstance, $SteamID ); + } + + // S2A_EXTRA_DATA_HAS_SPECTATOR_DATA - Next 2 bytes include the spectator port, then the spectator server name. + if( $Flags & 0x40 ) + { + $Server[ 'SpecPort' ] = $Buffer->GetShort( ); + $Server[ 'SpecName' ] = $Buffer->GetString( ); + } + + // S2A_EXTRA_DATA_HAS_GAMETAG_DATA - Next bytes are the game tag string + if( $Flags & 0x20 ) + { + $Server[ 'GameTags' ] = $Buffer->GetString( ); + } + + // S2A_EXTRA_DATA_GAMEID - Next 8 bytes are the gameID of the server + if( $Flags & 0x01 ) + { + $Server[ 'GameID' ] = $Buffer->GetUnsignedLong( ) | ( $Buffer->GetUnsignedLong( ) << 32 ); + } + + if( $Buffer->Remaining( ) > 0 ) + { + throw new InvalidPacketException( 'GetInfo: unread data? ' . $Buffer->Remaining( ) . ' bytes remaining in the buffer. Please report it to the library developer.', + InvalidPacketException::BUFFER_NOT_EMPTY ); + } + } + + return $Server; + } + + /** + * Get players on the server + * + * @throws InvalidPacketException + * @throws SocketException + * + * @return array Returns an array with players on success + */ + public function GetPlayers( ) : array + { + if( !$this->Connected ) + { + throw new SocketException( 'Not connected.', SocketException::NOT_CONNECTED ); + } + + $this->GetChallenge( self::A2S_PLAYER, self::S2A_PLAYER ); + + $this->Socket->Write( self::A2S_PLAYER, $this->Challenge ); + $Buffer = $this->Socket->Read( 14000 ); // Moronic Arma 3 developers do not split their packets, so we have to read more data + // This violates the protocol spec, and they probably should fix it: https://developer.valvesoftware.com/wiki/Server_queries#Protocol + + $Type = $Buffer->GetByte( ); + + if( $Type !== self::S2A_PLAYER ) + { + throw new InvalidPacketException( 'GetPlayers: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + + $Players = []; + $Count = $Buffer->GetByte( ); + + while( $Count-- > 0 && $Buffer->Remaining( ) > 0 ) + { + $Player = []; + $Player[ 'Id' ] = $Buffer->GetByte( ); // PlayerID, is it just always 0? + $Player[ 'Name' ] = $Buffer->GetString( ); + $Player[ 'Frags' ] = $Buffer->GetLong( ); + $Player[ 'Time' ] = (int)$Buffer->GetFloat( ); + $Player[ 'TimeF' ] = GMDate( ( $Player[ 'Time' ] > 3600 ? "H:i:s" : "i:s" ), $Player[ 'Time' ] ); + + $Players[ ] = $Player; + } + + return $Players; + } + + /** + * Get rules (cvars) from the server + * + * @throws InvalidPacketException + * @throws SocketException + * + * @return array Returns an array with rules on success + */ + public function GetRules( ) : array + { + if( !$this->Connected ) + { + throw new SocketException( 'Not connected.', SocketException::NOT_CONNECTED ); + } + + $this->GetChallenge( self::A2S_RULES, self::S2A_RULES ); + + $this->Socket->Write( self::A2S_RULES, $this->Challenge ); + $Buffer = $this->Socket->Read( ); + + $Type = $Buffer->GetByte( ); + + if( $Type !== self::S2A_RULES ) + { + throw new InvalidPacketException( 'GetRules: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + + $Rules = []; + $Count = $Buffer->GetShort( ); + + while( $Count-- > 0 && $Buffer->Remaining( ) > 0 ) + { + $Rule = $Buffer->GetString( ); + $Value = $Buffer->GetString( ); + + if( !Empty( $Rule ) ) + { + $Rules[ $Rule ] = $Value; + } + } + + return $Rules; + } + + /** + * Get challenge (used for players/rules packets) + * + * @throws InvalidPacketException + */ + private function GetChallenge( int $Header, int $ExpectedResult ) : void + { + if( $this->Challenge ) + { + return; + } + + if( $this->UseOldGetChallengeMethod ) + { + $Header = self::A2S_SERVERQUERY_GETCHALLENGE; + } + + $this->Socket->Write( $Header, "\xFF\xFF\xFF\xFF" ); + $Buffer = $this->Socket->Read( ); + + $Type = $Buffer->GetByte( ); + + switch( $Type ) + { + case self::S2C_CHALLENGE: + { + $this->Challenge = $Buffer->Get( 4 ); + + return; + } + case $ExpectedResult: + { + // Goldsource (HLTV) + + return; + } + case 0: + { + throw new InvalidPacketException( 'GetChallenge: Failed to get challenge.' ); + } + default: + { + throw new InvalidPacketException( 'GetChallenge: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + } + } + + /** + * Sets rcon password, for future use in Rcon() + * + * @param string $Password Rcon Password + * + * @throws AuthenticationException + * @throws InvalidPacketException + * @throws SocketException + */ + public function SetRconPassword( string $Password ) : void + { + if( !$this->Connected ) + { + throw new SocketException( 'Not connected.', SocketException::NOT_CONNECTED ); + } + + switch( $this->Socket->Engine ) + { + case SourceQuery::GOLDSOURCE: + { + $this->Rcon = new GoldSourceRcon( $this->Socket ); + + break; + } + case SourceQuery::SOURCE: + { + $this->Rcon = new SourceRcon( $this->Socket ); + + break; + } + default: + { + throw new SocketException( 'Unknown engine.', SocketException::INVALID_ENGINE ); + } + } + + $this->Rcon->Open( ); + $this->Rcon->Authorize( $Password ); + } + + /** + * Sends a command to the server for execution. + * + * @param string $Command Command to execute + * + * @throws AuthenticationException + * @throws InvalidPacketException + * @throws SocketException + * + * @return string Answer from server in string + */ + public function Rcon( string $Command ) : string + { + if( !$this->Connected ) + { + throw new SocketException( 'Not connected.', SocketException::NOT_CONNECTED ); + } + + if( $this->Rcon === null ) + { + throw new SocketException( 'You must set a RCON password before trying to execute a RCON command.', SocketException::NOT_CONNECTED ); + } + + return $this->Rcon->Command( $Command ); + } + } diff --git a/includes/SourceQuery/SourceRcon.php b/includes/SourceQuery/SourceRcon.php new file mode 100644 index 00000000..0a77d58a --- /dev/null +++ b/includes/SourceQuery/SourceRcon.php @@ -0,0 +1,200 @@ +Socket = $Socket; + } + + public function Close( ) : void + { + if( $this->RconSocket ) + { + FClose( $this->RconSocket ); + + $this->RconSocket = null; + } + + $this->RconRequestId = 0; + } + + public function Open( ) : void + { + if( !$this->RconSocket ) + { + $this->RconSocket = @FSockOpen( $this->Socket->Address, $this->Socket->Port, $ErrNo, $ErrStr, $this->Socket->Timeout ); + + if( $ErrNo || !$this->RconSocket ) + { + throw new SocketException( 'Can\'t connect to RCON server: ' . $ErrStr, SocketException::CONNECTION_FAILED ); + } + + Stream_Set_Timeout( $this->RconSocket, $this->Socket->Timeout ); + Stream_Set_Blocking( $this->RconSocket, true ); + } + } + + public function Write( int $Header, string $String = '' ) : bool + { + // Pack the packet together + $Command = Pack( 'VV', ++$this->RconRequestId, $Header ) . $String . "\x00\x00"; + + // Prepend packet length + $Command = Pack( 'V', StrLen( $Command ) ) . $Command; + $Length = StrLen( $Command ); + + return $Length === FWrite( $this->RconSocket, $Command, $Length ); + } + + public function Read( ) : Buffer + { + $Buffer = new Buffer( ); + $Buffer->Set( FRead( $this->RconSocket, 4 ) ); + + if( $Buffer->Remaining( ) < 4 ) + { + throw new InvalidPacketException( 'Rcon read: Failed to read any data from socket', InvalidPacketException::BUFFER_EMPTY ); + } + + $PacketSize = $Buffer->GetLong( ); + + $Buffer->Set( FRead( $this->RconSocket, $PacketSize ) ); + + $Data = $Buffer->Get( ); + + $Remaining = $PacketSize - StrLen( $Data ); + + while( $Remaining > 0 ) + { + $Data2 = FRead( $this->RconSocket, $Remaining ); + + $PacketSize = StrLen( $Data2 ); + + if( $PacketSize === 0 ) + { + throw new InvalidPacketException( 'Read ' . strlen( $Data ) . ' bytes from socket, ' . $Remaining . ' remaining', InvalidPacketException::BUFFER_EMPTY ); + + break; + } + + $Data .= $Data2; + $Remaining -= $PacketSize; + } + + $Buffer->Set( $Data ); + + return $Buffer; + } + + public function Command( string $Command ) : string + { + $this->Write( SourceQuery::SERVERDATA_EXECCOMMAND, $Command ); + $Buffer = $this->Read( ); + + $Buffer->GetLong( ); // RequestID + + $Type = $Buffer->GetLong( ); + + if( $Type === SourceQuery::SERVERDATA_AUTH_RESPONSE ) + { + throw new AuthenticationException( 'Bad rcon_password.', AuthenticationException::BAD_PASSWORD ); + } + else if( $Type !== SourceQuery::SERVERDATA_RESPONSE_VALUE ) + { + throw new InvalidPacketException( 'Invalid rcon response.', InvalidPacketException::PACKET_HEADER_MISMATCH ); + } + + $Data = $Buffer->Get( ); + + // We do this stupid hack to handle split packets + // See https://developer.valvesoftware.com/wiki/Source_RCON_Protocol#Multiple-packet_Responses + if( StrLen( $Data ) >= 4000 ) + { + $this->Write( SourceQuery::SERVERDATA_REQUESTVALUE ); + + do + { + $Buffer = $this->Read( ); + + $Buffer->GetLong( ); // RequestID + + if( $Buffer->GetLong( ) !== SourceQuery::SERVERDATA_RESPONSE_VALUE ) + { + break; + } + + $Data2 = $Buffer->Get( ); + + if( $Data2 === "\x00\x01\x00\x00\x00\x00" ) + { + break; + } + + $Data .= $Data2; + } + while( true ); + } + + return rtrim( $Data, "\0" ); + } + + public function Authorize( string $Password ) : void + { + $this->Write( SourceQuery::SERVERDATA_AUTH, $Password ); + $Buffer = $this->Read( ); + + $RequestID = $Buffer->GetLong( ); + $Type = $Buffer->GetLong( ); + + // If we receive SERVERDATA_RESPONSE_VALUE, then we need to read again + // More info: https://developer.valvesoftware.com/wiki/Source_RCON_Protocol#Additional_Comments + + if( $Type === SourceQuery::SERVERDATA_RESPONSE_VALUE ) + { + $Buffer = $this->Read( ); + + $RequestID = $Buffer->GetLong( ); + $Type = $Buffer->GetLong( ); + } + + if( $RequestID === -1 || $Type !== SourceQuery::SERVERDATA_AUTH_RESPONSE ) + { + throw new AuthenticationException( 'RCON authorization failed.', AuthenticationException::BAD_PASSWORD ); + } + } + } diff --git a/includes/SourceQuery/bootstrap.php b/includes/SourceQuery/bootstrap.php new file mode 100644 index 00000000..9cb65711 --- /dev/null +++ b/includes/SourceQuery/bootstrap.php @@ -0,0 +1,27 @@ +