14use Psr\Log\LoggerInterface;
15use Shellbox\Command\BoxedCommand;
27use Wikimedia\RequestTimeout\TimeoutException;
28use Wikimedia\Timestamp\ConvertibleTimestamp;
29use Wikimedia\Timestamp\TimestampFormat as TS;
41 private const DEFAULT_HTTP_OPTIONS = [
'httpVersion' =>
'v1.1' ];
42 private const AUTH_FAILURE_ERROR =
'Could not connect due to prior authentication failure';
133 parent::__construct( $config );
135 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
136 $this->swiftUser = $config[
'swiftUser'];
137 $this->swiftKey = $config[
'swiftKey'];
139 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
140 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
141 $this->canShellboxGetTempUrl = $config[
'canShellboxGetTempUrl'] ??
false;
142 $this->shellboxIpRange = $config[
'shellboxIpRange'] ??
null;
143 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
144 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
145 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
146 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
150 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
151 if ( isset( $config[$optionName] ) ) {
152 $httpOptions[$optionName] = $config[$optionName];
156 $this->http->setLogger( $this->logger );
161 $this->containerStatCache =
new MapCacheLRU( 300 );
163 if ( !empty( $config[
'cacheAuthInfo'] ) ) {
168 $this->readUsers = $config[
'readUsers'] ?? [];
169 $this->writeUsers = $config[
'writeUsers'] ?? [];
170 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
171 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
176 $this->maxFileSize = 5 * 1024 * 1024 * 1024;
181 $this->http->setLogger(
$logger );
187 self::ATTR_UNICODE_PATHS |
195 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
197 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
201 return $relStoragePath;
206 [ $container, $rel ] = $this->resolveStoragePathReal( $storagePath );
207 if ( $rel ===
null ) {
211 return is_array( $this->getContainerStat( $container ) );
224 $contentHeaders = [];
226 foreach ( $headers as $name => $value ) {
227 $name = strtolower( $name );
228 if ( $name ===
'x-delete-at' && is_numeric( $value ) ) {
230 $contentHeaders[$name] = $value;
231 } elseif ( $name ===
'x-delete-after' && is_numeric( $value ) ) {
233 $contentHeaders[$name] = $value;
234 } elseif ( preg_match(
'/^(x-)?content-(?!length$)/', $name ) ) {
236 $contentHeaders[$name] = $value;
237 } elseif ( $name ===
'content-type' && $value !==
'' ) {
239 $contentHeaders[$name] = $value;
243 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
246 $offset = $maxLength - strlen( $contentHeaders[
'content-disposition'] );
248 $pos = strrpos( $contentHeaders[
'content-disposition'],
';', $offset );
249 $contentHeaders[
'content-disposition'] = $pos ===
false
251 : trim( substr( $contentHeaders[
'content-disposition'], 0, $pos ) );
255 return $contentHeaders;
264 $metadataHeaders = [];
265 foreach ( $headers as $name => $value ) {
266 $name = strtolower( $name );
267 if ( str_starts_with( $name,
'x-object-meta-' ) ) {
268 $metadataHeaders[$name] = $value;
272 return $metadataHeaders;
281 $prefixLen = strlen(
'x-object-meta-' );
284 foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) {
285 $metadata[substr( $name, $prefixLen )] = $value;
293 $status = $this->newStatus();
295 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
296 if ( $dstRel ===
null ) {
297 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
303 $mutableHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
305 $mutableHeaders[
'content-type']
306 ??= $this->getContentType( $params[
'dst'], $params[
'content'],
null );
310 'container' => $dstCont,
311 'relPath' => $dstRel,
312 'headers' => array_merge(
315 'etag' => md5( $params[
'content'] ),
316 'content-length' => strlen( $params[
'content'] ),
317 'x-object-meta-sha1base36' =>
318 \
Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
321 'body' => $params[
'content']
324 $method = __METHOD__;
325 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
326 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
327 if ( $rcode === 201 || $rcode === 202 ) {
329 } elseif ( $rcode === 412 ) {
330 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
332 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
335 return SwiftFileOpHandle::CONTINUE_IF_OK;
339 if ( !empty( $params[
'async'] ) ) {
340 $status->value = $opHandle;
342 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
350 $status = $this->newStatus();
352 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
353 if ( $dstRel ===
null ) {
354 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
363 $srcHandle = @fopen( $params[
'src'],
'rb' );
364 if ( $srcHandle ===
false ) {
365 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
371 $srcSize = fstat( $srcHandle )[
'size'];
372 $md5Context = hash_init(
'md5' );
373 $sha1Context = hash_init(
'sha1' );
375 while ( !feof( $srcHandle ) ) {
376 $buffer = (string)fread( $srcHandle, 131_072 );
377 hash_update( $md5Context, $buffer );
378 hash_update( $sha1Context, $buffer );
379 $hashDigestSize += strlen( $buffer );
382 rewind( $srcHandle );
384 if ( $hashDigestSize !== $srcSize ) {
385 $status->fatal(
'backend-fail-hash', $params[
'src'] );
391 $mutableHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
393 $mutableHeaders[
'content-type']
394 ??= $this->getContentType( $params[
'dst'],
null, $params[
'src'] );
398 'container' => $dstCont,
399 'relPath' => $dstRel,
400 'headers' => array_merge(
403 'content-length' => $srcSize,
404 'etag' => hash_final( $md5Context ),
405 'x-object-meta-sha1base36' =>
406 \
Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
412 $method = __METHOD__;
413 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
414 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
415 if ( $rcode === 201 || $rcode === 202 ) {
417 } elseif ( $rcode === 412 ) {
418 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
420 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
423 return SwiftFileOpHandle::CONTINUE_IF_OK;
427 $opHandle->resourcesToClose[] = $srcHandle;
429 if ( !empty( $params[
'async'] ) ) {
430 $status->value = $opHandle;
432 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
440 $status = $this->newStatus();
442 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
443 if ( $srcRel ===
null ) {
444 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
449 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
450 if ( $dstRel ===
null ) {
451 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
458 'container' => $dstCont,
459 'relPath' => $dstRel,
460 'headers' => array_merge(
461 $this->extractMutableContentHeaders( $params[
'headers'] ?? [] ),
463 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
464 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
469 $method = __METHOD__;
470 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
471 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
472 if ( $rcode === 201 ) {
474 } elseif ( $rcode === 404 ) {
475 if ( empty( $params[
'ignoreMissingSource'] ) ) {
476 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
479 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
482 return SwiftFileOpHandle::CONTINUE_IF_OK;
486 if ( !empty( $params[
'async'] ) ) {
487 $status->value = $opHandle;
489 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
497 $status = $this->newStatus();
499 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
500 if ( $srcRel ===
null ) {
501 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
506 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
507 if ( $dstRel ===
null ) {
508 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
515 'container' => $dstCont,
516 'relPath' => $dstRel,
517 'headers' => array_merge(
518 $this->extractMutableContentHeaders( $params[
'headers'] ?? [] ),
520 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
521 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
525 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
527 'method' =>
'DELETE',
528 'container' => $srcCont,
529 'relPath' => $srcRel,
534 $method = __METHOD__;
535 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
536 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
537 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
539 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
541 } elseif ( $rcode === 404 ) {
542 if ( empty( $params[
'ignoreMissingSource'] ) ) {
543 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
546 return SwiftFileOpHandle::CONTINUE_NO;
549 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
552 return SwiftFileOpHandle::CONTINUE_IF_OK;
556 if ( !empty( $params[
'async'] ) ) {
557 $status->value = $opHandle;
559 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
567 $status = $this->newStatus();
569 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
570 if ( $srcRel ===
null ) {
571 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
577 'method' =>
'DELETE',
578 'container' => $srcCont,
579 'relPath' => $srcRel,
583 $method = __METHOD__;
584 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
585 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
586 if ( $rcode === 204 ) {
588 } elseif ( $rcode === 404 ) {
589 if ( empty( $params[
'ignoreMissingSource'] ) ) {
590 $status->fatal(
'backend-fail-delete', $params[
'src'] );
593 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
596 return SwiftFileOpHandle::CONTINUE_IF_OK;
600 if ( !empty( $params[
'async'] ) ) {
601 $status->value = $opHandle;
603 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
611 $status = $this->newStatus();
613 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
614 if ( $srcRel ===
null ) {
615 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
621 $stat = $this->getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
622 if ( $stat && !isset( $stat[
'xattr'] ) ) {
623 $stat = $this->doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
626 $status->fatal(
'backend-fail-describe', $params[
'src'] );
634 $oldMetadataHeaders = [];
635 foreach ( $stat[
'xattr'][
'metadata'] as $name => $value ) {
636 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
638 $newContentHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
639 $oldContentHeaders = $stat[
'xattr'][
'headers'];
643 'container' => $srcCont,
644 'relPath' => $srcRel,
645 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
648 $method = __METHOD__;
649 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
650 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
651 if ( $rcode === 202 ) {
653 } elseif ( $rcode === 404 ) {
654 $status->fatal(
'backend-fail-describe', $params[
'src'] );
656 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
661 if ( !empty( $params[
'async'] ) ) {
662 $status->value = $opHandle;
664 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
674 $status = $this->newStatus();
677 $stat = $this->getContainerStat( $fullCont );
678 if ( is_array( $stat ) ) {
680 } elseif ( $stat === self::RES_ERROR ) {
681 $status->fatal(
'backend-fail-internal', $this->name );
682 $this->logger->error( __METHOD__ .
': cannot get container stat' );
685 $params[
'op'] =
'prepare';
686 $status->merge( $this->createContainer( $fullCont, $params ) );
694 $status = $this->newStatus();
695 if ( empty( $params[
'noAccess'] ) ) {
699 $stat = $this->getContainerStat( $fullCont );
700 if ( is_array( $stat ) ) {
701 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
702 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
704 $status->merge( $this->setContainerAccess(
709 } elseif ( $stat === self::RES_ABSENT ) {
710 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
712 $status->fatal(
'backend-fail-internal', $this->name );
713 $this->logger->error( __METHOD__ .
': cannot get container stat' );
721 $status = $this->newStatus();
722 if ( empty( $params[
'access'] ) ) {
726 $stat = $this->getContainerStat( $fullCont );
727 if ( is_array( $stat ) ) {
728 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
729 if ( !empty( $params[
'listing'] ) ) {
730 $readUsers[] =
'.rlistings';
732 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
735 $status->merge( $this->setContainerAccess(
740 } elseif ( $stat === self::RES_ABSENT ) {
741 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
743 $status->fatal(
'backend-fail-internal', $this->name );
744 $this->logger->error( __METHOD__ .
': cannot get container stat' );
752 $status = $this->newStatus();
755 if ( $dirRel !=
'' ) {
760 $stat = $this->getContainerStat( $fullCont,
true );
761 if ( $stat === self::RES_ABSENT ) {
763 } elseif ( $stat === self::RES_ERROR ) {
764 $status->fatal(
'backend-fail-internal', $this->name );
765 $this->logger->error( __METHOD__ .
': cannot get container stat' );
766 } elseif ( is_array( $stat ) && $stat[
'count'] == 0 ) {
768 $params[
'op'] =
'clean';
769 $status->merge( $this->deleteContainer( $fullCont, $params ) );
777 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
778 unset( $params[
'src'] );
779 $stats = $this->doGetFileStatMulti( $params );
781 return reset( $stats );
796 $timestamp =
new ConvertibleTimestamp( $ts );
798 return $timestamp->getTimestamp( $format );
799 }
catch ( TimeoutException $e ) {
801 }
catch ( Exception $e ) {
814 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
819 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
820 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
821 [
'path' =>
$path ] );
823 $objHdrs[
'x-object-meta-sha1base36'] =
false;
826 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
828 $postHeaders += $this->extractMetadataHeaders( $objHdrs );
830 $status = $this->newStatus();
832 $scopeLockS = $this->getScopedFileLocks( [
$path ], LockManager::LOCK_UW, $status );
833 if ( $status->isOK() ) {
834 $tmpFile = $this->getLocalCopy( [
'src' =>
$path,
'latest' => 1 ] );
836 $hash = $tmpFile->getSha1Base36();
837 if ( $hash !==
false ) {
838 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
840 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
841 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
842 [ $rcode ] = $this->requestWithAuth( [
844 'container' => $srcCont,
845 'relPath' => $srcRel,
846 'headers' => $postHeaders
848 if ( $rcode >= 200 && $rcode <= 299 ) {
849 $this->deleteFileCache(
$path );
857 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
858 [
'path' =>
$path ] );
865 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
871 $contents = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
872 foreach ( $params[
'srcs'] as
$path ) {
873 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
874 if ( $srcRel ===
null ) {
878 $handle = fopen(
'php://temp',
'wb' );
882 'container' => $srcCont,
883 'relPath' => $srcRel,
884 'headers' => $this->headersFromParams( $params ),
890 $reqs = $this->requestMultiWithAuth(
892 [
'maxConnsPerHost' => $params[
'concurrency'] ]
894 foreach ( $reqs as
$path => $op ) {
895 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
896 if ( $rcode >= 200 && $rcode <= 299 ) {
897 rewind( $op[
'stream'] );
898 $content = (string)stream_get_contents( $op[
'stream'] );
899 $size = strlen( $content );
901 if ( $size === (
int)$rhdrs[
'content-length'] ) {
902 $contents[
$path] = $content;
904 $contents[
$path] = self::RES_ERROR;
905 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
906 $this->onError(
null, __METHOD__,
907 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
909 } elseif ( $rcode === 404 ) {
910 $contents[
$path] = self::RES_ABSENT;
912 $contents[
$path] = self::RES_ERROR;
913 $this->onError(
null, __METHOD__,
914 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
916 fclose( $op[
'stream'] );
924 $prefix = ( $dirRel ==
'' ) ?
null :
"{$dirRel}/";
925 $status = $this->objectListing( $fullCont,
'names', 1,
null, $prefix );
926 if ( $status->isOK() ) {
927 return ( count( $status->value ) ) > 0;
930 return self::RES_ERROR;
968 if ( $after === INF ) {
973 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
975 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
977 if ( !empty( $params[
'topOnly'] ) ) {
978 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
979 if ( !$status->isOK() ) {
982 $objects = $status->value;
983 foreach ( $objects as $object ) {
984 if ( str_ends_with( $object,
'/' ) ) {
990 $getParentDir =
static function (
$path ) {
991 return (
$path !==
null && str_contains(
$path,
'/' ) ) ? dirname(
$path ) :
false;
995 $lastDir = $getParentDir( $after );
996 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
998 if ( !$status->isOK() ) {
1002 $objects = $status->value;
1004 foreach ( $objects as $object ) {
1005 $objectDir = $getParentDir( $object );
1007 if ( $objectDir !==
false && $objectDir !== $dir ) {
1012 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1015 $dirs[] =
"{$pDir}/";
1016 $pDir = $getParentDir( $pDir );
1017 }
while ( $pDir !==
false
1018 && strcmp( $pDir, $lastDir ) > 0
1019 && strlen( $pDir ) > strlen( $dir )
1022 $lastDir = $objectDir;
1027 if ( count( $objects ) < $limit ) {
1030 $after = end( $objects );
1049 if ( $after === INF ) {
1054 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
1056 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1059 if ( !empty( $params[
'topOnly'] ) ) {
1060 if ( !empty( $params[
'adviseStat'] ) ) {
1061 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1063 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1067 if ( !empty( $params[
'adviseStat'] ) ) {
1068 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix );
1070 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1075 if ( !$status->isOK() ) {
1079 $objects = $status->value;
1080 $files = $this->buildFileObjectListing( $objects );
1083 if ( count( $objects ) < $limit ) {
1086 $after = end( $objects );
1087 $after = is_object( $after ) ? $after->name : $after;
1100 private function buildFileObjectListing( array $objects ) {
1102 foreach ( $objects as $object ) {
1103 if ( is_object( $object ) ) {
1104 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1109 'mtime' => $this->convertSwiftDate( $object->last_modified, TS::MW ),
1110 'size' => (int)$object->bytes,
1113 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1116 $names[] = [ $object->name, $stat ];
1117 } elseif ( !str_ends_with( $object,
'/' ) ) {
1119 $names[] = [ $object, null ];
1133 $this->cheapCache->setField(
$path,
'stat', $val );
1138 $stat = $this->getFileStat( $params );
1140 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1141 $this->clearCache( [ $params[
'src'] ] );
1142 $stat = $this->getFileStat( $params );
1145 if ( is_array( $stat ) ) {
1146 return $stat[
'xattr'];
1149 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1156 $params[
'requireSHA1'] =
true;
1158 $stat = $this->getFileStat( $params );
1159 if ( is_array( $stat ) ) {
1160 return $stat[
'sha1'];
1163 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1168 $status = $this->newStatus();
1172 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
1173 if ( $srcRel ===
null ) {
1175 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1180 if ( !is_array( $this->getContainerStat( $srcCont ) ) ) {
1182 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1189 if ( $params[
'headers'] && !$this->fileExists( $params ) ) {
1191 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1197 if ( empty( $params[
'headless'] ) ) {
1198 foreach ( $params[
'headers'] as $header ) {
1199 $this->header( $header );
1203 if ( empty( $params[
'allowOB'] ) ) {
1205 $this->resetOutputBuffer();
1208 $handle = fopen(
'php://output',
'wb' );
1209 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1211 'container' => $srcCont,
1212 'relPath' => $srcRel,
1213 'headers' => $this->headersFromParams( $params ) + $params[
'options'],
1214 'stream' => $handle,
1215 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1218 if ( $rcode >= 200 && $rcode <= 299 ) {
1220 } elseif ( $rcode === 404 ) {
1221 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1225 $this->clearCache( [ $params[
'src'] ] );
1226 $this->deleteFileCache( $params[
'src'] );
1228 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1236 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1242 $tmpFiles = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
1243 foreach ( $params[
'srcs'] as
$path ) {
1244 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
1245 if ( $srcRel ===
null ) {
1251 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_', $ext );
1252 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1256 'container' => $srcCont,
1257 'relPath' => $srcRel,
1258 'headers' => $this->headersFromParams( $params ),
1259 'stream' => $handle,
1261 $tmpFiles[
$path] = $tmpFile;
1266 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1268 $reqs = $this->requestMultiWithAuth(
1270 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1272 foreach ( $reqs as
$path => $op ) {
1273 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1274 fclose( $op[
'stream'] );
1275 if ( $rcode >= 200 && $rcode <= 299 ) {
1277 $tmpFile = $tmpFiles[
$path];
1279 $size = $tmpFile->getSize();
1280 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1281 $tmpFiles[
$path] = self::RES_ERROR;
1282 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1283 $this->onError(
null, __METHOD__,
1284 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1287 $stat = $this->getStatFromHeaders( $rhdrs );
1288 $stat[
'latest'] = $latest;
1289 $this->cheapCache->setField(
$path,
'stat', $stat );
1290 } elseif ( $rcode === 404 ) {
1291 $tmpFiles[
$path] = self::RES_ABSENT;
1292 $this->cheapCache->setField(
1295 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1298 $tmpFiles[
$path] = self::RES_ERROR;
1299 $this->onError(
null, __METHOD__,
1300 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1311 if ( $this->canShellboxGetTempUrl ) {
1312 $urlParams = [
'src' => $params[
'src'] ];
1313 if ( $this->shellboxIpRange !==
null ) {
1314 $urlParams[
'ipRange'] = $this->shellboxIpRange;
1316 $url = $this->getFileHttpUrl( $urlParams );
1318 $command->inputFileFromUrl( $boxedName,
$url );
1319 return $this->newStatus();
1322 return parent::addShellboxInputFile( $command, $boxedName, $params );
1327 if ( $this->swiftTempUrlKey ==
'' &&
1328 ( $this->rgwS3AccessKey ==
'' || $this->rgwS3SecretKey !=
'' )
1330 $this->logger->debug(
"Can't get Swift file URL: no key available" );
1331 return self::TEMPURL_ERROR;
1334 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
1335 if ( $srcRel ===
null ) {
1336 $this->logger->debug(
"Can't get Swift file URL: can't resolve path" );
1337 return self::TEMPURL_ERROR;
1340 $auth = $this->getAuthentication();
1342 $this->logger->debug(
"Can't get Swift file URL: authentication failed" );
1343 return self::TEMPURL_ERROR;
1346 $method = $params[
'method'] ??
'GET';
1347 $ttl = $params[
'ttl'] ?? 86400;
1348 $expires = time() + $ttl;
1350 if ( $this->swiftTempUrlKey !=
'' ) {
1351 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1353 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1357 "{$contPath}/{$srcRel}"
1360 'temp_url_expires' => $expires,
1362 if ( isset( $params[
'ipRange'] ) ) {
1363 array_unshift( $messageParts,
"ip={$params['ipRange']}" );
1364 $query[
'temp_url_ip_range'] = $params[
'ipRange'];
1367 $signature = hash_hmac(
'sha1',
1368 implode(
"\n", $messageParts ),
1369 $this->swiftTempUrlKey
1371 $query = [
'temp_url_sig' => $signature ] + $query;
1373 return $url .
'?' . http_build_query( $query );
1376 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1377 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1379 $signature = base64_encode( hash_hmac(
1381 "{$method}\n\n\n{$expires}\n{$spath}",
1382 $this->rgwS3SecretKey,
1388 return str_replace(
'/swift/v1',
'', $this->storageUrl( $auth ) . $spath ) .
1391 'Signature' => $signature,
1392 'Expires' => $expires,
1393 'AWSAccessKeyId' => $this->rgwS3AccessKey
1413 if ( !empty( $params[
'latest'] ) ) {
1414 $hdrs[
'x-newest'] =
'true';
1423 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1429 $httpReqsByStage = [];
1430 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1431 $reqs = $fileOpHandle->httpOp;
1432 foreach ( $reqs as $stage => $req ) {
1433 $httpReqsByStage[$stage][$index] = $req;
1435 $statuses[$index] = $this->newStatus();
1439 $reqCount = count( $httpReqsByStage );
1440 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1441 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1442 foreach ( $httpReqs as $index => $httpReq ) {
1444 $fileOpHandle = $fileOpHandles[$index];
1446 $status = $statuses[$index];
1447 ( $fileOpHandle->callback )( $httpReq, $status );
1452 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1454 $stages = count( $fileOpHandle->httpOp );
1455 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1456 unset( $httpReqsByStage[$s][$index] );
1488 $status = $this->newStatus();
1490 [ $rcode, , , , ] = $this->requestWithAuth( [
1492 'container' => $container,
1494 'x-container-read' => implode(
',', $readUsers ),
1495 'x-container-write' => implode(
',', $writeUsers )
1499 if ( $rcode != 204 && $rcode !== 202 ) {
1500 $status->fatal(
'backend-fail-internal', $this->name );
1501 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1502 [
'rcode' => $rcode ] );
1518 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
1520 if ( $bypassCache ) {
1521 $this->containerStatCache->clear( $container );
1522 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1523 $this->primeContainerCache( [ $container ] );
1525 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1526 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1528 'container' => $container
1531 if ( $rcode === 204 ) {
1533 'count' => $rhdrs[
'x-container-object-count'],
1534 'bytes' => $rhdrs[
'x-container-bytes-used']
1536 if ( $bypassCache ) {
1539 $this->containerStatCache->setField( $container,
'stat', $stat );
1540 $this->setContainerCache( $container, $stat );
1542 } elseif ( $rcode === 404 ) {
1543 return self::RES_ABSENT;
1545 $this->onError(
null, __METHOD__,
1546 [
'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1548 return self::RES_ERROR;
1552 return $this->containerStatCache->getField( $container,
'stat' );
1563 $status = $this->newStatus();
1566 if ( empty( $params[
'noAccess'] ) ) {
1568 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1569 if ( empty( $params[
'noListing'] ) ) {
1570 $readUsers[] =
'.rlistings';
1572 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1575 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1576 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1579 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1581 'container' => $container,
1583 'x-container-read' => implode(
',', $readUsers ),
1584 'x-container-write' => implode(
',', $writeUsers )
1588 if ( $rcode === 201 ) {
1590 } elseif ( $rcode === 202 ) {
1593 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1607 $status = $this->newStatus();
1609 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1610 'method' =>
'DELETE',
1611 'container' => $container
1614 if ( $rcode >= 200 && $rcode <= 299 ) {
1615 $this->containerStatCache->clear( $container );
1616 } elseif ( $rcode === 404 ) {
1618 } elseif ( $rcode === 409 ) {
1619 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1621 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1639 private function objectListing(
1640 $fullCont, $type, $limit, $after =
null, $prefix =
null, $delim =
null
1642 $status = $this->newStatus();
1644 $query = [
'limit' => $limit ];
1645 if ( $type ===
'info' ) {
1646 $query[
'format'] =
'json';
1648 if ( $after !==
null ) {
1649 $query[
'marker'] = $after;
1651 if ( $prefix !==
null ) {
1652 $query[
'prefix'] = $prefix;
1654 if ( $delim !==
null ) {
1655 $query[
'delimiter'] = $delim;
1658 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1660 'container' => $fullCont,
1664 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1665 if ( $rcode === 200 ) {
1666 if ( $type ===
'info' ) {
1667 $status->value = json_decode( trim( $rbody ) );
1669 $status->value = explode(
"\n", trim( $rbody ) );
1671 } elseif ( $rcode === 204 ) {
1672 $status->value = [];
1673 } elseif ( $rcode === 404 ) {
1674 $status->value = [];
1676 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1684 foreach ( $containerInfo as $container => $info ) {
1685 $this->containerStatCache->setField( $container,
'stat', $info );
1695 foreach ( $params[
'srcs'] as
$path ) {
1696 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
1697 if ( $srcRel ===
null ) {
1699 $stats[
$path] = self::RES_ERROR;
1703 $cstat = $this->getContainerStat( $srcCont );
1704 if ( $cstat === self::RES_ABSENT ) {
1705 $stats[
$path] = self::RES_ABSENT;
1707 } elseif ( $cstat === self::RES_ERROR ) {
1708 $stats[
$path] = self::RES_ERROR;
1714 'container' => $srcCont,
1715 'relPath' => $srcRel,
1716 'headers' => $this->headersFromParams( $params )
1721 $reqs = $this->requestMultiWithAuth(
1723 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1725 foreach ( $reqs as
$path => $op ) {
1726 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1727 if ( $rcode === 200 || $rcode === 204 ) {
1729 if ( !empty( $params[
'requireSHA1'] ) ) {
1730 $rhdrs = $this->addMissingHashMetadata( $rhdrs,
$path );
1733 $stat = $this->getStatFromHeaders( $rhdrs );
1734 if ( $this->isRGW ) {
1735 $stat[
'latest'] =
true;
1737 } elseif ( $rcode === 404 ) {
1738 $stat = self::RES_ABSENT;
1740 $stat = self::RES_ERROR;
1741 $this->onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1743 $stats[
$path] = $stat;
1755 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1757 $headers = $this->extractMutableContentHeaders( $rhdrs );
1761 'mtime' => $this->convertSwiftDate( $rhdrs[
'last-modified'], TS::MW ),
1763 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1764 'sha1' => $metadata[
'sha1base36'] ??
null,
1766 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1767 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1777 if ( $this->authErrorTimestamp !==
null ) {
1778 $interval = time() - $this->authErrorTimestamp;
1779 if ( $interval < 60 ) {
1780 $this->logger->debug(
1781 'rejecting request since auth failure occurred {interval} seconds ago',
1782 [
'interval' => $interval ]
1786 $this->authErrorTimestamp =
null;
1790 if ( !$this->authCreds ) {
1791 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1792 $creds = $this->credentialCache->get( $cacheKey );
1794 isset( $creds[
'auth_token'] ) &&
1795 isset( $creds[
'storage_url'] ) &&
1796 isset( $creds[
'expiry_time'] ) &&
1797 $creds[
'expiry_time'] > time()
1800 $this->setAuthCreds( $creds );
1803 $this->refreshAuthentication();
1807 return $this->authCreds;
1815 private function setAuthCreds( ?array $creds ) {
1816 $this->logger->debug(
'Using auth token with expiry_time={expiry_time}',
1818 'expiry_time' => isset( $creds[
'expiry_time'] )
1819 ? gmdate(
'c', $creds[
'expiry_time'] ) :
'null'
1822 $this->authCreds = $creds;
1824 if ( $creds && str_ends_with( $creds[
'storage_url'],
'/v1' ) ) {
1825 $this->isRGW =
true;
1834 private function refreshAuthentication() {
1835 [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [
1837 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1839 'x-auth-user' => $this->swiftUser,
1840 'x-auth-key' => $this->swiftKey
1842 ], self::DEFAULT_HTTP_OPTIONS );
1844 if ( $rcode >= 200 && $rcode <= 299 ) {
1845 if ( isset( $rhdrs[
'x-auth-token-expires'] ) ) {
1846 $ttl = intval( $rhdrs[
'x-auth-token-expires'] );
1848 $ttl = $this->authTTL;
1850 $expiryTime = time() + $ttl;
1852 'auth_token' => $rhdrs[
'x-auth-token'],
1853 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url'],
1854 'expiry_time' => $expiryTime,
1856 $this->credentialCache->set(
1857 $this->getCredsCacheKey( $this->swiftUser ),
1861 } elseif ( $rcode === 401 ) {
1862 $this->onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1863 $this->authErrorTimestamp = time();
1866 $this->onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode, $rbody );
1867 $this->authErrorTimestamp = time();
1870 $this->setAuthCreds( $creds );
1880 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1881 $parts = [ $creds[
'storage_url'] ];
1882 if ( ( $container ??
'' ) !==
'' ) {
1883 $parts[] = rawurlencode( $container );
1885 if ( ( $object ??
'' ) !==
'' ) {
1886 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1889 return implode(
'/', $parts );
1897 return [
'x-auth-token' => $creds[
'auth_token'] ];
1906 private function getCredsCacheKey( $username ) {
1907 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1922 private function requestWithAuth( array $req ) {
1923 return $this->requestMultiWithAuth( [ $req ] )[0][
'response'];
1935 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1936 $remainingTries = 2;
1937 $auth = $this->getAuthentication();
1940 foreach ( $reqs as &$req ) {
1941 if ( !isset( $req[
'response'] ) ) {
1942 $req[
'response'] = $this->getAuthFailureResponse();
1947 foreach ( $reqs as &$req ) {
1948 '@phan-var array $req';
1949 if ( isset( $req[
'response'] ) ) {
1952 if ( $req[
'response'][
'code'] !== 401 ) {
1956 $req[
'headers'] = $this->authTokenHeaders( $auth ) + ( $req[
'headers'] ?? [] );
1957 $req[
'url'] = $this->storageUrl( $auth, $req[
'container'], $req[
'relPath'] ??
null );
1960 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1961 if ( --$remainingTries > 0 ) {
1963 foreach ( $reqs as $req ) {
1964 if ( $req[
'response'][
'code'] === 401 ) {
1965 $auth = $this->refreshAuthentication();
1983 private function getAuthFailureResponse() {
1993 'error' => self::AUTH_FAILURE_ERROR,
1994 4 => self::AUTH_FAILURE_ERROR
2010 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'', $body =
'' ) {
2011 if ( $code === 0 && $err === self::AUTH_FAILURE_ERROR ) {
2013 $status->fatal(
'backend-fail-connect', $this->name );
2019 $status->fatal(
'backend-fail-internal', $this->name );
2021 $msg =
"HTTP {code} ({desc}) in '{func}'";
2026 'req_params' => $params,
2030 $msgParams[
'err'] = $err;
2032 if ( $code == 502 ) {
2033 $msg .=
' ({truncatedBody})';
2034 $msgParams[
'truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
2036 $this->logger->error( $msg, $msgParams );
2041class_alias( SwiftFileBackend::class,
'SwiftFileBackend' );
Generic operation result class Has warning/error list, boolean status and arbitrary value.