Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,8 @@ public function receive(float $waitSeconds = 0.0): ?array
return null;
}

$data = $this->socket->receive(AbstractSocket::DEFAULT_RECEIVE_LENGTH, $waitSeconds);

if (!$data) {
return [];
}
// payloads that arrived with the handshake response are returned without waiting
$data = $this->socket->receive(AbstractSocket::DEFAULT_RECEIVE_LENGTH, [] === $this->received ? $waitSeconds : 0.0);

$this->payloadHandler->handle($data);
$received = $this->received;
Expand Down Expand Up @@ -232,6 +229,8 @@ public function connect(): bool
return false;
}

$this->received = [];

$key = $this->protocol->generateKey();
$handshake = $this->protocol->getRequestHandshake(
$this->uri,
Expand All @@ -242,11 +241,26 @@ public function connect(): bool

$this->socket->send($handshake);

// wait for the response to arrive, since receive() does not block waiting for data
$response = $this->socket->receive(self::MAX_HANDSHAKE_RESPONSE, ClientSocket::TIMEOUT_SOCKET);
$response = '';
$deadline = \hrtime(true) + ClientSocket::TIMEOUT_SOCKET * 1000000000;

do {
$response .= $this->socket->receive(AbstractSocket::DEFAULT_RECEIVE_LENGTH, \max(0, $deadline - \hrtime(true)) / 1e9);
$end = \strpos($response, "\r\n\r\n");
} while (false === $end
&& \strlen($response) < self::MAX_HANDSHAKE_RESPONSE
&& \hrtime(true) < $deadline
&& $this->socket->isConnected()
);

return $this->connected =
$this->protocol->validateResponseHandshake($response, $key);
$this->connected = $this->protocol->validateResponseHandshake($response, $key);

// frames may arrive in the same read as the response
if ($this->connected && false !== $end) {
$this->payloadHandler->handle(\substr($response, $end + 4));
}

return $this->connected;
}

