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