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
3 changes: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ jobs:

- name: Run Tests
run: composer run-script test-unit

- name: Run Integration Tests
run: composer run-script test-integration
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
},
"autoload-dev": {
"psr-4": {
"Tests\\Unit\\FreeDSx\\Socket\\": "tests/unit"
"Tests\\Unit\\FreeDSx\\Socket\\": "tests/unit",
"Tests\\Integration\\FreeDSx\\Socket\\": "tests/integration"
}
},
"config": {
Expand All @@ -47,6 +48,9 @@
"test-unit": [
"@php -d xdebug.mode=off vendor/bin/phpunit --testsuite unit"
],
"test-integration": [
"@php -d xdebug.mode=off vendor/bin/phpunit --testsuite integration"
],
"test-coverage": [
"@php -d xdebug.mode=coverage vendor/bin/phpunit --testsuite unit --coverage-clover=coverage.xml"
],
Expand Down
3 changes: 3 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,8 @@
<testsuite name="unit">
<directory>./tests/unit</directory>
</testsuite>
<testsuite name="integration">
<directory>./tests/integration</directory>
</testsuite>
</testsuites>
</phpunit>
23 changes: 23 additions & 0 deletions src/FreeDSx/Socket/Exception/ReadTimeoutException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

/**
* This file is part of the FreeDSx Socket package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace FreeDSx\Socket\Exception;

/**
* Thrown when a blocking read does not complete within the timeout given for that read.
*
* @author Chad Sikorra <Chad.Sikorra@gmail.com>
*/
final class ReadTimeoutException extends ConnectionException
{
}
162 changes: 117 additions & 45 deletions src/FreeDSx/Socket/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

use FreeDSx\Socket\Exception\ConnectionException;
use FreeDSx\Socket\Exception\IdleTimeoutException;
use FreeDSx\Socket\Exception\ReadTimeoutException;
use FreeDSx\Socket\Timeout\ReadDeadline;
use FreeDSx\Socket\Timeout\WriteTimeoutEnforcerInterface;
use FreeDSx\Socket\Tls\Certificate;
use OpenSSLCertificate;
Expand All @@ -27,7 +29,7 @@
use function is_array;
use function is_resource;
use function is_string;
use function microtime;
use function max;
use function sprintf;
use function stream_context_create;
use function stream_context_get_options;
Expand All @@ -49,6 +51,8 @@ class Socket
{
private const MICROSECONDS_PER_SECOND = 1_000_000;

private const MINIMUM_STREAM_TIMEOUT = 0.001;

protected bool $isEncrypted = false;

protected ?SocketAddress $peerAddress = null;
Expand Down Expand Up @@ -87,43 +91,96 @@ public function __construct(
}

/**
* @param float|null $timeout The most seconds a blocking read may take when shorter than the read timeout.
* @throws IdleTimeoutException when a blocking read makes no progress within the configured read timeout.
* @throws ReadTimeoutException when a blocking read does not complete within the timeout given for it.
*/
public function read(bool $block = true): string|false
{
public function read(
bool $block = true,
?float $timeout = null,
): string|false {
$stream = $this->getStream();
if (!$block) {
$data = $this->readWithoutBlocking($stream);

return $data === ''
? false
: $data;
}

// Bytes decrypted into the TLS buffer are off the wire already.
$buffered = $block && $this->isEncrypted
$buffered = $this->isEncrypted
? $this->readWithoutBlocking($stream)
: '';
if ($buffered !== '') {
return $buffered;

return $buffered !== ''
? $buffered
: $this->readBlocking(
$stream,
ReadDeadline::start(
$this->options->getTimeoutRead(),
$timeout,
),
);
}

/**
* A timeout given for the read also bounds the stream, which a partial TLS record would otherwise hold.
*
* @param resource $stream
* @throws IdleTimeoutException|ReadTimeoutException
*/
private function readBlocking(
$stream,
ReadDeadline $deadline,
): string|false {
$this->awaitReadable(
$stream,
$deadline,
);
$streamTimeout = $deadline->streamTimeout();
if ($streamTimeout === null) {
return $this->fetch(
$stream,
$deadline,
);
}
if ($block) {
$this->awaitReadable($stream);

$this->setReadTimeout(
$stream,
$streamTimeout,
);
try {
return $this->fetch(
$stream,
$deadline,
);
} finally {
$this->setStreamOpts();
}
stream_set_blocking($stream, $block);
}

/**
* @param resource $stream
* @throws IdleTimeoutException|ReadTimeoutException
*/
private function fetch(
$stream,
ReadDeadline $deadline,
): string|false {
stream_set_blocking(
$stream,
true,
);
$data = fread(
$stream,
$this->options->getBufferSize(),
);

// A blocking read yields no bytes on either a peer disconnect (feof, empty string) or a read timeout
// (false). Only the timeout case sets the timed_out meta flag, which distinguishes the two.
if ($block && ($data === '' || $data === false) && $this->hasReadTimedOut($stream)) {
throw new IdleTimeoutException(sprintf(
'The connection was idle for longer than the read timeout of %d seconds.',
$this->options->getTimeoutRead(),
));
}

if (!$block) {
stream_set_blocking(
$stream,
true,
);
if (($data === '' || $data === false) && $this->hasReadTimedOut($stream, $deadline)) {
throw $deadline->exceeded();
}

return $data === ''
Expand Down Expand Up @@ -154,35 +211,21 @@ private function readWithoutBlocking($stream): string
}

/**
* Wait for the socket to become readable. This enforces the read timeout that the blocking read would.
* Wait for the socket to become readable. This enforces the deadline that the blocking read would.
*
* Waiting here returns on EINTR and lets the caller run its signal handlers.
*
* @param resource $stream
* @throws IdleTimeoutException
* @throws IdleTimeoutException|ReadTimeoutException
*/
private function awaitReadable($stream): void
{
$timeout = $this->options->getTimeoutRead();
$deadline = $timeout > 0
? microtime(true) + $timeout
: null;

private function awaitReadable(
$stream,
ReadDeadline $deadline,
): void {
while (true) {
$remaining = $deadline === null
? null
: $deadline - microtime(true);

if ($remaining !== null && $remaining <= 0) {
throw new IdleTimeoutException(sprintf(
'The connection was idle for longer than the read timeout of %d seconds.',
$timeout,
));
}

$ready = self::selectReadable(
$stream,
$remaining,
$deadline->remaining(),
);

if ($ready > 0) {
Expand All @@ -191,18 +234,47 @@ private function awaitReadable($stream): void
if (!is_resource($stream)) {
return;
}
if ($deadline->hasPassed()) {
throw $deadline->exceeded();
}
}
}

/**
* @param resource $stream
*/
private function hasReadTimedOut($stream): bool
{
return $this->options->getTimeoutRead() > 0
private function hasReadTimedOut(
$stream,
ReadDeadline $deadline,
): bool {
return $deadline->isBounded()
&& stream_get_meta_data($stream)['timed_out'] === true;
}

/**
* Never below a millisecond, since a stream timeout of zero waits without limit on TLS.
*
* @param resource $stream
*/
private function setReadTimeout(
$stream,
float $seconds,
): void {
$seconds = max(
self::MINIMUM_STREAM_TIMEOUT,
$seconds,
);

stream_set_timeout(
$stream,
(int) $seconds,
(int) (fmod(
$seconds,
1.0,
) * self::MICROSECONDS_PER_SECOND),
);
}

public function write(string $data): static
{
$timeout = $this->options->getTimeoutWrite();
Expand Down
Loading
Loading