HummingBirdAnimeClient/src/API/HummingbirdClient.php

1311 lines
33 KiB
PHP
Raw Normal View History

2018-10-01 13:03:48 -04:00
<?php // declare(strict_types=1);
2018-10-05 14:32:05 -04:00
2018-01-15 14:43:15 -05:00
/**
* Hummingbird Anime List Client
*
2018-08-22 13:48:27 -04:00
* An API client for Kitsu to manage anime and manga watch lists
2018-01-15 14:43:15 -05:00
*
2018-10-01 11:35:51 -04:00
* PHP version 7.1
2018-01-15 14:43:15 -05:00
*
* @package HummingbirdAnimeClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2018 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2018-10-01 11:35:51 -04:00
* @version 4.1
2018-01-15 14:43:15 -05:00
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API;
use Amp\{
CancellationToken,
CancelledException,
Deferred,
Delayed,
Emitter,
Failure,
Loop,
NullCancellationToken,
Promise,
Success,
TimeoutCancellationToken
};
use Amp\Artax\{
2018-10-05 14:32:05 -04:00
ConnectionInfo,
Client,
DnsException,
HttpException,
HttpSocketPool,
MetaInfo,
ParseException,
RequestBody,
Response,
Request,
SocketException,
TimeoutException,
TlsInfo,
TooManyRedirectsException
2018-01-15 14:43:15 -05:00
};
use Amp\Artax\Cookie\{
Cookie,
CookieFormatException,
CookieJar,
2018-01-15 14:43:15 -05:00
NullCookieJar
};
use Amp\Artax\Internal\{
2018-10-05 14:32:05 -04:00
CombinedCancellationToken,
Parser,
PublicSuffixList,
RequestCycle
2018-01-15 14:43:15 -05:00
};
use Amp\ByteStream\{
InputStream, IteratorStream, Message, ZlibInputStream
};
use Amp\Dns\ResolutionException;
use Amp\Socket\{
ClientSocket, ClientTlsContext, ConnectException
};
use Amp\Uri\{
InvalidUriException, Uri
};
2018-08-24 14:23:01 -04:00
use const Aviat\AnimeClient\USER_AGENT;
2018-01-15 14:43:15 -05:00
use function Amp\{
asyncCall, call
};
/**
2018-10-05 14:32:05 -04:00
* Re-implementation of Artax's default client
2018-01-15 14:43:15 -05:00
*/
2018-10-05 14:32:05 -04:00
class HummingbirdClient implements Client {
2018-08-24 14:23:01 -04:00
const DEFAULT_USER_AGENT = USER_AGENT;
2018-01-15 14:43:15 -05:00
private $cookieJar;
private $socketPool;
private $tlsContext;
private $hasZlib;
private $options = [
2018-10-05 14:32:05 -04:00
self::OP_AUTO_ENCODING => TRUE,
2018-10-01 11:35:51 -04:00
self::OP_TRANSFER_TIMEOUT => 100000,
2018-01-15 14:43:15 -05:00
self::OP_MAX_REDIRECTS => 5,
2018-10-05 14:32:05 -04:00
self::OP_AUTO_REFERER => TRUE,
self::OP_DISCARD_BODY => FALSE,
2018-01-15 14:43:15 -05:00
self::OP_DEFAULT_HEADERS => [],
self::OP_MAX_HEADER_BYTES => Parser::DEFAULT_MAX_HEADER_BYTES,
self::OP_MAX_BODY_BYTES => Parser::DEFAULT_MAX_BODY_BYTES,
];
public function __construct(
2018-10-05 14:32:05 -04:00
CookieJar $cookieJar = NULL,
HttpSocketPool $socketPool = NULL,
ClientTlsContext $tlsContext = NULL
2018-01-15 14:43:15 -05:00
)
{
$this->cookieJar = $cookieJar ?? new NullCookieJar;
$this->tlsContext = $tlsContext ?? new ClientTlsContext;
$this->socketPool = $socketPool ?? new HttpSocketPool;
$this->hasZlib = \extension_loaded('zlib');
2018-01-15 14:43:15 -05:00
}
/** @inheritdoc */
2018-10-05 14:32:05 -04:00
public function request($uriOrRequest, array $options = [], CancellationToken $cancellation = NULL): Promise
2018-01-15 14:43:15 -05:00
{
return call(function () use ($uriOrRequest, $options, $cancellation) {
$cancellation = $cancellation ?? new NullCancellationToken;
2018-10-05 14:32:05 -04:00
foreach ($options as $option => $value)
{
2018-01-15 14:43:15 -05:00
$this->validateOption($option, $value);
}
/** @var Request $request */
list($request, $uri) = $this->generateRequestFromUri($uriOrRequest);
$options = $options ? array_merge($this->options, $options) : $this->options;
2018-10-05 14:32:05 -04:00
foreach ($this->options[self::OP_DEFAULT_HEADERS] as $name => $header)
{
if ( ! $request->hasHeader($name))
{
2018-01-15 14:43:15 -05:00
$request = $request->withHeaders([$name => $header]);
}
}
/** @var array $headers */
$headers = yield $request->getBody()->getHeaders();
2018-10-05 14:32:05 -04:00
foreach ($headers as $name => $header)
{
if ( ! $request->hasHeader($name))
{
2018-01-15 14:43:15 -05:00
$request = $request->withHeaders([$name => $header]);
}
}
$originalUri = $uri;
2018-10-05 14:32:05 -04:00
$previousResponse = NULL;
2018-01-15 14:43:15 -05:00
$maxRedirects = $options[self::OP_MAX_REDIRECTS];
$requestNr = 1;
2018-10-05 14:32:05 -04:00
do
{
2018-01-15 14:43:15 -05:00
/** @var Request $request */
$request = yield from $this->normalizeRequestBodyHeaders($request);
$request = $this->normalizeRequestHeaders($request, $uri, $options);
// Always normalize this as last item, because we need to strip sensitive headers
$request = $this->normalizeTraceRequest($request);
/** @var Response $response */
$response = yield $this->doRequest($request, $uri, $options, $previousResponse, $cancellation);
// Explicit $maxRedirects !== 0 check to not consume redirect bodies if redirect following is disabled
2018-10-05 14:32:05 -04:00
if ($maxRedirects !== 0 && $redirectUri = $this->getRedirectUri($response))
{
2018-01-15 14:43:15 -05:00
// Discard response body of redirect responses
$body = $response->getBody();
2018-10-05 14:32:05 -04:00
while (NULL !== yield $body->read()) ;
2018-01-15 14:43:15 -05:00
/**
* If this is a 302/303 we need to follow the location with a GET if the original request wasn't
* GET. Otherwise we need to send the body again.
*
* We won't resend the body nor any headers on redirects to other hosts for security reasons.
*
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3
*/
$method = $request->getMethod();
$status = $response->getStatus();
2018-10-05 14:32:05 -04:00
$isSameHost = $redirectUri->getAuthority(FALSE) === $originalUri->getAuthority(FALSE);
2018-01-15 14:43:15 -05:00
2018-10-05 14:32:05 -04:00
if ($isSameHost)
{
2018-01-15 14:43:15 -05:00
$request = $request->withUri($redirectUri);
2018-10-05 14:32:05 -04:00
if ($status >= 300 && $status <= 303 && $method !== 'GET')
{
2018-01-15 14:43:15 -05:00
$request = $request->withMethod('GET');
$request = $request->withoutHeader('Transfer-Encoding');
$request = $request->withoutHeader('Content-Length');
$request = $request->withoutHeader('Content-Type');
2018-10-05 14:32:05 -04:00
$request = $request->withBody(NULL);
2018-01-15 14:43:15 -05:00
}
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
// We ALWAYS follow with a GET and without any set headers or body for redirects to other hosts.
$optionsWithoutHeaders = $options;
unset($optionsWithoutHeaders[self::OP_DEFAULT_HEADERS]);
$request = new Request((string)$redirectUri);
$request = $this->normalizeRequestHeaders($request, $redirectUri, $optionsWithoutHeaders);
}
2018-10-05 14:32:05 -04:00
if ($options[self::OP_AUTO_REFERER])
{
2018-01-15 14:43:15 -05:00
$request = $this->assignRedirectRefererHeader($request, $originalUri, $redirectUri);
}
$previousResponse = $response;
$originalUri = $redirectUri;
$uri = $redirectUri;
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
break;
}
} while (++$requestNr <= $maxRedirects + 1);
2018-10-05 14:32:05 -04:00
if ($maxRedirects !== 0 && $redirectUri = $this->getRedirectUri($response))
{
2018-01-15 14:43:15 -05:00
throw new TooManyRedirectsException($response);
}
return $response;
});
}
private function validateOption(string $option, $value)
{
2018-10-05 14:32:05 -04:00
switch ($option)
{
2018-01-15 14:43:15 -05:00
case self::OP_AUTO_ENCODING:
2018-10-05 14:32:05 -04:00
if ( ! \is_bool($value))
{
2018-01-15 14:43:15 -05:00
throw new \TypeError("Invalid value for OP_AUTO_ENCODING, bool expected");
}
break;
case self::OP_TRANSFER_TIMEOUT:
2018-10-05 14:32:05 -04:00
if ( ! \is_int($value) || $value < 0)
{
2018-01-15 14:43:15 -05:00
throw new \Error("Invalid value for OP_TRANSFER_TIMEOUT, int >= 0 expected");
}
break;
case self::OP_MAX_REDIRECTS:
2018-10-05 14:32:05 -04:00
if ( ! \is_int($value) || $value < 0)
{
2018-01-15 14:43:15 -05:00
throw new \Error("Invalid value for OP_MAX_REDIRECTS, int >= 0 expected");
}
break;
case self::OP_AUTO_REFERER:
2018-10-05 14:32:05 -04:00
if ( ! \is_bool($value))
{
2018-01-15 14:43:15 -05:00
throw new \TypeError("Invalid value for OP_AUTO_REFERER, bool expected");
}
break;
case self::OP_DISCARD_BODY:
2018-10-05 14:32:05 -04:00
if ( ! \is_bool($value))
{
2018-01-15 14:43:15 -05:00
throw new \TypeError("Invalid value for OP_DISCARD_BODY, bool expected");
}
break;
case self::OP_DEFAULT_HEADERS:
// We attempt to set the headers here, because they're automatically validated then.
(new Request("https://example.com/"))->withHeaders($value);
break;
case self::OP_MAX_HEADER_BYTES:
2018-10-05 14:32:05 -04:00
if ( ! \is_int($value) || $value < 0)
{
2018-01-15 14:43:15 -05:00
throw new \Error("Invalid value for OP_MAX_HEADER_BYTES, int >= 0 expected");
}
break;
case self::OP_MAX_BODY_BYTES:
2018-10-05 14:32:05 -04:00
if ( ! \is_int($value) || $value < 0)
{
2018-01-15 14:43:15 -05:00
throw new \Error("Invalid value for OP_MAX_BODY_BYTES, int >= 0 expected");
}
break;
default:
throw new \Error(
sprintf("Unknown option: %s", $option)
);
}
}
private function generateRequestFromUri($uriOrRequest)
{
2018-10-05 14:32:05 -04:00
if (is_string($uriOrRequest))
{
2018-01-15 14:43:15 -05:00
$uri = $this->buildUriFromString($uriOrRequest);
$request = new Request($uri);
2018-10-05 14:32:05 -04:00
} elseif ($uriOrRequest instanceof Request)
{
2018-01-15 14:43:15 -05:00
$uri = $this->buildUriFromString($uriOrRequest->getUri());
$request = $uriOrRequest;
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
throw new HttpException(
'Request must be a valid HTTP URI or Amp\Artax\Request instance'
);
}
return [$request, $uri];
}
private function buildUriFromString($str): Uri
{
2018-10-05 14:32:05 -04:00
try
{
2018-01-15 14:43:15 -05:00
$uri = new Uri($str);
$scheme = $uri->getScheme();
2018-10-05 14:32:05 -04:00
if (($scheme === "http" || $scheme === "https") && $uri->getHost())
{
2018-01-15 14:43:15 -05:00
return $uri;
}
throw new HttpException("Request must specify a valid HTTP URI");
2018-10-05 14:32:05 -04:00
} catch (InvalidUriException $e)
{
2018-01-15 14:43:15 -05:00
throw new HttpException("Request must specify a valid HTTP URI", 0, $e);
}
}
private function normalizeRequestBodyHeaders(Request $request): \Generator
{
2018-10-05 14:32:05 -04:00
if ($request->hasHeader("Transfer-Encoding"))
{
2018-01-15 14:43:15 -05:00
return $request->withoutHeader("Content-Length");
}
2018-10-05 14:32:05 -04:00
if ($request->hasHeader("Content-Length"))
{
2018-01-15 14:43:15 -05:00
return $request;
}
/** @var RequestBody $body */
$body = $request->getBody();
$bodyLength = yield $body->getBodyLength();
2018-10-05 14:32:05 -04:00
if ($bodyLength === 0)
{
2018-01-15 14:43:15 -05:00
$request = $request->withHeader('Content-Length', '0');
$request = $request->withoutHeader('Transfer-Encoding');
2018-10-05 14:32:05 -04:00
} else
{
if ($bodyLength > 0)
{
2018-08-22 13:51:58 -04:00
$request = $request->withHeader("Content-Length", (string)$bodyLength);
2018-01-15 14:43:15 -05:00
$request = $request->withoutHeader("Transfer-Encoding");
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
$request = $request->withHeader("Transfer-Encoding", "chunked");
}
}
return $request;
}
private function normalizeRequestHeaders($request, $uri, $options)
{
$request = $this->normalizeRequestEncodingHeaderForZlib($request, $options);
$request = $this->normalizeRequestHostHeader($request, $uri);
$request = $this->normalizeRequestUserAgent($request);
$request = $this->normalizeRequestAcceptHeader($request);
$request = $this->assignApplicableRequestCookies($request);
return $request;
}
private function normalizeRequestEncodingHeaderForZlib(Request $request, array $options): Request
{
$autoEncoding = $options[self::OP_AUTO_ENCODING];
2018-10-05 14:32:05 -04:00
if ( ! $autoEncoding)
{
2018-01-15 14:43:15 -05:00
return $request;
}
2018-10-05 14:32:05 -04:00
if ($this->hasZlib)
{
2018-01-15 14:43:15 -05:00
return $request->withHeader('Accept-Encoding', 'gzip, deflate, identity');
}
return $request->withoutHeader('Accept-Encoding');
}
private function normalizeRequestHostHeader(Request $request, Uri $uri): Request
{
2018-10-05 14:32:05 -04:00
if ($request->hasHeader('Host'))
{
2018-01-15 14:43:15 -05:00
return $request;
}
$authority = $this->generateAuthorityFromUri($uri);
$request = $request->withHeader('Host', $this->normalizeHostHeader($authority));
return $request;
}
private function generateAuthorityFromUri(Uri $uri): string
{
$host = $uri->getHost();
$port = $uri->getPort();
return "{$host}:{$port}";
}
private function normalizeHostHeader(string $host): string
{
// Though servers are supposed to be able to handle standard port names on the end of the
// Host header some fail to do this correctly. As a result, we strip the port from the end
// if it's a standard 80 or 443
2018-10-05 14:32:05 -04:00
if (strpos($host, ':80') === strlen($host) - 3)
{
2018-01-15 14:43:15 -05:00
return substr($host, 0, -3);
2018-10-05 14:32:05 -04:00
} elseif (strpos($host, ':443') === strlen($host) - 4)
{
2018-01-15 14:43:15 -05:00
return substr($host, 0, -4);
}
return $host;
}
private function normalizeRequestUserAgent(Request $request): Request
{
2018-10-05 14:32:05 -04:00
if ($request->hasHeader('User-Agent'))
{
2018-01-15 14:43:15 -05:00
return $request;
}
return $request->withHeader('User-Agent', self::DEFAULT_USER_AGENT);
}
private function normalizeRequestAcceptHeader(Request $request): Request
{
2018-10-05 14:32:05 -04:00
if ($request->hasHeader('Accept'))
{
2018-01-15 14:43:15 -05:00
return $request;
}
return $request->withHeader('Accept', '*/*');
}
private function assignApplicableRequestCookies(Request $request): Request
{
$uri = new Uri($request->getUri());
$domain = $uri->getHost();
$path = $uri->getPath();
2018-10-05 14:32:05 -04:00
if ( ! $applicableCookies = $this->cookieJar->get($domain, $path))
{
2018-01-15 14:43:15 -05:00
// No cookies matched our request; we're finished.
return $request->withoutHeader("Cookie");
}
$isRequestSecure = strcasecmp($uri->getScheme(), "https") === 0;
$cookiePairs = [];
/** @var Cookie $cookie */
2018-10-05 14:32:05 -04:00
foreach ($applicableCookies as $cookie)
{
if ( ! $cookie->isSecure() || $isRequestSecure)
{
2018-01-15 14:43:15 -05:00
$cookiePairs[] = $cookie->getName() . "=" . $cookie->getValue();
}
}
2018-10-05 14:32:05 -04:00
if ($cookiePairs)
{
2018-01-15 14:43:15 -05:00
return $request->withHeader("Cookie", \implode("; ", $cookiePairs));
}
return $request->withoutHeader("Cookie");
}
private function normalizeTraceRequest(Request $request): Request
{
$method = $request->getMethod();
2018-10-05 14:32:05 -04:00
if ($method !== 'TRACE')
{
2018-01-15 14:43:15 -05:00
return $request;
}
// https://tools.ietf.org/html/rfc7231#section-4.3.8
/** @var Request $request */
2018-10-05 14:32:05 -04:00
$request = $request->withBody(NULL);
2018-01-15 14:43:15 -05:00
// Remove all body and sensitive headers
$request = $request->withHeaders([
"Transfer-Encoding" => [],
"Content-Length" => [],
"Authorization" => [],
"Proxy-Authorization" => [],
"Cookie" => [],
]);
return $request;
}
2018-10-05 14:32:05 -04:00
private function doRequest(Request $request, Uri $uri, array $options, Response $previousResponse = NULL, CancellationToken $cancellation): Promise
2018-01-15 14:43:15 -05:00
{
$deferred = new Deferred;
$requestCycle = new RequestCycle;
$requestCycle->request = $request;
$requestCycle->uri = $uri;
$requestCycle->options = $options;
$requestCycle->previousResponse = $previousResponse;
$requestCycle->deferred = $deferred;
$requestCycle->bodyDeferred = new Deferred;
$requestCycle->body = new Emitter;
$requestCycle->cancellation = $cancellation;
$protocolVersions = $request->getProtocolVersions();
2018-10-05 14:32:05 -04:00
if (\in_array("1.1", $protocolVersions, TRUE))
{
2018-01-15 14:43:15 -05:00
$requestCycle->protocolVersion = "1.1";
2018-10-05 14:32:05 -04:00
} elseif (\in_array("1.0", $protocolVersions, TRUE))
{
2018-01-15 14:43:15 -05:00
$requestCycle->protocolVersion = "1.0";
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
return new Failure(new HttpException(
"None of the requested protocol versions are supported: " . \implode(", ", $protocolVersions)
));
}
asyncCall(function () use ($requestCycle) {
2018-10-05 14:32:05 -04:00
try
{
2018-01-15 14:43:15 -05:00
yield from $this->doWrite($requestCycle);
2018-10-05 14:32:05 -04:00
} catch (\Throwable $e)
{
2018-01-15 14:43:15 -05:00
$this->fail($requestCycle, $e);
}
});
return $deferred->promise();
}
private function doWrite(RequestCycle $requestCycle)
{
$timeout = $requestCycle->options[self::OP_TRANSFER_TIMEOUT];
$timeoutToken = new NullCancellationToken;
2018-10-05 14:32:05 -04:00
if ($timeout > 0)
{
2018-01-15 14:43:15 -05:00
$transferTimeoutWatcher = Loop::delay($timeout, function () use ($requestCycle, $timeout) {
$this->fail($requestCycle, new TimeoutException(
sprintf('Allowed transfer timeout exceeded: %d ms', $timeout)
));
});
$requestCycle->bodyDeferred->promise()->onResolve(static function () use ($transferTimeoutWatcher) {
Loop::cancel($transferTimeoutWatcher);
});
$timeoutToken = new TimeoutCancellationToken($timeout);
}
$authority = $this->generateAuthorityFromUri($requestCycle->uri);
$socketCheckoutUri = $requestCycle->uri->getScheme() . "://{$authority}";
$connectTimeoutToken = new CombinedCancellationToken($requestCycle->cancellation, $timeoutToken);
2018-10-05 14:32:05 -04:00
try
{
2018-01-15 14:43:15 -05:00
/** @var ClientSocket $socket */
$socket = yield $this->socketPool->checkout($socketCheckoutUri, $connectTimeoutToken);
$requestCycle->socket = $socket;
2018-10-05 14:32:05 -04:00
} catch (ResolutionException $dnsException)
{
2018-01-15 14:43:15 -05:00
throw new DnsException(\sprintf("Resolving the specified domain failed: '%s'", $requestCycle->uri->getHost()), 0, $dnsException);
2018-10-05 14:32:05 -04:00
} catch (ConnectException $e)
{
2018-01-15 14:43:15 -05:00
throw new SocketException(\sprintf("Connection to '%s' failed", $authority), 0, $e);
2018-10-05 14:32:05 -04:00
} catch (CancelledException $e)
{
2018-01-15 14:43:15 -05:00
// In case of a user cancellation request, throw the expected exception
$requestCycle->cancellation->throwIfRequested();
// Otherwise we ran into a timeout of our TimeoutCancellationToken
throw new SocketException(\sprintf("Connection to '%s' timed out", $authority), 0, $e);
}
$cancellation = $requestCycle->cancellation->subscribe(function ($error) use ($requestCycle) {
$this->fail($requestCycle, $error);
});
2018-10-05 14:32:05 -04:00
try
{
if ($requestCycle->uri->getScheme() === 'https')
{
2018-01-15 14:43:15 -05:00
$tlsContext = $this->tlsContext
->withPeerName($requestCycle->uri->getHost())
->withPeerCapturing();
yield $socket->enableCrypto($tlsContext);
}
// Collect this here, because it fails in case the remote closes the connection directly.
$connectionInfo = $this->collectConnectionInfo($socket);
$rawHeaders = $this->generateRawRequestHeaders($requestCycle->request, $requestCycle->protocolVersion);
yield $socket->write($rawHeaders);
$body = $requestCycle->request->getBody()->createBodyStream();
$chunking = $requestCycle->request->getHeader("transfer-encoding") === "chunked";
$remainingBytes = $requestCycle->request->getHeader("content-length");
2018-10-05 14:32:05 -04:00
if ($chunking && $requestCycle->protocolVersion === "1.0")
{
2018-01-15 14:43:15 -05:00
throw new HttpException("Can't send chunked bodies over HTTP/1.0");
}
// We always buffer the last chunk to make sure we don't write $contentLength bytes if the body is too long.
$buffer = "";
2018-10-05 14:32:05 -04:00
while (NULL !== $chunk = yield $body->read())
{
2018-01-15 14:43:15 -05:00
$requestCycle->cancellation->throwIfRequested();
2018-10-05 14:32:05 -04:00
if ($chunk === "")
{
2018-01-15 14:43:15 -05:00
continue;
}
2018-10-05 14:32:05 -04:00
if ($chunking)
{
2018-01-15 14:43:15 -05:00
$chunk = \dechex(\strlen($chunk)) . "\r\n" . $chunk . "\r\n";
}/* elseif ($remainingBytes !== null) {
$remainingBytes -= \strlen($chunk);
if ($remainingBytes < 0) {
throw new HttpException("Body contained more bytes than specified in Content-Length, aborting request");
}
}*/
yield $socket->write($buffer);
$buffer = $chunk;
}
// Flush last buffered chunk.
yield $socket->write($buffer);
2018-10-05 14:32:05 -04:00
if ($chunking)
{
2018-01-15 14:43:15 -05:00
yield $socket->write("0\r\n\r\n");
}/* elseif ($remainingBytes !== null && $remainingBytes > 0) {
throw new HttpException("Body contained fewer bytes than specified in Content-Length, aborting request");
}*/
yield from $this->doRead($requestCycle, $socket, $connectionInfo);
2018-10-05 14:32:05 -04:00
} finally
{
2018-01-15 14:43:15 -05:00
$requestCycle->cancellation->unsubscribe($cancellation);
}
}
private function fail(RequestCycle $requestCycle, \Throwable $error)
{
$toFails = [];
2018-10-05 14:32:05 -04:00
$socket = NULL;
2018-01-15 14:43:15 -05:00
2018-10-05 14:32:05 -04:00
if ($requestCycle->deferred)
{
2018-01-15 14:43:15 -05:00
$toFails[] = $requestCycle->deferred;
2018-10-05 14:32:05 -04:00
$requestCycle->deferred = NULL;
2018-01-15 14:43:15 -05:00
}
2018-10-05 14:32:05 -04:00
if ($requestCycle->body)
{
2018-01-15 14:43:15 -05:00
$toFails[] = $requestCycle->body;
2018-10-05 14:32:05 -04:00
$requestCycle->body = NULL;
2018-01-15 14:43:15 -05:00
}
2018-10-05 14:32:05 -04:00
if ($requestCycle->bodyDeferred)
{
2018-01-15 14:43:15 -05:00
$toFails[] = $requestCycle->bodyDeferred;
2018-10-05 14:32:05 -04:00
$requestCycle->bodyDeferred = NULL;
2018-01-15 14:43:15 -05:00
}
2018-10-05 14:32:05 -04:00
if ($requestCycle->socket)
{
2018-01-15 14:43:15 -05:00
$this->socketPool->clear($requestCycle->socket);
$socket = $requestCycle->socket;
2018-10-05 14:32:05 -04:00
$requestCycle->socket = NULL;
2018-01-15 14:43:15 -05:00
$socket->close();
}
2018-10-05 14:32:05 -04:00
foreach ($toFails as $toFail)
{
2018-01-15 14:43:15 -05:00
$toFail->fail($error);
}
}
private function collectConnectionInfo(ClientSocket $socket): ConnectionInfo
{
2018-10-05 14:32:05 -04:00
$crypto = \stream_get_meta_data($socket->getResource())["crypto"] ?? NULL;
2018-01-15 14:43:15 -05:00
return new ConnectionInfo(
$socket->getLocalAddress(),
$socket->getRemoteAddress(),
2018-10-05 14:32:05 -04:00
$crypto ? TlsInfo::fromMetaData($crypto, \stream_context_get_options($socket->getResource())["ssl"]) : NULL
2018-01-15 14:43:15 -05:00
);
}
/**
* @param Request $request
* @param string $protocolVersion
*
* @return string
*
* @TODO Send absolute URIs in the request line when using a proxy server
* Right now this doesn't matter because all proxy requests use a CONNECT
* tunnel but this likely will not always be the case.
*/
private function generateRawRequestHeaders(Request $request, string $protocolVersion): string
{
$uri = $request->getUri();
$uri = new Uri($uri);
$requestUri = $uri->getPath() ?: '/';
2018-10-05 14:32:05 -04:00
if ($query = $uri->getQuery())
{
2018-01-15 14:43:15 -05:00
$requestUri .= '?' . $query;
}
$head = $request->getMethod() . ' ' . $requestUri . ' HTTP/' . $protocolVersion . "\r\n";
2018-10-05 14:32:05 -04:00
$headers = $request->getHeaders(TRUE);
2018-01-15 14:43:15 -05:00
2018-10-05 14:32:05 -04:00
foreach ($headers as $field => $values)
2018-01-15 14:43:15 -05:00
{
2018-10-05 14:32:05 -04:00
if (\strcspn($field, "\r\n") !== \strlen($field))
2018-01-15 14:43:15 -05:00
{
throw new HttpException("Blocked header injection attempt for header '{$field}'");
}
2018-10-05 14:32:05 -04:00
foreach ($values as $value)
{
if (\strcspn($value, "\r\n") !== \strlen($value))
{
2018-01-15 14:43:15 -05:00
throw new HttpException("Blocked header injection attempt for header '{$field}' with value '{$value}'");
}
$head .= "{$field}: {$value}\r\n";
}
}
$head .= "\r\n";
return $head;
}
private function doRead(RequestCycle $requestCycle, ClientSocket $socket, ConnectionInfo $connectionInfo): \Generator
{
2018-10-05 14:32:05 -04:00
try
{
2018-01-15 14:43:15 -05:00
$backpressure = new Success;
$bodyCallback = $requestCycle->options[self::OP_DISCARD_BODY]
2018-10-05 14:32:05 -04:00
? NULL
2018-01-15 14:43:15 -05:00
: static function ($data) use ($requestCycle, &$backpressure) {
$backpressure = $requestCycle->body->emit($data);
};
$parser = new Parser($bodyCallback);
$parser->enqueueResponseMethodMatch($requestCycle->request->getMethod());
$parser->setAllOptions([
Parser::OP_MAX_HEADER_BYTES => $requestCycle->options[self::OP_MAX_HEADER_BYTES],
Parser::OP_MAX_BODY_BYTES => $requestCycle->options[self::OP_MAX_BODY_BYTES],
]);
2018-10-05 14:32:05 -04:00
while (NULL !== $chunk = yield $socket->read())
{
2018-01-15 14:43:15 -05:00
$requestCycle->cancellation->throwIfRequested();
$parseResult = $parser->parse($chunk);
2018-10-05 14:32:05 -04:00
if ( ! $parseResult)
{
2018-01-15 14:43:15 -05:00
continue;
}
$parseResult["headers"] = \array_change_key_case($parseResult["headers"], \CASE_LOWER);
$response = $this->finalizeResponse($requestCycle, $parseResult, $connectionInfo);
$shouldCloseSocketAfterResponse = $this->shouldCloseSocketAfterResponse($response);
2018-10-05 14:32:05 -04:00
$ignoreIncompleteBodyCheck = FALSE;
2018-01-15 14:43:15 -05:00
$responseHeaders = $response->getHeaders();
2018-10-05 14:32:05 -04:00
if ($requestCycle->deferred)
{
2018-01-15 14:43:15 -05:00
$deferred = $requestCycle->deferred;
2018-10-05 14:32:05 -04:00
$requestCycle->deferred = NULL;
2018-01-15 14:43:15 -05:00
$deferred->resolve($response);
2018-10-05 14:32:05 -04:00
$response = NULL; // clear references
$deferred = NULL; // there's also a reference in the deferred
} else
{
2018-01-15 14:43:15 -05:00
return;
}
// Required, otherwise responses without body hang
2018-10-05 14:32:05 -04:00
if ($parseResult["headersOnly"])
{
2018-01-15 14:43:15 -05:00
// Directly parse again in case we already have the full body but aborted parsing
// to resolve promise with headers.
2018-10-05 14:32:05 -04:00
$chunk = NULL;
2018-01-15 14:43:15 -05:00
2018-10-05 14:32:05 -04:00
do
{
try
{
2018-01-15 14:43:15 -05:00
$parseResult = $parser->parse($chunk);
2018-10-05 14:32:05 -04:00
} catch (ParseException $e)
{
2018-01-15 14:43:15 -05:00
$this->fail($requestCycle, $e);
throw $e;
}
2018-10-05 14:32:05 -04:00
if ($parseResult)
{
2018-01-15 14:43:15 -05:00
break;
}
2018-10-05 14:32:05 -04:00
if ( ! $backpressure instanceof Success)
{
2018-01-15 14:43:15 -05:00
yield $this->withCancellation($backpressure, $requestCycle->cancellation);
}
2018-10-05 14:32:05 -04:00
if ($requestCycle->bodyTooLarge)
{
2018-01-15 14:43:15 -05:00
throw new HttpException("Response body exceeded the specified size limit");
}
2018-10-05 14:32:05 -04:00
} while (NULL !== $chunk = yield $socket->read());
2018-01-15 14:43:15 -05:00
$parserState = $parser->getState();
2018-10-05 14:32:05 -04:00
if ($parserState !== Parser::AWAITING_HEADERS)
{
2018-01-15 14:43:15 -05:00
// Ignore check if neither content-length nor chunked encoding are given.
$ignoreIncompleteBodyCheck = $parserState === Parser::BODY_IDENTITY_EOF &&
2018-10-05 14:32:05 -04:00
! isset($responseHeaders["content-length"]) &&
2018-01-15 14:43:15 -05:00
strcasecmp('identity', $responseHeaders['transfer-encoding'][0] ?? "");
2018-10-05 14:32:05 -04:00
if ( ! $ignoreIncompleteBodyCheck)
{
2018-01-15 14:43:15 -05:00
throw new SocketException(sprintf(
'Socket disconnected prior to response completion (Parser state: %s)',
$parserState
));
}
}
}
2018-10-05 14:32:05 -04:00
if ($shouldCloseSocketAfterResponse || $ignoreIncompleteBodyCheck)
{
2018-01-15 14:43:15 -05:00
$this->socketPool->clear($socket);
$socket->close();
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
$this->socketPool->checkin($socket);
}
2018-10-05 14:32:05 -04:00
$requestCycle->socket = NULL;
2018-01-15 14:43:15 -05:00
// Complete body AFTER socket checkin, so the socket can be reused for a potential redirect
$body = $requestCycle->body;
2018-10-05 14:32:05 -04:00
$requestCycle->body = NULL;
2018-01-15 14:43:15 -05:00
$bodyDeferred = $requestCycle->bodyDeferred;
2018-10-05 14:32:05 -04:00
$requestCycle->bodyDeferred = NULL;
2018-01-15 14:43:15 -05:00
$body->complete();
$bodyDeferred->resolve();
return;
}
2018-10-05 14:32:05 -04:00
} catch (\Throwable $e)
{
2018-01-15 14:43:15 -05:00
$this->fail($requestCycle, $e);
return;
}
2018-10-05 14:32:05 -04:00
if ($socket->getResource() !== NULL)
{
$requestCycle->socket = NULL;
2018-01-15 14:43:15 -05:00
$this->socketPool->clear($socket);
$socket->close();
}
// Required, because if the write fails, the read() call immediately resolves.
yield new Delayed(0);
2018-10-05 14:32:05 -04:00
if ($requestCycle->deferred === NULL)
{
2018-01-15 14:43:15 -05:00
return;
}
$parserState = $parser->getState();
2018-10-05 14:32:05 -04:00
if ($parserState === Parser::AWAITING_HEADERS && $requestCycle->retryCount < 1)
{
2018-01-15 14:43:15 -05:00
$requestCycle->retryCount++;
yield from $this->doWrite($requestCycle);
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
$this->fail($requestCycle, new SocketException(sprintf(
'Socket disconnected prior to response completion (Parser state: %s)',
$parserState
)));
}
}
private function finalizeResponse(RequestCycle $requestCycle, array $parserResult, ConnectionInfo $connectionInfo)
{
$body = new IteratorStream($requestCycle->body->iterate());
2018-10-05 14:32:05 -04:00
if ($encoding = $this->determineCompressionEncoding($parserResult["headers"]))
{
2018-01-15 14:43:15 -05:00
$body = new ZlibInputStream($body, $encoding);
}
// Wrap the input stream so we can discard the body in case it's destructed but hasn't been consumed.
// This allows reusing the connection for further requests. It's important to have __destruct in InputStream and
// not in Message, because an InputStream might be pulled out of Message and used separately.
2018-10-05 14:32:05 -04:00
$body = new class($body, $requestCycle, $this->socketPool) implements InputStream {
2018-01-15 14:43:15 -05:00
private $body;
private $bodySize = 0;
private $requestCycle;
private $socketPool;
2018-10-05 14:32:05 -04:00
private $successfulEnd = FALSE;
2018-01-15 14:43:15 -05:00
public function __construct(InputStream $body, RequestCycle $requestCycle, HttpSocketPool $socketPool)
{
$this->body = $body;
$this->requestCycle = $requestCycle;
$this->socketPool = $socketPool;
}
public function read(): Promise
{
$promise = $this->body->read();
$promise->onResolve(function ($error, $value) {
2018-10-05 14:32:05 -04:00
if ($value !== NULL)
{
2018-01-15 14:43:15 -05:00
$this->bodySize += \strlen($value);
$maxBytes = $this->requestCycle->options[Client::OP_MAX_BODY_BYTES];
2018-10-05 14:32:05 -04:00
if ($maxBytes !== 0 && $this->bodySize >= $maxBytes)
{
$this->requestCycle->bodyTooLarge = TRUE;
2018-01-15 14:43:15 -05:00
}
2018-10-05 14:32:05 -04:00
} elseif ($error === NULL)
{
$this->successfulEnd = TRUE;
2018-01-15 14:43:15 -05:00
}
});
return $promise;
}
public function __destruct()
{
2018-10-05 14:32:05 -04:00
if ( ! $this->successfulEnd && $this->requestCycle->socket)
{
2018-01-15 14:43:15 -05:00
$this->socketPool->clear($this->requestCycle->socket);
$socket = $this->requestCycle->socket;
2018-10-05 14:32:05 -04:00
$this->requestCycle->socket = NULL;
2018-01-15 14:43:15 -05:00
$socket->close();
}
}
};
2018-10-05 14:32:05 -04:00
$response = new class($parserResult["protocol"], $parserResult["status"], $parserResult["reason"], $parserResult["headers"], $body, $requestCycle->request, $requestCycle->previousResponse, new MetaInfo($connectionInfo)) implements Response {
2018-01-15 14:43:15 -05:00
private $protocolVersion;
private $status;
private $reason;
private $request;
private $previousResponse;
private $headers;
private $body;
private $metaInfo;
public function __construct(
string $protocolVersion,
int $status,
string $reason,
array $headers,
InputStream $body,
Request $request,
2018-10-05 14:32:05 -04:00
Response $previousResponse = NULL,
2018-01-15 14:43:15 -05:00
MetaInfo $metaInfo
)
{
$this->protocolVersion = $protocolVersion;
$this->status = $status;
$this->reason = $reason;
$this->headers = $headers;
$this->body = new Message($body);
$this->request = $request;
$this->previousResponse = $previousResponse;
$this->metaInfo = $metaInfo;
}
public function getProtocolVersion(): string
{
return $this->protocolVersion;
}
public function getStatus(): int
{
return $this->status;
}
public function getReason(): string
{
return $this->reason;
}
public function getRequest(): Request
{
return $this->request;
}
public function getOriginalRequest(): Request
{
2018-10-05 14:32:05 -04:00
if (empty($this->previousResponse))
{
2018-01-15 14:43:15 -05:00
return $this->request;
}
return $this->previousResponse->getOriginalRequest();
}
public function getPreviousResponse()
{
return $this->previousResponse;
}
public function hasHeader(string $field): bool
{
return isset($this->headers[\strtolower($field)]);
}
public function getHeader(string $field)
{
2018-10-05 14:32:05 -04:00
return $this->headers[\strtolower($field)][0] ?? NULL;
2018-01-15 14:43:15 -05:00
}
public function getHeaderArray(string $field): array
{
return $this->headers[\strtolower($field)] ?? [];
}
public function getHeaders(): array
{
return $this->headers;
}
public function getBody(): Message
{
return $this->body;
}
public function getMetaInfo(): MetaInfo
{
return $this->metaInfo;
}
};
2018-10-05 14:32:05 -04:00
if ($response->hasHeader('Set-Cookie'))
{
2018-01-15 14:43:15 -05:00
$requestDomain = $requestCycle->uri->getHost();
$cookies = $response->getHeaderArray('Set-Cookie');
2018-10-05 14:32:05 -04:00
foreach ($cookies as $rawCookieStr)
{
2018-01-15 14:43:15 -05:00
$this->storeResponseCookie($requestDomain, $rawCookieStr);
}
}
return $response;
}
private function determineCompressionEncoding(array $responseHeaders): int
{
2018-10-05 14:32:05 -04:00
if ( ! $this->hasZlib)
{
2018-01-15 14:43:15 -05:00
return 0;
}
2018-10-05 14:32:05 -04:00
if ( ! isset($responseHeaders["content-encoding"]))
{
2018-01-15 14:43:15 -05:00
return 0;
}
$contentEncodingHeader = \trim(\current($responseHeaders["content-encoding"]));
2018-10-05 14:32:05 -04:00
if (strcasecmp($contentEncodingHeader, 'gzip') === 0)
{
2018-01-15 14:43:15 -05:00
return \ZLIB_ENCODING_GZIP;
}
2018-10-05 14:32:05 -04:00
if (strcasecmp($contentEncodingHeader, 'deflate') === 0)
{
2018-01-15 14:43:15 -05:00
return \ZLIB_ENCODING_DEFLATE;
}
return 0;
}
private function storeResponseCookie(string $requestDomain, string $rawCookieStr)
{
2018-10-05 14:32:05 -04:00
try
{
2018-01-15 14:43:15 -05:00
$cookie = Cookie::fromString($rawCookieStr);
2018-10-05 14:32:05 -04:00
if ( ! $cookie->getDomain())
{
2018-01-15 14:43:15 -05:00
$cookie = $cookie->withDomain($requestDomain);
2018-10-05 14:32:05 -04:00
} else
{
2018-01-15 14:43:15 -05:00
// https://tools.ietf.org/html/rfc6265#section-4.1.2.3
$cookieDomain = $cookie->getDomain();
// If a domain is set, left dots are ignored and it's always a wildcard
$cookieDomain = \ltrim($cookieDomain, ".");
2018-10-05 14:32:05 -04:00
if ($cookieDomain !== $requestDomain)
{
2018-01-15 14:43:15 -05:00
// ignore cookies on domains that are public suffixes
2018-10-05 14:32:05 -04:00
if (PublicSuffixList::isPublicSuffix($cookieDomain))
{
2018-01-15 14:43:15 -05:00
return;
}
// cookie origin would not be included when sending the cookie
2018-10-05 14:32:05 -04:00
if (\substr($requestDomain, 0, -\strlen($cookieDomain) - 1) . "." . $cookieDomain !== $requestDomain)
{
2018-01-15 14:43:15 -05:00
return;
}
}
// always add the dot, it's used internally for wildcard matching when an explicit domain is sent
$cookie = $cookie->withDomain("." . $cookieDomain);
}
$this->cookieJar->store($cookie);
2018-10-05 14:32:05 -04:00
} catch (CookieFormatException $e)
{
2018-01-15 14:43:15 -05:00
// Ignore malformed Set-Cookie headers
}
}
private function shouldCloseSocketAfterResponse(Response $response)
{
$request = $response->getRequest();
$requestConnHeader = $request->getHeader('Connection');
$responseConnHeader = $response->getHeader('Connection');
2018-10-05 14:32:05 -04:00
if ($requestConnHeader && ! strcasecmp($requestConnHeader, 'close'))
{
return TRUE;
} elseif ($responseConnHeader && ! strcasecmp($responseConnHeader, 'close'))
{
return TRUE;
} elseif ($response->getProtocolVersion() === '1.0' && ! $responseConnHeader)
{
return TRUE;
2018-01-15 14:43:15 -05:00
}
2018-10-05 14:32:05 -04:00
return FALSE;
2018-01-15 14:43:15 -05:00
}
private function withCancellation(Promise $promise, CancellationToken $cancellationToken): Promise
{
$deferred = new Deferred;
$newPromise = $deferred->promise();
$promise->onResolve(function ($error, $value) use (&$deferred) {
2018-10-05 14:32:05 -04:00
if ($deferred)
{
if ($error)
{
2018-01-15 14:43:15 -05:00
$deferred->fail($error);
2018-10-05 14:32:05 -04:00
$deferred = NULL;
} else
{
2018-01-15 14:43:15 -05:00
$deferred->resolve($value);
2018-10-05 14:32:05 -04:00
$deferred = NULL;
2018-01-15 14:43:15 -05:00
}
}
});
$cancellationSubscription = $cancellationToken->subscribe(function ($e) use (&$deferred) {
2018-10-05 14:32:05 -04:00
if ($deferred)
{
2018-01-15 14:43:15 -05:00
$deferred->fail($e);
2018-10-05 14:32:05 -04:00
$deferred = NULL;
2018-01-15 14:43:15 -05:00
}
});
$newPromise->onResolve(function () use ($cancellationToken, $cancellationSubscription) {
$cancellationToken->unsubscribe($cancellationSubscription);
});
return $newPromise;
}
private function getRedirectUri(Response $response)
{
2018-10-05 14:32:05 -04:00
if ( ! $response->hasHeader('Location'))
{
return NULL;
2018-01-15 14:43:15 -05:00
}
$request = $response->getRequest();
$status = $response->getStatus();
$method = $request->getMethod();
2018-10-05 14:32:05 -04:00
if ($status < 300 || $status > 399 || $method === 'HEAD')
{
return NULL;
2018-01-15 14:43:15 -05:00
}
$requestUri = new Uri($request->getUri());
$redirectLocation = $response->getHeader('Location');
2018-10-05 14:32:05 -04:00
try
{
2018-01-15 14:43:15 -05:00
return $requestUri->resolve($redirectLocation);
2018-10-05 14:32:05 -04:00
} catch (InvalidUriException $e)
{
return NULL;
2018-01-15 14:43:15 -05:00
}
}
/**
* Clients must not add a Referer header when leaving an unencrypted resource and redirecting to an encrypted
* resource.
*
* @param Request $request
* @param string $refererUri
* @param string $newUri
*
* @return Request
*
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3
*/
private function assignRedirectRefererHeader(Request $request, string $refererUri, string $newUri): Request
{
$refererIsEncrypted = (\stripos($refererUri, 'https') === 0);
$destinationIsEncrypted = (\stripos($newUri, 'https') === 0);
2018-10-05 14:32:05 -04:00
if ( ! $refererIsEncrypted || $destinationIsEncrypted)
{
2018-01-15 14:43:15 -05:00
return $request->withHeader('Referer', $refererUri);
}
return $request->withoutHeader('Referer');
}
/**
* Set multiple options at once.
*
* @param array $options An array of the form [OP_CONSTANT => $value]
*
* @throws \Error On unknown option key or invalid value.
*/
public function setOptions(array $options)
{
2018-10-05 14:32:05 -04:00
foreach ($options as $option => $value)
{
2018-01-15 14:43:15 -05:00
$this->setOption($option, $value);
}
}
/**
* Set an option.
*
* @param string $option A Client option constant
* @param mixed $value The option value to assign
*
* @throws \Error On unknown option key or invalid value.
*/
public function setOption(string $option, $value)
{
$this->validateOption($option, $value);
$this->options[$option] = $value;
}
}