227941e50b7626a995570e3d4fb5c64cbfb86a6a
[lhc/web/wiklou.git] / includes / filerepo / backend / FileBackend.php
1 <?php
2 /**
3 * @defgroup FileBackend File backend
4 * @ingroup FileRepo
5 *
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
8 */
9
10 /**
11 * @file
12 * @ingroup FileBackend
13 * @author Aaron Schulz
14 */
15
16 /**
17 * @brief Base class for all file backend classes (including multi-write backends).
18 *
19 * This class defines the methods as abstract that subclasses must implement.
20 * Outside callers can assume that all backends will have these functions.
21 *
22 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
23 * The <path> portion is a relative path that uses UNIX file system (FS) notation,
24 * though any particular backend may not actually be using a local filesystem.
25 * Therefore, the relative paths are only virtual.
26 *
27 * Backend contents are stored under wiki-specific container names by default.
28 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
29 * segregation must be done by setting the container paths appropriately.
30 *
31 * FS-based backends are somewhat more restrictive due to the existence of real
32 * directory files; a regular file cannot have the same name as a directory. Other
33 * backends with virtual directories may not have this limitation. Callers should
34 * store files in such a way that no files and directories are under the same path.
35 *
36 * Methods should avoid throwing exceptions at all costs.
37 * As a corollary, external dependencies should be kept to a minimum.
38 *
39 * @ingroup FileBackend
40 * @since 1.19
41 */
42 abstract class FileBackend {
43 protected $name; // string; unique backend name
44 protected $wikiId; // string; unique wiki name
45 protected $readOnly; // string; read-only explanation message
46 /** @var LockManager */
47 protected $lockManager;
48
49 /**
50 * Create a new backend instance from configuration.
51 * This should only be called from within FileBackendGroup.
52 *
53 * $config includes:
54 * 'name' : The unique name of this backend.
55 * This should consist of alphanumberic, '-', and '_' characters.
56 * This name should not be changed after use.
57 * 'wikiId' : Prefix to container names that is unique to this wiki.
58 * This should consist of alphanumberic, '-', and '_' characters.
59 * 'lockManager' : Registered name of a file lock manager to use.
60 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
61 * It should be an explanation for the backend being read-only.
62 *
63 * @param $config Array
64 */
65 public function __construct( array $config ) {
66 $this->name = $config['name'];
67 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
68 throw new MWException( "Backend name `{$this->name}` is invalid." );
69 }
70 $this->wikiId = isset( $config['wikiId'] )
71 ? $config['wikiId']
72 : wfWikiID(); // e.g. "my_wiki-en_"
73 $this->lockManager = ( $config['lockManager'] instanceof LockManager )
74 ? $config['lockManager']
75 : LockManagerGroup::singleton()->get( $config['lockManager'] );
76 $this->readOnly = isset( $config['readOnly'] )
77 ? (string)$config['readOnly']
78 : '';
79 }
80
81 /**
82 * Get the unique backend name.
83 * We may have multiple different backends of the same type.
84 * For example, we can have two Swift backends using different proxies.
85 *
86 * @return string
87 */
88 final public function getName() {
89 return $this->name;
90 }
91
92 /**
93 * Check if this backend is read-only
94 *
95 * @return bool
96 */
97 final public function isReadOnly() {
98 return ( $this->readOnly != '' );
99 }
100
101 /**
102 * Get an explanatory message if this backend is read-only
103 *
104 * @return string|bool Returns falls if the backend is not read-only
105 */
106 final public function getReadOnlyReason() {
107 return ( $this->readOnly != '' ) ? $this->readOnly : false;
108 }
109
110 /**
111 * This is the main entry point into the backend for write operations.
112 * Callers supply an ordered list of operations to perform as a transaction.
113 * Files will be locked, the stat cache cleared, and then the operations attempted.
114 * If any serious errors occur, all attempted operations will be rolled back.
115 *
116 * $ops is an array of arrays. The outer array holds a list of operations.
117 * Each inner array is a set of key value pairs that specify an operation.
118 *
119 * Supported operations and their parameters:
120 * a) Create a new file in storage with the contents of a string
121 * array(
122 * 'op' => 'create',
123 * 'dst' => <storage path>,
124 * 'content' => <string of new file contents>,
125 * 'overwrite' => <boolean>,
126 * 'overwriteSame' => <boolean>
127 * )
128 * b) Copy a file system file into storage
129 * array(
130 * 'op' => 'store',
131 * 'src' => <file system path>,
132 * 'dst' => <storage path>,
133 * 'overwrite' => <boolean>,
134 * 'overwriteSame' => <boolean>
135 * )
136 * c) Copy a file within storage
137 * array(
138 * 'op' => 'copy',
139 * 'src' => <storage path>,
140 * 'dst' => <storage path>,
141 * 'overwrite' => <boolean>,
142 * 'overwriteSame' => <boolean>
143 * )
144 * d) Move a file within storage
145 * array(
146 * 'op' => 'move',
147 * 'src' => <storage path>,
148 * 'dst' => <storage path>,
149 * 'overwrite' => <boolean>,
150 * 'overwriteSame' => <boolean>
151 * )
152 * e) Delete a file within storage
153 * array(
154 * 'op' => 'delete',
155 * 'src' => <storage path>,
156 * 'ignoreMissingSource' => <boolean>
157 * )
158 * f) Do nothing (no-op)
159 * array(
160 * 'op' => 'null',
161 * )
162 *
163 * Boolean flags for operations (operation-specific):
164 * 'ignoreMissingSource' : The operation will simply succeed and do
165 * nothing if the source file does not exist.
166 * 'overwrite' : Any destination file will be overwritten.
167 * 'overwriteSame' : An error will not be given if a file already
168 * exists at the destination that has the same
169 * contents as the new contents to be written there.
170 *
171 * $opts is an associative of boolean flags, including:
172 * 'force' : Errors that would normally cause a rollback do not.
173 * The remaining operations are still attempted if any fail.
174 * 'nonLocking' : No locks are acquired for the operations.
175 * This can increase performance for non-critical writes.
176 * This has no effect unless the 'force' flag is set.
177 * 'allowStale' : Don't require the latest available data.
178 * This can increase performance for non-critical writes.
179 * This has no effect unless the 'force' flag is set.
180 *
181 * Remarks on locking:
182 * File system paths given to operations should refer to files that are
183 * already locked or otherwise safe from modification from other processes.
184 * Normally these files will be new temp files, which should be adequate.
185 *
186 * Return value:
187 * This returns a Status, which contains all warnings and fatals that occured
188 * during the operation. The 'failCount', 'successCount', and 'success' members
189 * will reflect each operation attempted. The status will be "OK" unless any
190 * of the operations failed and the 'force' parameter was not set.
191 *
192 * @param $ops Array List of operations to execute in order
193 * @param $opts Array Batch operation options
194 * @return Status
195 */
196 final public function doOperations( array $ops, array $opts = array() ) {
197 if ( $this->isReadOnly() ) {
198 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
199 }
200 if ( empty( $opts['force'] ) ) { // sanity
201 unset( $opts['nonLocking'] );
202 unset( $opts['allowStale'] );
203 }
204 return $this->doOperationsInternal( $ops, $opts );
205 }
206
207 /**
208 * @see FileBackend::doOperations()
209 */
210 abstract protected function doOperationsInternal( array $ops, array $opts );
211
212 /**
213 * Same as doOperations() except it takes a single operation.
214 * If you are doing a batch of operations that should either
215 * all succeed or all fail, then use that function instead.
216 *
217 * @see FileBackend::doOperations()
218 *
219 * @param $op Array Operation
220 * @param $opts Array Operation options
221 * @return Status
222 */
223 final public function doOperation( array $op, array $opts = array() ) {
224 return $this->doOperations( array( $op ), $opts );
225 }
226
227 /**
228 * Performs a single create operation.
229 * This sets $params['op'] to 'create' and passes it to doOperation().
230 *
231 * @see FileBackend::doOperation()
232 *
233 * @param $params Array Operation parameters
234 * @param $opts Array Operation options
235 * @return Status
236 */
237 final public function create( array $params, array $opts = array() ) {
238 $params['op'] = 'create';
239 return $this->doOperation( $params, $opts );
240 }
241
242 /**
243 * Performs a single store operation.
244 * This sets $params['op'] to 'store' and passes it to doOperation().
245 *
246 * @see FileBackend::doOperation()
247 *
248 * @param $params Array Operation parameters
249 * @param $opts Array Operation options
250 * @return Status
251 */
252 final public function store( array $params, array $opts = array() ) {
253 $params['op'] = 'store';
254 return $this->doOperation( $params, $opts );
255 }
256
257 /**
258 * Performs a single copy operation.
259 * This sets $params['op'] to 'copy' and passes it to doOperation().
260 *
261 * @see FileBackend::doOperation()
262 *
263 * @param $params Array Operation parameters
264 * @param $opts Array Operation options
265 * @return Status
266 */
267 final public function copy( array $params, array $opts = array() ) {
268 $params['op'] = 'copy';
269 return $this->doOperation( $params, $opts );
270 }
271
272 /**
273 * Performs a single move operation.
274 * This sets $params['op'] to 'move' and passes it to doOperation().
275 *
276 * @see FileBackend::doOperation()
277 *
278 * @param $params Array Operation parameters
279 * @param $opts Array Operation options
280 * @return Status
281 */
282 final public function move( array $params, array $opts = array() ) {
283 $params['op'] = 'move';
284 return $this->doOperation( $params, $opts );
285 }
286
287 /**
288 * Performs a single delete operation.
289 * This sets $params['op'] to 'delete' and passes it to doOperation().
290 *
291 * @see FileBackend::doOperation()
292 *
293 * @param $params Array Operation parameters
294 * @param $opts Array Operation options
295 * @return Status
296 */
297 final public function delete( array $params, array $opts = array() ) {
298 $params['op'] = 'delete';
299 return $this->doOperation( $params, $opts );
300 }
301
302 /**
303 * Concatenate a list of storage files into a single file system file.
304 * The target path should refer to a file that is already locked or
305 * otherwise safe from modification from other processes. Normally,
306 * the file will be a new temp file, which should be adequate.
307 * $params include:
308 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
309 * dst : file system path to 0-byte temp file
310 *
311 * @param $params Array Operation parameters
312 * @return Status
313 */
314 abstract public function concatenate( array $params );
315
316 /**
317 * Prepare a storage directory for usage.
318 * This will create any required containers and parent directories.
319 * Backends using key/value stores only need to create the container.
320 *
321 * $params include:
322 * dir : storage directory
323 *
324 * @param $params Array
325 * @return Status
326 */
327 final public function prepare( array $params ) {
328 if ( $this->isReadOnly() ) {
329 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
330 }
331 return $this->doPrepare( $params );
332 }
333
334 /**
335 * @see FileBackend::prepare()
336 */
337 abstract protected function doPrepare( array $params );
338
339 /**
340 * Take measures to block web access to a storage directory and
341 * the container it belongs to. FS backends might add .htaccess
342 * files whereas key/value store backends might restrict container
343 * access to the auth user that represents end-users in web request.
344 * This is not guaranteed to actually do anything.
345 *
346 * $params include:
347 * dir : storage directory
348 * noAccess : try to deny file access
349 * noListing : try to deny file listing
350 *
351 * @param $params Array
352 * @return Status
353 */
354 final public function secure( array $params ) {
355 if ( $this->isReadOnly() ) {
356 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
357 }
358 $status = $this->doPrepare( $params ); // dir must exist to restrict it
359 if ( $status->isOK() ) {
360 $status->merge( $this->doSecure( $params ) );
361 }
362 return $status;
363 }
364
365 /**
366 * @see FileBackend::secure()
367 */
368 abstract protected function doSecure( array $params );
369
370 /**
371 * Delete a storage directory if it is empty.
372 * Backends using key/value stores may do nothing unless the directory
373 * is that of an empty container, in which case it should be deleted.
374 *
375 * $params include:
376 * dir : storage directory
377 *
378 * @param $params Array
379 * @return Status
380 */
381 final public function clean( array $params ) {
382 if ( $this->isReadOnly() ) {
383 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
384 }
385 return $this->doClean( $params );
386 }
387
388 /**
389 * @see FileBackend::clean()
390 */
391 abstract protected function doClean( array $params );
392
393 /**
394 * Check if a file exists at a storage path in the backend.
395 * This returns false if only a directory exists at the path.
396 *
397 * $params include:
398 * src : source storage path
399 * latest : use the latest available data
400 *
401 * @param $params Array
402 * @return bool|null Returns null on failure
403 */
404 abstract public function fileExists( array $params );
405
406 /**
407 * Get the last-modified timestamp of the file at a storage path.
408 *
409 * $params include:
410 * src : source storage path
411 * latest : use the latest available data
412 *
413 * @param $params Array
414 * @return string|bool TS_MW timestamp or false on failure
415 */
416 abstract public function getFileTimestamp( array $params );
417
418 /**
419 * Get the contents of a file at a storage path in the backend.
420 * This should be avoided for potentially large files.
421 *
422 * $params include:
423 * src : source storage path
424 * latest : use the latest available data
425 *
426 * @param $params Array
427 * @return string|bool Returns false on failure
428 */
429 abstract public function getFileContents( array $params );
430
431 /**
432 * Get the size (bytes) of a file at a storage path in the backend.
433 *
434 * $params include:
435 * src : source storage path
436 * latest : use the latest available data
437 *
438 * @param $params Array
439 * @return integer|bool Returns false on failure
440 */
441 abstract public function getFileSize( array $params );
442
443 /**
444 * Get quick information about a file at a storage path in the backend.
445 * If the file does not exist, then this returns false.
446 * Otherwise, the result is an associative array that includes:
447 * mtime : the last-modified timestamp (TS_MW)
448 * size : the file size (bytes)
449 * Additional values may be included for internal use only.
450 *
451 * $params include:
452 * src : source storage path
453 * latest : use the latest available data
454 *
455 * @param $params Array
456 * @return Array|bool|null Returns null on failure
457 */
458 abstract public function getFileStat( array $params );
459
460 /**
461 * Get a SHA-1 hash of the file at a storage path in the backend.
462 *
463 * $params include:
464 * src : source storage path
465 * latest : use the latest available data
466 *
467 * @param $params Array
468 * @return string|bool Hash string or false on failure
469 */
470 abstract public function getFileSha1Base36( array $params );
471
472 /**
473 * Get the properties of the file at a storage path in the backend.
474 * Returns FSFile::placeholderProps() on failure.
475 *
476 * $params include:
477 * src : source storage path
478 * latest : use the latest available data
479 *
480 * @param $params Array
481 * @return Array
482 */
483 abstract public function getFileProps( array $params );
484
485 /**
486 * Stream the file at a storage path in the backend.
487 * If the file does not exists, a 404 error will be given.
488 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
489 * must be sent if streaming began, while none should be sent otherwise.
490 * Implementations should flush the output buffer before sending data.
491 *
492 * $params include:
493 * src : source storage path
494 * headers : additional HTTP headers to send on success
495 * latest : use the latest available data
496 *
497 * @param $params Array
498 * @return Status
499 */
500 abstract public function streamFile( array $params );
501
502 /**
503 * Returns a file system file, identical to the file at a storage path.
504 * The file returned is either:
505 * a) A local copy of the file at a storage path in the backend.
506 * The temporary copy will have the same extension as the source.
507 * b) An original of the file at a storage path in the backend.
508 * Temporary files may be purged when the file object falls out of scope.
509 *
510 * Write operations should *never* be done on this file as some backends
511 * may do internal tracking or may be instances of FileBackendMultiWrite.
512 * In that later case, there are copies of the file that must stay in sync.
513 * Additionally, further calls to this function may return the same file.
514 *
515 * $params include:
516 * src : source storage path
517 * latest : use the latest available data
518 *
519 * @param $params Array
520 * @return FSFile|null Returns null on failure
521 */
522 abstract public function getLocalReference( array $params );
523
524 /**
525 * Get a local copy on disk of the file at a storage path in the backend.
526 * The temporary copy will have the same file extension as the source.
527 * Temporary files may be purged when the file object falls out of scope.
528 *
529 * $params include:
530 * src : source storage path
531 * latest : use the latest available data
532 *
533 * @param $params Array
534 * @return TempFSFile|null Returns null on failure
535 */
536 abstract public function getLocalCopy( array $params );
537
538 /**
539 * Get an iterator to list out all stored files under a storage directory.
540 * If the directory is of the form "mwstore://backend/container",
541 * then all files in the container should be listed.
542 * If the directory is of form "mwstore://backend/container/dir",
543 * then all files under that container directory should be listed.
544 * Results should be storage paths relative to the given directory.
545 *
546 * Storage backends with eventual consistency might return stale data.
547 *
548 * $params include:
549 * dir : storage path directory
550 *
551 * @return Traversable|Array|null Returns null on failure
552 */
553 abstract public function getFileList( array $params );
554
555 /**
556 * Invalidate any in-process file existence and property cache.
557 * If $paths is given, then only the cache for those files will be cleared.
558 *
559 * @param $paths Array Storage paths (optional)
560 * @return void
561 */
562 public function clearCache( array $paths = null ) {}
563
564 /**
565 * Lock the files at the given storage paths in the backend.
566 * This will either lock all the files or none (on failure).
567 *
568 * Callers should consider using getScopedFileLocks() instead.
569 *
570 * @param $paths Array Storage paths
571 * @param $type integer LockManager::LOCK_* constant
572 * @return Status
573 */
574 final public function lockFiles( array $paths, $type ) {
575 return $this->lockManager->lock( $paths, $type );
576 }
577
578 /**
579 * Unlock the files at the given storage paths in the backend.
580 *
581 * @param $paths Array Storage paths
582 * @param $type integer LockManager::LOCK_* constant
583 * @return Status
584 */
585 final public function unlockFiles( array $paths, $type ) {
586 return $this->lockManager->unlock( $paths, $type );
587 }
588
589 /**
590 * Lock the files at the given storage paths in the backend.
591 * This will either lock all the files or none (on failure).
592 * On failure, the status object will be updated with errors.
593 *
594 * Once the return value goes out scope, the locks will be released and
595 * the status updated. Unlock fatals will not change the status "OK" value.
596 *
597 * @param $paths Array Storage paths
598 * @param $type integer LockManager::LOCK_* constant
599 * @param $status Status Status to update on lock/unlock
600 * @return ScopedLock|null Returns null on failure
601 */
602 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
603 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
604 }
605
606 /**
607 * Check if a given path is a "mwstore://" path.
608 * This does not do any further validation or any existence checks.
609 *
610 * @param $path string
611 * @return bool
612 */
613 final public static function isStoragePath( $path ) {
614 return ( strpos( $path, 'mwstore://' ) === 0 );
615 }
616
617 /**
618 * Split a storage path into a backend name, a container name,
619 * and a relative file path. The relative path may be the empty string.
620 * This does not do any path normalization or traversal checks.
621 *
622 * @param $storagePath string
623 * @return Array (backend, container, rel object) or (null, null, null)
624 */
625 final public static function splitStoragePath( $storagePath ) {
626 if ( self::isStoragePath( $storagePath ) ) {
627 // Remove the "mwstore://" prefix and split the path
628 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
629 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
630 if ( count( $parts ) == 3 ) {
631 return $parts; // e.g. "backend/container/path"
632 } else {
633 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
634 }
635 }
636 }
637 return array( null, null, null );
638 }
639
640 /**
641 * Normalize a storage path by cleaning up directory separators.
642 * Returns null if the path is not of the format of a valid storage path.
643 *
644 * @param $storagePath string
645 * @return string|null
646 */
647 final public static function normalizeStoragePath( $storagePath ) {
648 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
649 if ( $relPath !== null ) { // must be for this backend
650 $relPath = self::normalizeContainerPath( $relPath );
651 if ( $relPath !== null ) {
652 return ( $relPath != '' )
653 ? "mwstore://{$backend}/{$container}/{$relPath}"
654 : "mwstore://{$backend}/{$container}";
655 }
656 }
657 return null;
658 }
659
660 /**
661 * Get the parent storage directory of a storage path.
662 * This returns a path like "mwstore://backend/container",
663 * "mwstore://backend/container/...", or null if there is no parent.
664 *
665 * @param $storagePath string
666 * @return string|null
667 */
668 final public static function parentStoragePath( $storagePath ) {
669 $storagePath = dirname( $storagePath );
670 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
671 return ( $rel === null ) ? null : $storagePath;
672 }
673
674 /**
675 * Get the final extension from a storage or FS path
676 *
677 * @param $path string
678 * @return string
679 */
680 final public static function extensionFromPath( $path ) {
681 $i = strrpos( $path, '.' );
682 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
683 }
684
685 /**
686 * Validate and normalize a relative storage path.
687 * Null is returned if the path involves directory traversal.
688 * Traversal is insecure for FS backends and broken for others.
689 *
690 * @param $path string Storage path relative to a container
691 * @return string|null
692 */
693 final protected static function normalizeContainerPath( $path ) {
694 // Normalize directory separators
695 $path = strtr( $path, '\\', '/' );
696 // Collapse any consecutive directory separators
697 $path = preg_replace( '![/]{2,}!', '/', $path );
698 // Remove any leading directory separator
699 $path = ltrim( $path, '/' );
700 // Use the same traversal protection as Title::secureAndSplit()
701 if ( strpos( $path, '.' ) !== false ) {
702 if (
703 $path === '.' ||
704 $path === '..' ||
705 strpos( $path, './' ) === 0 ||
706 strpos( $path, '../' ) === 0 ||
707 strpos( $path, '/./' ) !== false ||
708 strpos( $path, '/../' ) !== false
709 ) {
710 return null;
711 }
712 }
713 return $path;
714 }
715 }