MediaWiki master
FSFileBackend.php
Go to the documentation of this file.
1<?php
16// @phan-file-suppress UnusedPluginSuppression,UnusedPluginFileSuppression False positive on Windows only
17
18namespace Wikimedia\FileBackend;
19
20use Shellbox\Command\BoxedCommand;
21use Shellbox\Shellbox;
22use StatusValue;
23use Wikimedia\AtEase\AtEase;
30use Wikimedia\Timestamp\ConvertibleTimestamp;
31use Wikimedia\Timestamp\TimestampFormat as TS;
32
51 protected $usableDirCache;
52
54 protected $basePath;
55
57 protected $containerPaths;
58
60 protected $dirMode;
62 protected $fileMode;
64 protected $fileOwner;
65
67 protected $os;
69 protected $currentUser;
70
72 private $warningTrapStack = [];
73
84 public function __construct( array $config ) {
85 parent::__construct( $config );
86
87 if ( PHP_OS_FAMILY === 'Windows' ) {
88 $this->os = 'Windows';
89 } elseif ( PHP_OS_FAMILY === 'BSD' || PHP_OS_FAMILY === 'Darwin' ) {
90 $this->os = 'BSD';
91 } else {
92 $this->os = 'Linux';
93 }
94 // Remove any possible trailing slash from directories
95 if ( isset( $config['basePath'] ) ) {
96 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
97 } else {
98 $this->basePath = null; // none; containers must have explicit paths
99 }
100
101 $this->containerPaths = [];
102 foreach ( ( $config['containerPaths'] ?? [] ) as $container => $fsPath ) {
103 $this->containerPaths[$container] = rtrim( $fsPath, '/' ); // remove trailing slash
104 }
105
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'];
110 // Cache this, assuming it doesn't change
111 $this->currentUser = posix_getpwuid( posix_getuid() )['name'];
112 }
113
114 $this->usableDirCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
115 }
116
118 public function getFeatures() {
120 }
121
123 protected function resolveContainerPath( $container, $relStoragePath ) {
124 // Check that container has a root directory
125 if ( isset( $this->containerPaths[$container] ) || $this->basePath !== null ) {
126 // Check for sensible relative paths (assume the base paths are OK)
127 if ( $this->isLegalRelPath( $relStoragePath ) ) {
128 return $relStoragePath;
129 }
130 }
131
132 return null; // invalid
133 }
134
141 protected function isLegalRelPath( $fsPath ) {
142 // Check for file names longer than 255 chars
143 if ( preg_match( '![^/]{256}!', $fsPath ) ) { // ext3/NTFS
144 return false;
145 }
146 if ( $this->os === 'Windows' ) { // NTFS
147 return !preg_match( '![:*?"<>|]!', $fsPath );
148 } else {
149 return true;
150 }
151 }
152
161 protected function containerFSRoot( $shortCont, $fullCont ) {
162 if ( isset( $this->containerPaths[$shortCont] ) ) {
163 return $this->containerPaths[$shortCont];
164 } elseif ( $this->basePath !== null ) {
165 return "{$this->basePath}/{$fullCont}";
166 }
167
168 return null; // no container base path defined
169 }
170
177 protected function resolveToFSPath( $storagePath ) {
178 [ $fullCont, $relPath ] = $this->resolveStoragePathReal( $storagePath );
179 if ( $relPath === null ) {
180 return null; // invalid
181 }
182 [ , $shortCont, ] = FileBackend::splitStoragePath( $storagePath );
183 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
184 if ( $relPath != '' ) {
185 $fsPath .= "/{$relPath}";
186 }
187
188 return $fsPath;
189 }
190
192 public function isPathUsableInternal( $storagePath ) {
193 $fsPath = $this->resolveToFSPath( $storagePath );
194 if ( $fsPath === null ) {
195 return false; // invalid
196 }
197
198 if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
199 trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
200 return false;
201 }
202
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 );
210 }
211
212 return $usable;
213 }
214
216 protected function doCreateInternal( array $params ) {
217 $status = $this->newStatus();
218
219 $fsDstPath = $this->resolveToFSPath( $params['dst'] );
220 if ( $fsDstPath === null ) {
221 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
222
223 return $status;
224 }
225
226 if ( !empty( $params['async'] ) ) { // deferred
227 $tempFile = $this->newTempFileWithContent( $params );
228 if ( !$tempFile ) {
229 $status->fatal( 'backend-fail-create', $params['dst'] );
230
231 return $status;
232 }
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 ); // command output
238 }
239 };
240 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
241 $tempFile->bind( $status->value );
242 } else { // immediate write
243 $created = false;
244 // Use fwrite+rename since (a) this clears xattrs, (b) threads still reading the old
245 // inode are unaffected since it writes to a new inode, and (c) new threads reading
246 // the file will either totally see the old version or totally see the new version
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;
255 }
256 $hadError = $this->untrapWarnings();
257 if ( $hadError || !$created ) {
258 $status->fatal( 'backend-fail-create', $params['dst'] );
259
260 return $status;
261 }
262 $this->chmod( $fsDstPath );
263 }
264
265 return $status;
266 }
267
269 protected function doStoreInternal( array $params ) {
270 $status = $this->newStatus();
271
272 $fsSrcPath = $params['src']; // file system path
273 $fsDstPath = $this->resolveToFSPath( $params['dst'] );
274 if ( $fsDstPath === null ) {
275 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
276
277 return $status;
278 }
279
280 if ( $fsSrcPath === $fsDstPath ) {
281 $status->fatal( 'backend-fail-internal', $this->name );
282
283 return $status;
284 }
285
286 if ( !empty( $params['async'] ) ) { // deferred
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 ); // command output
292 }
293 };
294 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
295 } else { // immediate write
296 $stored = false;
297 // Use fwrite+rename since (a) this clears xattrs, (b) threads still reading the old
298 // inode are unaffected since it writes to a new inode, and (c) new threads reading
299 // the file will either totally see the old version or totally see the new version
300 $fsStagePath = $this->makeStagingPath( $fsDstPath );
302 $srcHandle = fopen( $fsSrcPath, 'rb' );
303 if ( $srcHandle ) {
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;
310 }
311 fclose( $srcHandle );
312 }
313 $hadError = $this->untrapWarnings();
314 if ( $hadError || !$stored ) {
315 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
316
317 return $status;
318 }
319 $this->chmod( $fsDstPath );
320 }
321
322 return $status;
323 }
324
326 protected function doCopyInternal( array $params ) {
327 $status = $this->newStatus();
328
329 $fsSrcPath = $this->resolveToFSPath( $params['src'] );
330 if ( $fsSrcPath === null ) {
331 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
332
333 return $status;
334 }
335
336 $fsDstPath = $this->resolveToFSPath( $params['dst'] );
337 if ( $fsDstPath === null ) {
338 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
339
340 return $status;
341 }
342
343 if ( $fsSrcPath === $fsDstPath ) {
344 return $status; // no-op
345 }
346
347 $ignoreMissing = !empty( $params['ignoreMissingSource'] );
348
349 if ( !empty( $params['async'] ) ) { // deferred
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 ); // command output
355 }
356 };
357 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
358 } else { // immediate write
359 $copied = false;
360 // Use fwrite+rename since (a) this clears xattrs, (b) threads still reading the old
361 // inode are unaffected since it writes to a new inode, and (c) new threads reading
362 // the file will either totally see the old version or totally see the new version
363 $fsStagePath = $this->makeStagingPath( $fsDstPath );
365 $srcHandle = fopen( $fsSrcPath, 'rb' );
366 if ( $srcHandle ) {
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;
373 }
374 fclose( $srcHandle );
375 }
376 $hadError = $this->untrapWarnings();
377 if ( $hadError || ( !$copied && !$ignoreMissing ) ) {
378 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
379
380 return $status;
381 }
382 if ( $copied ) {
383 $this->chmod( $fsDstPath );
384 }
385 }
386
387 return $status;
388 }
389
391 protected function doMoveInternal( array $params ) {
392 $status = $this->newStatus();
393
394 $fsSrcPath = $this->resolveToFSPath( $params['src'] );
395 if ( $fsSrcPath === null ) {
396 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
397
398 return $status;
399 }
400
401 $fsDstPath = $this->resolveToFSPath( $params['dst'] );
402 if ( $fsDstPath === null ) {
403 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
404
405 return $status;
406 }
407
408 if ( $fsSrcPath === $fsDstPath ) {
409 return $status; // no-op
410 }
411
412 $ignoreMissing = !empty( $params['ignoreMissingSource'] );
413
414 if ( !empty( $params['async'] ) ) { // deferred
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 ); // command output
420 }
421 };
422 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
423 } else { // immediate write
424 // Use rename() here since (a) this clears xattrs, (b) any threads still reading the
425 // old inode are unaffected since it writes to a new inode, and (c) this is fast and
426 // atomic within a file system volume (as is normally the case)
428 $moved = rename( $fsSrcPath, $fsDstPath );
429 $hadError = $this->untrapWarnings();
430 if ( $hadError || ( !$moved && !$ignoreMissing ) ) {
431 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
432
433 return $status;
434 }
435 }
436
437 return $status;
438 }
439
441 protected function doDeleteInternal( array $params ) {
442 $status = $this->newStatus();
443
444 $fsSrcPath = $this->resolveToFSPath( $params['src'] );
445 if ( $fsSrcPath === null ) {
446 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
447
448 return $status;
449 }
450
451 $ignoreMissing = !empty( $params['ignoreMissingSource'] );
452
453 if ( !empty( $params['async'] ) ) { // deferred
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 ); // command output
459 }
460 };
461 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
462 } else { // immediate write
464 $deleted = unlink( $fsSrcPath );
465 $hadError = $this->untrapWarnings();
466 if ( $hadError || ( !$deleted && !$ignoreMissing ) ) {
467 $status->fatal( 'backend-fail-delete', $params['src'] );
468
469 return $status;
470 }
471 }
472
473 return $status;
474 }
475
479 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
480 $status = $this->newStatus();
481 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
482 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
483 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
484 // Create the directory and its parents as needed...
485 $created = false;
486 AtEase::suppressWarnings();
487 $alreadyExisted = is_dir( $fsDirectory ); // already there?
488 if ( !$alreadyExisted ) {
489 $created = mkdir( $fsDirectory, $this->dirMode, true );
490 if ( !$created ) {
491 $alreadyExisted = is_dir( $fsDirectory ); // another thread made it?
492 }
493 }
494 $isWritable = $created ?: is_writable( $fsDirectory ); // assume writable if created here
495 AtEase::restoreWarnings();
496 if ( !$alreadyExisted && !$created ) {
497 $this->logger->error( __METHOD__ . ": cannot create directory $fsDirectory" );
498 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
499 } elseif ( !$isWritable ) {
500 $this->logger->error( __METHOD__ . ": directory $fsDirectory is read-only" );
501 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
502 }
503 // Respect any 'noAccess' or 'noListing' flags...
504 if ( $created ) {
505 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
506 }
507
508 if ( $status->isGood() ) {
509 $this->usableDirCache->set( $fsDirectory, 1 );
510 }
511
512 return $status;
513 }
514
516 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
517 $status = $this->newStatus();
518 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
519 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
520 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
521 // Seed new directories with a blank index.html, to prevent crawling...
522 if ( !empty( $params['noListing'] ) && !is_file( "{$fsDirectory}/index.html" ) ) {
523 $this->trapWarnings();
524 $bytes = file_put_contents( "{$fsDirectory}/index.html", $this->indexHtmlPrivate() );
525 $this->untrapWarnings();
526 if ( $bytes === false ) {
527 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
528 }
529 }
530 // Add a .htaccess file to the root of the container...
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" );
538 }
539 }
540
541 return $status;
542 }
543
545 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
546 $status = $this->newStatus();
547 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
548 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
549 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
550 // Unseed new directories with a blank index.html, to allow crawling...
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" ) ) { // reverse secure()
554 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
555 }
556 }
557 // Remove the .htaccess file from the root of the container...
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" ) ) { // reverse secure()
561 $storeDir = "mwstore://{$this->name}/{$shortCont}";
562 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
563 }
564 }
565
566 return $status;
567 }
568
570 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
571 $status = $this->newStatus();
572 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
573 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
574 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
575
576 $this->rmdir( $fsDirectory );
577
578 return $status;
579 }
580
582 protected function doGetFileStat( array $params ) {
583 $fsSrcPath = $this->resolveToFSPath( $params['src'] );
584 if ( $fsSrcPath === null ) {
585 return self::RES_ERROR; // invalid storage path
586 }
587
588 $this->trapWarnings(); // don't trust 'false' if there were errors
589 $stat = is_file( $fsSrcPath ) ? stat( $fsSrcPath ) : false; // regular files only
590 $hadError = $this->untrapWarnings();
591
592 if ( is_array( $stat ) ) {
593 $ct = new ConvertibleTimestamp( $stat['mtime'] );
594
595 return [
596 'mtime' => $ct->getTimestamp( TS::MW ),
597 'size' => $stat['size']
598 ];
599 }
600
601 return $hadError ? self::RES_ERROR : self::RES_ABSENT;
602 }
603
605 protected function doClearCache( ?array $paths = null ) {
606 if ( is_array( $paths ) ) {
607 foreach ( $paths as $path ) {
608 $fsPath = $this->resolveToFSPath( $path );
609 if ( $fsPath !== null ) {
610 clearstatcache( true, $fsPath );
611 $this->usableDirCache->clear( $fsPath );
612 }
613 }
614 } else {
615 clearstatcache( true ); // clear the PHP file stat cache
616 $this->usableDirCache->clear();
617 }
618 }
619
621 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
622 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
623 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
624 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
625
626 $this->trapWarnings(); // don't trust 'false' if there were errors
627 $exists = is_dir( $fsDirectory );
628 $hadError = $this->untrapWarnings();
629
630 return $hadError ? self::RES_ERROR : $exists;
631 }
632
640 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
641 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
642 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
643 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
644
645 $list = new FSFileBackendDirList( $fsDirectory, $params );
646 $error = $list->getLastError();
647 if ( $error !== null ) {
648 if ( $this->isFileNotFoundError( $error ) ) {
649 $this->logger->info( __METHOD__ . ": non-existant directory: '$fsDirectory'" );
650
651 return []; // nothing under this dir
652 } elseif ( is_dir( $fsDirectory ) ) {
653 $this->logger->warning( __METHOD__ . ": unreadable directory: '$fsDirectory'" );
654
655 return self::RES_ERROR; // bad permissions?
656 } else {
657 $this->logger->warning( __METHOD__ . ": unreachable directory: '$fsDirectory'" );
658
659 return self::RES_ERROR;
660 }
661 }
662
663 return $list;
664 }
665
673 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
674 [ , $shortCont, ] = FileBackend::splitStoragePath( $params['dir'] );
675 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
676 $fsDirectory = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
677
678 $list = new FSFileBackendFileList( $fsDirectory, $params );
679 $error = $list->getLastError();
680 if ( $error !== null ) {
681 if ( $this->isFileNotFoundError( $error ) ) {
682 $this->logger->info( __METHOD__ . ": non-existent directory: '$fsDirectory'" );
683
684 return []; // nothing under this dir
685 } elseif ( is_dir( $fsDirectory ) ) {
686 $this->logger->warning( __METHOD__ .
687 ": unreadable directory: '$fsDirectory': $error" );
688
689 return self::RES_ERROR; // bad permissions?
690 } else {
691 $this->logger->warning( __METHOD__ .
692 ": unreachable directory: '$fsDirectory': $error" );
693
694 return self::RES_ERROR;
695 }
696 }
697
698 return $list;
699 }
700
702 protected function doGetLocalReferenceMulti( array $params ) {
703 $fsFiles = []; // (path => FSFile)
704
705 foreach ( $params['srcs'] as $src ) {
706 $source = $this->resolveToFSPath( $src );
707 if ( $source === null ) {
708 $fsFiles[$src] = self::RES_ERROR; // invalid path
709 continue;
710 }
711
712 $this->trapWarnings(); // don't trust 'false' if there were errors
713 $isFile = is_file( $source ); // regular files only
714 $hadError = $this->untrapWarnings();
715
716 if ( $isFile ) {
717 $fsFiles[$src] = new FSFile( $source );
718 } elseif ( $hadError ) {
719 $fsFiles[$src] = self::RES_ERROR;
720 } else {
721 $fsFiles[$src] = self::RES_ABSENT;
722 }
723 }
724
725 return $fsFiles;
726 }
727
729 protected function doGetLocalCopyMulti( array $params ) {
730 $tmpFiles = []; // (path => TempFSFile)
731
732 foreach ( $params['srcs'] as $src ) {
733 $source = $this->resolveToFSPath( $src );
734 if ( $source === null ) {
735 $tmpFiles[$src] = self::RES_ERROR; // invalid path
736 continue;
737 }
738 // Create a new temporary file with the same extension...
739 $ext = FileBackend::extensionFromPath( $src );
740 $tmpFile = $this->tmpFileFactory->newTempFSFile( 'localcopy_', $ext );
741 if ( !$tmpFile ) {
742 $tmpFiles[$src] = self::RES_ERROR;
743 continue;
744 }
745
746 $tmpPath = $tmpFile->getPath();
747 // Copy the source file over the temp file
748 $this->trapWarnings(); // don't trust 'false' if there were errors
749 $isFile = is_file( $source ); // regular files only
750 $copySuccess = $isFile ? copy( $source, $tmpPath ) : false;
751 $hadError = $this->untrapWarnings();
752
753 if ( $copySuccess ) {
754 $this->chmod( $tmpPath );
755 $tmpFiles[$src] = $tmpFile;
756 } elseif ( $hadError ) {
757 $tmpFiles[$src] = self::RES_ERROR; // copy failed
758 } else {
759 $tmpFiles[$src] = self::RES_ABSENT;
760 }
761 }
762
763 return $tmpFiles;
764 }
765
767 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
768 array $params
769 ) {
770 $path = $this->resolveToFSPath( $params['src'] );
771 if ( $path === null ) {
772 return $this->newStatus( 'backend-fail-invalidpath', $params['src'] );
773 }
774 $command->inputFileFromFile( $boxedName, $path );
775 return $this->newStatus();
776 }
777
779 protected function directoriesAreVirtual() {
780 return false;
781 }
782
788 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
789 $statuses = [];
790
791 $pipes = [];
792 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
793 $pipes[$index] = popen( $fileOpHandle->cmd, 'r' );
794 }
795
796 $errs = [];
797 foreach ( $pipes as $index => $pipe ) {
798 // Result will be empty on success in *NIX. On Windows,
799 // it may be something like " 1 file(s) [copied|moved].".
800 $errs[$index] = stream_get_contents( $pipe );
801 fclose( $pipe );
802 }
803
804 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
805 $status = $this->newStatus();
806 $function = $fileOpHandle->callback;
807 $function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
808 $statuses[$index] = $status;
809 }
810
811 return $statuses;
812 }
813
818 private function makeStagingPath( $fsPath ) {
819 $time = dechex( time() ); // make it easy to find old orphans
820 $hash = \Wikimedia\base_convert( md5( basename( $fsPath ) ), 16, 36, 25 );
821 $unique = \Wikimedia\base_convert( bin2hex( random_bytes( 16 ) ), 16, 36, 25 );
822
823 return dirname( $fsPath ) . "/.{$time}_{$hash}_{$unique}.tmpfsfile";
824 }
825
832 private function makeCopyCommand( $fsSrcPath, $fsDstPath, $ignoreMissing ) {
833 // Use copy+rename since (a) this clears xattrs, (b) threads still reading the old
834 // inode are unaffected since it writes to a new inode, and (c) new threads reading
835 // the file will either totally see the old version or totally see the new version
836 $fsStagePath = $this->makeStagingPath( $fsDstPath );
837 $encSrc = Shellbox::escape( $this->cleanPathSlashes( $fsSrcPath ) );
838 $encStage = Shellbox::escape( $this->cleanPathSlashes( $fsStagePath ) );
839 $encDst = Shellbox::escape( $this->cleanPathSlashes( $fsDstPath ) );
840 if ( $this->os === 'Windows' ) {
841 // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/copy
842 // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/move
843 $cmdWrite = "COPY /B /Y $encSrc $encStage 2>&1 && MOVE /Y $encStage $encDst 2>&1";
844 $cmd = $ignoreMissing ? "IF EXIST $encSrc $cmdWrite" : $cmdWrite;
845 } else {
846 // https://manpages.debian.org/buster/coreutils/cp.1.en.html
847 // https://manpages.debian.org/buster/coreutils/mv.1.en.html
848 $cmdWrite = "cp $encSrc $encStage 2>&1 && mv $encStage $encDst 2>&1";
849 $cmd = $ignoreMissing ? "test -f $encSrc && $cmdWrite" : $cmdWrite;
850 // Clean up permissions on any newly created destination file
851 $octalPermissions = '0' . decoct( $this->fileMode );
852 if ( strlen( $octalPermissions ) == 4 ) {
853 $cmd .= " && chmod $octalPermissions $encDst 2>/dev/null";
854 }
855 }
856
857 return $cmd;
858 }
859
866 private function makeMoveCommand( $fsSrcPath, $fsDstPath, $ignoreMissing = false ) {
867 // https://manpages.debian.org/buster/coreutils/mv.1.en.html
868 // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/move
869 $encSrc = Shellbox::escape( $this->cleanPathSlashes( $fsSrcPath ) );
870 $encDst = Shellbox::escape( $this->cleanPathSlashes( $fsDstPath ) );
871 if ( $this->os === 'Windows' ) {
872 $writeCmd = "MOVE /Y $encSrc $encDst 2>&1";
873 $cmd = $ignoreMissing ? "IF EXIST $encSrc $writeCmd" : $writeCmd;
874 } else {
875 $writeCmd = "mv -f $encSrc $encDst 2>&1";
876 $cmd = $ignoreMissing ? "test -f $encSrc && $writeCmd" : $writeCmd;
877 }
878
879 return $cmd;
880 }
881
887 private function makeUnlinkCommand( $fsPath, $ignoreMissing = false ) {
888 // https://manpages.debian.org/buster/coreutils/rm.1.en.html
889 // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/del
890 $encSrc = Shellbox::escape( $this->cleanPathSlashes( $fsPath ) );
891 if ( $this->os === 'Windows' ) {
892 $writeCmd = "DEL /Q $encSrc 2>&1";
893 $cmd = $ignoreMissing ? "IF EXIST $encSrc $writeCmd" : $writeCmd;
894 } else {
895 $cmd = $ignoreMissing ? "rm -f $encSrc 2>&1" : "rm $encSrc 2>&1";
896 }
897
898 return $cmd;
899 }
900
907 protected function chmod( $fsPath ) {
908 if ( $this->os === 'Windows' ) {
909 return true;
910 }
911
912 AtEase::suppressWarnings();
913 $ok = chmod( $fsPath, $this->fileMode );
914 AtEase::restoreWarnings();
915
916 return $ok;
917 }
918
925 protected function unlink( $fsPath ) {
926 AtEase::suppressWarnings();
927 $ok = unlink( $fsPath );
928 AtEase::restoreWarnings();
929 clearstatcache( true, $fsPath );
930
931 return $ok;
932 }
933
940 protected function rmdir( $fsDirectory ) {
941 AtEase::suppressWarnings();
942 $ok = rmdir( $fsDirectory ); // remove directory if empty
943 AtEase::restoreWarnings();
944 clearstatcache( true, $fsDirectory );
945
946 return $ok;
947 }
948
953 protected function newTempFileWithContent( array $params ) {
954 $tempFile = $this->tmpFileFactory->newTempFSFile( 'create_', 'tmp' );
955 if ( !$tempFile ) {
956 return null;
957 }
958
959 AtEase::suppressWarnings();
960 if ( file_put_contents( $tempFile->getPath(), $params['content'] ) === false ) {
961 $tempFile = null;
962 }
963 AtEase::restoreWarnings();
964
965 return $tempFile;
966 }
967
973 protected function indexHtmlPrivate() {
974 return '';
975 }
976
982 protected function htaccessPrivate() {
983 return "Require all denied\n" .
984 "Satisfy All\n";
985 }
986
993 protected function cleanPathSlashes( $fsPath ) {
994 return ( $this->os === 'Windows' ) ? strtr( $fsPath, '/', '\\' ) : $fsPath;
995 }
996
1002 protected function trapWarnings( $regexIgnore = null ) {
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;
1008 }
1009 return true; // suppress from PHP handler
1010 }, E_WARNING );
1011 }
1012
1016 protected function trapWarningsIgnoringNotFound() {
1017 $this->trapWarnings( $this->getFileNotFoundRegex() );
1018 }
1019
1025 protected function untrapWarnings() {
1026 restore_error_handler();
1027
1028 return array_pop( $this->warningTrapStack );
1029 }
1030
1036 protected function getFileNotFoundRegex() {
1037 static $regex;
1038 if ( $regex === null ) {
1039 // "No such file or directory": string literal in spl_directory.c etc.
1040 $alternatives = [ ': No such file or directory' ];
1041 if ( $this->os === 'Windows' ) {
1042 // 2 = The system cannot find the file specified.
1043 // 3 = The system cannot find the path specified.
1044 $alternatives[] = ' \‍(code: [23]\‍)';
1045 }
1046 if ( function_exists( 'pcntl_strerror' ) ) {
1047 $alternatives[] = preg_quote( ': ' . pcntl_strerror( 2 ), '/' );
1048 } elseif ( function_exists( 'socket_strerror' ) && defined( 'SOCKET_ENOENT' ) ) {
1049 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive on Windows only
1050 $alternatives[] = preg_quote( ': ' . socket_strerror( SOCKET_ENOENT ), '/' );
1051 }
1052 $regex = '/(' . implode( '|', $alternatives ) . ')$/';
1053 }
1054 return $regex;
1055 }
1056
1063 protected function isFileNotFoundError( $error ) {
1064 return (bool)preg_match( $this->getFileNotFoundRegex(), $error );
1065 }
1066}
1067
1069class_alias( FSFileBackend::class, 'FSFileBackend' );
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Class for a file system (FS) based file backend.
doDirectoryExists( $fullCont, $dirRel, array $params)
FileBackendStore::directoryExists()bool|null
doDeleteInternal(array $params)
FileBackendStore::deleteInternal() StatusValue
addShellboxInputFile(BoxedCommand $command, string $boxedName, array $params)
Add a file to a Shellbox command as an input file.StatusValue 1.43
doStoreInternal(array $params)
FileBackendStore::storeInternal() StatusValue
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path in the backend.FS backends should c...
doPrepareInternal( $fullCont, $dirRel, array $params)
FileBackendStore::doPrepare() to override StatusValue Good status without value for success,...
indexHtmlPrivate()
Return the text of an index.html file to hide directory listings.
doSecureInternal( $fullCont, $dirRel, array $params)
FileBackendStore::doSecure() to override StatusValue Good status without value for success,...
doCreateInternal(array $params)
FileBackendStore::createInternal() StatusValue
MapCacheLRU $usableDirCache
Cache for known prepared/usable directories.
string $fileOwner
Required OS username to own files.
htaccessPrivate()
Return the text of a .htaccess file to make a directory private.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.to overrideint Bitfield of FileB...
isLegalRelPath( $fsPath)
Check a relative file system path for validity.
resolveToFSPath( $storagePath)
Get the absolute file system path for a storage path.
string $currentUser
OS username running this script.
trapWarningsIgnoringNotFound()
Track E_WARNING errors but ignore any that correspond to ENOENT "No such file or directory".
unlink( $fsPath)
Unlink a file, suppressing the warnings.
getDirectoryListInternal( $fullCont, $dirRel, array $params)
int $dirMode
Directory permission mode.
doExecuteOpHandlesInternal(array $fileOpHandles)
containerFSRoot( $shortCont, $fullCont)
Given the short (unresolved) and full (resolved) name of a container, return the file system path of ...
doGetFileStat(array $params)
FileBackendStore::getFileStat() array|false|null
doCopyInternal(array $params)
FileBackendStore::copyInternal() StatusValue
untrapWarnings()
Stop listening for E_WARNING errors and get whether any happened.
array< string, string > $containerPaths
Map of container names to root paths for custom container paths.
isFileNotFoundError( $error)
Determine whether a given error message is a file not found error.
trapWarnings( $regexIgnore=null)
Listen for E_WARNING errors and track whether any that happen.
doPublishInternal( $fullCont, $dirRel, array $params)
FileBackendStore::doPublish() to override StatusValue
string null $basePath
Directory holding the container directories.
cleanPathSlashes( $fsPath)
Clean up directory separators for the given OS.
doCleanInternal( $fullCont, $dirRel, array $params)
FileBackendStore::doClean() to override StatusValue
string $os
Simpler version of PHP_OS_FAMILY.
doMoveInternal(array $params)
FileBackendStore::moveInternal() StatusValue
doGetLocalCopyMulti(array $params)
FileBackendStore::getLocalCopyMulti() string[]|bool[]|null[] Map of (path => TempFSFile,...
doClearCache(?array $paths=null)
Clears any additional stat caches for storage paths.to overrideFileBackend::clearCache()
int $fileMode
File permission mode.
rmdir( $fsDirectory)
Remove an empty directory, suppressing the warnings.
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
doGetLocalReferenceMulti(array $params)
FileBackendStore::getLocalReferenceMulti() to override string[]|bool[]|null[] Map of (path => FSFile,...
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.This is intended for interna...
chmod( $fsPath)
Chmod a file, suppressing the warnings.
getFileNotFoundRegex()
Get a regex matching file not found errors.
getFileListInternal( $fullCont, $dirRel, array $params)
Class representing a non-directory file on the file system.
Definition FSFile.php:21
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Base class for all backends using particular storage medium.
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
newStatus( $message=null,... $params)
Yields the result of the status wrapper callback on either:
copy(array $params, array $opts=[])
Performs a single copy operation.
Store key-value entries in a size-limited in-memory LRU cache.
$source