20use Shellbox\Command\BoxedCommand;
23use Wikimedia\AtEase\AtEase;
30use Wikimedia\Timestamp\ConvertibleTimestamp;
31use Wikimedia\Timestamp\TimestampFormat as TS;
72 private $warningTrapStack = [];
85 parent::__construct( $config );
87 if ( PHP_OS_FAMILY ===
'Windows' ) {
88 $this->os =
'Windows';
89 } elseif ( PHP_OS_FAMILY ===
'BSD' || PHP_OS_FAMILY ===
'Darwin' ) {
95 if ( isset( $config[
'basePath'] ) ) {
96 $this->basePath = rtrim( $config[
'basePath'],
'/' );
98 $this->basePath =
null;
101 $this->containerPaths = [];
102 foreach ( ( $config[
'containerPaths'] ?? [] ) as $container => $fsPath ) {
103 $this->containerPaths[$container] = rtrim( $fsPath,
'/' );
106 $this->fileMode = $config[
'fileMode'] ?? 0o644;
107 $this->dirMode = $config[
'directoryMode'] ?? 0o777;
108 if ( isset( $config[
'fileOwner'] ) && function_exists(
'posix_getuid' ) ) {
109 $this->fileOwner = $config[
'fileOwner'];
111 $this->currentUser = posix_getpwuid( posix_getuid() )[
'name'];
114 $this->usableDirCache =
new MapCacheLRU( self::CACHE_CHEAP_SIZE );
125 if ( isset( $this->containerPaths[$container] ) || $this->basePath !==
null ) {
128 return $relStoragePath;
143 if ( preg_match(
'![^/]{256}!', $fsPath ) ) {
146 if ( $this->os ===
'Windows' ) {
147 return !preg_match(
'![:*?"<>|]!', $fsPath );
162 if ( isset( $this->containerPaths[$shortCont] ) ) {
163 return $this->containerPaths[$shortCont];
164 } elseif ( $this->basePath !==
null ) {
165 return "{$this->basePath}/{$fullCont}";
179 if ( $relPath ===
null ) {
184 if ( $relPath !=
'' ) {
185 $fsPath .=
"/{$relPath}";
194 if ( $fsPath ===
null ) {
198 if ( $this->fileOwner !==
null && $this->currentUser !== $this->fileOwner ) {
199 trigger_error( __METHOD__ .
": PHP process owner is not '{$this->fileOwner}'." );
203 $fsDirectory = dirname( $fsPath );
204 $usable = $this->usableDirCache->get( $fsDirectory, MapCacheLRU::TTL_PROC_SHORT );
205 if ( $usable ===
null ) {
206 AtEase::suppressWarnings();
207 $usable = is_dir( $fsDirectory ) && is_writable( $fsDirectory );
208 AtEase::restoreWarnings();
209 $this->usableDirCache->set( $fsDirectory, $usable ? 1 : 0 );
220 if ( $fsDstPath ===
null ) {
221 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
226 if ( !empty( $params[
'async'] ) ) {
229 $status->fatal(
'backend-fail-create', $params[
'dst'] );
233 $cmd = $this->makeCopyCommand( $tempFile->getPath(), $fsDstPath,
false );
234 $handler =
function ( $errors,
StatusValue $status, array $params, $cmd ) {
235 if ( $errors !==
'' && !( $this->os ===
'Windows' && $errors[0] ===
" " ) ) {
236 $status->fatal(
'backend-fail-create', $params[
'dst'] );
237 trigger_error(
"$cmd\n$errors", E_USER_WARNING );
240 $status->value =
new FSFileOpHandle( $this, $params, $handler, $cmd );
241 $tempFile->bind( $status->value );
247 $fsStagePath = $this->makeStagingPath( $fsDstPath );
249 $stageHandle = fopen( $fsStagePath,
'xb' );
250 if ( $stageHandle ) {
251 $bytes = fwrite( $stageHandle, $params[
'content'] );
252 $created = ( $bytes === strlen( $params[
'content'] ) );
253 fclose( $stageHandle );
254 $created = $created ? rename( $fsStagePath, $fsDstPath ) :
false;
257 if ( $hadError || !$created ) {
258 $status->fatal(
'backend-fail-create', $params[
'dst'] );
262 $this->
chmod( $fsDstPath );
272 $fsSrcPath = $params[
'src'];
274 if ( $fsDstPath ===
null ) {
275 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
280 if ( $fsSrcPath === $fsDstPath ) {
281 $status->fatal(
'backend-fail-internal', $this->name );
286 if ( !empty( $params[
'async'] ) ) {
287 $cmd = $this->makeCopyCommand( $fsSrcPath, $fsDstPath,
false );
288 $handler =
function ( $errors,
StatusValue $status, array $params, $cmd ) {
289 if ( $errors !==
'' && !( $this->os ===
'Windows' && $errors[0] ===
" " ) ) {
290 $status->fatal(
'backend-fail-store', $params[
'src'], $params[
'dst'] );
291 trigger_error(
"$cmd\n$errors", E_USER_WARNING );
294 $status->value =
new FSFileOpHandle( $this, $params, $handler, $cmd );
300 $fsStagePath = $this->makeStagingPath( $fsDstPath );
302 $srcHandle = fopen( $fsSrcPath,
'rb' );
304 $stageHandle = fopen( $fsStagePath,
'xb' );
305 if ( $stageHandle ) {
306 $bytes = stream_copy_to_stream( $srcHandle, $stageHandle );
307 $stored = ( $bytes !==
false && $bytes === fstat( $srcHandle )[
'size'] );
308 fclose( $stageHandle );
309 $stored = $stored ? rename( $fsStagePath, $fsDstPath ) :
false;
311 fclose( $srcHandle );
314 if ( $hadError || !$stored ) {
315 $status->fatal(
'backend-fail-store', $params[
'src'], $params[
'dst'] );
319 $this->
chmod( $fsDstPath );
330 if ( $fsSrcPath ===
null ) {
331 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
337 if ( $fsDstPath ===
null ) {
338 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
343 if ( $fsSrcPath === $fsDstPath ) {
347 $ignoreMissing = !empty( $params[
'ignoreMissingSource'] );
349 if ( !empty( $params[
'async'] ) ) {
350 $cmd = $this->makeCopyCommand( $fsSrcPath, $fsDstPath, $ignoreMissing );
351 $handler =
function ( $errors,
StatusValue $status, array $params, $cmd ) {
352 if ( $errors !==
'' && !( $this->os ===
'Windows' && $errors[0] ===
" " ) ) {
353 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
354 trigger_error(
"$cmd\n$errors", E_USER_WARNING );
357 $status->value =
new FSFileOpHandle( $this, $params, $handler, $cmd );
363 $fsStagePath = $this->makeStagingPath( $fsDstPath );
365 $srcHandle = fopen( $fsSrcPath,
'rb' );
367 $stageHandle = fopen( $fsStagePath,
'xb' );
368 if ( $stageHandle ) {
369 $bytes = stream_copy_to_stream( $srcHandle, $stageHandle );
370 $copied = ( $bytes !==
false && $bytes === fstat( $srcHandle )[
'size'] );
371 fclose( $stageHandle );
372 $copied = $copied ? rename( $fsStagePath, $fsDstPath ) :
false;
374 fclose( $srcHandle );
377 if ( $hadError || ( !$copied && !$ignoreMissing ) ) {
378 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
383 $this->
chmod( $fsDstPath );
395 if ( $fsSrcPath ===
null ) {
396 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
402 if ( $fsDstPath ===
null ) {
403 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
408 if ( $fsSrcPath === $fsDstPath ) {
412 $ignoreMissing = !empty( $params[
'ignoreMissingSource'] );
414 if ( !empty( $params[
'async'] ) ) {
415 $cmd = $this->makeMoveCommand( $fsSrcPath, $fsDstPath, $ignoreMissing );
416 $handler =
function ( $errors,
StatusValue $status, array $params, $cmd ) {
417 if ( $errors !==
'' && !( $this->os ===
'Windows' && $errors[0] ===
" " ) ) {
418 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
419 trigger_error(
"$cmd\n$errors", E_USER_WARNING );
422 $status->value =
new FSFileOpHandle( $this, $params, $handler, $cmd );
428 $moved = rename( $fsSrcPath, $fsDstPath );
430 if ( $hadError || ( !$moved && !$ignoreMissing ) ) {
431 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
445 if ( $fsSrcPath ===
null ) {
446 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
451 $ignoreMissing = !empty( $params[
'ignoreMissingSource'] );
453 if ( !empty( $params[
'async'] ) ) {
454 $cmd = $this->makeUnlinkCommand( $fsSrcPath, $ignoreMissing );
455 $handler =
function ( $errors,
StatusValue $status, array $params, $cmd ) {
456 if ( $errors !==
'' && !( $this->os ===
'Windows' && $errors[0] ===
" " ) ) {
457 $status->fatal(
'backend-fail-delete', $params[
'src'] );
458 trigger_error(
"$cmd\n$errors", E_USER_WARNING );
461 $status->value =
new FSFileOpHandle( $this, $params, $handler, $cmd );
464 $deleted =
unlink( $fsSrcPath );
466 if ( $hadError || ( !$deleted && !$ignoreMissing ) ) {
467 $status->fatal(
'backend-fail-delete', $params[
'src'] );
483 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
486 AtEase::suppressWarnings();
487 $alreadyExisted = is_dir( $fsDirectory );
488 if ( !$alreadyExisted ) {
489 $created = mkdir( $fsDirectory, $this->dirMode,
true );
491 $alreadyExisted = is_dir( $fsDirectory );
494 $isWritable = $created ?: is_writable( $fsDirectory );
495 AtEase::restoreWarnings();
496 if ( !$alreadyExisted && !$created ) {
497 $this->logger->error( __METHOD__ .
": cannot create directory $fsDirectory" );
498 $status->fatal(
'directorycreateerror', $params[
'dir'] );
499 } elseif ( !$isWritable ) {
500 $this->logger->error( __METHOD__ .
": directory $fsDirectory is read-only" );
501 $status->fatal(
'directoryreadonlyerror', $params[
'dir'] );
508 if ( $status->isGood() ) {
509 $this->usableDirCache->set( $fsDirectory, 1 );
520 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
522 if ( !empty( $params[
'noListing'] ) && !is_file(
"{$fsDirectory}/index.html" ) ) {
524 $bytes = file_put_contents(
"{$fsDirectory}/index.html", $this->
indexHtmlPrivate() );
526 if ( $bytes ===
false ) {
527 $status->fatal(
'backend-fail-create', $params[
'dir'] .
'/index.html' );
531 if ( !empty( $params[
'noAccess'] ) && !is_file(
"{$contRoot}/.htaccess" ) ) {
532 AtEase::suppressWarnings();
533 $bytes = file_put_contents(
"{$contRoot}/.htaccess", $this->
htaccessPrivate() );
534 AtEase::restoreWarnings();
535 if ( $bytes ===
false ) {
536 $storeDir =
"mwstore://{$this->name}/{$shortCont}";
537 $status->fatal(
'backend-fail-create',
"{$storeDir}/.htaccess" );
549 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
551 if ( !empty( $params[
'listing'] ) && is_file(
"{$fsDirectory}/index.html" ) ) {
552 $exists = ( file_get_contents(
"{$fsDirectory}/index.html" ) === $this->
indexHtmlPrivate() );
553 if ( $exists && !$this->
unlink(
"{$fsDirectory}/index.html" ) ) {
554 $status->fatal(
'backend-fail-delete', $params[
'dir'] .
'/index.html' );
558 if ( !empty( $params[
'access'] ) && is_file(
"{$contRoot}/.htaccess" ) ) {
559 $exists = ( file_get_contents(
"{$contRoot}/.htaccess" ) === $this->
htaccessPrivate() );
560 if ( $exists && !$this->
unlink(
"{$contRoot}/.htaccess" ) ) {
561 $storeDir =
"mwstore://{$this->name}/{$shortCont}";
562 $status->fatal(
'backend-fail-delete',
"{$storeDir}/.htaccess" );
574 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
576 $this->
rmdir( $fsDirectory );
584 if ( $fsSrcPath ===
null ) {
585 return self::RES_ERROR;
589 $stat = is_file( $fsSrcPath ) ? stat( $fsSrcPath ) :
false;
592 if ( is_array( $stat ) ) {
593 $ct =
new ConvertibleTimestamp( $stat[
'mtime'] );
596 'mtime' => $ct->getTimestamp( TS::MW ),
597 'size' => $stat[
'size']
601 return $hadError ? self::RES_ERROR : self::RES_ABSENT;
606 if ( is_array( $paths ) ) {
607 foreach ( $paths as
$path ) {
609 if ( $fsPath !==
null ) {
610 clearstatcache(
true, $fsPath );
611 $this->usableDirCache->clear( $fsPath );
615 clearstatcache(
true );
616 $this->usableDirCache->clear();
624 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
627 $exists = is_dir( $fsDirectory );
630 return $hadError ? self::RES_ERROR : $exists;
643 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
646 $error = $list->getLastError();
647 if ( $error !==
null ) {
649 $this->logger->info( __METHOD__ .
": non-existant directory: '$fsDirectory'" );
652 } elseif ( is_dir( $fsDirectory ) ) {
653 $this->logger->warning( __METHOD__ .
": unreadable directory: '$fsDirectory'" );
655 return self::RES_ERROR;
657 $this->logger->warning( __METHOD__ .
": unreachable directory: '$fsDirectory'" );
659 return self::RES_ERROR;
676 $fsDirectory = ( $dirRel !=
'' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
679 $error = $list->getLastError();
680 if ( $error !==
null ) {
682 $this->logger->info( __METHOD__ .
": non-existent directory: '$fsDirectory'" );
685 } elseif ( is_dir( $fsDirectory ) ) {
686 $this->logger->warning( __METHOD__ .
687 ": unreadable directory: '$fsDirectory': $error" );
689 return self::RES_ERROR;
691 $this->logger->warning( __METHOD__ .
692 ": unreachable directory: '$fsDirectory': $error" );
694 return self::RES_ERROR;
705 foreach ( $params[
'srcs'] as $src ) {
708 $fsFiles[$src] = self::RES_ERROR;
718 } elseif ( $hadError ) {
719 $fsFiles[$src] = self::RES_ERROR;
721 $fsFiles[$src] = self::RES_ABSENT;
732 foreach ( $params[
'srcs'] as $src ) {
735 $tmpFiles[$src] = self::RES_ERROR;
740 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_', $ext );
742 $tmpFiles[$src] = self::RES_ERROR;
746 $tmpPath = $tmpFile->getPath();
750 $copySuccess = $isFile ?
copy(
$source, $tmpPath ) :
false;
753 if ( $copySuccess ) {
754 $this->
chmod( $tmpPath );
755 $tmpFiles[$src] = $tmpFile;
756 } elseif ( $hadError ) {
757 $tmpFiles[$src] = self::RES_ERROR;
759 $tmpFiles[$src] = self::RES_ABSENT;
771 if (
$path ===
null ) {
772 return $this->
newStatus(
'backend-fail-invalidpath', $params[
'src'] );
774 $command->inputFileFromFile( $boxedName,
$path );
792 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
793 $pipes[$index] = popen( $fileOpHandle->cmd,
'r' );
797 foreach ( $pipes as $index => $pipe ) {
800 $errs[$index] = stream_get_contents( $pipe );
804 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
806 $function = $fileOpHandle->callback;
807 $function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
808 $statuses[$index] = $status;
818 private function makeStagingPath( $fsPath ) {
819 $time = dechex( time() );
820 $hash = \Wikimedia\base_convert( md5( basename( $fsPath ) ), 16, 36, 25 );
821 $unique = \Wikimedia\base_convert( bin2hex( random_bytes( 16 ) ), 16, 36, 25 );
823 return dirname( $fsPath ) .
"/.{$time}_{$hash}_{$unique}.tmpfsfile";
832 private function makeCopyCommand( $fsSrcPath, $fsDstPath, $ignoreMissing ) {
836 $fsStagePath = $this->makeStagingPath( $fsDstPath );
840 if ( $this->os ===
'Windows' ) {
843 $cmdWrite =
"COPY /B /Y $encSrc $encStage 2>&1 && MOVE /Y $encStage $encDst 2>&1";
844 $cmd = $ignoreMissing ?
"IF EXIST $encSrc $cmdWrite" : $cmdWrite;
848 $cmdWrite =
"cp $encSrc $encStage 2>&1 && mv $encStage $encDst 2>&1";
849 $cmd = $ignoreMissing ?
"test -f $encSrc && $cmdWrite" : $cmdWrite;
851 $octalPermissions =
'0' . decoct( $this->fileMode );
852 if ( strlen( $octalPermissions ) == 4 ) {
853 $cmd .=
" && chmod $octalPermissions $encDst 2>/dev/null";
866 private function makeMoveCommand( $fsSrcPath, $fsDstPath, $ignoreMissing =
false ) {
871 if ( $this->os ===
'Windows' ) {
872 $writeCmd =
"MOVE /Y $encSrc $encDst 2>&1";
873 $cmd = $ignoreMissing ?
"IF EXIST $encSrc $writeCmd" : $writeCmd;
875 $writeCmd =
"mv -f $encSrc $encDst 2>&1";
876 $cmd = $ignoreMissing ?
"test -f $encSrc && $writeCmd" : $writeCmd;
887 private function makeUnlinkCommand( $fsPath, $ignoreMissing =
false ) {
891 if ( $this->os ===
'Windows' ) {
892 $writeCmd =
"DEL /Q $encSrc 2>&1";
893 $cmd = $ignoreMissing ?
"IF EXIST $encSrc $writeCmd" : $writeCmd;
895 $cmd = $ignoreMissing ?
"rm -f $encSrc 2>&1" :
"rm $encSrc 2>&1";
907 protected function chmod( $fsPath ) {
908 if ( $this->os ===
'Windows' ) {
912 AtEase::suppressWarnings();
913 $ok =
chmod( $fsPath, $this->fileMode );
914 AtEase::restoreWarnings();
926 AtEase::suppressWarnings();
928 AtEase::restoreWarnings();
929 clearstatcache(
true, $fsPath );
940 protected function rmdir( $fsDirectory ) {
941 AtEase::suppressWarnings();
942 $ok =
rmdir( $fsDirectory );
943 AtEase::restoreWarnings();
944 clearstatcache(
true, $fsDirectory );
954 $tempFile = $this->tmpFileFactory->newTempFSFile(
'create_',
'tmp' );
959 AtEase::suppressWarnings();
960 if ( file_put_contents( $tempFile->getPath(), $params[
'content'] ) ===
false ) {
963 AtEase::restoreWarnings();
983 return "Require all denied\n" .
994 return ( $this->os ===
'Windows' ) ? strtr( $fsPath,
'/',
'\\' ) : $fsPath;
1003 $this->warningTrapStack[] =
false;
1004 set_error_handler(
function ( $errno, $errstr ) use ( $regexIgnore ) {
1005 if ( $regexIgnore ===
null || !preg_match( $regexIgnore, $errstr ) ) {
1006 $this->logger->error( $errstr );
1007 $this->warningTrapStack[count( $this->warningTrapStack ) - 1] =
true;
1026 restore_error_handler();
1028 return array_pop( $this->warningTrapStack );
1038 if ( $regex ===
null ) {
1040 $alternatives = [
': No such file or directory' ];
1041 if ( $this->os ===
'Windows' ) {
1044 $alternatives[] =
' \(code: [23]\)';
1046 if ( function_exists(
'pcntl_strerror' ) ) {
1047 $alternatives[] = preg_quote(
': ' . pcntl_strerror( 2 ),
'/' );
1048 } elseif ( function_exists(
'socket_strerror' ) && defined(
'SOCKET_ENOENT' ) ) {
1050 $alternatives[] = preg_quote(
': ' . socket_strerror( SOCKET_ENOENT ),
'/' );
1052 $regex =
'/(' . implode(
'|', $alternatives ) .
')$/';
1069class_alias( FSFileBackend::class,
'FSFileBackend' );
Generic operation result class Has warning/error list, boolean status and arbitrary value.