15use Psr\Log\LoggerInterface;
16use Shellbox\Command\BoxedCommand;
19use Wikimedia\AtEase\AtEase;
28use Wikimedia\RequestTimeout\TimeoutException;
29use Wikimedia\Timestamp\ConvertibleTimestamp;
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'] );
362 AtEase::suppressWarnings();
363 $srcHandle = fopen( $params[
'src'],
'rb' );
364 AtEase::restoreWarnings();
365 if ( $srcHandle ===
false ) {
366 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
372 $srcSize = fstat( $srcHandle )[
'size'];
373 $md5Context = hash_init(
'md5' );
374 $sha1Context = hash_init(
'sha1' );
376 while ( !feof( $srcHandle ) ) {
377 $buffer = (string)fread( $srcHandle, 131_072 );
378 hash_update( $md5Context, $buffer );
379 hash_update( $sha1Context, $buffer );
380 $hashDigestSize += strlen( $buffer );
383 rewind( $srcHandle );
385 if ( $hashDigestSize !== $srcSize ) {
386 $status->fatal(
'backend-fail-hash', $params[
'src'] );
392 $mutableHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
394 $mutableHeaders[
'content-type']
395 ??= $this->getContentType( $params[
'dst'],
null, $params[
'src'] );
399 'container' => $dstCont,
400 'relPath' => $dstRel,
401 'headers' => array_merge(
404 'content-length' => $srcSize,
405 'etag' => hash_final( $md5Context ),
406 'x-object-meta-sha1base36' =>
407 \
Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
413 $method = __METHOD__;
414 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
415 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
416 if ( $rcode === 201 || $rcode === 202 ) {
418 } elseif ( $rcode === 412 ) {
419 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
421 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
424 return SwiftFileOpHandle::CONTINUE_IF_OK;
428 $opHandle->resourcesToClose[] = $srcHandle;
430 if ( !empty( $params[
'async'] ) ) {
431 $status->value = $opHandle;
433 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
441 $status = $this->newStatus();
443 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
444 if ( $srcRel ===
null ) {
445 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
450 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
451 if ( $dstRel ===
null ) {
452 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
459 'container' => $dstCont,
460 'relPath' => $dstRel,
461 'headers' => array_merge(
462 $this->extractMutableContentHeaders( $params[
'headers'] ?? [] ),
464 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
465 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
470 $method = __METHOD__;
471 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
472 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
473 if ( $rcode === 201 ) {
475 } elseif ( $rcode === 404 ) {
476 if ( empty( $params[
'ignoreMissingSource'] ) ) {
477 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
480 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
483 return SwiftFileOpHandle::CONTINUE_IF_OK;
487 if ( !empty( $params[
'async'] ) ) {
488 $status->value = $opHandle;
490 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
498 $status = $this->newStatus();
500 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
501 if ( $srcRel ===
null ) {
502 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
507 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
508 if ( $dstRel ===
null ) {
509 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
516 'container' => $dstCont,
517 'relPath' => $dstRel,
518 'headers' => array_merge(
519 $this->extractMutableContentHeaders( $params[
'headers'] ?? [] ),
521 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
522 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
526 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
528 'method' =>
'DELETE',
529 'container' => $srcCont,
530 'relPath' => $srcRel,
535 $method = __METHOD__;
536 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
537 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
538 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
540 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
542 } elseif ( $rcode === 404 ) {
543 if ( empty( $params[
'ignoreMissingSource'] ) ) {
544 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
547 return SwiftFileOpHandle::CONTINUE_NO;
550 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
553 return SwiftFileOpHandle::CONTINUE_IF_OK;
557 if ( !empty( $params[
'async'] ) ) {
558 $status->value = $opHandle;
560 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
568 $status = $this->newStatus();
570 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
571 if ( $srcRel ===
null ) {
572 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
578 'method' =>
'DELETE',
579 'container' => $srcCont,
580 'relPath' => $srcRel,
584 $method = __METHOD__;
585 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
586 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
587 if ( $rcode === 204 ) {
589 } elseif ( $rcode === 404 ) {
590 if ( empty( $params[
'ignoreMissingSource'] ) ) {
591 $status->fatal(
'backend-fail-delete', $params[
'src'] );
594 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
597 return SwiftFileOpHandle::CONTINUE_IF_OK;
601 if ( !empty( $params[
'async'] ) ) {
602 $status->value = $opHandle;
604 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
612 $status = $this->newStatus();
614 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
615 if ( $srcRel ===
null ) {
616 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
622 $stat = $this->getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
623 if ( $stat && !isset( $stat[
'xattr'] ) ) {
624 $stat = $this->doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
627 $status->fatal(
'backend-fail-describe', $params[
'src'] );
635 $oldMetadataHeaders = [];
636 foreach ( $stat[
'xattr'][
'metadata'] as $name => $value ) {
637 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
639 $newContentHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
640 $oldContentHeaders = $stat[
'xattr'][
'headers'];
644 'container' => $srcCont,
645 'relPath' => $srcRel,
646 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
649 $method = __METHOD__;
650 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
651 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
652 if ( $rcode === 202 ) {
654 } elseif ( $rcode === 404 ) {
655 $status->fatal(
'backend-fail-describe', $params[
'src'] );
657 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
662 if ( !empty( $params[
'async'] ) ) {
663 $status->value = $opHandle;
665 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
675 $status = $this->newStatus();
678 $stat = $this->getContainerStat( $fullCont );
679 if ( is_array( $stat ) ) {
681 } elseif ( $stat === self::RES_ERROR ) {
682 $status->fatal(
'backend-fail-internal', $this->name );
683 $this->logger->error( __METHOD__ .
': cannot get container stat' );
686 $params[
'op'] =
'prepare';
687 $status->merge( $this->createContainer( $fullCont, $params ) );
695 $status = $this->newStatus();
696 if ( empty( $params[
'noAccess'] ) ) {
700 $stat = $this->getContainerStat( $fullCont );
701 if ( is_array( $stat ) ) {
702 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
703 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
705 $status->merge( $this->setContainerAccess(
710 } elseif ( $stat === self::RES_ABSENT ) {
711 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
713 $status->fatal(
'backend-fail-internal', $this->name );
714 $this->logger->error( __METHOD__ .
': cannot get container stat' );
722 $status = $this->newStatus();
723 if ( empty( $params[
'access'] ) ) {
727 $stat = $this->getContainerStat( $fullCont );
728 if ( is_array( $stat ) ) {
729 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
730 if ( !empty( $params[
'listing'] ) ) {
731 $readUsers[] =
'.rlistings';
733 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
736 $status->merge( $this->setContainerAccess(
741 } elseif ( $stat === self::RES_ABSENT ) {
742 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
744 $status->fatal(
'backend-fail-internal', $this->name );
745 $this->logger->error( __METHOD__ .
': cannot get container stat' );
753 $status = $this->newStatus();
756 if ( $dirRel !=
'' ) {
761 $stat = $this->getContainerStat( $fullCont,
true );
762 if ( $stat === self::RES_ABSENT ) {
764 } elseif ( $stat === self::RES_ERROR ) {
765 $status->fatal(
'backend-fail-internal', $this->name );
766 $this->logger->error( __METHOD__ .
': cannot get container stat' );
767 } elseif ( is_array( $stat ) && $stat[
'count'] == 0 ) {
769 $params[
'op'] =
'clean';
770 $status->merge( $this->deleteContainer( $fullCont, $params ) );
778 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
779 unset( $params[
'src'] );
780 $stats = $this->doGetFileStatMulti( $params );
782 return reset( $stats );
797 $timestamp =
new ConvertibleTimestamp( $ts );
799 return $timestamp->getTimestamp( $format );
800 }
catch ( TimeoutException $e ) {
802 }
catch ( Exception $e ) {
815 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
820 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
821 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
822 [
'path' =>
$path ] );
824 $objHdrs[
'x-object-meta-sha1base36'] =
false;
827 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
829 $postHeaders += $this->extractMetadataHeaders( $objHdrs );
831 $status = $this->newStatus();
833 $scopeLockS = $this->getScopedFileLocks( [
$path ], LockManager::LOCK_UW, $status );
834 if ( $status->isOK() ) {
835 $tmpFile = $this->getLocalCopy( [
'src' =>
$path,
'latest' => 1 ] );
837 $hash = $tmpFile->getSha1Base36();
838 if ( $hash !==
false ) {
839 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
841 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
842 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
843 [ $rcode ] = $this->requestWithAuth( [
845 'container' => $srcCont,
846 'relPath' => $srcRel,
847 'headers' => $postHeaders
849 if ( $rcode >= 200 && $rcode <= 299 ) {
850 $this->deleteFileCache(
$path );
858 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
859 [
'path' =>
$path ] );
866 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
872 $contents = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
873 foreach ( $params[
'srcs'] as
$path ) {
874 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
875 if ( $srcRel ===
null ) {
879 $handle = fopen(
'php://temp',
'wb' );
883 'container' => $srcCont,
884 'relPath' => $srcRel,
885 'headers' => $this->headersFromParams( $params ),
891 $reqs = $this->requestMultiWithAuth(
893 [
'maxConnsPerHost' => $params[
'concurrency'] ]
895 foreach ( $reqs as
$path => $op ) {
896 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
897 if ( $rcode >= 200 && $rcode <= 299 ) {
898 rewind( $op[
'stream'] );
899 $content = (string)stream_get_contents( $op[
'stream'] );
900 $size = strlen( $content );
902 if ( $size === (
int)$rhdrs[
'content-length'] ) {
903 $contents[
$path] = $content;
905 $contents[
$path] = self::RES_ERROR;
906 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
907 $this->onError(
null, __METHOD__,
908 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
910 } elseif ( $rcode === 404 ) {
911 $contents[
$path] = self::RES_ABSENT;
913 $contents[
$path] = self::RES_ERROR;
914 $this->onError(
null, __METHOD__,
915 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
917 fclose( $op[
'stream'] );
925 $prefix = ( $dirRel ==
'' ) ?
null :
"{$dirRel}/";
926 $status = $this->objectListing( $fullCont,
'names', 1,
null, $prefix );
927 if ( $status->isOK() ) {
928 return ( count( $status->value ) ) > 0;
931 return self::RES_ERROR;
969 if ( $after === INF ) {
974 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
976 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
978 if ( !empty( $params[
'topOnly'] ) ) {
979 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
980 if ( !$status->isOK() ) {
983 $objects = $status->value;
984 foreach ( $objects as $object ) {
985 if ( str_ends_with( $object,
'/' ) ) {
991 $getParentDir =
static function (
$path ) {
992 return (
$path !==
null && str_contains(
$path,
'/' ) ) ? dirname(
$path ) :
false;
996 $lastDir = $getParentDir( $after );
997 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
999 if ( !$status->isOK() ) {
1003 $objects = $status->value;
1005 foreach ( $objects as $object ) {
1006 $objectDir = $getParentDir( $object );
1008 if ( $objectDir !==
false && $objectDir !== $dir ) {
1013 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1016 $dirs[] =
"{$pDir}/";
1017 $pDir = $getParentDir( $pDir );
1018 }
while ( $pDir !==
false
1019 && strcmp( $pDir, $lastDir ) > 0
1020 && strlen( $pDir ) > strlen( $dir )
1023 $lastDir = $objectDir;
1028 if ( count( $objects ) < $limit ) {
1031 $after = end( $objects );
1050 if ( $after === INF ) {
1055 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
1057 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1060 if ( !empty( $params[
'topOnly'] ) ) {
1061 if ( !empty( $params[
'adviseStat'] ) ) {
1062 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1064 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1068 if ( !empty( $params[
'adviseStat'] ) ) {
1069 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix );
1071 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1076 if ( !$status->isOK() ) {
1080 $objects = $status->value;
1081 $files = $this->buildFileObjectListing( $objects );
1084 if ( count( $objects ) < $limit ) {
1087 $after = end( $objects );
1088 $after = is_object( $after ) ? $after->name : $after;
1101 private function buildFileObjectListing( array $objects ) {
1103 foreach ( $objects as $object ) {
1104 if ( is_object( $object ) ) {
1105 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1110 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
1111 'size' => (int)$object->bytes,
1114 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1117 $names[] = [ $object->name, $stat ];
1118 } elseif ( !str_ends_with( $object,
'/' ) ) {
1120 $names[] = [ $object, null ];
1134 $this->cheapCache->setField(
$path,
'stat', $val );
1139 $stat = $this->getFileStat( $params );
1141 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1142 $this->clearCache( [ $params[
'src'] ] );
1143 $stat = $this->getFileStat( $params );
1146 if ( is_array( $stat ) ) {
1147 return $stat[
'xattr'];
1150 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1157 $params[
'requireSHA1'] =
true;
1159 $stat = $this->getFileStat( $params );
1160 if ( is_array( $stat ) ) {
1161 return $stat[
'sha1'];
1164 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1169 $status = $this->newStatus();
1173 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
1174 if ( $srcRel ===
null ) {
1176 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1181 if ( !is_array( $this->getContainerStat( $srcCont ) ) ) {
1183 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1190 if ( $params[
'headers'] && !$this->fileExists( $params ) ) {
1192 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1198 if ( empty( $params[
'headless'] ) ) {
1199 foreach ( $params[
'headers'] as $header ) {
1200 $this->header( $header );
1204 if ( empty( $params[
'allowOB'] ) ) {
1206 $this->resetOutputBuffer();
1209 $handle = fopen(
'php://output',
'wb' );
1210 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1212 'container' => $srcCont,
1213 'relPath' => $srcRel,
1214 'headers' => $this->headersFromParams( $params ) + $params[
'options'],
1215 'stream' => $handle,
1216 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1219 if ( $rcode >= 200 && $rcode <= 299 ) {
1221 } elseif ( $rcode === 404 ) {
1222 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1226 $this->clearCache( [ $params[
'src'] ] );
1227 $this->deleteFileCache( $params[
'src'] );
1229 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1237 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1243 $tmpFiles = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
1244 foreach ( $params[
'srcs'] as
$path ) {
1245 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
1246 if ( $srcRel ===
null ) {
1252 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_', $ext );
1253 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1257 'container' => $srcCont,
1258 'relPath' => $srcRel,
1259 'headers' => $this->headersFromParams( $params ),
1260 'stream' => $handle,
1262 $tmpFiles[
$path] = $tmpFile;
1267 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1269 $reqs = $this->requestMultiWithAuth(
1271 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1273 foreach ( $reqs as
$path => $op ) {
1274 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1275 fclose( $op[
'stream'] );
1276 if ( $rcode >= 200 && $rcode <= 299 ) {
1278 $tmpFile = $tmpFiles[
$path];
1280 $size = $tmpFile->getSize();
1281 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1282 $tmpFiles[
$path] = self::RES_ERROR;
1283 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1284 $this->onError(
null, __METHOD__,
1285 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1288 $stat = $this->getStatFromHeaders( $rhdrs );
1289 $stat[
'latest'] = $latest;
1290 $this->cheapCache->setField(
$path,
'stat', $stat );
1291 } elseif ( $rcode === 404 ) {
1292 $tmpFiles[
$path] = self::RES_ABSENT;
1293 $this->cheapCache->setField(
1296 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1299 $tmpFiles[
$path] = self::RES_ERROR;
1300 $this->onError(
null, __METHOD__,
1301 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1312 if ( $this->canShellboxGetTempUrl ) {
1313 $urlParams = [
'src' => $params[
'src'] ];
1314 if ( $this->shellboxIpRange !==
null ) {
1315 $urlParams[
'ipRange'] = $this->shellboxIpRange;
1317 $url = $this->getFileHttpUrl( $urlParams );
1319 $command->inputFileFromUrl( $boxedName,
$url );
1320 return $this->newStatus();
1323 return parent::addShellboxInputFile( $command, $boxedName, $params );
1328 if ( $this->swiftTempUrlKey ==
'' &&
1329 ( $this->rgwS3AccessKey ==
'' || $this->rgwS3SecretKey !=
'' )
1331 $this->logger->debug(
"Can't get Swift file URL: no key available" );
1332 return self::TEMPURL_ERROR;
1335 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
1336 if ( $srcRel ===
null ) {
1337 $this->logger->debug(
"Can't get Swift file URL: can't resolve path" );
1338 return self::TEMPURL_ERROR;
1341 $auth = $this->getAuthentication();
1343 $this->logger->debug(
"Can't get Swift file URL: authentication failed" );
1344 return self::TEMPURL_ERROR;
1347 $method = $params[
'method'] ??
'GET';
1348 $ttl = $params[
'ttl'] ?? 86400;
1349 $expires = time() + $ttl;
1351 if ( $this->swiftTempUrlKey !=
'' ) {
1352 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1354 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1358 "{$contPath}/{$srcRel}"
1361 'temp_url_expires' => $expires,
1363 if ( isset( $params[
'ipRange'] ) ) {
1364 array_unshift( $messageParts,
"ip={$params['ipRange']}" );
1365 $query[
'temp_url_ip_range'] = $params[
'ipRange'];
1368 $signature = hash_hmac(
'sha1',
1369 implode(
"\n", $messageParts ),
1370 $this->swiftTempUrlKey
1372 $query = [
'temp_url_sig' => $signature ] + $query;
1374 return $url .
'?' . http_build_query( $query );
1377 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1378 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1380 $signature = base64_encode( hash_hmac(
1382 "{$method}\n\n\n{$expires}\n{$spath}",
1383 $this->rgwS3SecretKey,
1389 return str_replace(
'/swift/v1',
'', $this->storageUrl( $auth ) . $spath ) .
1392 'Signature' => $signature,
1393 'Expires' => $expires,
1394 'AWSAccessKeyId' => $this->rgwS3AccessKey
1414 if ( !empty( $params[
'latest'] ) ) {
1415 $hdrs[
'x-newest'] =
'true';
1424 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1430 $httpReqsByStage = [];
1431 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1432 $reqs = $fileOpHandle->httpOp;
1433 foreach ( $reqs as $stage => $req ) {
1434 $httpReqsByStage[$stage][$index] = $req;
1436 $statuses[$index] = $this->newStatus();
1440 $reqCount = count( $httpReqsByStage );
1441 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1442 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1443 foreach ( $httpReqs as $index => $httpReq ) {
1445 $fileOpHandle = $fileOpHandles[$index];
1447 $status = $statuses[$index];
1448 ( $fileOpHandle->callback )( $httpReq, $status );
1453 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1455 $stages = count( $fileOpHandle->httpOp );
1456 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1457 unset( $httpReqsByStage[$s][$index] );
1489 $status = $this->newStatus();
1491 [ $rcode, , , , ] = $this->requestWithAuth( [
1493 'container' => $container,
1495 'x-container-read' => implode(
',', $readUsers ),
1496 'x-container-write' => implode(
',', $writeUsers )
1500 if ( $rcode != 204 && $rcode !== 202 ) {
1501 $status->fatal(
'backend-fail-internal', $this->name );
1502 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1503 [
'rcode' => $rcode ] );
1519 $ps = $this->scopedProfileSection( __METHOD__ .
"-{$this->name}" );
1521 if ( $bypassCache ) {
1522 $this->containerStatCache->clear( $container );
1523 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1524 $this->primeContainerCache( [ $container ] );
1526 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1527 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1529 'container' => $container
1532 if ( $rcode === 204 ) {
1534 'count' => $rhdrs[
'x-container-object-count'],
1535 'bytes' => $rhdrs[
'x-container-bytes-used']
1537 if ( $bypassCache ) {
1540 $this->containerStatCache->setField( $container,
'stat', $stat );
1541 $this->setContainerCache( $container, $stat );
1543 } elseif ( $rcode === 404 ) {
1544 return self::RES_ABSENT;
1546 $this->onError(
null, __METHOD__,
1547 [
'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1549 return self::RES_ERROR;
1553 return $this->containerStatCache->getField( $container,
'stat' );
1564 $status = $this->newStatus();
1567 if ( empty( $params[
'noAccess'] ) ) {
1569 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1570 if ( empty( $params[
'noListing'] ) ) {
1571 $readUsers[] =
'.rlistings';
1573 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1576 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1577 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1580 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1582 'container' => $container,
1584 'x-container-read' => implode(
',', $readUsers ),
1585 'x-container-write' => implode(
',', $writeUsers )
1589 if ( $rcode === 201 ) {
1591 } elseif ( $rcode === 202 ) {
1594 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1608 $status = $this->newStatus();
1610 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1611 'method' =>
'DELETE',
1612 'container' => $container
1615 if ( $rcode >= 200 && $rcode <= 299 ) {
1616 $this->containerStatCache->clear( $container );
1617 } elseif ( $rcode === 404 ) {
1619 } elseif ( $rcode === 409 ) {
1620 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1622 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1640 private function objectListing(
1641 $fullCont, $type, $limit, $after =
null, $prefix =
null, $delim =
null
1643 $status = $this->newStatus();
1645 $query = [
'limit' => $limit ];
1646 if ( $type ===
'info' ) {
1647 $query[
'format'] =
'json';
1649 if ( $after !==
null ) {
1650 $query[
'marker'] = $after;
1652 if ( $prefix !==
null ) {
1653 $query[
'prefix'] = $prefix;
1655 if ( $delim !==
null ) {
1656 $query[
'delimiter'] = $delim;
1659 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1661 'container' => $fullCont,
1665 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1666 if ( $rcode === 200 ) {
1667 if ( $type ===
'info' ) {
1668 $status->value = json_decode( trim( $rbody ) );
1670 $status->value = explode(
"\n", trim( $rbody ) );
1672 } elseif ( $rcode === 204 ) {
1673 $status->value = [];
1674 } elseif ( $rcode === 404 ) {
1675 $status->value = [];
1677 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1685 foreach ( $containerInfo as $container => $info ) {
1686 $this->containerStatCache->setField( $container,
'stat', $info );
1696 foreach ( $params[
'srcs'] as
$path ) {
1697 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
1698 if ( $srcRel ===
null ) {
1700 $stats[
$path] = self::RES_ERROR;
1704 $cstat = $this->getContainerStat( $srcCont );
1705 if ( $cstat === self::RES_ABSENT ) {
1706 $stats[
$path] = self::RES_ABSENT;
1708 } elseif ( $cstat === self::RES_ERROR ) {
1709 $stats[
$path] = self::RES_ERROR;
1715 'container' => $srcCont,
1716 'relPath' => $srcRel,
1717 'headers' => $this->headersFromParams( $params )
1722 $reqs = $this->requestMultiWithAuth(
1724 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1726 foreach ( $reqs as
$path => $op ) {
1727 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1728 if ( $rcode === 200 || $rcode === 204 ) {
1730 if ( !empty( $params[
'requireSHA1'] ) ) {
1731 $rhdrs = $this->addMissingHashMetadata( $rhdrs,
$path );
1734 $stat = $this->getStatFromHeaders( $rhdrs );
1735 if ( $this->isRGW ) {
1736 $stat[
'latest'] =
true;
1738 } elseif ( $rcode === 404 ) {
1739 $stat = self::RES_ABSENT;
1741 $stat = self::RES_ERROR;
1742 $this->onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1744 $stats[
$path] = $stat;
1756 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1758 $headers = $this->extractMutableContentHeaders( $rhdrs );
1762 'mtime' => $this->convertSwiftDate( $rhdrs[
'last-modified'], TS_MW ),
1764 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1765 'sha1' => $metadata[
'sha1base36'] ??
null,
1767 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1768 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1778 if ( $this->authErrorTimestamp !==
null ) {
1779 $interval = time() - $this->authErrorTimestamp;
1780 if ( $interval < 60 ) {
1781 $this->logger->debug(
1782 'rejecting request since auth failure occurred {interval} seconds ago',
1783 [
'interval' => $interval ]
1787 $this->authErrorTimestamp =
null;
1791 if ( !$this->authCreds ) {
1792 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1793 $creds = $this->credentialCache->get( $cacheKey );
1795 isset( $creds[
'auth_token'] ) &&
1796 isset( $creds[
'storage_url'] ) &&
1797 isset( $creds[
'expiry_time'] ) &&
1798 $creds[
'expiry_time'] > time()
1801 $this->setAuthCreds( $creds );
1804 $this->refreshAuthentication();
1808 return $this->authCreds;
1816 private function setAuthCreds( ?array $creds ) {
1817 $this->logger->debug(
'Using auth token with expiry_time={expiry_time}',
1819 'expiry_time' => isset( $creds[
'expiry_time'] )
1820 ? gmdate(
'c', $creds[
'expiry_time'] ) :
'null'
1823 $this->authCreds = $creds;
1825 if ( $creds && str_ends_with( $creds[
'storage_url'],
'/v1' ) ) {
1826 $this->isRGW =
true;
1835 private function refreshAuthentication() {
1836 [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [
1838 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1840 'x-auth-user' => $this->swiftUser,
1841 'x-auth-key' => $this->swiftKey
1843 ], self::DEFAULT_HTTP_OPTIONS );
1845 if ( $rcode >= 200 && $rcode <= 299 ) {
1846 if ( isset( $rhdrs[
'x-auth-token-expires'] ) ) {
1847 $ttl = intval( $rhdrs[
'x-auth-token-expires'] );
1849 $ttl = $this->authTTL;
1851 $expiryTime = time() + $ttl;
1853 'auth_token' => $rhdrs[
'x-auth-token'],
1854 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url'],
1855 'expiry_time' => $expiryTime,
1857 $this->credentialCache->set(
1858 $this->getCredsCacheKey( $this->swiftUser ),
1862 } elseif ( $rcode === 401 ) {
1863 $this->onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1864 $this->authErrorTimestamp = time();
1867 $this->onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode, $rbody );
1868 $this->authErrorTimestamp = time();
1871 $this->setAuthCreds( $creds );
1881 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1882 $parts = [ $creds[
'storage_url'] ];
1883 if ( ( $container ??
'' ) !==
'' ) {
1884 $parts[] = rawurlencode( $container );
1886 if ( ( $object ??
'' ) !==
'' ) {
1887 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1890 return implode(
'/', $parts );
1898 return [
'x-auth-token' => $creds[
'auth_token'] ];
1907 private function getCredsCacheKey( $username ) {
1908 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1923 private function requestWithAuth( array $req ) {
1924 return $this->requestMultiWithAuth( [ $req ] )[0][
'response'];
1936 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1937 $remainingTries = 2;
1938 $auth = $this->getAuthentication();
1941 foreach ( $reqs as &$req ) {
1942 if ( !isset( $req[
'response'] ) ) {
1943 $req[
'response'] = $this->getAuthFailureResponse();
1948 foreach ( $reqs as &$req ) {
1949 '@phan-var array $req';
1950 if ( isset( $req[
'response'] ) ) {
1953 if ( $req[
'response'][
'code'] !== 401 ) {
1957 $req[
'headers'] = $this->authTokenHeaders( $auth ) + ( $req[
'headers'] ?? [] );
1958 $req[
'url'] = $this->storageUrl( $auth, $req[
'container'], $req[
'relPath'] ??
null );
1961 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1962 if ( --$remainingTries > 0 ) {
1964 foreach ( $reqs as $req ) {
1965 if ( $req[
'response'][
'code'] === 401 ) {
1966 $auth = $this->refreshAuthentication();
1984 private function getAuthFailureResponse() {
1994 'error' => self::AUTH_FAILURE_ERROR,
1995 4 => self::AUTH_FAILURE_ERROR
2011 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'', $body =
'' ) {
2012 if ( $code === 0 && $err === self::AUTH_FAILURE_ERROR ) {
2014 $status->fatal(
'backend-fail-connect', $this->name );
2020 $status->fatal(
'backend-fail-internal', $this->name );
2022 $msg =
"HTTP {code} ({desc}) in '{func}'";
2027 'req_params' => $params,
2031 $msgParams[
'err'] = $err;
2033 if ( $code == 502 ) {
2034 $msg .=
' ({truncatedBody})';
2035 $msgParams[
'truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
2037 $this->logger->error( $msg, $msgParams );
2042class_alias( SwiftFileBackend::class,
'SwiftFileBackend' );
Resource locking handling.
Generic operation result class Has warning/error list, boolean status and arbitrary value.