From d2a00767b2064d209902b73e1a9eaddc951279f2 Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 31 Oct 2026 01:56:35 +0800 Subject: [PATCH] refactor(storage): share immutable artifact transport --- .../Cloud/CloudImmutableArtifactTransport.php | 215 +++++++++++++ .../Cloud/CloudRemoteArtifactFetcher.php | 300 ++++++++++++++++++ .../Cloud/CloudTemplateArtifactManager.php | 188 ++++------- .../Cloud/CloudTemplateRemoteFetcher.php | 230 +------------- 4 files changed, 591 insertions(+), 342 deletions(-) create mode 100644 web/app/Services/Cloud/CloudImmutableArtifactTransport.php create mode 100644 web/app/Services/Cloud/CloudRemoteArtifactFetcher.php diff --git a/web/app/Services/Cloud/CloudImmutableArtifactTransport.php b/web/app/Services/Cloud/CloudImmutableArtifactTransport.php new file mode 100644 index 00000000..54b33c87 --- /dev/null +++ b/web/app/Services/Cloud/CloudImmutableArtifactTransport.php @@ -0,0 +1,215 @@ +,credentials:array, + * revision:int} $runtime + * @param array{path:string,size_bytes:int,sha256:string} $file + * @return array{resolution:string,identity:?array,error_code:string, + * message:string} + */ + public function publish( + array $runtime, + string $objectKey, + array $file + ): array { + self::assertRuntime($runtime); + self::assertFile($file); + $client = $this->client ?? new CloudObjectStorageS3Client(); + try { + $identity = $client->putImmutableFile( + $runtime['config'], + $runtime['credentials'], + $objectKey, + $file['path'], + $file['size_bytes'], + $file['sha256'] + ); + return self::result('applied', $identity); + } catch (CloudObjectStorageTransferError $error) { + if (!$error->effectMayHaveApplied) { + return self::result( + 'not_applied', null, $error->publicCode, + $error->getMessage() + ); + } + $failureCode = $error->publicCode; + } catch (\Throwable $error) { + $failureCode = 'artifact_publish_failed'; + } + + try { + $identity = $client->inspectObject( + $runtime['config'], + $runtime['credentials'], + $objectKey + ); + } catch (\Throwable $error) { + return self::result( + 'unknown', null, 'artifact_publish_reconcile_unavailable', + '无法确认不可变对象是否已经保存' + ); + } + if ($identity === null) { + return self::result( + 'not_applied', null, $failureCode, + '对象存储已确认不可变对象未保存' + ); + } + if ((int) ($identity['size_bytes'] ?? 0) !== $file['size_bytes']) { + return self::result( + 'conflict', $identity, 'artifact_identity_mismatch', + '不可变对象大小与本地文件不一致' + ); + } + return self::result('applied', $identity); + } + + /** + * @param array{config:array,credentials:array, + * revision:int} $runtime + */ + public function inspect( + array $runtime, + string $objectKey, + string $versionId = '' + ): ?array { + self::assertRuntime($runtime); + return ($this->client ?? new CloudObjectStorageS3Client()) + ->inspectObject( + $runtime['config'], + $runtime['credentials'], + $objectKey, + $versionId + ); + } + + /** + * @param array{config:array,credentials:array, + * revision:int} $runtime + * @return array{size_bytes:int,etag:string,version_id:string} + */ + public function head( + array $runtime, + string $objectKey, + string $versionId = '' + ): array { + self::assertRuntime($runtime); + return ($this->client ?? new CloudObjectStorageS3Client())->headObject( + $runtime['config'], + $runtime['credentials'], + $objectKey, + $versionId + ); + } + + /** + * @param array{config:array,credentials:array, + * revision:int} $runtime + */ + public function presignedDownload( + array $runtime, + string $objectKey, + string $versionId, + int $expiresSeconds + ): string { + self::assertRuntime($runtime); + return ($this->client ?? new CloudObjectStorageS3Client()) + ->presignedVersionedGet( + $runtime['config'], + $runtime['credentials'], + $objectKey, + $versionId, + $expiresSeconds + ); + } + + /** + * @param array{config:array,credentials:array, + * revision:int} $runtime + */ + public function deleteExact( + array $runtime, + string $objectKey, + string $versionId + ): void { + self::assertRuntime($runtime); + ($this->client ?? new CloudObjectStorageS3Client())->deleteObject( + $runtime['config'], + $runtime['credentials'], + $objectKey, + $versionId + ); + } + + /** @param array $identity */ + public static function identityMatches( + array $identity, + int $sizeBytes, + string $etag, + string $versionId + ): bool { + return (int) ($identity['size_bytes'] ?? -1) === $sizeBytes + && is_string($identity['etag'] ?? null) + && hash_equals($etag, (string) $identity['etag']) + && is_string($identity['version_id'] ?? null) + && hash_equals($versionId, (string) $identity['version_id']); + } + + /** @return array{resolution:string,identity:?array,error_code:string,message:string} */ + private static function result( + string $resolution, + ?array $identity = null, + string $errorCode = '', + string $message = '' + ): array { + return [ + 'resolution' => $resolution, + 'identity' => $identity, + 'error_code' => $errorCode, + 'message' => $message, + ]; + } + + /** @param array $runtime */ + private static function assertRuntime(array $runtime): void + { + if (!is_array($runtime['config'] ?? null) + || !is_array($runtime['credentials'] ?? null) + || !is_int($runtime['revision'] ?? null) + || (int) $runtime['revision'] < 1) { + throw new \InvalidArgumentException( + 'Immutable artifact storage runtime is invalid' + ); + } + } + + /** @param array $file */ + private static function assertFile(array $file): void + { + if (!is_string($file['path'] ?? null) + || !is_int($file['size_bytes'] ?? null) + || (int) $file['size_bytes'] < 1 + || !is_string($file['sha256'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', $file['sha256']) !== 1) { + throw new \InvalidArgumentException( + 'Immutable artifact file identity is invalid' + ); + } + } +} diff --git a/web/app/Services/Cloud/CloudRemoteArtifactFetcher.php b/web/app/Services/Cloud/CloudRemoteArtifactFetcher.php new file mode 100644 index 00000000..2f929282 --- /dev/null +++ b/web/app/Services/Cloud/CloudRemoteArtifactFetcher.php @@ -0,0 +1,300 @@ +|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} */ + 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 */ + 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 */ + 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, + ]; + } +} diff --git a/web/app/Services/Cloud/CloudTemplateArtifactManager.php b/web/app/Services/Cloud/CloudTemplateArtifactManager.php index ef550073..75baebe6 100644 --- a/web/app/Services/Cloud/CloudTemplateArtifactManager.php +++ b/web/app/Services/Cloud/CloudTemplateArtifactManager.php @@ -78,45 +78,54 @@ final class CloudTemplateArtifactManager throw new CloudError('模板主副本不在可发布状态', 409); } $runtime = self::runtime($artifact); - $s3 = $client ?? new CloudObjectStorageS3Client(); - try { - $identity = $s3->putImmutableFile( - $runtime['config'], - $runtime['credentials'], - (string) $artifact->object_key, - (string) $file['path'], - (int) $file['size_bytes'], - (string) $file['sha256'] + $publication = (new CloudImmutableArtifactTransport($client))->publish( + $runtime, + (string) $artifact->object_key, + [ + 'path' => (string) $file['path'], + 'size_bytes' => (int) $file['size_bytes'], + 'sha256' => (string) $file['sha256'], + ] + ); + $resolution = (string) ($publication['resolution'] ?? 'unknown'); + if ($resolution !== 'applied') { + $unknown = in_array($resolution, ['unknown', 'conflict'], true); + $code = match ($resolution) { + 'unknown' => 'template_source_reconcile_unavailable', + 'conflict' => 'template_source_identity_mismatch', + default => (string) ($publication['error_code'] ?? + 'template_source_publish_failed'), + }; + if ($code === 'artifact_publish_failed') { + $code = 'template_source_publish_failed'; + } + self::recordPublishFailure( + (string) $template->id, + $code, + $unknown ); - } catch (CloudObjectStorageTransferError $error) { - if (!$error->effectMayHaveApplied) { - self::recordPublishFailure( - (string) $template->id, - $error->publicCode, - false + if ($resolution === 'unknown') { + throw new CloudError( + '无法确认模板主副本是否已保存,记录已锁定,请勿重新导入', + 502 ); - throw new CloudError($error->getMessage(), 502); } - $identity = self::reconcileUnknownPublish( - $template, - $artifact, - $file, - $runtime, - $s3, - $error->publicCode - ); - } catch (\Throwable $error) { - // An unclassified failure may still have happened after PUT was - // dispatched. Reconcile the reserved exact key before deciding. - $identity = self::reconcileUnknownPublish( - $template, - $artifact, - $file, - $runtime, - $s3, - 'template_source_publish_failed' + if ($resolution === 'conflict') { + throw new CloudError( + '模板主副本对象大小与导入文件不一致,记录已锁定', + 409 + ); + } + throw new CloudError( + (string) ($publication['message'] ?? + '对象存储已确认模板主副本未保存'), + 502 ); } + $identity = $publication['identity'] ?? null; + if (!is_array($identity)) { + throw new CloudError('模板主副本对象身份无效', 502); + } return $artifact->getConnection()->transaction(static function () use ( $template, $identity @@ -146,68 +155,6 @@ final class CloudTemplateArtifactManager }, 3); } - /** - * Resolve one ambiguous immutable PUT using the already reserved exact - * object key. Absence is a proven failure; matching presence can finish - * publication; unavailable or conflicting evidence remains fenced. - * - * @param array{path:string,size_bytes:int,sha256:string} $file - * @param array{config:array, - * credentials:array,revision:int} $runtime - * @return array{size_bytes:int,etag:string,version_id:string} - */ - private static function reconcileUnknownPublish( - CloudTemplate $template, - CloudTemplateArtifact $artifact, - array $file, - array $runtime, - CloudObjectStorageS3Client $client, - string $failureCode - ): array { - try { - $identity = $client->inspectObject( - $runtime['config'], - $runtime['credentials'], - (string) $artifact->object_key - ); - } catch (\Throwable $error) { - self::recordPublishFailure( - (string) $template->id, - 'template_source_reconcile_unavailable', - true - ); - throw new CloudError( - '无法确认模板主副本是否已保存,记录已锁定,请勿重新导入', - 502 - ); - } - - if ($identity === null) { - self::recordPublishFailure( - (string) $template->id, - $failureCode, - false - ); - throw new CloudError('对象存储已确认模板主副本未保存', 502); - } - // The key contains the reserved random generation and the PUT payload - // is SHA-256-bound by SigV4. Exact-key presence plus the expected size - // is therefore sufficient to freeze the provider identity returned by - // HEAD; a size conflict must remain fenced for operator review. - if ((int) $identity['size_bytes'] !== (int) $file['size_bytes']) { - self::recordPublishFailure( - (string) $template->id, - 'template_source_identity_mismatch', - true - ); - throw new CloudError( - '模板主副本对象大小与导入文件不一致,记录已锁定', - 409 - ); - } - return $identity; - } - /** Return a bounded read capability after revalidating the frozen object. */ public static function downloadSource( CloudTemplate $template, @@ -223,24 +170,23 @@ final class CloudTemplateArtifactManager throw new CloudError('模板主副本尚未就绪', 409); } $runtime = self::runtime($artifact); - $s3 = $client ?? new CloudObjectStorageS3Client(); - $identity = $s3->headObject( - $runtime['config'], - $runtime['credentials'], + $transport = new CloudImmutableArtifactTransport($client); + $identity = $transport->head( + $runtime, (string) $artifact->object_key, (string) $artifact->object_version_id ); - if ((int) $identity['size_bytes'] !== (int) $artifact->size_bytes - || !hash_equals( - (string) $identity['etag'], - (string) $artifact->object_etag + if (!CloudImmutableArtifactTransport::identityMatches( + $identity, + (int) $artifact->size_bytes, + (string) $artifact->object_etag, + (string) $artifact->object_version_id )) { throw new CloudError('模板主副本对象身份已经变化', 409); } return [ - 'source_url' => $s3->presignedVersionedGet( - $runtime['config'], - $runtime['credentials'], + 'source_url' => $transport->presignedDownload( + $runtime, (string) $artifact->object_key, (string) $artifact->object_version_id, self::DOWNLOAD_SECONDS @@ -256,9 +202,8 @@ final class CloudTemplateArtifactManager ?CloudObjectStorageS3Client $client = null ): ?array { $runtime = self::runtime($artifact); - return ($client ?? new CloudObjectStorageS3Client())->inspectObject( - $runtime['config'], - $runtime['credentials'], + return (new CloudImmutableArtifactTransport($client))->inspect( + $runtime, (string) $artifact->object_key, (string) $artifact->object_version_id ); @@ -270,9 +215,8 @@ final class CloudTemplateArtifactManager ?CloudObjectStorageS3Client $client = null ): void { $runtime = self::runtime($artifact); - ($client ?? new CloudObjectStorageS3Client())->deleteObject( - $runtime['config'], - $runtime['credentials'], + (new CloudImmutableArtifactTransport($client))->deleteExact( + $runtime, (string) $artifact->object_key, (string) $artifact->object_version_id ); @@ -283,18 +227,12 @@ final class CloudTemplateArtifactManager CloudTemplateArtifact $artifact, array $identity ): bool { - return (int) ($identity['size_bytes'] ?? -1) - === (int) $artifact->size_bytes - && is_string($identity['etag'] ?? null) - && hash_equals( - (string) $artifact->object_etag, - (string) $identity['etag'] - ) - && is_string($identity['version_id'] ?? null) - && hash_equals( - (string) $artifact->object_version_id, - (string) $identity['version_id'] - ); + return CloudImmutableArtifactTransport::identityMatches( + $identity, + (int) $artifact->size_bytes, + (string) $artifact->object_etag, + (string) $artifact->object_version_id + ); } private static function recordPublishFailure(string $templateId, diff --git a/web/app/Services/Cloud/CloudTemplateRemoteFetcher.php b/web/app/Services/Cloud/CloudTemplateRemoteFetcher.php index eb5555ed..5c5baa7b 100644 --- a/web/app/Services/Cloud/CloudTemplateRemoteFetcher.php +++ b/web/app/Services/Cloud/CloudTemplateRemoteFetcher.php @@ -2,235 +2,31 @@ namespace App\Services\Cloud; -use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; -use GuzzleHttp\Exception\GuzzleException; -use GuzzleHttp\Psr7\Uri; -use GuzzleHttp\Psr7\UriResolver; -/** Secure, bounded panel-side acquisition for one canonical QCOW2 source. */ +/** Backward-stable cloud-template adapter for shared artifact acquisition. */ final class CloudTemplateRemoteFetcher { - private const MIN_BYTES = 1048576; - private const MAX_BYTES = 4294967296; - private const MAX_REDIRECTS = 5; - private const CHUNK_BYTES = 1048576; - - /** @var callable(string):list|null */ - private $resolver; + private CloudRemoteArtifactFetcher $fetcher; + /** @param null|callable(string):list $resolver */ public function __construct( - private readonly ?ClientInterface $http = null, + ?ClientInterface $http = null, ?callable $resolver = null ) { - $this->resolver = $resolver; + $this->fetcher = new CloudRemoteArtifactFetcher( + '云镜像', + 1048576, + 4294967296, + 'virt-cloud-template-', + $http, + $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('下载云镜像主副本失败', 502); - } - $status = $response->getStatusCode(); - if (in_array($status, [301, 302, 303, 307, 308], true)) { - if ($redirect === self::MAX_REDIRECTS) { - throw new CloudError('云镜像下载跳转次数过多', 422); - } - $location = trim($response->getHeaderLine('Location')); - if ($location === '' || strlen($location) > 2048) { - throw new CloudError('云镜像下载跳转地址无效', 422); - } - $current = (string) UriResolver::resolve( - new Uri($current), - new Uri($location) - ); - continue; - } - if ($status !== 200) { - throw new CloudError('远程云镜像下载请求被拒绝', 502); - } - $encoding = strtolower(trim( - $response->getHeaderLine('Content-Encoding') - )); - if ($encoding !== '' && $encoding !== 'identity') { - throw new CloudError('远程云镜像不能使用内容压缩传输', 422); - } - $declared = trim($response->getHeaderLine('Content-Length')); - if ($declared !== '' - && (preg_match('/^[0-9]+$/D', $declared) !== 1 - || (int) $declared < self::MIN_BYTES - || (int) $declared > self::MAX_BYTES)) { - throw new CloudError('远程云镜像大小超出允许范围', 413); - } - return $this->capture( - $response->getBody(), - $declared, - $expectedSha256 - ); - } - throw new CloudError('云镜像下载跳转状态无效', 502); - } - - /** @return array{0:string,1:list} */ - private function validatedTarget(string $url): array - { - if (strlen($url) > 2048 || preg_match('//u', $url) !== 1) { - throw new CloudError('云镜像地址无效', 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('云镜像跳转必须使用无凭据的 HTTPS 443 地址', 422); - } - $host = strtolower(trim((string) $parts['host'], '[]')); - $ips = ($this->resolver ?? self::resolve(...))($host); - if (!is_array($ips) || $ips === []) { - throw new CloudError('无法解析云镜像下载主机', 502); - } - $valid = []; - foreach (array_values(array_unique($ips)) as $ip) { - if (!is_string($ip) || !self::publicIp($ip)) { - throw new CloudError('云镜像地址解析到非公网地址', 422); - } - $valid[] = $ip; - } - return [$host, $valid]; - } - - /** @return list */ - 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 */ - 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(), 'virt-cloud-template-'); - if ($path === false) { - throw new CloudError('无法创建云镜像临时文件', 503); - } - @chmod($path, 0600); - $target = @fopen($path, 'wb'); - if ($target === false) { - @unlink($path); - throw new CloudError('无法写入云镜像临时文件', 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('读取远程云镜像失败', 502); - } - $bytes += strlen($chunk); - if ($bytes > self::MAX_BYTES) { - throw new CloudError('远程云镜像大小超出允许范围', 413); - } - if (!hash_update($hash, $chunk) - || fwrite($target, $chunk) !== strlen($chunk)) { - throw new CloudError('保存远程云镜像失败', 503); - } - } - if ($bytes < self::MIN_BYTES) { - throw new CloudError('远程云镜像文件过小', 422); - } - if ($declared !== '' && (int) $declared !== $bytes) { - throw new CloudError('远程云镜像长度与响应不一致', 502); - } - $sha256 = hash_final($hash); - if ($expectedSha256 !== '' - && !hash_equals($expectedSha256, $sha256)) { - throw new CloudError('远程云镜像 SHA-256 不匹配', 422); - } - if (!fflush($target)) { - throw new CloudError('保存远程云镜像失败', 503); - } - } catch (\Throwable $error) { - fclose($target); - @unlink($path); - throw $error; - } - fclose($target); - return [ - 'path' => $path, - 'size_bytes' => $bytes, - 'sha256' => $sha256, - ]; + return $this->fetcher->fetch($url, $expectedSha256); } }