373ad93a34b94fd95c2d0ae1ec079549d7e6dcce
[lhc/web/wiklou.git] / includes / libs / filebackend / SwiftFileBackend.php
1 <?php
2 /**
3 * OpenStack Swift based file backend.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Russ Nelson
23 */
24
25 /**
26 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
27 *
28 * StatusValue messages should avoid mentioning the Swift account name.
29 * Likewise, error suppression should be used to avoid path disclosure.
30 *
31 * @ingroup FileBackend
32 * @since 1.19
33 */
34 class SwiftFileBackend extends FileBackendStore {
35 /** @var MultiHttpClient */
36 protected $http;
37 /** @var int TTL in seconds */
38 protected $authTTL;
39 /** @var string Authentication base URL (without version) */
40 protected $swiftAuthUrl;
41 /** @var string Override of storage base URL */
42 protected $swiftStorageUrl;
43 /** @var string Swift user (account:user) to authenticate as */
44 protected $swiftUser;
45 /** @var string Secret key for user */
46 protected $swiftKey;
47 /** @var string Shared secret value for making temp URLs */
48 protected $swiftTempUrlKey;
49 /** @var string S3 access key (RADOS Gateway) */
50 protected $rgwS3AccessKey;
51 /** @var string S3 authentication key (RADOS Gateway) */
52 protected $rgwS3SecretKey;
53 /** @var array Additional users (account:user) to open read permissions for */
54 protected $readUsers;
55 /** @var array Additional users (account:user) to open write permissions for */
56 protected $writeUsers;
57
58 /** @var BagOStuff */
59 protected $srvCache;
60
61 /** @var ProcessCacheLRU Container stat cache */
62 protected $containerStatCache;
63
64 /** @var array */
65 protected $authCreds;
66 /** @var int UNIX timestamp */
67 protected $authSessionTimestamp = 0;
68 /** @var int UNIX timestamp */
69 protected $authErrorTimestamp = null;
70
71 /** @var bool Whether the server is an Ceph RGW */
72 protected $isRGW = false;
73
74 /**
75 * @see FileBackendStore::__construct()
76 * @param array $config Params include:
77 * - swiftAuthUrl : Swift authentication server URL
78 * - swiftUser : Swift user used by MediaWiki (account:username)
79 * - swiftKey : Swift authentication key for the above user
80 * - swiftAuthTTL : Swift authentication TTL (seconds)
81 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
82 * Do not set this until it has been set in the backend.
83 * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response).
84 * This is useful to set if a TLS proxy is in use.
85 * - shardViaHashLevels : Map of container names to sharding config with:
86 * - base : base of hash characters, 16 or 36
87 * - levels : the number of hash levels (and digits)
88 * - repeat : hash subdirectories are prefixed with all the
89 * parent hash directory names (e.g. "a/ab/abc")
90 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
91 * If those are not available, then the main cache will be used.
92 * This is probably insecure in shared hosting environments.
93 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
94 * Do not set this until it has been set in the backend.
95 * This is used for generating expiring pre-authenticated URLs.
96 * Only use this when using rgw and to work around
97 * http://tracker.newdream.net/issues/3454.
98 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
99 * Do not set this until it has been set in the backend.
100 * This is used for generating expiring pre-authenticated URLs.
101 * Only use this when using rgw and to work around
102 * http://tracker.newdream.net/issues/3454.
103 * - readUsers : Swift users that should have read access (account:username)
104 * - writeUsers : Swift users that should have write access (account:username)
105 */
106 public function __construct( array $config ) {
107 parent::__construct( $config );
108 // Required settings
109 $this->swiftAuthUrl = $config['swiftAuthUrl'];
110 $this->swiftUser = $config['swiftUser'];
111 $this->swiftKey = $config['swiftKey'];
112 // Optional settings
113 $this->authTTL = isset( $config['swiftAuthTTL'] )
114 ? $config['swiftAuthTTL']
115 : 15 * 60; // some sane number
116 $this->swiftTempUrlKey = isset( $config['swiftTempUrlKey'] )
117 ? $config['swiftTempUrlKey']
118 : '';
119 $this->swiftStorageUrl = isset( $config['swiftStorageUrl'] )
120 ? $config['swiftStorageUrl']
121 : null;
122 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
123 ? $config['shardViaHashLevels']
124 : '';
125 $this->rgwS3AccessKey = isset( $config['rgwS3AccessKey'] )
126 ? $config['rgwS3AccessKey']
127 : '';
128 $this->rgwS3SecretKey = isset( $config['rgwS3SecretKey'] )
129 ? $config['rgwS3SecretKey']
130 : '';
131 // HTTP helper client
132 $this->http = new MultiHttpClient( [] );
133 // Cache container information to mask latency
134 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache ) {
135 $this->memCache = $config['wanCache'];
136 }
137 // Process cache for container info
138 $this->containerStatCache = new ProcessCacheLRU( 300 );
139 // Cache auth token information to avoid RTTs
140 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
141 $this->srvCache = $config['srvCache'];
142 } else {
143 $this->srvCache = new EmptyBagOStuff();
144 }
145 $this->readUsers = isset( $config['readUsers'] )
146 ? $config['readUsers']
147 : [];
148 $this->writeUsers = isset( $config['writeUsers'] )
149 ? $config['writeUsers']
150 : [];
151 }
152
153 public function getFeatures() {
154 return ( FileBackend::ATTR_UNICODE_PATHS |
155 FileBackend::ATTR_HEADERS | FileBackend::ATTR_METADATA );
156 }
157
158 protected function resolveContainerPath( $container, $relStoragePath ) {
159 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
160 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
161 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
162 return null; // too long for Swift
163 }
164
165 return $relStoragePath;
166 }
167
168 public function isPathUsableInternal( $storagePath ) {
169 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
170 if ( $rel === null ) {
171 return false; // invalid
172 }
173
174 return is_array( $this->getContainerStat( $container ) );
175 }
176
177 /**
178 * Sanitize and filter the custom headers from a $params array.
179 * Only allows certain "standard" Content- and X-Content- headers.
180 *
181 * @param array $params
182 * @return array Sanitized value of 'headers' field in $params
183 */
184 protected function sanitizeHdrs( array $params ) {
185 return isset( $params['headers'] )
186 ? $this->getCustomHeaders( $params['headers'] )
187 : [];
188 }
189
190 /**
191 * @param array $rawHeaders
192 * @return array Custom non-metadata HTTP headers
193 */
194 protected function getCustomHeaders( array $rawHeaders ) {
195 $headers = [];
196
197 // Normalize casing, and strip out illegal headers
198 foreach ( $rawHeaders as $name => $value ) {
199 $name = strtolower( $name );
200 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
201 continue; // blacklisted
202 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
203 $headers[$name] = $value; // allowed
204 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
205 $headers[$name] = $value; // allowed
206 }
207 }
208 // By default, Swift has annoyingly low maximum header value limits
209 if ( isset( $headers['content-disposition'] ) ) {
210 $disposition = '';
211 // @note: assume FileBackend::makeContentDisposition() already used
212 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
213 $part = trim( $part );
214 $new = ( $disposition === '' ) ? $part : "{$disposition};{$part}";
215 if ( strlen( $new ) <= 255 ) {
216 $disposition = $new;
217 } else {
218 break; // too long; sigh
219 }
220 }
221 $headers['content-disposition'] = $disposition;
222 }
223
224 return $headers;
225 }
226
227 /**
228 * @param array $rawHeaders
229 * @return array Custom metadata headers
230 */
231 protected function getMetadataHeaders( array $rawHeaders ) {
232 $headers = [];
233 foreach ( $rawHeaders as $name => $value ) {
234 $name = strtolower( $name );
235 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
236 $headers[$name] = $value;
237 }
238 }
239
240 return $headers;
241 }
242
243 /**
244 * @param array $rawHeaders
245 * @return array Custom metadata headers with prefix removed
246 */
247 protected function getMetadata( array $rawHeaders ) {
248 $metadata = [];
249 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
250 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
251 }
252
253 return $metadata;
254 }
255
256 protected function doCreateInternal( array $params ) {
257 $status = $this->newStatus();
258
259 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
260 if ( $dstRel === null ) {
261 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
262
263 return $status;
264 }
265
266 $sha1Hash = Wikimedia\base_convert( sha1( $params['content'] ), 16, 36, 31 );
267 $contentType = isset( $params['headers']['content-type'] )
268 ? $params['headers']['content-type']
269 : $this->getContentType( $params['dst'], $params['content'], null );
270
271 $reqs = [ [
272 'method' => 'PUT',
273 'url' => [ $dstCont, $dstRel ],
274 'headers' => [
275 'content-length' => strlen( $params['content'] ),
276 'etag' => md5( $params['content'] ),
277 'content-type' => $contentType,
278 'x-object-meta-sha1base36' => $sha1Hash
279 ] + $this->sanitizeHdrs( $params ),
280 'body' => $params['content']
281 ] ];
282
283 $method = __METHOD__;
284 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
285 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
286 if ( $rcode === 201 ) {
287 // good
288 } elseif ( $rcode === 412 ) {
289 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
290 } else {
291 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
292 }
293 };
294
295 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
296 if ( !empty( $params['async'] ) ) { // deferred
297 $status->value = $opHandle;
298 } else { // actually write the object in Swift
299 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
300 }
301
302 return $status;
303 }
304
305 protected function doStoreInternal( array $params ) {
306 $status = $this->newStatus();
307
308 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
309 if ( $dstRel === null ) {
310 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
311
312 return $status;
313 }
314
315 MediaWiki\suppressWarnings();
316 $sha1Hash = sha1_file( $params['src'] );
317 MediaWiki\restoreWarnings();
318 if ( $sha1Hash === false ) { // source doesn't exist?
319 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
320
321 return $status;
322 }
323 $sha1Hash = Wikimedia\base_convert( $sha1Hash, 16, 36, 31 );
324 $contentType = isset( $params['headers']['content-type'] )
325 ? $params['headers']['content-type']
326 : $this->getContentType( $params['dst'], null, $params['src'] );
327
328 $handle = fopen( $params['src'], 'rb' );
329 if ( $handle === false ) { // source doesn't exist?
330 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
331
332 return $status;
333 }
334
335 $reqs = [ [
336 'method' => 'PUT',
337 'url' => [ $dstCont, $dstRel ],
338 'headers' => [
339 'content-length' => filesize( $params['src'] ),
340 'etag' => md5_file( $params['src'] ),
341 'content-type' => $contentType,
342 'x-object-meta-sha1base36' => $sha1Hash
343 ] + $this->sanitizeHdrs( $params ),
344 'body' => $handle // resource
345 ] ];
346
347 $method = __METHOD__;
348 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
351 // good
352 } elseif ( $rcode === 412 ) {
353 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
354 } else {
355 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
356 }
357 };
358
359 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
360 $opHandle->resourcesToClose[] = $handle;
361
362 if ( !empty( $params['async'] ) ) { // deferred
363 $status->value = $opHandle;
364 } else { // actually write the object in Swift
365 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
366 }
367
368 return $status;
369 }
370
371 protected function doCopyInternal( array $params ) {
372 $status = $this->newStatus();
373
374 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
375 if ( $srcRel === null ) {
376 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
377
378 return $status;
379 }
380
381 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
382 if ( $dstRel === null ) {
383 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
384
385 return $status;
386 }
387
388 $reqs = [ [
389 'method' => 'PUT',
390 'url' => [ $dstCont, $dstRel ],
391 'headers' => [
392 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
393 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
394 ] + $this->sanitizeHdrs( $params ), // extra headers merged into object
395 ] ];
396
397 $method = __METHOD__;
398 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
399 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
400 if ( $rcode === 201 ) {
401 // good
402 } elseif ( $rcode === 404 ) {
403 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
404 } else {
405 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
406 }
407 };
408
409 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
410 if ( !empty( $params['async'] ) ) { // deferred
411 $status->value = $opHandle;
412 } else { // actually write the object in Swift
413 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
414 }
415
416 return $status;
417 }
418
419 protected function doMoveInternal( array $params ) {
420 $status = $this->newStatus();
421
422 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
423 if ( $srcRel === null ) {
424 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
425
426 return $status;
427 }
428
429 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
430 if ( $dstRel === null ) {
431 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
432
433 return $status;
434 }
435
436 $reqs = [
437 [
438 'method' => 'PUT',
439 'url' => [ $dstCont, $dstRel ],
440 'headers' => [
441 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
442 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
443 ] + $this->sanitizeHdrs( $params ) // extra headers merged into object
444 ]
445 ];
446 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
447 $reqs[] = [
448 'method' => 'DELETE',
449 'url' => [ $srcCont, $srcRel ],
450 'headers' => []
451 ];
452 }
453
454 $method = __METHOD__;
455 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
456 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
457 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
458 // good
459 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
460 // good
461 } elseif ( $rcode === 404 ) {
462 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
463 } else {
464 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
465 }
466 };
467
468 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
469 if ( !empty( $params['async'] ) ) { // deferred
470 $status->value = $opHandle;
471 } else { // actually move the object in Swift
472 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
473 }
474
475 return $status;
476 }
477
478 protected function doDeleteInternal( array $params ) {
479 $status = $this->newStatus();
480
481 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
482 if ( $srcRel === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
484
485 return $status;
486 }
487
488 $reqs = [ [
489 'method' => 'DELETE',
490 'url' => [ $srcCont, $srcRel ],
491 'headers' => []
492 ] ];
493
494 $method = __METHOD__;
495 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
496 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
497 if ( $rcode === 204 ) {
498 // good
499 } elseif ( $rcode === 404 ) {
500 if ( empty( $params['ignoreMissingSource'] ) ) {
501 $status->fatal( 'backend-fail-delete', $params['src'] );
502 }
503 } else {
504 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
505 }
506 };
507
508 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
509 if ( !empty( $params['async'] ) ) { // deferred
510 $status->value = $opHandle;
511 } else { // actually delete the object in Swift
512 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
513 }
514
515 return $status;
516 }
517
518 protected function doDescribeInternal( array $params ) {
519 $status = $this->newStatus();
520
521 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
522 if ( $srcRel === null ) {
523 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
524
525 return $status;
526 }
527
528 // Fetch the old object headers/metadata...this should be in stat cache by now
529 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
530 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
531 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
532 }
533 if ( !$stat ) {
534 $status->fatal( 'backend-fail-describe', $params['src'] );
535
536 return $status;
537 }
538
539 // POST clears prior headers, so we need to merge the changes in to the old ones
540 $metaHdrs = [];
541 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
542 $metaHdrs["x-object-meta-$name"] = $value;
543 }
544 $customHdrs = $this->sanitizeHdrs( $params ) + $stat['xattr']['headers'];
545
546 $reqs = [ [
547 'method' => 'POST',
548 'url' => [ $srcCont, $srcRel ],
549 'headers' => $metaHdrs + $customHdrs
550 ] ];
551
552 $method = __METHOD__;
553 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
554 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
555 if ( $rcode === 202 ) {
556 // good
557 } elseif ( $rcode === 404 ) {
558 $status->fatal( 'backend-fail-describe', $params['src'] );
559 } else {
560 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
561 }
562 };
563
564 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
565 if ( !empty( $params['async'] ) ) { // deferred
566 $status->value = $opHandle;
567 } else { // actually change the object in Swift
568 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
569 }
570
571 return $status;
572 }
573
574 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
575 $status = $this->newStatus();
576
577 // (a) Check if container already exists
578 $stat = $this->getContainerStat( $fullCont );
579 if ( is_array( $stat ) ) {
580 return $status; // already there
581 } elseif ( $stat === null ) {
582 $status->fatal( 'backend-fail-internal', $this->name );
583 $this->logger->error( __METHOD__ . ': cannot get container stat' );
584
585 return $status;
586 }
587
588 // (b) Create container as needed with proper ACLs
589 if ( $stat === false ) {
590 $params['op'] = 'prepare';
591 $status->merge( $this->createContainer( $fullCont, $params ) );
592 }
593
594 return $status;
595 }
596
597 protected function doSecureInternal( $fullCont, $dir, array $params ) {
598 $status = $this->newStatus();
599 if ( empty( $params['noAccess'] ) ) {
600 return $status; // nothing to do
601 }
602
603 $stat = $this->getContainerStat( $fullCont );
604 if ( is_array( $stat ) ) {
605 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser ] );
606 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
607 // Make container private to end-users...
608 $status->merge( $this->setContainerAccess(
609 $fullCont,
610 $readUsers,
611 $writeUsers
612 ) );
613 } elseif ( $stat === false ) {
614 $status->fatal( 'backend-fail-usable', $params['dir'] );
615 } else {
616 $status->fatal( 'backend-fail-internal', $this->name );
617 $this->logger->error( __METHOD__ . ': cannot get container stat' );
618 }
619
620 return $status;
621 }
622
623 protected function doPublishInternal( $fullCont, $dir, array $params ) {
624 $status = $this->newStatus();
625
626 $stat = $this->getContainerStat( $fullCont );
627 if ( is_array( $stat ) ) {
628 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser, '.r:*' ] );
629 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
630
631 // Make container public to end-users...
632 $status->merge( $this->setContainerAccess(
633 $fullCont,
634 $readUsers,
635 $writeUsers
636 ) );
637 } elseif ( $stat === false ) {
638 $status->fatal( 'backend-fail-usable', $params['dir'] );
639 } else {
640 $status->fatal( 'backend-fail-internal', $this->name );
641 $this->logger->error( __METHOD__ . ': cannot get container stat' );
642 }
643
644 return $status;
645 }
646
647 protected function doCleanInternal( $fullCont, $dir, array $params ) {
648 $status = $this->newStatus();
649
650 // Only containers themselves can be removed, all else is virtual
651 if ( $dir != '' ) {
652 return $status; // nothing to do
653 }
654
655 // (a) Check the container
656 $stat = $this->getContainerStat( $fullCont, true );
657 if ( $stat === false ) {
658 return $status; // ok, nothing to do
659 } elseif ( !is_array( $stat ) ) {
660 $status->fatal( 'backend-fail-internal', $this->name );
661 $this->logger->error( __METHOD__ . ': cannot get container stat' );
662
663 return $status;
664 }
665
666 // (b) Delete the container if empty
667 if ( $stat['count'] == 0 ) {
668 $params['op'] = 'clean';
669 $status->merge( $this->deleteContainer( $fullCont, $params ) );
670 }
671
672 return $status;
673 }
674
675 protected function doGetFileStat( array $params ) {
676 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] + $params;
677 unset( $params['src'] );
678 $stats = $this->doGetFileStatMulti( $params );
679
680 return reset( $stats );
681 }
682
683 /**
684 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
685 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
686 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
687 *
688 * @param string $ts
689 * @param int $format Output format (TS_* constant)
690 * @return string
691 * @throws FileBackendError
692 */
693 protected function convertSwiftDate( $ts, $format = TS_MW ) {
694 try {
695 $timestamp = new MWTimestamp( $ts );
696
697 return $timestamp->getTimestamp( $format );
698 } catch ( Exception $e ) {
699 throw new FileBackendError( $e->getMessage() );
700 }
701 }
702
703 /**
704 * Fill in any missing object metadata and save it to Swift
705 *
706 * @param array $objHdrs Object response headers
707 * @param string $path Storage path to object
708 * @return array New headers
709 */
710 protected function addMissingMetadata( array $objHdrs, $path ) {
711 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
712 return $objHdrs; // nothing to do
713 }
714
715 /** @noinspection PhpUnusedLocalVariableInspection */
716 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
717 $this->logger->error( __METHOD__ . ": {path} was not stored with SHA-1 metadata.",
718 [ 'path' => $path ] );
719
720 $objHdrs['x-object-meta-sha1base36'] = false;
721
722 $auth = $this->getAuthentication();
723 if ( !$auth ) {
724 return $objHdrs; // failed
725 }
726
727 // Find prior custom HTTP headers
728 $postHeaders = $this->getCustomHeaders( $objHdrs );
729 // Find prior metadata headers
730 $postHeaders += $this->getMetadataHeaders( $objHdrs );
731
732 $status = $this->newStatus();
733 /** @noinspection PhpUnusedLocalVariableInspection */
734 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager::LOCK_UW, $status );
735 if ( $status->isOK() ) {
736 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
737 if ( $tmpFile ) {
738 $hash = $tmpFile->getSha1Base36();
739 if ( $hash !== false ) {
740 $objHdrs['x-object-meta-sha1base36'] = $hash;
741 // Merge new SHA1 header into the old ones
742 $postHeaders['x-object-meta-sha1base36'] = $hash;
743 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
744 list( $rcode ) = $this->http->run( [
745 'method' => 'POST',
746 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
747 'headers' => $this->authTokenHeaders( $auth ) + $postHeaders
748 ] );
749 if ( $rcode >= 200 && $rcode <= 299 ) {
750 $this->deleteFileCache( $path );
751
752 return $objHdrs; // success
753 }
754 }
755 }
756 }
757
758 $this->logger->error( __METHOD__ . ': unable to set SHA-1 metadata for {path}',
759 [ 'path' => $path ] );
760
761 return $objHdrs; // failed
762 }
763
764 protected function doGetFileContentsMulti( array $params ) {
765 $contents = [];
766
767 $auth = $this->getAuthentication();
768
769 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
770 // Blindly create tmp files and stream to them, catching any exception if the file does
771 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
772 $reqs = []; // (path => op)
773
774 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
775 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
776 if ( $srcRel === null || !$auth ) {
777 $contents[$path] = false;
778 continue;
779 }
780 // Create a new temporary memory file...
781 $handle = fopen( 'php://temp', 'wb' );
782 if ( $handle ) {
783 $reqs[$path] = [
784 'method' => 'GET',
785 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
786 'headers' => $this->authTokenHeaders( $auth )
787 + $this->headersFromParams( $params ),
788 'stream' => $handle,
789 ];
790 }
791 $contents[$path] = false;
792 }
793
794 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
795 $reqs = $this->http->runMulti( $reqs, $opts );
796 foreach ( $reqs as $path => $op ) {
797 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
798 if ( $rcode >= 200 && $rcode <= 299 ) {
799 rewind( $op['stream'] ); // start from the beginning
800 $contents[$path] = stream_get_contents( $op['stream'] );
801 } elseif ( $rcode === 404 ) {
802 $contents[$path] = false;
803 } else {
804 $this->onError( null, __METHOD__,
805 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
806 }
807 fclose( $op['stream'] ); // close open handle
808 }
809
810 return $contents;
811 }
812
813 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
814 $prefix = ( $dir == '' ) ? null : "{$dir}/";
815 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
816 if ( $status->isOK() ) {
817 return ( count( $status->value ) ) > 0;
818 }
819
820 return null; // error
821 }
822
823 /**
824 * @see FileBackendStore::getDirectoryListInternal()
825 * @param string $fullCont
826 * @param string $dir
827 * @param array $params
828 * @return SwiftFileBackendDirList
829 */
830 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
831 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
832 }
833
834 /**
835 * @see FileBackendStore::getFileListInternal()
836 * @param string $fullCont
837 * @param string $dir
838 * @param array $params
839 * @return SwiftFileBackendFileList
840 */
841 public function getFileListInternal( $fullCont, $dir, array $params ) {
842 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
843 }
844
845 /**
846 * Do not call this function outside of SwiftFileBackendFileList
847 *
848 * @param string $fullCont Resolved container name
849 * @param string $dir Resolved storage directory with no trailing slash
850 * @param string|null &$after Resolved container relative path to list items after
851 * @param int $limit Max number of items to list
852 * @param array $params Parameters for getDirectoryList()
853 * @return array List of container relative resolved paths of directories directly under $dir
854 * @throws FileBackendError
855 */
856 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
857 $dirs = [];
858 if ( $after === INF ) {
859 return $dirs; // nothing more
860 }
861
862 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
863
864 $prefix = ( $dir == '' ) ? null : "{$dir}/";
865 // Non-recursive: only list dirs right under $dir
866 if ( !empty( $params['topOnly'] ) ) {
867 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
868 if ( !$status->isOK() ) {
869 throw new FileBackendError( "Iterator page I/O error." );
870 }
871 $objects = $status->value;
872 foreach ( $objects as $object ) { // files and directories
873 if ( substr( $object, -1 ) === '/' ) {
874 $dirs[] = $object; // directories end in '/'
875 }
876 }
877 } else {
878 // Recursive: list all dirs under $dir and its subdirs
879 $getParentDir = function ( $path ) {
880 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
881 };
882
883 // Get directory from last item of prior page
884 $lastDir = $getParentDir( $after ); // must be first page
885 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
886
887 if ( !$status->isOK() ) {
888 throw new FileBackendError( "Iterator page I/O error." );
889 }
890
891 $objects = $status->value;
892
893 foreach ( $objects as $object ) { // files
894 $objectDir = $getParentDir( $object ); // directory of object
895
896 if ( $objectDir !== false && $objectDir !== $dir ) {
897 // Swift stores paths in UTF-8, using binary sorting.
898 // See function "create_container_table" in common/db.py.
899 // If a directory is not "greater" than the last one,
900 // then it was already listed by the calling iterator.
901 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
902 $pDir = $objectDir;
903 do { // add dir and all its parent dirs
904 $dirs[] = "{$pDir}/";
905 $pDir = $getParentDir( $pDir );
906 } while ( $pDir !== false // sanity
907 && strcmp( $pDir, $lastDir ) > 0 // not done already
908 && strlen( $pDir ) > strlen( $dir ) // within $dir
909 );
910 }
911 $lastDir = $objectDir;
912 }
913 }
914 }
915 // Page on the unfiltered directory listing (what is returned may be filtered)
916 if ( count( $objects ) < $limit ) {
917 $after = INF; // avoid a second RTT
918 } else {
919 $after = end( $objects ); // update last item
920 }
921
922 return $dirs;
923 }
924
925 /**
926 * Do not call this function outside of SwiftFileBackendFileList
927 *
928 * @param string $fullCont Resolved container name
929 * @param string $dir Resolved storage directory with no trailing slash
930 * @param string|null &$after Resolved container relative path of file to list items after
931 * @param int $limit Max number of items to list
932 * @param array $params Parameters for getDirectoryList()
933 * @return array List of resolved container relative paths of files under $dir
934 * @throws FileBackendError
935 */
936 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
937 $files = []; // list of (path, stat array or null) entries
938 if ( $after === INF ) {
939 return $files; // nothing more
940 }
941
942 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
943
944 $prefix = ( $dir == '' ) ? null : "{$dir}/";
945 // $objects will contain a list of unfiltered names or CF_Object items
946 // Non-recursive: only list files right under $dir
947 if ( !empty( $params['topOnly'] ) ) {
948 if ( !empty( $params['adviseStat'] ) ) {
949 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
950 } else {
951 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
952 }
953 } else {
954 // Recursive: list all files under $dir and its subdirs
955 if ( !empty( $params['adviseStat'] ) ) {
956 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
957 } else {
958 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
959 }
960 }
961
962 // Reformat this list into a list of (name, stat array or null) entries
963 if ( !$status->isOK() ) {
964 throw new FileBackendError( "Iterator page I/O error." );
965 }
966
967 $objects = $status->value;
968 $files = $this->buildFileObjectListing( $params, $dir, $objects );
969
970 // Page on the unfiltered object listing (what is returned may be filtered)
971 if ( count( $objects ) < $limit ) {
972 $after = INF; // avoid a second RTT
973 } else {
974 $after = end( $objects ); // update last item
975 $after = is_object( $after ) ? $after->name : $after;
976 }
977
978 return $files;
979 }
980
981 /**
982 * Build a list of file objects, filtering out any directories
983 * and extracting any stat info if provided in $objects (for CF_Objects)
984 *
985 * @param array $params Parameters for getDirectoryList()
986 * @param string $dir Resolved container directory path
987 * @param array $objects List of CF_Object items or object names
988 * @return array List of (names,stat array or null) entries
989 */
990 private function buildFileObjectListing( array $params, $dir, array $objects ) {
991 $names = [];
992 foreach ( $objects as $object ) {
993 if ( is_object( $object ) ) {
994 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
995 continue; // virtual directory entry; ignore
996 }
997 $stat = [
998 // Convert various random Swift dates to TS_MW
999 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
1000 'size' => (int)$object->bytes,
1001 'sha1' => null,
1002 // Note: manifiest ETags are not an MD5 of the file
1003 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
1004 'latest' => false // eventually consistent
1005 ];
1006 $names[] = [ $object->name, $stat ];
1007 } elseif ( substr( $object, -1 ) !== '/' ) {
1008 // Omit directories, which end in '/' in listings
1009 $names[] = [ $object, null ];
1010 }
1011 }
1012
1013 return $names;
1014 }
1015
1016 /**
1017 * Do not call this function outside of SwiftFileBackendFileList
1018 *
1019 * @param string $path Storage path
1020 * @param array $val Stat value
1021 */
1022 public function loadListingStatInternal( $path, array $val ) {
1023 $this->cheapCache->set( $path, 'stat', $val );
1024 }
1025
1026 protected function doGetFileXAttributes( array $params ) {
1027 $stat = $this->getFileStat( $params );
1028 if ( $stat ) {
1029 if ( !isset( $stat['xattr'] ) ) {
1030 // Stat entries filled by file listings don't include metadata/headers
1031 $this->clearCache( [ $params['src'] ] );
1032 $stat = $this->getFileStat( $params );
1033 }
1034
1035 return $stat['xattr'];
1036 } else {
1037 return false;
1038 }
1039 }
1040
1041 protected function doGetFileSha1base36( array $params ) {
1042 $stat = $this->getFileStat( $params );
1043 if ( $stat ) {
1044 if ( !isset( $stat['sha1'] ) ) {
1045 // Stat entries filled by file listings don't include SHA1
1046 $this->clearCache( [ $params['src'] ] );
1047 $stat = $this->getFileStat( $params );
1048 }
1049
1050 return $stat['sha1'];
1051 } else {
1052 return false;
1053 }
1054 }
1055
1056 protected function doStreamFile( array $params ) {
1057 $status = $this->newStatus();
1058
1059 $flags = !empty( $params['headless'] ) ? StreamFile::STREAM_HEADLESS : 0;
1060
1061 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1062 if ( $srcRel === null ) {
1063 StreamFile::send404Message( $params['src'], $flags );
1064 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1065
1066 return $status;
1067 }
1068
1069 $auth = $this->getAuthentication();
1070 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
1071 StreamFile::send404Message( $params['src'], $flags );
1072 $status->fatal( 'backend-fail-stream', $params['src'] );
1073
1074 return $status;
1075 }
1076
1077 // If "headers" is set, we only want to send them if the file is there.
1078 // Do not bother checking if the file exists if headers are not set though.
1079 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1080 StreamFile::send404Message( $params['src'], $flags );
1081 $status->fatal( 'backend-fail-stream', $params['src'] );
1082
1083 return $status;
1084 }
1085
1086 // Send the requested additional headers
1087 foreach ( $params['headers'] as $header ) {
1088 header( $header ); // aways send
1089 }
1090
1091 if ( empty( $params['allowOB'] ) ) {
1092 // Cancel output buffering and gzipping if set
1093 call_user_func( $this->obResetFunc );
1094 }
1095
1096 $handle = fopen( 'php://output', 'wb' );
1097 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1098 'method' => 'GET',
1099 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1100 'headers' => $this->authTokenHeaders( $auth )
1101 + $this->headersFromParams( $params ) + $params['options'],
1102 'stream' => $handle,
1103 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1104 ] );
1105
1106 if ( $rcode >= 200 && $rcode <= 299 ) {
1107 // good
1108 } elseif ( $rcode === 404 ) {
1109 $status->fatal( 'backend-fail-stream', $params['src'] );
1110 // Per T43113, nasty things can happen if bad cache entries get
1111 // stuck in cache. It's also possible that this error can come up
1112 // with simple race conditions. Clear out the stat cache to be safe.
1113 $this->clearCache( [ $params['src'] ] );
1114 $this->deleteFileCache( $params['src'] );
1115 } else {
1116 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1117 }
1118
1119 return $status;
1120 }
1121
1122 protected function doGetLocalCopyMulti( array $params ) {
1123 /** @var TempFSFile[] $tmpFiles */
1124 $tmpFiles = [];
1125
1126 $auth = $this->getAuthentication();
1127
1128 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1129 // Blindly create tmp files and stream to them, catching any exception if the file does
1130 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1131 $reqs = []; // (path => op)
1132
1133 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1134 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1135 if ( $srcRel === null || !$auth ) {
1136 $tmpFiles[$path] = null;
1137 continue;
1138 }
1139 // Get source file extension
1140 $ext = FileBackend::extensionFromPath( $path );
1141 // Create a new temporary file...
1142 $tmpFile = TempFSFile::factory( 'localcopy_', $ext, $this->tmpDirectory );
1143 if ( $tmpFile ) {
1144 $handle = fopen( $tmpFile->getPath(), 'wb' );
1145 if ( $handle ) {
1146 $reqs[$path] = [
1147 'method' => 'GET',
1148 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1149 'headers' => $this->authTokenHeaders( $auth )
1150 + $this->headersFromParams( $params ),
1151 'stream' => $handle,
1152 ];
1153 } else {
1154 $tmpFile = null;
1155 }
1156 }
1157 $tmpFiles[$path] = $tmpFile;
1158 }
1159
1160 $isLatest = ( $this->isRGW || !empty( $params['latest'] ) );
1161 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1162 $reqs = $this->http->runMulti( $reqs, $opts );
1163 foreach ( $reqs as $path => $op ) {
1164 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1165 fclose( $op['stream'] ); // close open handle
1166 if ( $rcode >= 200 && $rcode <= 299 ) {
1167 $size = $tmpFiles[$path] ? $tmpFiles[$path]->getSize() : 0;
1168 // Double check that the disk is not full/broken
1169 if ( $size != $rhdrs['content-length'] ) {
1170 $tmpFiles[$path] = null;
1171 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1172 $this->onError( null, __METHOD__,
1173 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1174 }
1175 // Set the file stat process cache in passing
1176 $stat = $this->getStatFromHeaders( $rhdrs );
1177 $stat['latest'] = $isLatest;
1178 $this->cheapCache->set( $path, 'stat', $stat );
1179 } elseif ( $rcode === 404 ) {
1180 $tmpFiles[$path] = false;
1181 } else {
1182 $tmpFiles[$path] = null;
1183 $this->onError( null, __METHOD__,
1184 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1185 }
1186 }
1187
1188 return $tmpFiles;
1189 }
1190
1191 public function getFileHttpUrl( array $params ) {
1192 if ( $this->swiftTempUrlKey != '' ||
1193 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1194 ) {
1195 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1196 if ( $srcRel === null ) {
1197 return null; // invalid path
1198 }
1199
1200 $auth = $this->getAuthentication();
1201 if ( !$auth ) {
1202 return null;
1203 }
1204
1205 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1206 $expires = time() + $ttl;
1207
1208 if ( $this->swiftTempUrlKey != '' ) {
1209 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1210 // Swift wants the signature based on the unencoded object name
1211 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1212 $signature = hash_hmac( 'sha1',
1213 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1214 $this->swiftTempUrlKey
1215 );
1216
1217 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1218 } else { // give S3 API URL for rgw
1219 // Path for signature starts with the bucket
1220 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1221 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1222 // Calculate the hash
1223 $signature = base64_encode( hash_hmac(
1224 'sha1',
1225 "GET\n\n\n{$expires}\n{$spath}",
1226 $this->rgwS3SecretKey,
1227 true // raw
1228 ) );
1229 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1230 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1231 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1232 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1233 '?' .
1234 http_build_query( [
1235 'Signature' => $signature,
1236 'Expires' => $expires,
1237 'AWSAccessKeyId' => $this->rgwS3AccessKey
1238 ] );
1239 }
1240 }
1241
1242 return null;
1243 }
1244
1245 protected function directoriesAreVirtual() {
1246 return true;
1247 }
1248
1249 /**
1250 * Get headers to send to Swift when reading a file based
1251 * on a FileBackend params array, e.g. that of getLocalCopy().
1252 * $params is currently only checked for a 'latest' flag.
1253 *
1254 * @param array $params
1255 * @return array
1256 */
1257 protected function headersFromParams( array $params ) {
1258 $hdrs = [];
1259 if ( !empty( $params['latest'] ) ) {
1260 $hdrs['x-newest'] = 'true';
1261 }
1262
1263 return $hdrs;
1264 }
1265
1266 /**
1267 * @param FileBackendStoreOpHandle[] $fileOpHandles
1268 *
1269 * @return StatusValue[]
1270 */
1271 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1272 /** @var StatusValue[] $statuses */
1273 $statuses = [];
1274
1275 $auth = $this->getAuthentication();
1276 if ( !$auth ) {
1277 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1278 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name );
1279 }
1280
1281 return $statuses;
1282 }
1283
1284 // Split the HTTP requests into stages that can be done concurrently
1285 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1286 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1287 /** @var SwiftFileOpHandle $fileOpHandle */
1288 $reqs = $fileOpHandle->httpOp;
1289 // Convert the 'url' parameter to an actual URL using $auth
1290 foreach ( $reqs as $stage => &$req ) {
1291 list( $container, $relPath ) = $req['url'];
1292 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1293 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : [];
1294 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1295 $httpReqsByStage[$stage][$index] = $req;
1296 }
1297 $statuses[$index] = $this->newStatus();
1298 }
1299
1300 // Run all requests for the first stage, then the next, and so on
1301 $reqCount = count( $httpReqsByStage );
1302 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1303 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1304 foreach ( $httpReqs as $index => $httpReq ) {
1305 // Run the callback for each request of this operation
1306 $callback = $fileOpHandles[$index]->callback;
1307 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1308 // On failure, abort all remaining requests for this operation
1309 // (e.g. abort the DELETE request if the COPY request fails for a move)
1310 if ( !$statuses[$index]->isOK() ) {
1311 $stages = count( $fileOpHandles[$index]->httpOp );
1312 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1313 unset( $httpReqsByStage[$s][$index] );
1314 }
1315 }
1316 }
1317 }
1318
1319 return $statuses;
1320 }
1321
1322 /**
1323 * Set read/write permissions for a Swift container.
1324 *
1325 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1326 *
1327 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1328 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1329 *
1330 * @param string $container Resolved Swift container
1331 * @param array $readUsers List of the possible criteria for a request to have
1332 * access to read a container. Each item is one of the following formats:
1333 * - account:user : Grants access if the request is by the given user
1334 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1335 * matches the expression and the request is not for a listing.
1336 * Setting this to '*' effectively makes a container public.
1337 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1338 * matches the expression and the request is for a listing.
1339 * @param array $writeUsers A list of the possible criteria for a request to have
1340 * access to write to a container. Each item is of the following format:
1341 * - account:user : Grants access if the request is by the given user
1342 * @return StatusValue
1343 */
1344 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1345 $status = $this->newStatus();
1346 $auth = $this->getAuthentication();
1347
1348 if ( !$auth ) {
1349 $status->fatal( 'backend-fail-connect', $this->name );
1350
1351 return $status;
1352 }
1353
1354 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1355 'method' => 'POST',
1356 'url' => $this->storageUrl( $auth, $container ),
1357 'headers' => $this->authTokenHeaders( $auth ) + [
1358 'x-container-read' => implode( ',', $readUsers ),
1359 'x-container-write' => implode( ',', $writeUsers )
1360 ]
1361 ] );
1362
1363 if ( $rcode != 204 && $rcode !== 202 ) {
1364 $status->fatal( 'backend-fail-internal', $this->name );
1365 $this->logger->error( __METHOD__ . ': unexpected rcode value ({rcode})',
1366 [ 'rcode' => $rcode ] );
1367 }
1368
1369 return $status;
1370 }
1371
1372 /**
1373 * Get a Swift container stat array, possibly from process cache.
1374 * Use $reCache if the file count or byte count is needed.
1375 *
1376 * @param string $container Container name
1377 * @param bool $bypassCache Bypass all caches and load from Swift
1378 * @return array|bool|null False on 404, null on failure
1379 */
1380 protected function getContainerStat( $container, $bypassCache = false ) {
1381 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1382
1383 if ( $bypassCache ) { // purge cache
1384 $this->containerStatCache->clear( $container );
1385 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1386 $this->primeContainerCache( [ $container ] ); // check persistent cache
1387 }
1388 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1389 $auth = $this->getAuthentication();
1390 if ( !$auth ) {
1391 return null;
1392 }
1393
1394 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1395 'method' => 'HEAD',
1396 'url' => $this->storageUrl( $auth, $container ),
1397 'headers' => $this->authTokenHeaders( $auth )
1398 ] );
1399
1400 if ( $rcode === 204 ) {
1401 $stat = [
1402 'count' => $rhdrs['x-container-object-count'],
1403 'bytes' => $rhdrs['x-container-bytes-used']
1404 ];
1405 if ( $bypassCache ) {
1406 return $stat;
1407 } else {
1408 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1409 $this->setContainerCache( $container, $stat ); // update persistent cache
1410 }
1411 } elseif ( $rcode === 404 ) {
1412 return false;
1413 } else {
1414 $this->onError( null, __METHOD__,
1415 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1416
1417 return null;
1418 }
1419 }
1420
1421 return $this->containerStatCache->get( $container, 'stat' );
1422 }
1423
1424 /**
1425 * Create a Swift container
1426 *
1427 * @param string $container Container name
1428 * @param array $params
1429 * @return StatusValue
1430 */
1431 protected function createContainer( $container, array $params ) {
1432 $status = $this->newStatus();
1433
1434 $auth = $this->getAuthentication();
1435 if ( !$auth ) {
1436 $status->fatal( 'backend-fail-connect', $this->name );
1437
1438 return $status;
1439 }
1440
1441 // @see SwiftFileBackend::setContainerAccess()
1442 if ( empty( $params['noAccess'] ) ) {
1443 $readUsers = array_merge( $this->readUsers, [ '.r:*', $this->swiftUser ] ); // public
1444 } else {
1445 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser ] ); // private
1446 }
1447
1448 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] ); // sanity
1449
1450 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1451 'method' => 'PUT',
1452 'url' => $this->storageUrl( $auth, $container ),
1453 'headers' => $this->authTokenHeaders( $auth ) + [
1454 'x-container-read' => implode( ',', $readUsers ),
1455 'x-container-write' => implode( ',', $writeUsers )
1456 ]
1457 ] );
1458
1459 if ( $rcode === 201 ) { // new
1460 // good
1461 } elseif ( $rcode === 202 ) { // already there
1462 // this shouldn't really happen, but is OK
1463 } else {
1464 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1465 }
1466
1467 return $status;
1468 }
1469
1470 /**
1471 * Delete a Swift container
1472 *
1473 * @param string $container Container name
1474 * @param array $params
1475 * @return StatusValue
1476 */
1477 protected function deleteContainer( $container, array $params ) {
1478 $status = $this->newStatus();
1479
1480 $auth = $this->getAuthentication();
1481 if ( !$auth ) {
1482 $status->fatal( 'backend-fail-connect', $this->name );
1483
1484 return $status;
1485 }
1486
1487 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1488 'method' => 'DELETE',
1489 'url' => $this->storageUrl( $auth, $container ),
1490 'headers' => $this->authTokenHeaders( $auth )
1491 ] );
1492
1493 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1494 $this->containerStatCache->clear( $container ); // purge
1495 } elseif ( $rcode === 404 ) { // not there
1496 // this shouldn't really happen, but is OK
1497 } elseif ( $rcode === 409 ) { // not empty
1498 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1499 } else {
1500 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1501 }
1502
1503 return $status;
1504 }
1505
1506 /**
1507 * Get a list of objects under a container.
1508 * Either just the names or a list of stdClass objects with details can be returned.
1509 *
1510 * @param string $fullCont
1511 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1512 * @param int $limit
1513 * @param string|null $after
1514 * @param string|null $prefix
1515 * @param string|null $delim
1516 * @return StatusValue With the list as value
1517 */
1518 private function objectListing(
1519 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1520 ) {
1521 $status = $this->newStatus();
1522
1523 $auth = $this->getAuthentication();
1524 if ( !$auth ) {
1525 $status->fatal( 'backend-fail-connect', $this->name );
1526
1527 return $status;
1528 }
1529
1530 $query = [ 'limit' => $limit ];
1531 if ( $type === 'info' ) {
1532 $query['format'] = 'json';
1533 }
1534 if ( $after !== null ) {
1535 $query['marker'] = $after;
1536 }
1537 if ( $prefix !== null ) {
1538 $query['prefix'] = $prefix;
1539 }
1540 if ( $delim !== null ) {
1541 $query['delimiter'] = $delim;
1542 }
1543
1544 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1545 'method' => 'GET',
1546 'url' => $this->storageUrl( $auth, $fullCont ),
1547 'query' => $query,
1548 'headers' => $this->authTokenHeaders( $auth )
1549 ] );
1550
1551 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1552 if ( $rcode === 200 ) { // good
1553 if ( $type === 'info' ) {
1554 $status->value = FormatJson::decode( trim( $rbody ) );
1555 } else {
1556 $status->value = explode( "\n", trim( $rbody ) );
1557 }
1558 } elseif ( $rcode === 204 ) {
1559 $status->value = []; // empty container
1560 } elseif ( $rcode === 404 ) {
1561 $status->value = []; // no container
1562 } else {
1563 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1564 }
1565
1566 return $status;
1567 }
1568
1569 protected function doPrimeContainerCache( array $containerInfo ) {
1570 foreach ( $containerInfo as $container => $info ) {
1571 $this->containerStatCache->set( $container, 'stat', $info );
1572 }
1573 }
1574
1575 protected function doGetFileStatMulti( array $params ) {
1576 $stats = [];
1577
1578 $auth = $this->getAuthentication();
1579
1580 $reqs = [];
1581 foreach ( $params['srcs'] as $path ) {
1582 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1583 if ( $srcRel === null ) {
1584 $stats[$path] = false;
1585 continue; // invalid storage path
1586 } elseif ( !$auth ) {
1587 $stats[$path] = null;
1588 continue;
1589 }
1590
1591 // (a) Check the container
1592 $cstat = $this->getContainerStat( $srcCont );
1593 if ( $cstat === false ) {
1594 $stats[$path] = false;
1595 continue; // ok, nothing to do
1596 } elseif ( !is_array( $cstat ) ) {
1597 $stats[$path] = null;
1598 continue;
1599 }
1600
1601 $reqs[$path] = [
1602 'method' => 'HEAD',
1603 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1604 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1605 ];
1606 }
1607
1608 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1609 $reqs = $this->http->runMulti( $reqs, $opts );
1610
1611 foreach ( $params['srcs'] as $path ) {
1612 if ( array_key_exists( $path, $stats ) ) {
1613 continue; // some sort of failure above
1614 }
1615 // (b) Check the file
1616 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1617 if ( $rcode === 200 || $rcode === 204 ) {
1618 // Update the object if it is missing some headers
1619 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1620 // Load the stat array from the headers
1621 $stat = $this->getStatFromHeaders( $rhdrs );
1622 if ( $this->isRGW ) {
1623 $stat['latest'] = true; // strong consistency
1624 }
1625 } elseif ( $rcode === 404 ) {
1626 $stat = false;
1627 } else {
1628 $stat = null;
1629 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1630 }
1631 $stats[$path] = $stat;
1632 }
1633
1634 return $stats;
1635 }
1636
1637 /**
1638 * @param array $rhdrs
1639 * @return array
1640 */
1641 protected function getStatFromHeaders( array $rhdrs ) {
1642 // Fetch all of the custom metadata headers
1643 $metadata = $this->getMetadata( $rhdrs );
1644 // Fetch all of the custom raw HTTP headers
1645 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1646
1647 return [
1648 // Convert various random Swift dates to TS_MW
1649 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1650 // Empty objects actually return no content-length header in Ceph
1651 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1652 'sha1' => isset( $metadata['sha1base36'] ) ? $metadata['sha1base36'] : null,
1653 // Note: manifiest ETags are not an MD5 of the file
1654 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1655 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1656 ];
1657 }
1658
1659 /**
1660 * @return array|null Credential map
1661 */
1662 protected function getAuthentication() {
1663 if ( $this->authErrorTimestamp !== null ) {
1664 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1665 return null; // failed last attempt; don't bother
1666 } else { // actually retry this time
1667 $this->authErrorTimestamp = null;
1668 }
1669 }
1670 // Session keys expire after a while, so we renew them periodically
1671 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1672 // Authenticate with proxy and get a session key...
1673 if ( !$this->authCreds || $reAuth ) {
1674 $this->authSessionTimestamp = 0;
1675 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1676 $creds = $this->srvCache->get( $cacheKey ); // credentials
1677 // Try to use the credential cache
1678 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1679 $this->authCreds = $creds;
1680 // Skew the timestamp for worst case to avoid using stale credentials
1681 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1682 } else { // cache miss
1683 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1684 'method' => 'GET',
1685 'url' => "{$this->swiftAuthUrl}/v1.0",
1686 'headers' => [
1687 'x-auth-user' => $this->swiftUser,
1688 'x-auth-key' => $this->swiftKey
1689 ]
1690 ] );
1691
1692 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1693 $this->authCreds = [
1694 'auth_token' => $rhdrs['x-auth-token'],
1695 'storage_url' => ( $this->swiftStorageUrl !== null )
1696 ? $this->swiftStorageUrl
1697 : $rhdrs['x-storage-url']
1698 ];
1699
1700 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1701 $this->authSessionTimestamp = time();
1702 } elseif ( $rcode === 401 ) {
1703 $this->onError( null, __METHOD__, [], "Authentication failed.", $rcode );
1704 $this->authErrorTimestamp = time();
1705
1706 return null;
1707 } else {
1708 $this->onError( null, __METHOD__, [], "HTTP return code: $rcode", $rcode );
1709 $this->authErrorTimestamp = time();
1710
1711 return null;
1712 }
1713 }
1714 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1715 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1716 $this->isRGW = true; // take advantage of strong consistency in Ceph
1717 }
1718 }
1719
1720 return $this->authCreds;
1721 }
1722
1723 /**
1724 * @param array $creds From getAuthentication()
1725 * @param string $container
1726 * @param string $object
1727 * @return string
1728 */
1729 protected function storageUrl( array $creds, $container = null, $object = null ) {
1730 $parts = [ $creds['storage_url'] ];
1731 if ( strlen( $container ) ) {
1732 $parts[] = rawurlencode( $container );
1733 }
1734 if ( strlen( $object ) ) {
1735 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1736 }
1737
1738 return implode( '/', $parts );
1739 }
1740
1741 /**
1742 * @param array $creds From getAuthentication()
1743 * @return array
1744 */
1745 protected function authTokenHeaders( array $creds ) {
1746 return [ 'x-auth-token' => $creds['auth_token'] ];
1747 }
1748
1749 /**
1750 * Get the cache key for a container
1751 *
1752 * @param string $username
1753 * @return string
1754 */
1755 private function getCredsCacheKey( $username ) {
1756 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1757 }
1758
1759 /**
1760 * Log an unexpected exception for this backend.
1761 * This also sets the StatusValue object to have a fatal error.
1762 *
1763 * @param StatusValue|null $status
1764 * @param string $func
1765 * @param array $params
1766 * @param string $err Error string
1767 * @param int $code HTTP status
1768 * @param string $desc HTTP StatusValue description
1769 */
1770 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1771 if ( $status instanceof StatusValue ) {
1772 $status->fatal( 'backend-fail-internal', $this->name );
1773 }
1774 if ( $code == 401 ) { // possibly a stale token
1775 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1776 }
1777 $msg = "HTTP {code} ({desc}) in '{func}' (given '{params}')";
1778 $msgParams = [
1779 'code' => $code,
1780 'desc' => $desc,
1781 'func' => $func,
1782 'req_params' => FormatJson::encode( $params ),
1783 ];
1784 if ( $err ) {
1785 $msg .= ': {err}';
1786 $msgParams['err'] = $err;
1787 }
1788 $this->logger->error( $msg, $msgParams );
1789 }
1790 }
1791
1792 /**
1793 * @see FileBackendStoreOpHandle
1794 */
1795 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1796 /** @var array List of Requests for MultiHttpClient */
1797 public $httpOp;
1798 /** @var Closure */
1799 public $callback;
1800
1801 /**
1802 * @param SwiftFileBackend $backend
1803 * @param Closure $callback Function that takes (HTTP request array, status)
1804 * @param array $httpOp MultiHttpClient op
1805 */
1806 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1807 $this->backend = $backend;
1808 $this->callback = $callback;
1809 $this->httpOp = $httpOp;
1810 }
1811 }
1812
1813 /**
1814 * SwiftFileBackend helper class to page through listings.
1815 * Swift also has a listing limit of 10,000 objects for sanity.
1816 * Do not use this class from places outside SwiftFileBackend.
1817 *
1818 * @ingroup FileBackend
1819 */
1820 abstract class SwiftFileBackendList implements Iterator {
1821 /** @var array List of path or (path,stat array) entries */
1822 protected $bufferIter = [];
1823
1824 /** @var string List items *after* this path */
1825 protected $bufferAfter = null;
1826
1827 /** @var int */
1828 protected $pos = 0;
1829
1830 /** @var array */
1831 protected $params = [];
1832
1833 /** @var SwiftFileBackend */
1834 protected $backend;
1835
1836 /** @var string Container name */
1837 protected $container;
1838
1839 /** @var string Storage directory */
1840 protected $dir;
1841
1842 /** @var int */
1843 protected $suffixStart;
1844
1845 const PAGE_SIZE = 9000; // file listing buffer size
1846
1847 /**
1848 * @param SwiftFileBackend $backend
1849 * @param string $fullCont Resolved container name
1850 * @param string $dir Resolved directory relative to container
1851 * @param array $params
1852 */
1853 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1854 $this->backend = $backend;
1855 $this->container = $fullCont;
1856 $this->dir = $dir;
1857 if ( substr( $this->dir, -1 ) === '/' ) {
1858 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1859 }
1860 if ( $this->dir == '' ) { // whole container
1861 $this->suffixStart = 0;
1862 } else { // dir within container
1863 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1864 }
1865 $this->params = $params;
1866 }
1867
1868 /**
1869 * @see Iterator::key()
1870 * @return int
1871 */
1872 public function key() {
1873 return $this->pos;
1874 }
1875
1876 /**
1877 * @see Iterator::next()
1878 */
1879 public function next() {
1880 // Advance to the next file in the page
1881 next( $this->bufferIter );
1882 ++$this->pos;
1883 // Check if there are no files left in this page and
1884 // advance to the next page if this page was not empty.
1885 if ( !$this->valid() && count( $this->bufferIter ) ) {
1886 $this->bufferIter = $this->pageFromList(
1887 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1888 ); // updates $this->bufferAfter
1889 }
1890 }
1891
1892 /**
1893 * @see Iterator::rewind()
1894 */
1895 public function rewind() {
1896 $this->pos = 0;
1897 $this->bufferAfter = null;
1898 $this->bufferIter = $this->pageFromList(
1899 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1900 ); // updates $this->bufferAfter
1901 }
1902
1903 /**
1904 * @see Iterator::valid()
1905 * @return bool
1906 */
1907 public function valid() {
1908 if ( $this->bufferIter === null ) {
1909 return false; // some failure?
1910 } else {
1911 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1912 }
1913 }
1914
1915 /**
1916 * Get the given list portion (page)
1917 *
1918 * @param string $container Resolved container name
1919 * @param string $dir Resolved path relative to container
1920 * @param string &$after
1921 * @param int $limit
1922 * @param array $params
1923 * @return Traversable|array
1924 */
1925 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1926 }
1927
1928 /**
1929 * Iterator for listing directories
1930 */
1931 class SwiftFileBackendDirList extends SwiftFileBackendList {
1932 /**
1933 * @see Iterator::current()
1934 * @return string|bool String (relative path) or false
1935 */
1936 public function current() {
1937 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1938 }
1939
1940 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1941 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1942 }
1943 }
1944
1945 /**
1946 * Iterator for listing regular files
1947 */
1948 class SwiftFileBackendFileList extends SwiftFileBackendList {
1949 /**
1950 * @see Iterator::current()
1951 * @return string|bool String (relative path) or false
1952 */
1953 public function current() {
1954 list( $path, $stat ) = current( $this->bufferIter );
1955 $relPath = substr( $path, $this->suffixStart );
1956 if ( is_array( $stat ) ) {
1957 $storageDir = rtrim( $this->params['dir'], '/' );
1958 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1959 }
1960
1961 return $relPath;
1962 }
1963
1964 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1965 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1966 }
1967 }