You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
301 lines
10 KiB
PHP
301 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\ClientInterface;
|
|
use GuzzleHttp\Exception\GuzzleException;
|
|
use GuzzleHttp\Psr7\Uri;
|
|
use GuzzleHttp\Psr7\UriResolver;
|
|
|
|
/** Secure, bounded acquisition shared by immutable catalog artifacts. */
|
|
final class CloudRemoteArtifactFetcher
|
|
{
|
|
private const MAX_REDIRECTS = 5;
|
|
private const CHUNK_BYTES = 1048576;
|
|
|
|
/** @var callable(string):list<string>|null */
|
|
private $resolver;
|
|
|
|
public function __construct(
|
|
private readonly string $label,
|
|
private readonly int $minimumBytes,
|
|
private readonly int $maximumBytes,
|
|
private readonly string $temporaryPrefix,
|
|
private readonly ?ClientInterface $http = null,
|
|
?callable $resolver = null
|
|
) {
|
|
if ($label === '' || $minimumBytes < 1
|
|
|| $maximumBytes < $minimumBytes
|
|
|| preg_match('/^[A-Za-z0-9_.-]{1,48}$/D', $temporaryPrefix)
|
|
!== 1) {
|
|
throw new \InvalidArgumentException(
|
|
'Remote artifact acquisition policy is invalid'
|
|
);
|
|
}
|
|
$this->resolver = $resolver;
|
|
}
|
|
|
|
/** @return array{path:string,size_bytes:int,sha256:string} */
|
|
public function fetch(string $url, string $expectedSha256 = ''): array
|
|
{
|
|
$expectedSha256 = strtolower(trim($expectedSha256));
|
|
if ($expectedSha256 !== ''
|
|
&& preg_match('/^[a-f0-9]{64}$/D', $expectedSha256) !== 1) {
|
|
throw new CloudError('SHA-256 格式无效', 422);
|
|
}
|
|
$current = $url;
|
|
for ($redirect = 0; $redirect <= self::MAX_REDIRECTS; $redirect++) {
|
|
[$host, $ips] = $this->validatedTarget($current);
|
|
try {
|
|
$response = ($this->http ?? new Client())->request(
|
|
'GET',
|
|
$current,
|
|
$this->requestOptions($host, $ips)
|
|
);
|
|
} catch (GuzzleException $error) {
|
|
throw new CloudError(
|
|
'下载' . $this->label . '主副本失败',
|
|
502
|
|
);
|
|
}
|
|
$status = $response->getStatusCode();
|
|
if (in_array($status, [301, 302, 303, 307, 308], true)) {
|
|
if ($redirect === self::MAX_REDIRECTS) {
|
|
throw new CloudError(
|
|
$this->label . '下载跳转次数过多',
|
|
422
|
|
);
|
|
}
|
|
$location = trim($response->getHeaderLine('Location'));
|
|
if ($location === '' || strlen($location) > 2048) {
|
|
throw new CloudError(
|
|
$this->label . '下载跳转地址无效',
|
|
422
|
|
);
|
|
}
|
|
$current = (string) UriResolver::resolve(
|
|
new Uri($current),
|
|
new Uri($location)
|
|
);
|
|
continue;
|
|
}
|
|
if ($status !== 200) {
|
|
throw new CloudError(
|
|
'远程' . $this->label . '下载请求被拒绝',
|
|
502
|
|
);
|
|
}
|
|
$encoding = strtolower(trim(
|
|
$response->getHeaderLine('Content-Encoding')
|
|
));
|
|
if ($encoding !== '' && $encoding !== 'identity') {
|
|
throw new CloudError(
|
|
'远程' . $this->label . '不能使用内容压缩传输',
|
|
422
|
|
);
|
|
}
|
|
$declared = trim($response->getHeaderLine('Content-Length'));
|
|
if ($declared !== ''
|
|
&& (preg_match('/^[0-9]+$/D', $declared) !== 1
|
|
|| (int) $declared < $this->minimumBytes
|
|
|| (int) $declared > $this->maximumBytes)) {
|
|
throw new CloudError(
|
|
'远程' . $this->label . '大小超出允许范围',
|
|
413
|
|
);
|
|
}
|
|
return $this->capture(
|
|
$response->getBody(),
|
|
$declared,
|
|
$expectedSha256
|
|
);
|
|
}
|
|
throw new CloudError($this->label . '下载跳转状态无效', 502);
|
|
}
|
|
|
|
/** @return array{0:string,1:list<string>} */
|
|
private function validatedTarget(string $url): array
|
|
{
|
|
if (strlen($url) > 2048 || preg_match('//u', $url) !== 1) {
|
|
throw new CloudError($this->label . '地址无效', 422);
|
|
}
|
|
$parts = parse_url($url);
|
|
if (!is_array($parts)
|
|
|| strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
|
|
|| !is_string($parts['host'] ?? null)
|
|
|| trim((string) $parts['host']) === ''
|
|
|| isset($parts['user']) || isset($parts['pass'])
|
|
|| isset($parts['fragment'])
|
|
|| (isset($parts['port']) && (int) $parts['port'] !== 443)) {
|
|
throw new CloudError(
|
|
$this->label . '跳转必须使用无凭据的 HTTPS 443 地址',
|
|
422
|
|
);
|
|
}
|
|
$host = strtolower(trim((string) $parts['host'], '[]'));
|
|
$ips = ($this->resolver ?? self::resolve(...))($host);
|
|
if (!is_array($ips) || $ips === []) {
|
|
throw new CloudError(
|
|
'无法解析' . $this->label . '下载主机',
|
|
502
|
|
);
|
|
}
|
|
$valid = [];
|
|
foreach (array_values(array_unique($ips)) as $ip) {
|
|
if (!is_string($ip) || !self::publicIp($ip)) {
|
|
throw new CloudError(
|
|
$this->label . '地址解析到非公网地址',
|
|
422
|
|
);
|
|
}
|
|
$valid[] = $ip;
|
|
}
|
|
return [$host, $valid];
|
|
}
|
|
|
|
/** @return list<string> */
|
|
private static function resolve(string $host): array
|
|
{
|
|
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
|
|
return [$host];
|
|
}
|
|
$records = @dns_get_record($host, DNS_A | DNS_AAAA);
|
|
if (!is_array($records)) {
|
|
return [];
|
|
}
|
|
$ips = [];
|
|
foreach ($records as $record) {
|
|
if (is_string($record['ip'] ?? null)) {
|
|
$ips[] = $record['ip'];
|
|
}
|
|
if (is_string($record['ipv6'] ?? null)) {
|
|
$ips[] = $record['ipv6'];
|
|
}
|
|
}
|
|
return array_values(array_unique($ips));
|
|
}
|
|
|
|
private static function publicIp(string $ip): bool
|
|
{
|
|
return filter_var(
|
|
$ip,
|
|
FILTER_VALIDATE_IP,
|
|
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
|
|
) !== false;
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function requestOptions(string $host, array $ips): array
|
|
{
|
|
$options = [
|
|
'http_errors' => false,
|
|
'allow_redirects' => false,
|
|
'stream' => true,
|
|
'headers' => ['Accept-Encoding' => 'identity'],
|
|
'connect_timeout' => 10.0,
|
|
'timeout' => 900.0,
|
|
'verify' => true,
|
|
'proxy' => '',
|
|
];
|
|
if (defined('CURLOPT_RESOLVE')) {
|
|
$options['curl'] = [CURLOPT_RESOLVE => array_map(
|
|
static fn (string $ip): string => $host . ':443:'
|
|
. (str_contains($ip, ':') ? '[' . $ip . ']' : $ip),
|
|
$ips
|
|
)];
|
|
} elseif ($this->http === null) {
|
|
throw new CloudError('PHP cURL 不支持安全固定下载地址', 503);
|
|
}
|
|
return $options;
|
|
}
|
|
|
|
/** @return array{path:string,size_bytes:int,sha256:string} */
|
|
private function capture($stream, string $declared,
|
|
string $expectedSha256): array
|
|
{
|
|
$path = tempnam(sys_get_temp_dir(), $this->temporaryPrefix);
|
|
if ($path === false) {
|
|
throw new CloudError(
|
|
'无法创建' . $this->label . '临时文件',
|
|
503
|
|
);
|
|
}
|
|
@chmod($path, 0600);
|
|
$target = @fopen($path, 'wb');
|
|
if ($target === false) {
|
|
@unlink($path);
|
|
throw new CloudError(
|
|
'无法写入' . $this->label . '临时文件',
|
|
503
|
|
);
|
|
}
|
|
$hash = hash_init('sha256');
|
|
$bytes = 0;
|
|
try {
|
|
while (!$stream->eof()) {
|
|
$chunk = $stream->read(self::CHUNK_BYTES);
|
|
if ($chunk === '') {
|
|
if ($stream->eof()) {
|
|
break;
|
|
}
|
|
throw new CloudError(
|
|
'读取远程' . $this->label . '失败',
|
|
502
|
|
);
|
|
}
|
|
$bytes += strlen($chunk);
|
|
if ($bytes > $this->maximumBytes) {
|
|
throw new CloudError(
|
|
'远程' . $this->label . '大小超出允许范围',
|
|
413
|
|
);
|
|
}
|
|
if (!hash_update($hash, $chunk)
|
|
|| fwrite($target, $chunk) !== strlen($chunk)) {
|
|
throw new CloudError(
|
|
'保存远程' . $this->label . '失败',
|
|
503
|
|
);
|
|
}
|
|
}
|
|
if ($bytes < $this->minimumBytes) {
|
|
throw new CloudError(
|
|
'远程' . $this->label . '文件过小',
|
|
422
|
|
);
|
|
}
|
|
if ($declared !== '' && (int) $declared !== $bytes) {
|
|
throw new CloudError(
|
|
'远程' . $this->label . '长度与响应不一致',
|
|
502
|
|
);
|
|
}
|
|
$sha256 = hash_final($hash);
|
|
if ($expectedSha256 !== ''
|
|
&& !hash_equals($expectedSha256, $sha256)) {
|
|
throw new CloudError(
|
|
'远程' . $this->label . ' SHA-256 不匹配',
|
|
422
|
|
);
|
|
}
|
|
if (!fflush($target)) {
|
|
throw new CloudError(
|
|
'保存远程' . $this->label . '失败',
|
|
503
|
|
);
|
|
}
|
|
} catch (\Throwable $error) {
|
|
fclose($target);
|
|
@unlink($path);
|
|
throw $error;
|
|
}
|
|
fclose($target);
|
|
return [
|
|
'path' => $path,
|
|
'size_bytes' => $bytes,
|
|
'sha256' => $sha256,
|
|
];
|
|
}
|
|
}
|