1
0
mirror of https://github.com/xPaw/PHP-Source-Query.git synced 2026-06-10 22:53:15 +02:00

Bring in CS-Fixer, reformat.

This commit is contained in:
Anthony Birkett
2021-05-30 10:05:34 +01:00
parent 3bfc073211
commit e62d011689
20 changed files with 1804 additions and 1883 deletions
-8
View File
@@ -1,8 +0,0 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = tab
insert_final_newline = true
-1
View File
@@ -1 +0,0 @@
* text=auto
+2
View File
@@ -1,2 +1,4 @@
vendor/ vendor/
composer.lock composer.lock
.php-cs-fixer.cache
.idea/
+30 -32
View File
@@ -1,34 +1,32 @@
<?php <?php
require __DIR__ . '/../SourceQuery/bootstrap.php';
use xPaw\SourceQuery\SourceQuery; declare(strict_types=1);
// For the sake of this example require __DIR__ . '/../SourceQuery/bootstrap.php';
header( 'Content-Type: text/plain' );
header( 'X-Content-Type-Options: nosniff' ); use xPaw\SourceQuery\SourceQuery;
// Edit this -> // For the sake of this example
define( 'SQ_SERVER_ADDR', 'localhost' ); header('Content-Type: text/plain');
define( 'SQ_SERVER_PORT', 27015 ); header('X-Content-Type-Options: nosniff');
define( 'SQ_TIMEOUT', 1 );
define( 'SQ_ENGINE', SourceQuery::SOURCE ); // Edit this ->
// Edit this <- define('SQ_SERVER_ADDR', 'localhost');
define('SQ_SERVER_PORT', 27015);
$Query = new SourceQuery( ); define('SQ_TIMEOUT', 1);
define('SQ_ENGINE', SourceQuery::SOURCE);
try // Edit this <-
{
$Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE ); $Query = new SourceQuery();
print_r( $Query->GetInfo( ) ); try {
print_r( $Query->GetPlayers( ) ); $Query->Connect(SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE);
print_r( $Query->GetRules( ) );
} print_r($Query->GetInfo());
catch( Exception $e ) print_r($Query->GetPlayers());
{ print_r($Query->GetRules());
echo $e->getMessage( ); } catch (Exception $e) {
} echo $e->getMessage();
finally } finally {
{ $Query->Disconnect();
$Query->Disconnect( ); }
}
+30 -32
View File
@@ -1,34 +1,32 @@
<?php <?php
require __DIR__ . '/../SourceQuery/bootstrap.php';
use xPaw\SourceQuery\SourceQuery; declare(strict_types=1);
// For the sake of this example require __DIR__ . '/../SourceQuery/bootstrap.php';
header( 'Content-Type: text/plain' );
header( 'X-Content-Type-Options: nosniff' ); use xPaw\SourceQuery\SourceQuery;
// Edit this -> // For the sake of this example
define( 'SQ_SERVER_ADDR', 'localhost' ); header('Content-Type: text/plain');
define( 'SQ_SERVER_PORT', 27015 ); header('X-Content-Type-Options: nosniff');
define( 'SQ_TIMEOUT', 1 );
define( 'SQ_ENGINE', SourceQuery::SOURCE ); // Edit this ->
// Edit this <- define('SQ_SERVER_ADDR', 'localhost');
define('SQ_SERVER_PORT', 27015);
$Query = new SourceQuery( ); define('SQ_TIMEOUT', 1);
define('SQ_ENGINE', SourceQuery::SOURCE);
try // Edit this <-
{
$Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE ); $Query = new SourceQuery();
$Query->SetRconPassword( 'my_awesome_password' ); try {
$Query->Connect(SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE);
var_dump( $Query->Rcon( 'say hello' ) );
} $Query->SetRconPassword('my_awesome_password');
catch( Exception $e )
{ var_dump($Query->Rcon('say hello'));
echo $e->getMessage( ); } catch (Exception $e) {
} echo $e->getMessage();
finally } finally {
{ $Query->Disconnect();
$Query->Disconnect( ); }
}
+64 -73
View File
@@ -1,43 +1,42 @@
<?php <?php
require __DIR__ . '/../SourceQuery/bootstrap.php';
use xPaw\SourceQuery\SourceQuery; declare(strict_types=1);
// Edit this -> require __DIR__ . '/../SourceQuery/bootstrap.php';
define( 'SQ_SERVER_ADDR', 'localhost' );
define( 'SQ_SERVER_PORT', 27015 ); use xPaw\SourceQuery\SourceQuery;
define( 'SQ_TIMEOUT', 3 );
define( 'SQ_ENGINE', SourceQuery::SOURCE ); // Edit this ->
// Edit this <- define('SQ_SERVER_ADDR', 'localhost');
define('SQ_SERVER_PORT', 27015);
$Timer = microtime( true ); define('SQ_TIMEOUT', 3);
define('SQ_ENGINE', SourceQuery::SOURCE);
$Query = new SourceQuery( ); // Edit this <-
$Info = []; $Timer = microtime(true);
$Rules = [];
$Players = []; $Query = new SourceQuery();
$Exception = null;
$Info = [];
try $Rules = [];
{ $Players = [];
$Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE ); $Exception = null;
//$Query->SetUseOldGetChallengeMethod( true ); // Use this when players/rules retrieval fails on games like Starbound
try {
$Info = $Query->GetInfo( ); $Query->Connect(SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE);
$Players = $Query->GetPlayers( ); //$Query->SetUseOldGetChallengeMethod( true ); // Use this when players/rules retrieval fails on games like Starbound
$Rules = $Query->GetRules( );
} $Info = $Query->GetInfo();
catch( Exception $e ) $Players = $Query->GetPlayers();
{ $Rules = $Query->GetRules();
$Exception = $e; } catch (Exception $e) {
} $Exception = $e;
finally } finally {
{ $Query->Disconnect();
$Query->Disconnect( ); }
}
$Timer = number_format(microtime(true) - $Timer, 4, '.', '');
$Timer = number_format( microtime( true ) - $Timer, 4, '.', '' );
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -88,9 +87,9 @@
</div> </div>
<div class="container"> <div class="container">
<?php if( $Exception !== null ): ?> <?php if ($Exception !== null): ?>
<div class="panel panel-error"> <div class="panel panel-error">
<pre class="panel-body"><?php echo htmlspecialchars( $Exception->__toString( ) ); ?></pre> <pre class="panel-body"><?php echo htmlspecialchars($Exception->__toString()); ?></pre>
</div> </div>
<?php endif; ?> <?php endif; ?>
<div class="row"> <div class="row">
@@ -103,32 +102,24 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php if( !empty( $Info ) ): ?> <?php if (!empty($Info)): ?>
<?php foreach( $Info as $InfoKey => $InfoValue ): ?> <?php foreach ($Info as $InfoKey => $InfoValue): ?>
<tr> <tr>
<td><?php echo htmlspecialchars( $InfoKey ); ?></td> <td><?php echo htmlspecialchars($InfoKey); ?></td>
<td><?php <td><?php
if( is_array( $InfoValue ) ) if (is_array($InfoValue)) {
{ echo "<pre>";
echo "<pre>"; print_r($InfoValue);
print_r( $InfoValue ); echo "</pre>";
echo "</pre>"; } else {
} if ($InfoValue === true) {
else echo 'true';
{ } elseif ($InfoValue === false) {
if( $InfoValue === true ) echo 'false';
{ } else {
echo 'true'; echo htmlspecialchars($InfoValue);
} }
else if( $InfoValue === false ) }
{
echo 'false';
}
else
{
echo htmlspecialchars( $InfoValue );
}
}
?></td> ?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
@@ -144,16 +135,16 @@
<table class="table table-bordered table-striped"> <table class="table table-bordered table-striped">
<thead> <thead>
<tr> <tr>
<th>Player <span class="label label-info"><?php echo count( $Players ); ?></span></th> <th>Player <span class="label label-info"><?php echo count($Players); ?></span></th>
<th class="frags-column">Frags</th> <th class="frags-column">Frags</th>
<th class="frags-column">Time</th> <th class="frags-column">Time</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php if( !empty( $Players ) ): ?> <?php if (!empty($Players)): ?>
<?php foreach( $Players as $Player ): ?> <?php foreach ($Players as $Player): ?>
<tr> <tr>
<td><?php echo htmlspecialchars( $Player[ 'Name' ] ); ?></td> <td><?php echo htmlspecialchars($Player[ 'Name' ]); ?></td>
<td><?php echo $Player[ 'Frags' ]; ?></td> <td><?php echo $Player[ 'Frags' ]; ?></td>
<td><?php echo $Player[ 'TimeF' ]; ?></td> <td><?php echo $Player[ 'TimeF' ]; ?></td>
</tr> </tr>
@@ -172,15 +163,15 @@
<table class="table table-bordered table-striped"> <table class="table table-bordered table-striped">
<thead> <thead>
<tr> <tr>
<th colspan="2">Rules <span class="label label-info"><?php echo count( $Rules ); ?></span></th> <th colspan="2">Rules <span class="label label-info"><?php echo count($Rules); ?></span></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php if( !empty( $Rules ) ): ?> <?php if (!empty($Rules)): ?>
<?php foreach( $Rules as $Rule => $Value ): ?> <?php foreach ($Rules as $Rule => $Value): ?>
<tr> <tr>
<td><?php echo htmlspecialchars( $Rule ); ?></td> <td><?php echo htmlspecialchars($Rule); ?></td>
<td><?php echo htmlspecialchars( $Value ); ?></td> <td><?php echo htmlspecialchars($Value); ?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<?php else: ?> <?php else: ?>
+125 -137
View File
@@ -1,139 +1,127 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery;
use xPaw\SourceQuery\Exception\InvalidPacketException;
use xPaw\SourceQuery\Exception\SocketException;
/** declare(strict_types=1);
* Base socket interface
* /**
* @package xPaw\SourceQuery * @author Pavel Djundik
* *
* @uses xPaw\SourceQuery\Exception\InvalidPacketException * @link https://xpaw.me
* @uses xPaw\SourceQuery\Exception\SocketException * @link https://github.com/xPaw/PHP-Source-Query
*/ *
abstract class BaseSocket * @license GNU Lesser General Public License, version 2.1
{ *
/** @var ?resource */ * @internal
public $Socket; */
public int $Engine;
namespace xPaw\SourceQuery;
public string $Address;
public int $Port; use xPaw\SourceQuery\Exception\InvalidPacketException;
public int $Timeout; use xPaw\SourceQuery\Exception\SocketException;
public function __destruct( ) /**
{ * Base socket interface
$this->Close( ); *
} * @package xPaw\SourceQuery
*
abstract public function Close( ) : void; * @uses xPaw\SourceQuery\Exception\InvalidPacketException
abstract public function Open( string $Address, int $Port, int $Timeout, int $Engine ) : void; * @uses xPaw\SourceQuery\Exception\SocketException
abstract public function Write( int $Header, string $String = '' ) : bool; */
abstract public function Read( int $Length = 1400 ) : Buffer; abstract class BaseSocket
{
protected function ReadInternal( Buffer $Buffer, int $Length, callable $SherlockFunction ) : Buffer /** @var ?resource */
{ public $Socket;
if( $Buffer->Remaining( ) === 0 ) public int $Engine;
{
throw new InvalidPacketException( 'Failed to read any data from socket', InvalidPacketException::BUFFER_EMPTY ); public string $Address;
} public int $Port;
public int $Timeout;
$Header = $Buffer->GetLong( );
public function __destruct()
if( $Header === -1 ) // Single packet {
{ $this->Close();
// We don't have to do anything }
}
else if( $Header === -2 ) // Split packet abstract public function Close(): void;
{ abstract public function Open(string $Address, int $Port, int $Timeout, int $Engine): void;
$Packets = []; abstract public function Write(int $Header, string $String = ''): bool;
$IsCompressed = false; abstract public function Read(int $Length = 1400): Buffer;
$ReadMore = false;
$PacketChecksum = null; protected function ReadInternal(Buffer $Buffer, int $Length, callable $SherlockFunction): Buffer
{
do if ($Buffer->Remaining() === 0) {
{ throw new InvalidPacketException('Failed to read any data from socket', InvalidPacketException::BUFFER_EMPTY);
$RequestID = $Buffer->GetLong( ); }
switch( $this->Engine ) $Header = $Buffer->GetLong();
{
case SourceQuery::GOLDSOURCE: if ($Header === -1) { // Single packet
{ // We don't have to do anything
$PacketCountAndNumber = $Buffer->GetByte( ); } elseif ($Header === -2) { // Split packet
$PacketCount = $PacketCountAndNumber & 0xF; $Packets = [];
$PacketNumber = $PacketCountAndNumber >> 4; $IsCompressed = false;
$ReadMore = false;
break; $PacketChecksum = null;
}
case SourceQuery::SOURCE: do {
{ $RequestID = $Buffer->GetLong();
$IsCompressed = ( $RequestID & 0x80000000 ) !== 0;
$PacketCount = $Buffer->GetByte( ); switch ($this->Engine) {
$PacketNumber = $Buffer->GetByte( ) + 1; case SourceQuery::GOLDSOURCE:
{
if( $IsCompressed ) $PacketCountAndNumber = $Buffer->GetByte();
{ $PacketCount = $PacketCountAndNumber & 0xF;
$Buffer->GetLong( ); // Split size $PacketNumber = $PacketCountAndNumber >> 4;
$PacketChecksum = $Buffer->GetUnsignedLong( ); break;
} }
else case SourceQuery::SOURCE:
{ {
$Buffer->GetShort( ); // Split size $IsCompressed = ($RequestID & 0x80000000) !== 0;
} $PacketCount = $Buffer->GetByte();
$PacketNumber = $Buffer->GetByte() + 1;
break;
} if ($IsCompressed) {
default: $Buffer->GetLong(); // Split size
{
throw new SocketException( 'Unknown engine.', SocketException::INVALID_ENGINE ); $PacketChecksum = $Buffer->GetUnsignedLong();
} } else {
} $Buffer->GetShort(); // Split size
}
$Packets[ $PacketNumber ] = $Buffer->Get( );
break;
$ReadMore = $PacketCount > sizeof( $Packets ); }
} default:
while( $ReadMore && $SherlockFunction( $Buffer, $Length ) ); {
throw new SocketException('Unknown engine.', SocketException::INVALID_ENGINE);
$Data = implode( $Packets ); }
}
// TODO: Test this
if( $IsCompressed ) $Packets[ $PacketNumber ] = $Buffer->Get();
{
// Let's make sure this function exists, it's not included in PHP by default $ReadMore = $PacketCount > sizeof($Packets);
if( !function_exists( 'bzdecompress' ) ) } while ($ReadMore && $SherlockFunction($Buffer, $Length));
{
throw new \RuntimeException( 'Received compressed packet, PHP doesn\'t have Bzip2 library installed, can\'t decompress.' ); $Data = implode($Packets);
}
// TODO: Test this
$Data = bzdecompress( $Data ); if ($IsCompressed) {
// Let's make sure this function exists, it's not included in PHP by default
if( !is_string( $Data ) || crc32( $Data ) !== $PacketChecksum ) if (!function_exists('bzdecompress')) {
{ throw new \RuntimeException('Received compressed packet, PHP doesn\'t have Bzip2 library installed, can\'t decompress.');
throw new InvalidPacketException( 'CRC32 checksum mismatch of uncompressed packet data.', InvalidPacketException::CHECKSUM_MISMATCH ); }
}
} $Data = bzdecompress($Data);
$Buffer->Set( substr( $Data, 4 ) ); if (!is_string($Data) || crc32($Data) !== $PacketChecksum) {
} throw new InvalidPacketException('CRC32 checksum mismatch of uncompressed packet data.', InvalidPacketException::CHECKSUM_MISMATCH);
else }
{ }
throw new InvalidPacketException( 'Socket read: Raw packet header mismatch. (0x' . dechex( $Header ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH );
} $Buffer->Set(substr($Data, 4));
} else {
return $Buffer; throw new InvalidPacketException('Socket read: Raw packet header mismatch. (0x' . dechex($Header) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH);
} }
}
return $Buffer;
}
}
+167 -173
View File
@@ -1,177 +1,171 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery; declare(strict_types=1);
use xPaw\SourceQuery\Exception\InvalidPacketException; /**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
/** namespace xPaw\SourceQuery;
* Class Buffer
* use xPaw\SourceQuery\Exception\InvalidPacketException;
* @package xPaw\SourceQuery
* /**
* @uses xPaw\SourceQuery\Exception\InvalidPacketException * Class Buffer
*/ *
class Buffer * @package xPaw\SourceQuery
{ *
/** * @uses xPaw\SourceQuery\Exception\InvalidPacketException
* Buffer */
*/ final class Buffer
private string $Buffer = ''; {
/**
/** * Buffer
* Buffer length */
*/ private string $Buffer = '';
private int $Length = 0;
/**
/** * Buffer length
* Current position in buffer */
*/ private int $Length = 0;
private int $Position = 0;
/**
/** * Current position in buffer
* Sets buffer */
*/ private int $Position = 0;
public function Set( string $Buffer ) : void
{ /**
$this->Buffer = $Buffer; * Sets buffer
$this->Length = strlen( $Buffer ); */
$this->Position = 0; public function Set(string $Buffer): void
} {
$this->Buffer = $Buffer;
/** $this->Length = strlen($Buffer);
* Get remaining bytes $this->Position = 0;
* }
* @return int Remaining bytes in buffer
*/ /**
public function Remaining( ) : int * Get remaining bytes
{ *
return $this->Length - $this->Position; * @return int Remaining bytes in buffer
} */
public function Remaining(): int
/** {
* Gets data from buffer return $this->Length - $this->Position;
* }
* @param int $Length Bytes to read
*/ /**
public function Get( int $Length = -1 ) : string * Gets data from buffer
{ *
if( $Length === 0 ) * @param int $Length Bytes to read
{ */
return ''; public function Get(int $Length = -1): string
} {
if ($Length === 0) {
$Remaining = $this->Remaining( ); return '';
}
if( $Length === -1 )
{ $Remaining = $this->Remaining();
$Length = $Remaining;
} if ($Length === -1) {
else if( $Length > $Remaining ) $Length = $Remaining;
{ } elseif ($Length > $Remaining) {
return ''; return '';
} }
$Data = substr( $this->Buffer, $this->Position, $Length ); $Data = substr($this->Buffer, $this->Position, $Length);
$this->Position += $Length; $this->Position += $Length;
return $Data; return $Data;
} }
/** /**
* Get byte from buffer * Get byte from buffer
*/ */
public function GetByte( ) : int public function GetByte(): int
{ {
return ord( $this->Get( 1 ) ); return ord($this->Get(1));
} }
/** /**
* Get short from buffer * Get short from buffer
*/ */
public function GetShort( ) : int public function GetShort(): int
{ {
if( $this->Remaining( ) < 2 ) if ($this->Remaining() < 2) {
{ throw new InvalidPacketException('Not enough data to unpack a short.', InvalidPacketException::BUFFER_EMPTY);
throw new InvalidPacketException( 'Not enough data to unpack a short.', InvalidPacketException::BUFFER_EMPTY ); }
}
$Data = unpack('v', $this->Get(2));
$Data = unpack( 'v', $this->Get( 2 ) );
return (int)$Data[ 1 ];
return (int)$Data[ 1 ]; }
}
/**
/** * Get long from buffer
* Get long from buffer */
*/ public function GetLong(): int
public function GetLong( ) : int {
{ if ($this->Remaining() < 4) {
if( $this->Remaining( ) < 4 ) throw new InvalidPacketException('Not enough data to unpack a long.', InvalidPacketException::BUFFER_EMPTY);
{ }
throw new InvalidPacketException( 'Not enough data to unpack a long.', InvalidPacketException::BUFFER_EMPTY );
} $Data = unpack('l', $this->Get(4));
$Data = unpack( 'l', $this->Get( 4 ) ); return (int)$Data[ 1 ];
}
return (int)$Data[ 1 ];
} /**
* Get float from buffer
/** */
* Get float from buffer public function GetFloat(): float
*/ {
public function GetFloat( ) : float if ($this->Remaining() < 4) {
{ throw new InvalidPacketException('Not enough data to unpack a float.', InvalidPacketException::BUFFER_EMPTY);
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 ];
$Data = unpack( 'f', $this->Get( 4 ) ); }
return (float)$Data[ 1 ]; /**
} * Get unsigned long from buffer
*/
/** public function GetUnsignedLong(): int
* Get unsigned long from buffer {
*/ if ($this->Remaining() < 4) {
public function GetUnsignedLong( ) : int throw new InvalidPacketException('Not enough data to unpack an usigned long.', InvalidPacketException::BUFFER_EMPTY);
{ }
if( $this->Remaining( ) < 4 )
{ $Data = unpack('V', $this->Get(4));
throw new InvalidPacketException( 'Not enough data to unpack an usigned long.', InvalidPacketException::BUFFER_EMPTY );
} return (int)$Data[ 1 ];
}
$Data = unpack( 'V', $this->Get( 4 ) );
/**
return (int)$Data[ 1 ]; * Read one string from buffer ending with null byte
} */
public function GetString(): string
/** {
* Read one string from buffer ending with null byte $ZeroBytePosition = strpos($this->Buffer, "\0", $this->Position);
*/
public function GetString( ) : string if ($ZeroBytePosition === false) {
{ return '';
$ZeroBytePosition = strpos( $this->Buffer, "\0", $this->Position ); }
if( $ZeroBytePosition === false ) $String = $this->Get($ZeroBytePosition - $this->Position);
{
return ''; $this->Position++;
}
return $String;
$String = $this->Get( $ZeroBytePosition - $this->Position ); }
}
$this->Position++;
return $String;
}
}
@@ -1,19 +1,22 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception; declare(strict_types=1);
class AuthenticationException extends SourceQueryException /**
{ * @author Pavel Djundik
const BAD_PASSWORD = 1; *
const BANNED = 2; * @link https://xpaw.me
} * @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception;
final class AuthenticationException extends SourceQueryException
{
public const BAD_PASSWORD = 1;
public const BANNED = 2;
}
@@ -1,18 +1,21 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception; declare(strict_types=1);
class InvalidArgumentException extends SourceQueryException /**
{ * @author Pavel Djundik
const TIMEOUT_NOT_INTEGER = 1; *
} * @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception;
final class InvalidArgumentException extends SourceQueryException
{
public const TIMEOUT_NOT_INTEGER = 1;
}
@@ -1,21 +1,24 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception; declare(strict_types=1);
class InvalidPacketException extends SourceQueryException /**
{ * @author Pavel Djundik
const PACKET_HEADER_MISMATCH = 1; *
const BUFFER_EMPTY = 2; * @link https://xpaw.me
const BUFFER_NOT_EMPTY = 3; * @link https://github.com/xPaw/PHP-Source-Query
const CHECKSUM_MISMATCH = 4; *
} * @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception;
final class InvalidPacketException extends SourceQueryException
{
public const PACKET_HEADER_MISMATCH = 1;
public const BUFFER_EMPTY = 2;
public const BUFFER_NOT_EMPTY = 3;
public const CHECKSUM_MISMATCH = 4;
}
+21 -18
View File
@@ -1,21 +1,24 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception; declare(strict_types=1);
class SocketException extends SourceQueryException /**
{ * @author Pavel Djundik
const COULD_NOT_CREATE_SOCKET = 1; *
const NOT_CONNECTED = 2; * @link https://xpaw.me
const CONNECTION_FAILED = 3; * @link https://github.com/xPaw/PHP-Source-Query
const INVALID_ENGINE = 3; *
} * @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception;
final class SocketException extends SourceQueryException
{
public const COULD_NOT_CREATE_SOCKET = 1;
public const NOT_CONNECTED = 2;
public const CONNECTION_FAILED = 3;
public const INVALID_ENGINE = 3;
}
+18 -15
View File
@@ -1,18 +1,21 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception; declare(strict_types=1);
abstract class SourceQueryException extends \Exception /**
{ * @author Pavel Djundik
// Base exception class *
} * @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery\Exception;
abstract class SourceQueryException extends \Exception
{
// Base exception class
}
+135 -142
View File
@@ -1,145 +1,138 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery; declare(strict_types=1);
use xPaw\SourceQuery\Exception\AuthenticationException;
use xPaw\SourceQuery\Exception\InvalidPacketException;
/** /**
* Class GoldSourceRcon * @author Pavel Djundik
* *
* @package xPaw\SourceQuery * @link https://xpaw.me
* * @link https://github.com/xPaw/PHP-Source-Query
* @uses xPaw\SourceQuery\Exception\AuthenticationException *
* @uses xPaw\SourceQuery\Exception\InvalidPacketException * @license GNU Lesser General Public License, version 2.1
*/ *
class GoldSourceRcon * @internal
{ */
/**
* Points to socket class namespace xPaw\SourceQuery;
*
* @var BaseSocket use xPaw\SourceQuery\Exception\AuthenticationException;
*/ use xPaw\SourceQuery\Exception\InvalidPacketException;
private $Socket;
/**
private string $RconPassword = ''; * Class GoldSourceRcon
private string $RconChallenge = ''; *
* @package xPaw\SourceQuery
public function __construct( BaseSocket $Socket ) *
{ * @uses AuthenticationException
$this->Socket = $Socket; * @uses InvalidPacketException
} */
final class GoldSourceRcon
public function Close( ) : void {
{ /**
$this->RconChallenge = ''; * Points to socket class
$this->RconPassword = ''; *
} * @var BaseSocket
*/
public function Open( ) : void private $Socket;
{
// private string $RconPassword = '';
} private string $RconChallenge = '';
public function Write( int $Header, string $String = '' ) : bool public function __construct(BaseSocket $Socket)
{ {
$Command = pack( 'cccca*', 0xFF, 0xFF, 0xFF, 0xFF, $String ); $this->Socket = $Socket;
$Length = strlen( $Command ); }
return $Length === fwrite( $this->Socket->Socket, $Command, $Length ); public function Close(): void
} {
$this->RconChallenge = '';
/** $this->RconPassword = '';
* @param int $Length }
* @throws AuthenticationException
* @return Buffer public function Open(): void
*/ {
public function Read( int $Length = 1400 ) : Buffer //
{ }
// GoldSource RCON has same structure as Query
$Buffer = $this->Socket->Read( ); public function Write(int $Header, string $String = ''): bool
{
$StringBuffer = ''; $Command = pack('cccca*', 0xFF, 0xFF, 0xFF, 0xFF, $String);
$ReadMore = false; $Length = strlen($Command);
// There is no indentifier of the end, so we just need to continue reading return $Length === fwrite($this->Socket->Socket, $Command, $Length);
do }
{
$ReadMore = $Buffer->Remaining( ) > 0; /**
* @param int $Length
if( $ReadMore ) * @throws AuthenticationException
{ * @return Buffer
if( $Buffer->GetByte( ) !== SourceQuery::S2A_RCON ) */
{ public function Read(int $Length = 1400): Buffer
throw new InvalidPacketException( 'Invalid rcon response.', InvalidPacketException::PACKET_HEADER_MISMATCH ); {
} // GoldSource RCON has same structure as Query
$Buffer = $this->Socket->Read();
$Packet = $Buffer->Get( );
$StringBuffer .= $Packet; $StringBuffer = '';
//$StringBuffer .= SubStr( $Packet, 0, -2 ); $ReadMore = false;
// Let's assume if this packet is not long enough, there are no more after this one // There is no indentifier of the end, so we just need to continue reading
$ReadMore = strlen( $Packet ) > 1000; // use 1300? do {
$ReadMore = $Buffer->Remaining() > 0;
if( $ReadMore )
{ if ($ReadMore) {
$Buffer = $this->Socket->Read( ); if ($Buffer->GetByte() !== SourceQuery::S2A_RCON) {
} throw new InvalidPacketException('Invalid rcon response.', InvalidPacketException::PACKET_HEADER_MISMATCH);
} }
}
while( $ReadMore ); $Packet = $Buffer->Get();
$StringBuffer .= $Packet;
$Trimmed = trim( $StringBuffer ); //$StringBuffer .= SubStr( $Packet, 0, -2 );
if( $Trimmed === 'Bad rcon_password.' ) // Let's assume if this packet is not long enough, there are no more after this one
{ $ReadMore = strlen($Packet) > 1000; // use 1300?
throw new AuthenticationException( $Trimmed, AuthenticationException::BAD_PASSWORD );
} if ($ReadMore) {
else if( $Trimmed === 'You have been banned from this server.' ) $Buffer = $this->Socket->Read();
{ }
throw new AuthenticationException( $Trimmed, AuthenticationException::BANNED ); }
} } while ($ReadMore);
$Buffer->Set( $Trimmed ); $Trimmed = trim($StringBuffer);
return $Buffer; if ($Trimmed === 'Bad rcon_password.') {
} throw new AuthenticationException($Trimmed, AuthenticationException::BAD_PASSWORD);
} elseif ($Trimmed === 'You have been banned from this server.') {
public function Command( string $Command ) : string throw new AuthenticationException($Trimmed, AuthenticationException::BANNED);
{ }
if( !$this->RconChallenge )
{ $Buffer->Set($Trimmed);
throw new AuthenticationException( 'Tried to execute a RCON command before successful authorization.', AuthenticationException::BAD_PASSWORD );
} return $Buffer;
}
$this->Write( 0, 'rcon ' . $this->RconChallenge . ' "' . $this->RconPassword . '" ' . $Command . "\0" );
$Buffer = $this->Read( ); public function Command(string $Command): string
{
return $Buffer->Get( ); if (!$this->RconChallenge) {
} throw new AuthenticationException('Tried to execute a RCON command before successful authorization.', AuthenticationException::BAD_PASSWORD);
}
public function Authorize( string $Password ) : void
{ $this->Write(0, 'rcon ' . $this->RconChallenge . ' "' . $this->RconPassword . '" ' . $Command . "\0");
$this->RconPassword = $Password; $Buffer = $this->Read();
$this->Write( 0, 'challenge rcon' ); return $Buffer->Get();
$Buffer = $this->Socket->Read( ); }
if( $Buffer->Get( 14 ) !== 'challenge rcon' ) public function Authorize(string $Password): void
{ {
throw new AuthenticationException( 'Failed to get RCON challenge.', AuthenticationException::BAD_PASSWORD ); $this->RconPassword = $Password;
}
$this->Write(0, 'challenge rcon');
$this->RconChallenge = trim( $Buffer->Get( ) ); $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());
}
}
+92 -92
View File
@@ -1,95 +1,95 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery; declare(strict_types=1);
use xPaw\SourceQuery\Exception\InvalidPacketException;
use xPaw\SourceQuery\Exception\SocketException;
/** /**
* Class Socket * @author Pavel Djundik
* *
* @package xPaw\SourceQuery * @link https://xpaw.me
* * @link https://github.com/xPaw/PHP-Source-Query
* @uses xPaw\SourceQuery\Exception\InvalidPacketException *
* @uses xPaw\SourceQuery\Exception\SocketException * @license GNU Lesser General Public License, version 2.1
*/ *
class Socket extends BaseSocket * @internal
{ */
public function Close( ) : void
{ namespace xPaw\SourceQuery;
if( $this->Socket !== null )
{ use xPaw\SourceQuery\Exception\InvalidPacketException;
fclose( $this->Socket ); use xPaw\SourceQuery\Exception\SocketException;
$this->Socket = null; /**
} * Class Socket
} *
* @package xPaw\SourceQuery
public function Open( string $Address, int $Port, int $Timeout, int $Engine ) : void *
{ * @uses InvalidPacketException
$this->Timeout = $Timeout; * @uses SocketException
$this->Engine = $Engine; */
$this->Port = $Port; final class Socket extends BaseSocket
$this->Address = $Address; {
public function Close(): void
$Socket = @fsockopen( 'udp://' . $Address, $Port, $ErrNo, $ErrStr, $Timeout ); {
if ($this->Socket !== null) {
if( $ErrNo || $Socket === false ) fclose($this->Socket);
{
throw new SocketException( 'Could not create socket: ' . $ErrStr, SocketException::COULD_NOT_CREATE_SOCKET ); $this->Socket = null;
} }
}
$this->Socket = $Socket;
stream_set_timeout( $this->Socket, $Timeout ); public function Open(string $Address, int $Port, int $Timeout, int $Engine): void
stream_set_blocking( $this->Socket, true ); {
} $this->Timeout = $Timeout;
$this->Engine = $Engine;
public function Write( int $Header, string $String = '' ) : bool $this->Port = $Port;
{ $this->Address = $Address;
$Command = pack( 'ccccca*', 0xFF, 0xFF, 0xFF, 0xFF, $Header, $String );
$Length = strlen( $Command ); $Socket = @fsockopen('udp://' . $Address, $Port, $ErrNo, $ErrStr, $Timeout);
return $Length === fwrite( $this->Socket, $Command, $Length ); if ($ErrNo || $Socket === false) {
} throw new SocketException('Could not create socket: ' . $ErrStr, SocketException::COULD_NOT_CREATE_SOCKET);
}
/**
* Reads from socket and returns Buffer. $this->Socket = $Socket;
* stream_set_timeout($this->Socket, $Timeout);
* @throws InvalidPacketException stream_set_blocking($this->Socket, true);
* }
* @return Buffer Buffer
*/ public function Write(int $Header, string $String = ''): bool
public function Read( int $Length = 1400 ) : Buffer {
{ $Command = pack('ccccca*', 0xFF, 0xFF, 0xFF, 0xFF, $Header, $String);
$Buffer = new Buffer( ); $Length = strlen($Command);
$Buffer->Set( fread( $this->Socket, $Length ) );
return $Length === fwrite($this->Socket, $Command, $Length);
$this->ReadInternal( $Buffer, $Length, [ $this, 'Sherlock' ] ); }
return $Buffer; /**
} * Reads from socket and returns Buffer.
*
public function Sherlock( Buffer $Buffer, int $Length ) : bool * @throws InvalidPacketException
{ *
$Data = fread( $this->Socket, $Length ); * @return Buffer Buffer
*/
if( strlen( $Data ) < 4 ) public function Read(int $Length = 1400): Buffer
{ {
return false; $Buffer = new Buffer();
} $Buffer->Set(fread($this->Socket, $Length));
$Buffer->Set( $Data ); $this->ReadInternal($Buffer, $Length, [ $this, 'Sherlock' ]);
return $Buffer->GetLong( ) === -2; 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;
}
}
File diff suppressed because it is too large Load Diff
+183 -196
View File
@@ -1,199 +1,186 @@
<?php <?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery; declare(strict_types=1);
use xPaw\SourceQuery\Exception\AuthenticationException;
use xPaw\SourceQuery\Exception\InvalidPacketException;
use xPaw\SourceQuery\Exception\SocketException;
/** /**
* Class SourceRcon * @author Pavel Djundik
* *
* @package xPaw\SourceQuery * @link https://xpaw.me
* * @link https://github.com/xPaw/PHP-Source-Query
* @uses xPaw\SourceQuery\Exception\AuthenticationException *
* @uses xPaw\SourceQuery\Exception\InvalidPacketException * @license GNU Lesser General Public License, version 2.1
* @uses xPaw\SourceQuery\Exception\SocketException *
*/ * @internal
class SourceRcon */
{
/** namespace xPaw\SourceQuery;
* Points to socket class
*/ use xPaw\SourceQuery\Exception\AuthenticationException;
private BaseSocket $Socket; use xPaw\SourceQuery\Exception\InvalidPacketException;
use xPaw\SourceQuery\Exception\SocketException;
/** @var ?resource */
private $RconSocket; /**
private int $RconRequestId = 0; * Class SourceRcon
*
public function __construct( BaseSocket $Socket ) * @package xPaw\SourceQuery
{ *
$this->Socket = $Socket; * @uses AuthenticationException
} * @uses InvalidPacketException
* @uses SocketException
public function Close( ) : void */
{ final class SourceRcon
if( $this->RconSocket ) {
{ /**
fclose( $this->RconSocket ); * Points to socket class
*/
$this->RconSocket = null; private BaseSocket $Socket;
}
/** @var ?resource */
$this->RconRequestId = 0; private $RconSocket;
} private int $RconRequestId = 0;
public function Open( ) : void public function __construct(BaseSocket $Socket)
{ {
if( !$this->RconSocket ) $this->Socket = $Socket;
{ }
$RconSocket = @fsockopen( $this->Socket->Address, $this->Socket->Port, $ErrNo, $ErrStr, $this->Socket->Timeout );
public function Close(): void
if( $ErrNo || !$RconSocket ) {
{ if ($this->RconSocket) {
throw new SocketException( 'Can\'t connect to RCON server: ' . $ErrStr, SocketException::CONNECTION_FAILED ); fclose($this->RconSocket);
}
$this->RconSocket = null;
$this->RconSocket = $RconSocket; }
stream_set_timeout( $this->RconSocket, $this->Socket->Timeout );
stream_set_blocking( $this->RconSocket, true ); $this->RconRequestId = 0;
} }
}
public function Open(): void
public function Write( int $Header, string $String = '' ) : bool {
{ if (!$this->RconSocket) {
// Pack the packet together $RconSocket = @fsockopen($this->Socket->Address, $this->Socket->Port, $ErrNo, $ErrStr, $this->Socket->Timeout);
$Command = pack( 'VV', ++$this->RconRequestId, $Header ) . $String . "\x00\x00";
if ($ErrNo || !$RconSocket) {
// Prepend packet length throw new SocketException('Can\'t connect to RCON server: ' . $ErrStr, SocketException::CONNECTION_FAILED);
$Command = pack( 'V', strlen( $Command ) ) . $Command; }
$Length = strlen( $Command );
$this->RconSocket = $RconSocket;
return $Length === fwrite( $this->RconSocket, $Command, $Length ); stream_set_timeout($this->RconSocket, $this->Socket->Timeout);
} stream_set_blocking($this->RconSocket, true);
}
public function Read( ) : Buffer }
{
$Buffer = new Buffer( ); public function Write(int $Header, string $String = ''): bool
$Buffer->Set( fread( $this->RconSocket, 4 ) ); {
// Pack the packet together
if( $Buffer->Remaining( ) < 4 ) $Command = pack('VV', ++$this->RconRequestId, $Header) . $String . "\x00\x00";
{
throw new InvalidPacketException( 'Rcon read: Failed to read any data from socket', InvalidPacketException::BUFFER_EMPTY ); // Prepend packet length
} $Command = pack('V', strlen($Command)) . $Command;
$Length = strlen($Command);
$PacketSize = $Buffer->GetLong( );
return $Length === fwrite($this->RconSocket, $Command, $Length);
$Buffer->Set( fread( $this->RconSocket, $PacketSize ) ); }
$Data = $Buffer->Get( ); public function Read(): Buffer
{
$Remaining = $PacketSize - strlen( $Data ); $Buffer = new Buffer();
$Buffer->Set(fread($this->RconSocket, 4));
while( $Remaining > 0 )
{ if ($Buffer->Remaining() < 4) {
$Data2 = fread( $this->RconSocket, $Remaining ); throw new InvalidPacketException('Rcon read: Failed to read any data from socket', InvalidPacketException::BUFFER_EMPTY);
}
$PacketSize = strlen( $Data2 );
$PacketSize = $Buffer->GetLong();
if( $PacketSize === 0 )
{ $Buffer->Set(fread($this->RconSocket, $PacketSize));
throw new InvalidPacketException( 'Read ' . strlen( $Data ) . ' bytes from socket, ' . $Remaining . ' remaining', InvalidPacketException::BUFFER_EMPTY );
} $Data = $Buffer->Get();
$Data .= $Data2; $Remaining = $PacketSize - strlen($Data);
$Remaining -= $PacketSize;
} while ($Remaining > 0) {
$Data2 = fread($this->RconSocket, $Remaining);
$Buffer->Set( $Data );
$PacketSize = strlen($Data2);
return $Buffer;
} if ($PacketSize === 0) {
throw new InvalidPacketException('Read ' . strlen($Data) . ' bytes from socket, ' . $Remaining . ' remaining', InvalidPacketException::BUFFER_EMPTY);
public function Command( string $Command ) : string }
{
$this->Write( SourceQuery::SERVERDATA_EXECCOMMAND, $Command ); $Data .= $Data2;
$Buffer = $this->Read( ); $Remaining -= $PacketSize;
}
$Buffer->GetLong( ); // RequestID
$Buffer->Set($Data);
$Type = $Buffer->GetLong( );
return $Buffer;
if( $Type === SourceQuery::SERVERDATA_AUTH_RESPONSE ) }
{
throw new AuthenticationException( 'Bad rcon_password.', AuthenticationException::BAD_PASSWORD ); public function Command(string $Command): string
} {
else if( $Type !== SourceQuery::SERVERDATA_RESPONSE_VALUE ) $this->Write(SourceQuery::SERVERDATA_EXECCOMMAND, $Command);
{ $Buffer = $this->Read();
throw new InvalidPacketException( 'Invalid rcon response.', InvalidPacketException::PACKET_HEADER_MISMATCH );
} $Buffer->GetLong(); // RequestID
$Data = $Buffer->Get( ); $Type = $Buffer->GetLong();
// We do this stupid hack to handle split packets if ($Type === SourceQuery::SERVERDATA_AUTH_RESPONSE) {
// See https://developer.valvesoftware.com/wiki/Source_RCON_Protocol#Multiple-packet_Responses throw new AuthenticationException('Bad rcon_password.', AuthenticationException::BAD_PASSWORD);
if( strlen( $Data ) >= 4000 ) } elseif ($Type !== SourceQuery::SERVERDATA_RESPONSE_VALUE) {
{ throw new InvalidPacketException('Invalid rcon response.', InvalidPacketException::PACKET_HEADER_MISMATCH);
$this->Write( SourceQuery::SERVERDATA_REQUESTVALUE ); }
do $Data = $Buffer->Get();
{
$Buffer = $this->Read( ); // We do this stupid hack to handle split packets
// See https://developer.valvesoftware.com/wiki/Source_RCON_Protocol#Multiple-packet_Responses
$Buffer->GetLong( ); // RequestID if (strlen($Data) >= 4000) {
$this->Write(SourceQuery::SERVERDATA_REQUESTVALUE);
if( $Buffer->GetLong( ) !== SourceQuery::SERVERDATA_RESPONSE_VALUE )
{ do {
break; $Buffer = $this->Read();
}
$Buffer->GetLong(); // RequestID
$Data2 = $Buffer->Get( );
if ($Buffer->GetLong() !== SourceQuery::SERVERDATA_RESPONSE_VALUE) {
if( $Data2 === "\x00\x01\x00\x00\x00\x00" ) break;
{ }
break;
} $Data2 = $Buffer->Get();
$Data .= $Data2; if ($Data2 === "\x00\x01\x00\x00\x00\x00") {
} break;
while( true ); }
}
$Data .= $Data2;
return rtrim( $Data, "\0" ); } while (true);
} }
public function Authorize( string $Password ) : void return rtrim($Data, "\0");
{ }
$this->Write( SourceQuery::SERVERDATA_AUTH, $Password );
$Buffer = $this->Read( ); public function Authorize(string $Password): void
{
$RequestID = $Buffer->GetLong( ); $this->Write(SourceQuery::SERVERDATA_AUTH, $Password);
$Type = $Buffer->GetLong( ); $Buffer = $this->Read();
// If we receive SERVERDATA_RESPONSE_VALUE, then we need to read again $RequestID = $Buffer->GetLong();
// More info: https://developer.valvesoftware.com/wiki/Source_RCON_Protocol#Additional_Comments $Type = $Buffer->GetLong();
if( $Type === SourceQuery::SERVERDATA_RESPONSE_VALUE ) // If we receive SERVERDATA_RESPONSE_VALUE, then we need to read again
{ // More info: https://developer.valvesoftware.com/wiki/Source_RCON_Protocol#Additional_Comments
$Buffer = $this->Read( );
if ($Type === SourceQuery::SERVERDATA_RESPONSE_VALUE) {
$RequestID = $Buffer->GetLong( ); $Buffer = $this->Read();
$Type = $Buffer->GetLong( );
} $RequestID = $Buffer->GetLong();
$Type = $Buffer->GetLong();
if( $RequestID === -1 || $Type !== SourceQuery::SERVERDATA_AUTH_RESPONSE ) }
{
throw new AuthenticationException( 'RCON authorization failed.', AuthenticationException::BAD_PASSWORD ); if ($RequestID === -1 || $Type !== SourceQuery::SERVERDATA_AUTH_RESPONSE) {
} throw new AuthenticationException('RCON authorization failed.', AuthenticationException::BAD_PASSWORD);
} }
} }
}
+27 -24
View File
@@ -1,27 +1,30 @@
<?php <?php
/**
* Library to query servers that implement Source Engine Query protocol.
*
* Special thanks to koraktor for his awesome Steam Condenser class,
* I used it as a reference at some points.
*
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*/
require_once __DIR__ . '/Exception/SourceQueryException.php'; declare(strict_types=1);
require_once __DIR__ . '/Exception/AuthenticationException.php';
require_once __DIR__ . '/Exception/InvalidArgumentException.php';
require_once __DIR__ . '/Exception/SocketException.php';
require_once __DIR__ . '/Exception/InvalidPacketException.php';
require_once __DIR__ . '/Buffer.php'; /**
require_once __DIR__ . '/BaseSocket.php'; * Library to query servers that implement Source Engine Query protocol.
require_once __DIR__ . '/Socket.php'; *
require_once __DIR__ . '/SourceRcon.php'; * Special thanks to koraktor for his awesome Steam Condenser class,
require_once __DIR__ . '/GoldSourceRcon.php'; * I used it as a reference at some points.
require_once __DIR__ . '/SourceQuery.php'; *
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*/
require_once __DIR__ . '/Exception/SourceQueryException.php';
require_once __DIR__ . '/Exception/AuthenticationException.php';
require_once __DIR__ . '/Exception/InvalidArgumentException.php';
require_once __DIR__ . '/Exception/SocketException.php';
require_once __DIR__ . '/Exception/InvalidPacketException.php';
require_once __DIR__ . '/Buffer.php';
require_once __DIR__ . '/BaseSocket.php';
require_once __DIR__ . '/Socket.php';
require_once __DIR__ . '/SourceRcon.php';
require_once __DIR__ . '/GoldSourceRcon.php';
require_once __DIR__ . '/SourceQuery.php';
+321 -327
View File
@@ -1,328 +1,322 @@
<?php <?php
use PHPUnit\Framework\TestCase;
use xPaw\SourceQuery\BaseSocket; declare(strict_types=1);
use xPaw\SourceQuery\SourceQuery;
use xPaw\SourceQuery\Buffer; use PHPUnit\Framework\TestCase;
use xPaw\SourceQuery\BaseSocket;
class TestableSocket extends BaseSocket use xPaw\SourceQuery\SourceQuery;
{ use xPaw\SourceQuery\Buffer;
/** @var \SplQueue<string> */
private \SplQueue $PacketQueue; final class TestableSocket extends BaseSocket
{
public function __construct( ) /** @var \SplQueue<string> */
{ private \SplQueue $PacketQueue;
/** @var \SplQueue<string> */
$this->PacketQueue = new \SplQueue(); public function __construct()
$this->PacketQueue->setIteratorMode( \SplDoublyLinkedList::IT_MODE_DELETE ); {
$this->PacketQueue = new \SplQueue();
} $this->PacketQueue->setIteratorMode(\SplDoublyLinkedList::IT_MODE_DELETE);
}
public function Queue( string $Data ) : void
{ public function Queue(string $Data): void
$this->PacketQueue->push( $Data ); {
} $this->PacketQueue->push($Data);
}
public function Close( ) : void
{ public function Close(): void
// {
} //
}
public function Open( string $Address, int $Port, int $Timeout, int $Engine ) : void
{ public function Open(string $Address, int $Port, int $Timeout, int $Engine): void
$this->Timeout = $Timeout; {
$this->Engine = $Engine; $this->Timeout = $Timeout;
$this->Port = $Port; $this->Engine = $Engine;
$this->Address = $Address; $this->Port = $Port;
} $this->Address = $Address;
}
public function Write( int $Header, string $String = '' ) : bool
{ public function Write(int $Header, string $String = ''): bool
return true; {
} return true;
}
public function Read( int $Length = 1400 ) : Buffer
{ public function Read(int $Length = 1400): Buffer
$Buffer = new Buffer( ); {
$Buffer->Set( $this->PacketQueue->shift() ); $Buffer = new Buffer();
$Buffer->Set($this->PacketQueue->shift());
$this->ReadInternal( $Buffer, $Length, [ $this, 'Sherlock' ] );
$this->ReadInternal($Buffer, $Length, [ $this, 'Sherlock' ]);
return $Buffer;
} return $Buffer;
}
public function Sherlock( Buffer $Buffer, int $Length ) : bool
{ public function Sherlock(Buffer $Buffer, int $Length): bool
if( $this->PacketQueue->isEmpty() ) {
{ if ($this->PacketQueue->isEmpty()) {
return false; return false;
} }
$Buffer->Set( $this->PacketQueue->shift() ); $Buffer->Set($this->PacketQueue->shift());
return $Buffer->GetLong( ) === -2; return $Buffer->GetLong() === -2;
} }
} }
class Tests extends \PHPUnit\Framework\TestCase final class Tests extends TestCase
{ {
private TestableSocket $Socket; private TestableSocket $Socket;
private SourceQuery $SourceQuery; private SourceQuery $SourceQuery;
public function setUp() : void public function setUp(): void
{ {
$this->Socket = new TestableSocket(); $this->Socket = new TestableSocket();
$this->SourceQuery = new SourceQuery( $this->Socket ); $this->SourceQuery = new SourceQuery($this->Socket);
$this->SourceQuery->Connect( '', 2 ); $this->SourceQuery->Connect('', 2);
} }
public function tearDown() : void public function tearDown(): void
{ {
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
unset( $this->Socket, $this->SourceQuery ); unset($this->Socket, $this->SourceQuery);
} }
public function testInvalidTimeout() : void public function testInvalidTimeout(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\InvalidArgumentException::class ); $this->expectException(xPaw\SourceQuery\Exception\InvalidArgumentException::class);
$SourceQuery = new SourceQuery( ); $SourceQuery = new SourceQuery();
$SourceQuery->Connect( '', 2, -1 ); $SourceQuery->Connect('', 2, -1);
} }
public function testNotConnectedGetInfo() : void public function testNotConnectedGetInfo(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
$this->SourceQuery->GetInfo(); $this->SourceQuery->GetInfo();
} }
public function testNotConnectedPing() : void public function testNotConnectedPing(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
$this->SourceQuery->Ping(); $this->SourceQuery->Ping();
} }
public function testNotConnectedGetPlayers() : void public function testNotConnectedGetPlayers(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
$this->SourceQuery->GetPlayers(); $this->SourceQuery->GetPlayers();
} }
/** /**
* @expectedException xPaw\SourceQuery\Exception\SocketException * @expectedException xPaw\SourceQuery\Exception\SocketException
*/ */
public function testNotConnectedGetRules() : void public function testNotConnectedGetRules(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
$this->SourceQuery->GetRules(); $this->SourceQuery->GetRules();
} }
public function testNotConnectedSetRconPassword() : void public function testNotConnectedSetRconPassword(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
$this->SourceQuery->SetRconPassword('a'); $this->SourceQuery->SetRconPassword('a');
} }
public function testNotConnectedRcon() : void public function testNotConnectedRcon(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Disconnect(); $this->SourceQuery->Disconnect();
$this->SourceQuery->Rcon('a'); $this->SourceQuery->Rcon('a');
} }
public function testRconWithoutPassword() : void public function testRconWithoutPassword(): void
{ {
$this->expectException( xPaw\SourceQuery\Exception\SocketException::class ); $this->expectException(xPaw\SourceQuery\Exception\SocketException::class);
$this->SourceQuery->Rcon('a'); $this->SourceQuery->Rcon('a');
} }
/** /**
* @dataProvider InfoProvider * @dataProvider InfoProvider
*/ */
public function testGetInfo( string $RawInput, array $ExpectedOutput ) : void public function testGetInfo(string $RawInput, array $ExpectedOutput): void
{ {
if( isset( $ExpectedOutput[ 'IsMod' ] ) ) if (isset($ExpectedOutput[ 'IsMod' ])) {
{ $this->Socket->Engine = SourceQuery::GOLDSOURCE;
$this->Socket->Engine = SourceQuery::GOLDSOURCE; }
}
$this->Socket->Queue($RawInput);
$this->Socket->Queue( $RawInput );
$RealOutput = $this->SourceQuery->GetInfo();
$RealOutput = $this->SourceQuery->GetInfo();
self::assertEquals($ExpectedOutput, $RealOutput);
$this->assertEquals( $ExpectedOutput, $RealOutput ); }
}
public function InfoProvider(): array
public function InfoProvider() : array {
{ $DataProvider = [];
$DataProvider = [];
$Files = glob(__DIR__ . '/Info/*.raw', GLOB_ERR);
$Files = glob( __DIR__ . '/Info/*.raw', GLOB_ERR );
foreach ($Files as $File) {
foreach( $Files as $File ) $DataProvider[] =
{ [
$DataProvider[] = hex2bin(trim(file_get_contents($File))),
[ json_decode(file_get_contents(str_replace('.raw', '.json', $File)), true)
hex2bin( trim( file_get_contents( $File ) ) ), ];
json_decode( file_get_contents( str_replace( '.raw', '.json', $File ) ), true ) }
];
} return $DataProvider;
}
return $DataProvider;
} /**
* @dataProvider BadPacketProvider
/** */
* @dataProvider BadPacketProvider public function testBadGetInfo(string $Data): void
*/ {
public function testBadGetInfo( string $Data ) : void $this->expectException(xPaw\SourceQuery\Exception\InvalidPacketException::class);
{ $this->Socket->Queue($Data);
$this->expectException( xPaw\SourceQuery\Exception\InvalidPacketException::class );
$this->Socket->Queue( $Data ); $this->SourceQuery->GetInfo();
}
$this->SourceQuery->GetInfo();
} /**
* @dataProvider BadPacketProvider
/** */
* @dataProvider BadPacketProvider public function testBadGetChallengeViaPlayers(string $Data): void
*/ {
public function testBadGetChallengeViaPlayers( string $Data ) : void $this->expectException(xPaw\SourceQuery\Exception\InvalidPacketException::class);
{ $this->Socket->Queue($Data);
$this->expectException( xPaw\SourceQuery\Exception\InvalidPacketException::class );
$this->Socket->Queue( $Data ); $this->SourceQuery->GetPlayers();
}
$this->SourceQuery->GetPlayers();
} /**
* @dataProvider BadPacketProvider
/** */
* @dataProvider BadPacketProvider public function testBadGetPlayersAfterCorrectChallenge(string $Data): void
*/ {
public function testBadGetPlayersAfterCorrectChallenge( string $Data ) : void $this->expectException(xPaw\SourceQuery\Exception\InvalidPacketException::class);
{ $this->Socket->Queue("\xFF\xFF\xFF\xFF\x41\x11\x11\x11\x11");
$this->expectException( xPaw\SourceQuery\Exception\InvalidPacketException::class ); $this->Socket->Queue($Data);
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\x41\x11\x11\x11\x11" );
$this->Socket->Queue( $Data ); $this->SourceQuery->GetPlayers();
}
$this->SourceQuery->GetPlayers();
} /**
* @dataProvider BadPacketProvider
/** */
* @dataProvider BadPacketProvider public function testBadGetRulesAfterCorrectChallenge(string $Data): void
*/ {
public function testBadGetRulesAfterCorrectChallenge( string $Data ) : void $this->expectException(xPaw\SourceQuery\Exception\InvalidPacketException::class);
{ $this->Socket->Queue("\xFF\xFF\xFF\xFF\x41\x11\x11\x11\x11");
$this->expectException( xPaw\SourceQuery\Exception\InvalidPacketException::class ); $this->Socket->Queue($Data);
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\x41\x11\x11\x11\x11" );
$this->Socket->Queue( $Data ); $this->SourceQuery->GetRules();
}
$this->SourceQuery->GetRules();
} public function BadPacketProvider(): array
{
public function BadPacketProvider( ) : array return
{ [
return [ "" ],
[ [ "\xff\xff\xff\xff" ], // No type
[ "" ], [ "\xff\xff\xff\xff\x49" ], // Correct type, but no data after
[ "\xff\xff\xff\xff" ], // No type [ "\xff\xff\xff\xff\x6D" ], // Old info packet, but tests are done for source
[ "\xff\xff\xff\xff\x49" ], // Correct type, but no data after [ "\xff\xff\xff\xff\x11" ], // Wrong type
[ "\xff\xff\xff\xff\x6D" ], // Old info packet, but tests are done for source [ "\x11\x11\x11\x11" ], // Wrong header
[ "\xff\xff\xff\xff\x11" ], // Wrong type [ "\xff" ], // Should be 4 bytes, but it's 1
[ "\x11\x11\x11\x11" ], // Wrong header ];
[ "\xff" ], // Should be 4 bytes, but it's 1 }
];
} public function testGetChallengeTwice(): void
{
public function testGetChallengeTwice( ) : void $this->Socket->Queue("\xFF\xFF\xFF\xFF\x41\x11\x11\x11\x11");
{ $this->Socket->Queue("\xFF\xFF\xFF\xFF\x45\x01\x00ayy\x00lmao\x00");
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\x41\x11\x11\x11\x11" ); self::assertEquals([ 'ayy' => 'lmao' ], $this->SourceQuery->GetRules());
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\x45\x01\x00ayy\x00lmao\x00" );
$this->assertEquals( [ 'ayy' => 'lmao' ], $this->SourceQuery->GetRules() ); $this->Socket->Queue("\xFF\xFF\xFF\xFF\x45\x01\x00wow\x00much\x00");
self::assertEquals([ 'wow' => 'much' ], $this->SourceQuery->GetRules());
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\x45\x01\x00wow\x00much\x00" ); }
$this->assertEquals( [ 'wow' => 'much' ], $this->SourceQuery->GetRules() );
} /**
* @dataProvider RulesProvider
/** * @param array<string> $RawInput
* @dataProvider RulesProvider */
* @param array<string> $RawInput public function testGetRules(array $RawInput, array $ExpectedOutput): void
*/ {
public function testGetRules( array $RawInput, array $ExpectedOutput ) : void $this->Socket->Queue(hex2bin("ffffffff4104fce20e")); // Challenge
{
$this->Socket->Queue( hex2bin( "ffffffff4104fce20e" ) ); // Challenge foreach ($RawInput as $Packet) {
$this->Socket->Queue(hex2bin($Packet));
foreach( $RawInput as $Packet ) }
{
$this->Socket->Queue( hex2bin( $Packet ) ); $RealOutput = $this->SourceQuery->GetRules();
}
self::assertEquals($ExpectedOutput, $RealOutput);
$RealOutput = $this->SourceQuery->GetRules(); }
$this->assertEquals( $ExpectedOutput, $RealOutput ); public function RulesProvider(): array
} {
$DataProvider = [];
public function RulesProvider() : array
{ $Files = glob(__DIR__ . '/Rules/*.raw', GLOB_ERR);
$DataProvider = [];
foreach ($Files as $File) {
$Files = glob( __DIR__ . '/Rules/*.raw', GLOB_ERR ); $DataProvider[] =
[
foreach( $Files as $File ) file($File, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES),
{ json_decode(file_get_contents(str_replace('.raw', '.json', $File)), true)
$DataProvider[] = ];
[ }
file( $File, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES ),
json_decode( file_get_contents( str_replace( '.raw', '.json', $File ) ), true ) return $DataProvider;
]; }
}
/**
return $DataProvider; * @dataProvider PlayersProvider
} * @param array<string> $RawInput
*/
/** public function testGetPlayers(array $RawInput, array $ExpectedOutput): void
* @dataProvider PlayersProvider {
* @param array<string> $RawInput $this->Socket->Queue(hex2bin("ffffffff4104fce20e")); // Challenge
*/
public function testGetPlayers( array $RawInput, array $ExpectedOutput ) : void foreach ($RawInput as $Packet) {
{ $this->Socket->Queue(hex2bin($Packet));
$this->Socket->Queue( hex2bin( "ffffffff4104fce20e" ) ); // Challenge }
foreach( $RawInput as $Packet ) $RealOutput = $this->SourceQuery->GetPlayers();
{
$this->Socket->Queue( hex2bin( $Packet ) ); self::assertEquals($ExpectedOutput, $RealOutput);
} }
$RealOutput = $this->SourceQuery->GetPlayers(); public function PlayersProvider(): array
{
$this->assertEquals( $ExpectedOutput, $RealOutput ); $DataProvider = [];
}
$Files = glob(__DIR__ . '/Players/*.raw', GLOB_ERR);
public function PlayersProvider() : array
{ foreach ($Files as $File) {
$DataProvider = []; $DataProvider[] =
[
$Files = glob( __DIR__ . '/Players/*.raw', GLOB_ERR ); file($File, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES),
json_decode(file_get_contents(str_replace('.raw', '.json', $File)), true)
foreach( $Files as $File ) ];
{ }
$DataProvider[] =
[ return $DataProvider;
file( $File, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES ), }
json_decode( file_get_contents( str_replace( '.raw', '.json', $File ) ), true )
]; public function testPing(): void
} {
$this->Socket->Queue("\xFF\xFF\xFF\xFF\x6A\x00");
return $DataProvider; self::assertTrue($this->SourceQuery->Ping());
}
$this->Socket->Queue("\xFF\xFF\xFF\xFF\xEE");
public function testPing() : void self::assertFalse($this->SourceQuery->Ping());
{ }
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\x6A\x00"); }
$this->assertTrue( $this->SourceQuery->Ping() );
$this->Socket->Queue( "\xFF\xFF\xFF\xFF\xEE");
$this->assertFalse( $this->SourceQuery->Ping() );
}
}
+2 -1
View File
@@ -24,7 +24,8 @@
{ {
"phpunit/phpunit": "^9.5", "phpunit/phpunit": "^9.5",
"vimeo/psalm": "^4.7", "vimeo/psalm": "^4.7",
"phpstan/phpstan": "^0.12.83" "phpstan/phpstan": "^0.12.83",
"friendsofphp/php-cs-fixer": "^3.0"
}, },
"autoload": "autoload":
{ {