/**
Expand Down Expand Up @@ -306,6 +320,10 @@ public function waitForData(float $maxSeconds): ?bool
return null;
}

if ([] !== $this->received) {
return true;
}

return $this->socket->waitForData($maxSeconds);
}
}
5 changes: 5 additions & 0 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,11 @@ public function process(): void
$data = $this->socket->receive();

if ('' === $data) {
// a readable socket does not always hold application data
if ($this->socket->isConnected()) {
return;
}

throw new CloseException('Error reading data from socket: '.$this->socket->getLastError());
}

Expand Down
119 changes: 43 additions & 76 deletions src/Socket/AbstractSocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ abstract class AbstractSocket extends Configurable implements ResourceInterface

public const DEFAULT_RECEIVE_LENGTH = 1400;

private const MAX_RECEIVE_LENGTH = 65536;

public const NAME_PART_IP = 0;
public const NAME_PART_PORT = 1;

Expand Down Expand Up @@ -257,97 +259,62 @@ public function waitForData(float $maxSeconds): ?bool
*/
public function receive(int $length = self::DEFAULT_RECEIVE_LENGTH, float $waitSeconds = 0.0): string
{
if ($waitSeconds > 0) {
$this->waitForData($waitSeconds);
}
$deadline = \hrtime(true) + $waitSeconds * 1e9;

$buffer = '';
$metadata['unread_bytes'] = 0;
$makeBlockingAfterRead = false;
do {
$buffer = $this->drain($length);

try {
do {
// feof means socket has been closed
// also, sometimes in long running processes the system seems to kill the underlying socket
if (!$this->socket || \feof($this->socket)) {
$this->disconnect();

return $buffer;
}
// poll before reading so that an empty socket returns immediately instead
// of blocking until the socket timeout; callers that expect a reply must
// wait for data to arrive before reading, as the handshake does
$readArray = [$this->socket];
$writeArray = null;
$exceptArray = null;
$selectResult = \stream_select($readArray, $writeArray, $exceptArray, 0);
// 1 means there is data to read, false means we were unable to check if there is data to read
if (1 === $selectResult || false === $selectResult) {
$result = \fread($this->socket, $length);
} else {
$result = false;
}
if ('' !== $buffer || !$this->socket) {
return $buffer;
}

if ($makeBlockingAfterRead) {
\stream_set_blocking($this->socket, true);
$makeBlockingAfterRead = false;
}
// a readable socket does not always hold application data, since an
// encrypted stream also carries records that the TLS layer consumes
$remaining = ($deadline - \hrtime(true)) / 1e9;
} while ($remaining > 0 && true === $this->waitForData($remaining));

if (false === $result) {
return $buffer;
}
return '';
}

$buffer .= $result;
/**
* Reads the data that has already arrived, without blocking.
*/
private function drain(int $length): string
{
if (!$this->socket) {
return '';
}

// feof means socket has been closed
if (\feof($this->socket)) {
$this->disconnect();
$buffer = '';

return $buffer;
}
// blocking reads and end of file checks cannot be bounded reliably
// on an encrypted stream, where older PHP versions wait for more data
\stream_set_blocking($this->socket, false);

$continue = false;
try {
do {
$result = \fread($this->socket, $length);

if (1 === \strlen($result)) {
// Workaround Chrome behavior (still needed?)
$continue = true;
if (false === $result || '' === $result) {
break;
}

if (\strlen($result) === $length) {
$continue = true;
}
$buffer .= $result;

// Continue if more data to be read
$metadata = \stream_get_meta_data($this->socket);

/** @phpstan-ignore-next-line */
if (isset($metadata['unread_bytes'])) {
if (!$metadata['unread_bytes']) {
// stop it, if we read a full message in previous time
$continue = false;
} else {
$continue = true;
// it makes sense only if unread_bytes less than DEFAULT_RECEIVE_LENGTH
if ($length > $metadata['unread_bytes']) {
// http://php.net/manual/en/function.stream-get-meta-data.php
// 'unread_bytes' don't describes real length correctly.
// $length = $metadata['unread_bytes'];

// Socket is a blocking by default. When we do a blocking read from an empty
// queue it will block and the server will hang. https://bugs.php.net/bug.php?id=1739
\stream_set_blocking($this->socket, false);
$makeBlockingAfterRead = true;
}
}
}
} while ($continue);
// an unbuffered stream gives one read of the length asked for
$buffered = \stream_get_meta_data($this->socket)['unread_bytes'] > 0;
} while ($buffered && \strlen($buffer) < self::MAX_RECEIVE_LENGTH);

return $buffer;
$closed = '' === $buffer && \feof($this->socket);
} finally {
if ($this->socket && !\feof($this->socket) && $makeBlockingAfterRead) {
\stream_set_blocking($this->socket, true);
}
\stream_set_blocking($this->socket, true);
}

if ($closed) {
$this->disconnect();
}

return $buffer;
}

/**
Expand Down
79 changes: 79 additions & 0 deletions tests/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use TypeError;
use Wrench\Payload\Payload;
use Wrench\Protocol\Protocol;
use Wrench\Protocol\Rfc6455Protocol;
use Wrench\Socket\ClientSocket;
use Wrench\Test\BaseTest;
use Wrench\Test\ServerTestHelper;
Expand Down Expand Up @@ -43,6 +44,44 @@ private function getMockSocket(): ClientSocket
->getMock();
}

/**
* Gets a client whose socket answers the handshake with the chunks the
* callback makes out of the response.
*/
private function getInstanceWithResponse(callable $chunk): Client
{
$socket = $this->getMockBuilder(ClientSocket::class)
->onlyMethods(['connect', 'isConnected', 'send', 'receive'])
->setConstructorArgs(['ws://localhost:8000'])
->getMock();

$chunks = [];

$socket->method('connect')->willReturn(true);
$socket->method('isConnected')->willReturn(true);
$socket->method('send')->willReturnCallback(static function (string $data) use (&$chunks, $chunk): int {
if (\preg_match('/Sec-WebSocket-Key: (.*)\r\n/i', $data, $matches)) {
$chunks = $chunk(\sprintf(
"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n",
(new Rfc6455Protocol())->getEncodedHash($matches[1])
));
}

return \strlen($data);
});
$socket->method('receive')->willReturnCallback(static function () use (&$chunks): string {
return (string) \array_shift($chunks);
});

$instance = self::getInstance('ws://localhost/test', 'http://example.org/');

(function () use ($socket): void {
$this->socket = $socket;
})->call($instance);

return $instance;
}

public function testConstructorUriInvalid(): void
{
$this->expectException(InvalidArgumentException::class);
Expand Down Expand Up @@ -78,6 +117,46 @@ public function testConstructorOriginInvalid(): void
new Client('ws://localhost:8000', 'NOTAVALIDURI');
}

public function testConnectWithResponseInParts(): void
{
$instance = $this->getInstanceWithResponse(static function (string $response): array {
return ['', \substr($response, 0, 40), \substr($response, 40)];
});

self::assertTrue($instance->connect());
self::assertSame([], $instance->receive());
}

public function testConnectWithPayloadAfterResponse(): void
{
$instance = $this->getInstanceWithResponse(static function (string $response): array {
return [$response."\x81\x06foobar"];
});

self::assertTrue($instance->connect());
self::assertTrue($instance->waitForData(0));

$responses = $instance->receive();
self::assertCount(1, $responses);
self::assertSame('foobar', $responses[0]->getPayload());
}

public function testConnectDiscardsPayloadsOfPreviousConnection(): void
{
$payloads = ['foo', 'bar'];
$instance = $this->getInstanceWithResponse(static function (string $response) use (&$payloads): array {
return [$response."\x81\x03".\array_shift($payloads)];
});

self::assertTrue($instance->connect());
self::assertTrue($instance->disconnect());
self::assertTrue($instance->connect());

$responses = $instance->receive();
self::assertCount(1, $responses);
self::assertSame('bar', $responses[0]->getPayload());
}

public function testSend(): void
{
try {
Expand Down
39 changes: 39 additions & 0 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PHPUnit\Framework\ExpectationFailedException;
use Wrench\Application\DataHandlerInterface;
use Wrench\Exception\CloseException;
use Wrench\Exception\HandshakeException;
use Wrench\Protocol\Protocol;
use Wrench\Socket\AbstractSocket;
Expand Down Expand Up @@ -62,6 +63,44 @@ public function testClose(int $code): void
$connection->close($code);
}

/**
* @doesNotPerformAssertions
*/
public function testProcessWithoutData(): void
{
$socket = $this->getMockBuilder(ServerClientSocket::class)
->onlyMethods(['getIp', 'getPort', 'isConnected', 'receive'])
->disableOriginalConstructor()
->getMock();

$socket->method('getIp')->willReturn('127.0.0.1');
$socket->method('getPort')->willReturn(\random_int(1025, 50000));
$socket->method('isConnected')->willReturn(true);
$socket->method('receive')->willReturn('');

$connection = self::getInstance($this->getMockConnectionManager(), $socket);
$connection->process();
}

public function testProcessClosedSocket(): void
{
$socket = $this->getMockBuilder(ServerClientSocket::class)
->onlyMethods(['getIp', 'getPort', 'isConnected', 'receive'])
->disableOriginalConstructor()
->getMock();

$socket->method('getIp')->willReturn('127.0.0.1');
$socket->method('getPort')->willReturn(\random_int(1025, 50000));
$socket->method('isConnected')->willReturn(false);
$socket->method('receive')->willReturn('');

$connection = self::getInstance($this->getMockConnectionManager(), $socket);

$this->expectException(CloseException::class);

$connection->process();
}

private function getMockSocket(): ServerClientSocket
{
return $this->getMockBuilder(ServerClientSocket::class)
Expand Down
Loading