14use Psr\Log\LoggerInterface;
15use Shellbox\Command\BoxedCommand;
25use Wikimedia\RequestTimeout\TimeoutException;
26use Wikimedia\Timestamp\ConvertibleTimestamp;
27use Wikimedia\Timestamp\TimestampFormat as TS;
39 private const DEFAULT_HTTP_OPTIONS = [
'httpVersion' =>
'v1.1' ];
117 parent::__construct( $config );
119 $this->swiftUser = $config[
'swiftUser'];
120 $this->swiftKey = $config[
'swiftKey'];
122 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
123 $this->canShellboxGetTempUrl = $config[
'canShellboxGetTempUrl'] ??
false;
124 $this->shellboxIpRange = $config[
'shellboxIpRange'] ??
null;
126 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
127 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
128 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
132 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
133 if ( isset( $config[$optionName] ) ) {
134 $httpOptions[$optionName] = $config[$optionName];
137 if ( isset( $config[
'telemetry'] ) ) {
138 $httpOptions[
'telemetry'] = $config[
'telemetry'];
141 $this->http->setLogger( $this->logger );
146 $this->containerStatCache =
new MapCacheLRU( 300 );
147 $this->readUsers = $config[
'readUsers'] ?? [];
148 $this->writeUsers = $config[
'writeUsers'] ?? [];
149 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
150 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
155 $this->maxFileSize = 5 * 1024 * 1024 * 1024;
157 $this->swiftAuthProvider =
new SwiftAuthProvider( $config, $this->http, $this->logger );
162 $this->http->setLogger(
$logger );
163 $this->swiftAuthProvider->setLogger(
$logger );
169 self::ATTR_UNICODE_PATHS |
177 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
179 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
183 return $relStoragePath;
188 [ $container, $rel ] = $this->resolveStoragePathReal( $storagePath );
189 if ( $rel ===
null ) {
193 return is_array( $this->getContainerStat( $container ) );
206 $contentHeaders = [];
208 foreach ( $headers as $name => $value ) {
209 $name = strtolower( $name );
210 if ( $name ===
'x-delete-at' && is_numeric( $value ) ) {
212 $contentHeaders[$name] = $value;
213 } elseif ( $name ===
'x-delete-after' && is_numeric( $value ) ) {
215 $contentHeaders[$name] = $value;
216 } elseif ( preg_match(
'/^(x-)?content-(?!length$)/', $name ) ) {
218 $contentHeaders[$name] = $value;
219 } elseif ( $name ===
'content-type' && $value !==
'' ) {
221 $contentHeaders[$name] = $value;
225 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
228 $offset = $maxLength - strlen( $contentHeaders[
'content-disposition'] );
230 $pos = strrpos( $contentHeaders[
'content-disposition'],
';', $offset );
231 $contentHeaders[
'content-disposition'] = $pos ===
false
233 : trim( substr( $contentHeaders[
'content-disposition'], 0, $pos ) );
237 return $contentHeaders;
246 $metadataHeaders = [];
247 foreach ( $headers as $name => $value ) {
248 $name = strtolower( $name );
249 if ( str_starts_with( $name,
'x-object-meta-' ) ) {
250 $metadataHeaders[$name] = $value;
254 return $metadataHeaders;
263 $prefixLen = strlen(
'x-object-meta-' );
266 foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) {
267 $metadata[substr( $name, $prefixLen )] = $value;
275 $status = $this->newStatus();
277 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
278 if ( $dstRel ===
null ) {
279 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
285 $mutableHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
287 $mutableHeaders[
'content-type']
288 ??= $this->getContentType( $params[
'dst'], $params[
'content'],
null );
292 'container' => $dstCont,
293 'relPath' => $dstRel,
294 'headers' => array_merge(
297 'etag' => md5( $params[
'content'] ),
298 'content-length' => strlen( $params[
'content'] ),
299 'x-object-meta-sha1base36' =>
300 \
Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
303 'body' => $params[
'content']
306 $method = __METHOD__;
308 [ $rcode, $rdesc, , $rbody, $rerr ] =
$request[
'response'];
309 if ( $rcode === 201 || $rcode === 202 ) {
311 } elseif ( $rcode === 412 ) {
312 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
314 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
317 return SwiftFileOpHandle::CONTINUE_IF_OK;
321 if ( !empty( $params[
'async'] ) ) {
322 $status->value = $opHandle;
324 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
332 $status = $this->newStatus();
334 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
335 if ( $dstRel ===
null ) {
336 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
345 $srcHandle = @fopen( $params[
'src'],
'rb' );
346 if ( $srcHandle ===
false ) {
347 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
353 $srcSize = fstat( $srcHandle )[
'size'];
354 $md5Context = hash_init(
'md5' );
355 $sha1Context = hash_init(
'sha1' );
357 while ( !feof( $srcHandle ) ) {
358 $buffer = (string)fread( $srcHandle, 131_072 );
359 hash_update( $md5Context, $buffer );
360 hash_update( $sha1Context, $buffer );
361 $hashDigestSize += strlen( $buffer );
364 rewind( $srcHandle );
366 if ( $hashDigestSize !== $srcSize ) {
367 $status->fatal(
'backend-fail-hash', $params[
'src'] );
373 $mutableHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
375 $mutableHeaders[
'content-type']
376 ??= $this->getContentType( $params[
'dst'],
null, $params[
'src'] );
380 'container' => $dstCont,
381 'relPath' => $dstRel,
382 'headers' => array_merge(
385 'content-length' => $srcSize,
386 'etag' => hash_final( $md5Context ),
387 'x-object-meta-sha1base36' =>
388 \
Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
394 $method = __METHOD__;
396 [ $rcode, $rdesc, , $rbody, $rerr ] =
$request[
'response'];
397 if ( $rcode === 201 || $rcode === 202 ) {
399 } elseif ( $rcode === 412 ) {
400 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
402 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
405 return SwiftFileOpHandle::CONTINUE_IF_OK;
409 $opHandle->resourcesToClose[] = $srcHandle;
411 if ( !empty( $params[
'async'] ) ) {
412 $status->value = $opHandle;
414 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
422 $status = $this->newStatus();
424 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
425 if ( $srcRel ===
null ) {
426 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
431 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
432 if ( $dstRel ===
null ) {
433 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
440 'container' => $dstCont,
441 'relPath' => $dstRel,
442 'headers' => array_merge(
443 $this->extractMutableContentHeaders( $params[
'headers'] ?? [] ),
445 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
446 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
451 $method = __METHOD__;
453 [ $rcode, $rdesc, , $rbody, $rerr ] =
$request[
'response'];
454 if ( $rcode === 201 ) {
456 } elseif ( $rcode === 404 ) {
457 if ( empty( $params[
'ignoreMissingSource'] ) ) {
458 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
461 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
464 return SwiftFileOpHandle::CONTINUE_IF_OK;
468 if ( !empty( $params[
'async'] ) ) {
469 $status->value = $opHandle;
471 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
479 $status = $this->newStatus();
481 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
482 if ( $srcRel ===
null ) {
483 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
488 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params[
'dst'] );
489 if ( $dstRel ===
null ) {
490 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
497 'container' => $dstCont,
498 'relPath' => $dstRel,
499 'headers' => array_merge(
500 $this->extractMutableContentHeaders( $params[
'headers'] ?? [] ),
502 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
503 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
507 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
509 'method' =>
'DELETE',
510 'container' => $srcCont,
511 'relPath' => $srcRel,
516 $method = __METHOD__;
518 [ $rcode, $rdesc, , $rbody, $rerr ] =
$request[
'response'];
519 if (
$request[
'method'] ===
'PUT' && $rcode === 201 ) {
521 } elseif (
$request[
'method'] ===
'DELETE' && $rcode === 204 ) {
523 } elseif ( $rcode === 404 ) {
524 if ( empty( $params[
'ignoreMissingSource'] ) ) {
525 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
528 return SwiftFileOpHandle::CONTINUE_NO;
531 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
534 return SwiftFileOpHandle::CONTINUE_IF_OK;
538 if ( !empty( $params[
'async'] ) ) {
539 $status->value = $opHandle;
541 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
549 $status = $this->newStatus();
551 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
552 if ( $srcRel ===
null ) {
553 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
559 'method' =>
'DELETE',
560 'container' => $srcCont,
561 'relPath' => $srcRel,
565 $method = __METHOD__;
567 [ $rcode, $rdesc, , $rbody, $rerr ] =
$request[
'response'];
568 if ( $rcode === 204 ) {
570 } elseif ( $rcode === 404 ) {
571 if ( empty( $params[
'ignoreMissingSource'] ) ) {
572 $status->fatal(
'backend-fail-delete', $params[
'src'] );
575 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
578 return SwiftFileOpHandle::CONTINUE_IF_OK;
582 if ( !empty( $params[
'async'] ) ) {
583 $status->value = $opHandle;
585 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
593 $status = $this->newStatus();
595 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
596 if ( $srcRel ===
null ) {
597 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
603 $stat = $this->getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
604 if ( $stat && !isset( $stat[
'xattr'] ) ) {
605 $stat = $this->doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
608 $status->fatal(
'backend-fail-describe', $params[
'src'] );
616 $oldMetadataHeaders = [];
617 foreach ( $stat[
'xattr'][
'metadata'] as $name => $value ) {
618 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
620 $newContentHeaders = $this->extractMutableContentHeaders( $params[
'headers'] ?? [] );
621 $oldContentHeaders = $stat[
'xattr'][
'headers'];
625 'container' => $srcCont,
626 'relPath' => $srcRel,
627 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
630 $method = __METHOD__;
632 [ $rcode, $rdesc, , $rbody, $rerr ] =
$request[
'response'];
633 if ( $rcode === 202 ) {
635 } elseif ( $rcode === 404 ) {
636 $status->fatal(
'backend-fail-describe', $params[
'src'] );
638 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
643 if ( !empty( $params[
'async'] ) ) {
644 $status->value = $opHandle;
646 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
656 $status = $this->newStatus();
659 $stat = $this->getContainerStat( $fullCont );
660 if ( is_array( $stat ) ) {
662 } elseif ( $stat === self::RES_ERROR ) {
663 $status->fatal(
'backend-fail-internal', $this->name );
664 $this->logger->error( __METHOD__ .
': cannot get container stat' );
667 $params[
'op'] =
'prepare';
668 $status->merge( $this->createContainer( $fullCont, $params ) );
676 $status = $this->newStatus();
677 if ( empty( $params[
'noAccess'] ) ) {
681 $stat = $this->getContainerStat( $fullCont );
682 if ( is_array( $stat ) ) {
683 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
684 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
686 $status->merge( $this->setContainerAccess(
691 } elseif ( $stat === self::RES_ABSENT ) {
692 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
694 $status->fatal(
'backend-fail-internal', $this->name );
695 $this->logger->error( __METHOD__ .
': cannot get container stat' );
703 $status = $this->newStatus();
704 if ( empty( $params[
'access'] ) ) {
708 $stat = $this->getContainerStat( $fullCont );
709 if ( is_array( $stat ) ) {
710 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
711 if ( !empty( $params[
'listing'] ) ) {
712 $readUsers[] =
'.rlistings';
714 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
717 $status->merge( $this->setContainerAccess(
722 } elseif ( $stat === self::RES_ABSENT ) {
723 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
725 $status->fatal(
'backend-fail-internal', $this->name );
726 $this->logger->error( __METHOD__ .
': cannot get container stat' );
734 $status = $this->newStatus();
737 if ( $dirRel !=
'' ) {
742 $stat = $this->getContainerStat( $fullCont,
true );
743 if ( $stat === self::RES_ABSENT ) {
745 } elseif ( $stat === self::RES_ERROR ) {
746 $status->fatal(
'backend-fail-internal', $this->name );
747 $this->logger->error( __METHOD__ .
': cannot get container stat' );
748 } elseif ( is_array( $stat ) && $stat[
'count'] == 0 ) {
750 $params[
'op'] =
'clean';
751 $status->merge( $this->deleteContainer( $fullCont, $params ) );
759 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
760 unset( $params[
'src'] );
761 $stats = $this->doGetFileStatMulti( $params );
763 return reset( $stats );
778 $timestamp =
new ConvertibleTimestamp( $ts );
780 return $timestamp->getTimestamp( $format );
781 }
catch ( TimeoutException $e ) {
783 }
catch ( Exception $e ) {
796 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
800 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
801 [
'path' =>
$path ] );
803 $objHdrs[
'x-object-meta-sha1base36'] =
false;
806 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
808 $postHeaders += $this->extractMetadataHeaders( $objHdrs );
810 $status = $this->newStatus();
812 $scopeLockS = $this->getScopedFileLocks( [
$path ], LockManager::LOCK_UW, $status );
813 if ( $status->isOK() ) {
814 $tmpFile = $this->getLocalCopy( [
'src' =>
$path,
'latest' => 1 ] );
816 $hash = $tmpFile->getSha1Base36();
817 if ( $hash !==
false ) {
818 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
820 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
821 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
822 [ $rcode ] = $this->requestWithAuth( [
824 'container' => $srcCont,
825 'relPath' => $srcRel,
826 'headers' => $postHeaders
828 if ( $rcode >= 200 && $rcode <= 299 ) {
829 $this->deleteFileCache(
$path );
837 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
838 [
'path' =>
$path ] );
845 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
851 $contents = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
852 foreach ( $params[
'srcs'] as
$path ) {
853 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
854 if ( $srcRel ===
null ) {
858 $handle = fopen(
'php://temp',
'wb' );
862 'container' => $srcCont,
863 'relPath' => $srcRel,
864 'headers' => $this->headersFromParams( $params ),
870 $reqs = $this->requestMultiWithAuth(
872 [
'maxConnsPerHost' => $params[
'concurrency'] ]
874 foreach ( $reqs as
$path => $op ) {
875 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
876 if ( $rcode >= 200 && $rcode <= 299 ) {
877 rewind( $op[
'stream'] );
878 $content = (string)stream_get_contents( $op[
'stream'] );
879 $size = strlen( $content );
881 if ( $size === (
int)$rhdrs[
'content-length'] ) {
882 $contents[
$path] = $content;
884 $contents[
$path] = self::RES_ERROR;
885 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
886 $this->onError(
null, __METHOD__,
887 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
889 } elseif ( $rcode === 404 ) {
890 $contents[
$path] = self::RES_ABSENT;
892 $contents[
$path] = self::RES_ERROR;
893 $this->onError(
null, __METHOD__,
894 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
896 fclose( $op[
'stream'] );
904 $prefix = ( $dirRel ==
'' ) ?
null :
"{$dirRel}/";
905 $status = $this->objectListing( $fullCont,
'names', 1,
null, $prefix );
906 if ( $status->isOK() ) {
907 return ( count( $status->value ) ) > 0;
910 return self::RES_ERROR;
948 if ( $after === INF ) {
952 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
954 if ( !empty( $params[
'topOnly'] ) ) {
955 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
956 if ( !$status->isOK() ) {
959 $objects = $status->value;
960 foreach ( $objects as $object ) {
961 if ( str_ends_with( $object,
'/' ) ) {
967 $getParentDir =
static function (
$path ) {
968 return (
$path !==
null && str_contains(
$path,
'/' ) ) ? dirname(
$path ) :
false;
972 $lastDir = $getParentDir( $after );
973 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
975 if ( !$status->isOK() ) {
979 $objects = $status->value;
981 foreach ( $objects as $object ) {
982 $objectDir = $getParentDir( $object );
984 if ( $objectDir !==
false && $objectDir !== $dir ) {
989 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
992 $dirs[] =
"{$pDir}/";
993 $pDir = $getParentDir( $pDir );
994 }
while ( $pDir !==
false
995 && strcmp( $pDir, $lastDir ) > 0
996 && strlen( $pDir ) > strlen( $dir )
999 $lastDir = $objectDir;
1004 if ( count( $objects ) < $limit ) {
1007 $after = end( $objects );
1026 if ( $after === INF ) {
1030 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1033 if ( !empty( $params[
'topOnly'] ) ) {
1034 if ( !empty( $params[
'adviseStat'] ) ) {
1035 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1037 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1041 if ( !empty( $params[
'adviseStat'] ) ) {
1042 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix );
1044 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1049 if ( !$status->isOK() ) {
1053 $objects = $status->value;
1054 $files = $this->buildFileObjectListing( $objects );
1057 if ( count( $objects ) < $limit ) {
1060 $after = end( $objects );
1061 $after = is_object( $after ) ? $after->name : $after;
1074 private function buildFileObjectListing( array $objects ) {
1076 foreach ( $objects as $object ) {
1077 if ( is_object( $object ) ) {
1078 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1083 'mtime' => $this->convertSwiftDate( $object->last_modified, TS::MW ),
1084 'size' => (int)$object->bytes,
1087 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1090 $names[] = [ $object->name, $stat ];
1091 } elseif ( !str_ends_with( $object,
'/' ) ) {
1093 $names[] = [ $object, null ];
1107 $this->procFileStatCache->setField(
$path,
'stat', $val );
1112 $stat = $this->getFileStat( $params );
1114 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1115 $this->clearCache( [ $params[
'src'] ] );
1116 $stat = $this->getFileStat( $params );
1119 if ( is_array( $stat ) ) {
1120 return $stat[
'xattr'];
1123 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1130 $params[
'requireSHA1'] =
true;
1132 $stat = $this->getFileStat( $params );
1133 if ( is_array( $stat ) ) {
1134 return $stat[
'sha1'];
1137 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1142 $status = $this->newStatus();
1146 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
1147 if ( $srcRel ===
null ) {
1149 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1154 if ( !is_array( $this->getContainerStat( $srcCont ) ) ) {
1156 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1163 if ( $params[
'headers'] && !$this->fileExists( $params ) ) {
1165 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1171 if ( empty( $params[
'headless'] ) ) {
1172 foreach ( $params[
'headers'] as $header ) {
1173 $this->header( $header );
1177 if ( empty( $params[
'allowOB'] ) ) {
1179 $this->resetOutputBuffer();
1182 $handle = fopen(
'php://output',
'wb' );
1183 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1185 'container' => $srcCont,
1186 'relPath' => $srcRel,
1187 'headers' => $this->headersFromParams( $params ) + $params[
'options'],
1188 'stream' => $handle,
1189 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1192 if ( $rcode >= 200 && $rcode <= 299 ) {
1194 } elseif ( $rcode === 404 ) {
1195 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1199 $this->clearCache( [ $params[
'src'] ] );
1200 $this->deleteFileCache( $params[
'src'] );
1202 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1210 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1216 $tmpFiles = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
1217 foreach ( $params[
'srcs'] as
$path ) {
1218 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
1219 if ( $srcRel ===
null ) {
1225 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_', $ext );
1226 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1230 'container' => $srcCont,
1231 'relPath' => $srcRel,
1232 'headers' => $this->headersFromParams( $params ),
1233 'stream' => $handle,
1235 $tmpFiles[
$path] = $tmpFile;
1240 $latest = !empty( $params[
'latest'] );
1242 $reqs = $this->requestMultiWithAuth(
1244 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1246 foreach ( $reqs as
$path => $op ) {
1247 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1248 fclose( $op[
'stream'] );
1249 if ( $rcode >= 200 && $rcode <= 299 ) {
1251 $tmpFile = $tmpFiles[
$path];
1253 $size = $tmpFile->getSize();
1254 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1255 $tmpFiles[
$path] = self::RES_ERROR;
1256 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1257 $this->onError(
null, __METHOD__,
1258 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1261 $stat = $this->getStatFromHeaders( $rhdrs );
1262 $stat[
'latest'] = $latest;
1263 $this->procFileStatCache->setField(
$path,
'stat', $stat );
1264 } elseif ( $rcode === 404 ) {
1265 $tmpFiles[
$path] = self::RES_ABSENT;
1266 $this->procFileStatCache->setField(
1269 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1272 $tmpFiles[
$path] = self::RES_ERROR;
1273 $this->onError(
null, __METHOD__,
1274 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1285 if ( $this->canShellboxGetTempUrl ) {
1286 $urlParams = [
'src' => $params[
'src'] ];
1287 if ( $this->shellboxIpRange !==
null ) {
1288 $urlParams[
'ipRange'] = $this->shellboxIpRange;
1290 $url = $this->getFileHttpUrl( $urlParams );
1292 $command->inputFileFromUrl( $boxedName,
$url );
1293 return $this->newStatus();
1296 return parent::addShellboxInputFile( $command, $boxedName, $params );
1301 if ( $this->swiftTempUrlKey ==
'' &&
1302 ( $this->rgwS3AccessKey ==
'' || $this->rgwS3SecretKey !=
'' )
1304 $this->logger->debug(
"Can't get Swift file URL: no key available" );
1305 return self::TEMPURL_ERROR;
1308 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params[
'src'] );
1309 if ( $srcRel ===
null ) {
1310 $this->logger->debug(
"Can't get Swift file URL: can't resolve path" );
1311 return self::TEMPURL_ERROR;
1314 $auth = $this->swiftAuthProvider->getAuthentication();
1316 $this->logger->debug(
"Can't get Swift file URL: authentication failed" );
1317 return self::TEMPURL_ERROR;
1320 $method = $params[
'method'] ??
'GET';
1321 $ttl = $params[
'ttl'] ?? 86400;
1322 $expires = time() + $ttl;
1324 if ( $this->swiftTempUrlKey !=
'' ) {
1325 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1327 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1331 "{$contPath}/{$srcRel}"
1334 'temp_url_expires' => $expires,
1336 if ( isset( $params[
'ipRange'] ) ) {
1337 array_unshift( $messageParts,
"ip={$params['ipRange']}" );
1338 $query[
'temp_url_ip_range'] = $params[
'ipRange'];
1341 $signature = hash_hmac(
'sha1',
1342 implode(
"\n", $messageParts ),
1343 $this->swiftTempUrlKey
1345 $query = [
'temp_url_sig' => $signature ] + $query;
1347 return $url .
'?' . http_build_query( $query );
1350 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1351 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1353 $signature = base64_encode( hash_hmac(
1355 "{$method}\n\n\n{$expires}\n{$spath}",
1356 $this->rgwS3SecretKey,
1362 return str_replace(
'/swift/v1',
'', $this->storageUrl( $auth ) . $spath ) .
1365 'Signature' => $signature,
1366 'Expires' => $expires,
1367 'AWSAccessKeyId' => $this->rgwS3AccessKey
1387 if ( !empty( $params[
'latest'] ) ) {
1388 $hdrs[
'x-newest'] =
'true';
1397 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1403 $httpReqsByStage = [];
1404 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1405 $reqs = $fileOpHandle->httpOp;
1406 foreach ( $reqs as $stage => $req ) {
1407 $httpReqsByStage[$stage][$index] = $req;
1409 $statuses[$index] = $this->newStatus();
1413 $reqCount = count( $httpReqsByStage );
1414 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1415 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1416 foreach ( $httpReqs as $index => $httpReq ) {
1418 $fileOpHandle = $fileOpHandles[$index];
1420 $status = $statuses[$index];
1421 ( $fileOpHandle->callback )( $httpReq, $status );
1426 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1428 $stages = count( $fileOpHandle->httpOp );
1429 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1430 unset( $httpReqsByStage[$s][$index] );
1462 $status = $this->newStatus();
1464 [ $rcode, , , , ] = $this->requestWithAuth( [
1466 'container' => $container,
1468 'x-container-read' => implode(
',', $readUsers ),
1469 'x-container-write' => implode(
',', $writeUsers )
1473 if ( $rcode != 204 && $rcode !== 202 ) {
1474 $status->fatal(
'backend-fail-internal', $this->name );
1475 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1476 [
'rcode' => $rcode ] );
1491 if ( $bypassCache ) {
1492 $this->containerStatCache->clear( $container );
1493 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1494 $this->primeContainerCache( [ $container ] );
1496 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1497 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1499 'container' => $container
1502 if ( $rcode === 204 ) {
1504 'count' => $rhdrs[
'x-container-object-count'],
1505 'bytes' => $rhdrs[
'x-container-bytes-used']
1507 if ( $bypassCache ) {
1510 $this->containerStatCache->setField( $container,
'stat', $stat );
1511 $this->setContainerCache( $container, $stat );
1513 } elseif ( $rcode === 404 ) {
1514 return self::RES_ABSENT;
1516 $this->onError(
null, __METHOD__,
1517 [
'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1519 return self::RES_ERROR;
1523 return $this->containerStatCache->getField( $container,
'stat' );
1534 $status = $this->newStatus();
1537 if ( empty( $params[
'noAccess'] ) ) {
1539 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1540 if ( empty( $params[
'noListing'] ) ) {
1541 $readUsers[] =
'.rlistings';
1543 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1546 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1547 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1550 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1552 'container' => $container,
1554 'x-container-read' => implode(
',', $readUsers ),
1555 'x-container-write' => implode(
',', $writeUsers )
1559 if ( $rcode === 201 ) {
1561 } elseif ( $rcode === 202 ) {
1564 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1578 $status = $this->newStatus();
1580 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1581 'method' =>
'DELETE',
1582 'container' => $container
1585 if ( $rcode >= 200 && $rcode <= 299 ) {
1586 $this->containerStatCache->clear( $container );
1587 } elseif ( $rcode === 404 ) {
1589 } elseif ( $rcode === 409 ) {
1590 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1592 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1610 private function objectListing(
1611 $fullCont, $type, $limit, $after =
null, $prefix =
null, $delim =
null
1613 $status = $this->newStatus();
1615 $query = [
'limit' => $limit ];
1616 if ( $type ===
'info' ) {
1617 $query[
'format'] =
'json';
1619 if ( $after !==
null ) {
1620 $query[
'marker'] = $after;
1622 if ( $prefix !==
null ) {
1623 $query[
'prefix'] = $prefix;
1625 if ( $delim !==
null ) {
1626 $query[
'delimiter'] = $delim;
1629 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1631 'container' => $fullCont,
1635 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1636 if ( $rcode === 200 ) {
1637 if ( $type ===
'info' ) {
1638 $status->value = json_decode( trim( $rbody ) );
1640 $status->value = explode(
"\n", trim( $rbody ) );
1642 } elseif ( $rcode === 204 ) {
1643 $status->value = [];
1644 } elseif ( $rcode === 404 ) {
1645 $status->value = [];
1647 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1655 foreach ( $containerInfo as $container => $info ) {
1656 $this->containerStatCache->setField( $container,
'stat', $info );
1666 foreach ( $params[
'srcs'] as
$path ) {
1667 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal(
$path );
1668 if ( $srcRel ===
null ) {
1670 $stats[
$path] = self::RES_ERROR;
1674 $cstat = $this->getContainerStat( $srcCont );
1675 if ( $cstat === self::RES_ABSENT ) {
1676 $stats[
$path] = self::RES_ABSENT;
1678 } elseif ( $cstat === self::RES_ERROR ) {
1679 $stats[
$path] = self::RES_ERROR;
1685 'container' => $srcCont,
1686 'relPath' => $srcRel,
1687 'headers' => $this->headersFromParams( $params )
1692 $reqs = $this->requestMultiWithAuth(
1694 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1696 foreach ( $reqs as
$path => $op ) {
1697 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1698 if ( $rcode === 200 || $rcode === 204 ) {
1700 if ( !empty( $params[
'requireSHA1'] ) ) {
1701 $rhdrs = $this->addMissingHashMetadata( $rhdrs,
$path );
1704 $stat = $this->getStatFromHeaders( $rhdrs );
1705 } elseif ( $rcode === 404 ) {
1706 $stat = self::RES_ABSENT;
1708 $stat = self::RES_ERROR;
1709 $this->onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1711 $stats[
$path] = $stat;
1723 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1725 $headers = $this->extractMutableContentHeaders( $rhdrs );
1729 'mtime' => $this->convertSwiftDate( $rhdrs[
'last-modified'], TS::MW ),
1731 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1732 'sha1' => $metadata[
'sha1base36'] ??
null,
1734 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1735 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1745 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1746 $parts = [ $creds[
'storage_url'] ];
1747 if ( ( $container ??
'' ) !==
'' ) {
1748 $parts[] = rawurlencode( $container );
1750 if ( ( $object ??
'' ) !==
'' ) {
1751 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1754 return implode(
'/', $parts );
1769 private function requestWithAuth( array $req ) {
1770 return $this->requestMultiWithAuth( [ $req ] )[0][
'response'];
1782 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1783 $remainingTries = 2;
1784 $auth = $this->swiftAuthProvider->getAuthentication();
1787 foreach ( $reqs as &$req ) {
1788 if ( !isset( $req[
'response'] ) ) {
1789 $req[
'response'] = $this->swiftAuthProvider->getAuthFailureResponse();
1794 foreach ( $reqs as &$req ) {
1795 '@phan-var array $req';
1796 if ( isset( $req[
'response'] ) ) {
1799 if ( $req[
'response'][
'code'] !== 401 ) {
1803 $req[
'headers'] = $this->swiftAuthProvider->authTokenHeaders( $auth ) + ( $req[
'headers'] ?? [] );
1804 $req[
'url'] = $this->storageUrl( $auth, $req[
'container'], $req[
'relPath'] ??
null );
1807 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1808 if ( --$remainingTries > 0 ) {
1810 foreach ( $reqs as $req ) {
1811 if ( $req[
'response'][
'code'] === 401 ) {
1812 $auth = $this->swiftAuthProvider->refreshAuthentication();
1834 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'', $body =
'' ) {
1837 $status->fatal(
'backend-fail-connect', $this->name );
1843 $status->fatal(
'backend-fail-internal', $this->name );
1845 $msg =
"HTTP {code} ({desc}) in '{func}'";
1850 'req_params' => $params,
1854 $msgParams[
'err'] = $err;
1856 if ( $code == 502 ) {
1857 $msg .=
' ({truncatedBody})';
1858 $msgParams[
'truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
1860 $this->logger->error( $msg, $msgParams );
1865class_alias( SwiftFileBackend::class,
'SwiftFileBackend' );
Generic operation result class Has warning/error list, boolean status and arbitrary value.