Merge "Add attributes parameter to ShowSearchHitTitle"
[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( urlencode( $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
760 return $objHdrs; // failed
761 }
762
763 protected function doGetFileContentsMulti( array $params ) {
764 $contents = [];
765
766 $auth = $this->getAuthentication();
767
768 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
769 // Blindly create tmp files and stream to them, catching any exception if the file does
770 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
771 $reqs = []; // (path => op)
772
773 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
774 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
775 if ( $srcRel === null || !$auth ) {
776 $contents[$path] = false;
777 continue;
778 }
779 // Create a new temporary memory file...
780 $handle = fopen( 'php://temp', 'wb' );
781 if ( $handle ) {
782 $reqs[$path] = [
783 'method' => 'GET',
784 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
785 'headers' => $this->authTokenHeaders( $auth )
786 + $this->headersFromParams( $params ),
787 'stream' => $handle,
788 ];
789 }
790 $contents[$path] = false;
791 }
792
793 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
794 $reqs = $this->http->runMulti( $reqs, $opts );
795 foreach ( $reqs as $path => $op ) {
796 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
797 if ( $rcode >= 200 && $rcode <= 299 ) {
798 rewind( $op['stream'] ); // start from the beginning
799 $contents[$path] = stream_get_contents( $op['stream'] );
800 } elseif ( $rcode === 404 ) {
801 $contents[$path] = false;
802 } else {
803 $this->onError( null, __METHOD__,
804 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
805 }
806 fclose( $op['stream'] ); // close open handle
807 }
808
809 return $contents;
810 }
811
812 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
813 $prefix = ( $dir == '' ) ? null : "{$dir}/";
814 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
815 if ( $status->isOK() ) {
816 return ( count( $status->value ) ) > 0;
817 }
818
819 return null; // error
820 }
821
822 /**
823 * @see FileBackendStore::getDirectoryListInternal()
824 * @param string $fullCont
825 * @param string $dir
826 * @param array $params
827 * @return SwiftFileBackendDirList
828 */
829 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
830 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
831 }
832
833 /**
834 * @see FileBackendStore::getFileListInternal()
835 * @param string $fullCont
836 * @param string $dir
837 * @param array $params
838 * @return SwiftFileBackendFileList
839 */
840 public function getFileListInternal( $fullCont, $dir, array $params ) {
841 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
842 }
843
844 /**
845 * Do not call this function outside of SwiftFileBackendFileList
846 *
847 * @param string $fullCont Resolved container name
848 * @param string $dir Resolved storage directory with no trailing slash
849 * @param string|null &$after Resolved container relative path to list items after
850 * @param int $limit Max number of items to list
851 * @param array $params Parameters for getDirectoryList()
852 * @return array List of container relative resolved paths of directories directly under $dir
853 * @throws FileBackendError
854 */
855 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
856 $dirs = [];
857 if ( $after === INF ) {
858 return $dirs; // nothing more
859 }
860
861 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
862
863 $prefix = ( $dir == '' ) ? null : "{$dir}/";
864 // Non-recursive: only list dirs right under $dir
865 if ( !empty( $params['topOnly'] ) ) {
866 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
867 if ( !$status->isOK() ) {
868 throw new FileBackendError( "Iterator page I/O error." );
869 }
870 $objects = $status->value;
871 foreach ( $objects as $object ) { // files and directories
872 if ( substr( $object, -1 ) === '/' ) {
873 $dirs[] = $object; // directories end in '/'
874 }
875 }
876 } else {
877 // Recursive: list all dirs under $dir and its subdirs
878 $getParentDir = function ( $path ) {
879 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
880 };
881
882 // Get directory from last item of prior page
883 $lastDir = $getParentDir( $after ); // must be first page
884 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
885
886 if ( !$status->isOK() ) {
887 throw new FileBackendError( "Iterator page I/O error." );
888 }
889
890 $objects = $status->value;
891
892 foreach ( $objects as $object ) { // files
893 $objectDir = $getParentDir( $object ); // directory of object
894
895 if ( $objectDir !== false && $objectDir !== $dir ) {
896 // Swift stores paths in UTF-8, using binary sorting.
897 // See function "create_container_table" in common/db.py.
898 // If a directory is not "greater" than the last one,
899 // then it was already listed by the calling iterator.
900 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
901 $pDir = $objectDir;
902 do { // add dir and all its parent dirs
903 $dirs[] = "{$pDir}/";
904 $pDir = $getParentDir( $pDir );
905 } while ( $pDir !== false // sanity
906 && strcmp( $pDir, $lastDir ) > 0 // not done already
907 && strlen( $pDir ) > strlen( $dir ) // within $dir
908 );
909 }
910 $lastDir = $objectDir;
911 }
912 }
913 }
914 // Page on the unfiltered directory listing (what is returned may be filtered)
915 if ( count( $objects ) < $limit ) {
916 $after = INF; // avoid a second RTT
917 } else {
918 $after = end( $objects ); // update last item
919 }
920
921 return $dirs;
922 }
923
924 /**
925 * Do not call this function outside of SwiftFileBackendFileList
926 *
927 * @param string $fullCont Resolved container name
928 * @param string $dir Resolved storage directory with no trailing slash
929 * @param string|null &$after Resolved container relative path of file to list items after
930 * @param int $limit Max number of items to list
931 * @param array $params Parameters for getDirectoryList()
932 * @return array List of resolved container relative paths of files under $dir
933 * @throws FileBackendError
934 */
935 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
936 $files = []; // list of (path, stat array or null) entries
937 if ( $after === INF ) {
938 return $files; // nothing more
939 }
940
941 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
942
943 $prefix = ( $dir == '' ) ? null : "{$dir}/";
944 // $objects will contain a list of unfiltered names or CF_Object items
945 // Non-recursive: only list files right under $dir
946 if ( !empty( $params['topOnly'] ) ) {
947 if ( !empty( $params['adviseStat'] ) ) {
948 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
949 } else {
950 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
951 }
952 } else {
953 // Recursive: list all files under $dir and its subdirs
954 if ( !empty( $params['adviseStat'] ) ) {
955 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
956 } else {
957 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
958 }
959 }
960
961 // Reformat this list into a list of (name, stat array or null) entries
962 if ( !$status->isOK() ) {
963 throw new FileBackendError( "Iterator page I/O error." );
964 }
965
966 $objects = $status->value;
967 $files = $this->buildFileObjectListing( $params, $dir, $objects );
968
969 // Page on the unfiltered object listing (what is returned may be filtered)
970 if ( count( $objects ) < $limit ) {
971 $after = INF; // avoid a second RTT
972 } else {
973 $after = end( $objects ); // update last item
974 $after = is_object( $after ) ? $after->name : $after;
975 }
976
977 return $files;
978 }
979
980 /**
981 * Build a list of file objects, filtering out any directories
982 * and extracting any stat info if provided in $objects (for CF_Objects)
983 *
984 * @param array $params Parameters for getDirectoryList()
985 * @param string $dir Resolved container directory path
986 * @param array $objects List of CF_Object items or object names
987 * @return array List of (names,stat array or null) entries
988 */
989 private function buildFileObjectListing( array $params, $dir, array $objects ) {
990 $names = [];
991 foreach ( $objects as $object ) {
992 if ( is_object( $object ) ) {
993 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
994 continue; // virtual directory entry; ignore
995 }
996 $stat = [
997 // Convert various random Swift dates to TS_MW
998 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
999 'size' => (int)$object->bytes,
1000 'sha1' => null,
1001 // Note: manifiest ETags are not an MD5 of the file
1002 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
1003 'latest' => false // eventually consistent
1004 ];
1005 $names[] = [ $object->name, $stat ];
1006 } elseif ( substr( $object, -1 ) !== '/' ) {
1007 // Omit directories, which end in '/' in listings
1008 $names[] = [ $object, null ];
1009 }
1010 }
1011
1012 return $names;
1013 }
1014
1015 /**
1016 * Do not call this function outside of SwiftFileBackendFileList
1017 *
1018 * @param string $path Storage path
1019 * @param array $val Stat value
1020 */
1021 public function loadListingStatInternal( $path, array $val ) {
1022 $this->cheapCache->set( $path, 'stat', $val );
1023 }
1024
1025 protected function doGetFileXAttributes( array $params ) {
1026 $stat = $this->getFileStat( $params );
1027 if ( $stat ) {
1028 if ( !isset( $stat['xattr'] ) ) {
1029 // Stat entries filled by file listings don't include metadata/headers
1030 $this->clearCache( [ $params['src'] ] );
1031 $stat = $this->getFileStat( $params );
1032 }
1033
1034 return $stat['xattr'];
1035 } else {
1036 return false;
1037 }
1038 }
1039
1040 protected function doGetFileSha1base36( array $params ) {
1041 $stat = $this->getFileStat( $params );
1042 if ( $stat ) {
1043 if ( !isset( $stat['sha1'] ) ) {
1044 // Stat entries filled by file listings don't include SHA1
1045 $this->clearCache( [ $params['src'] ] );
1046 $stat = $this->getFileStat( $params );
1047 }
1048
1049 return $stat['sha1'];
1050 } else {
1051 return false;
1052 }
1053 }
1054
1055 protected function doStreamFile( array $params ) {
1056 $status = $this->newStatus();
1057
1058 $flags = !empty( $params['headless'] ) ? StreamFile::STREAM_HEADLESS : 0;
1059
1060 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1061 if ( $srcRel === null ) {
1062 StreamFile::send404Message( $params['src'], $flags );
1063 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1064
1065 return $status;
1066 }
1067
1068 $auth = $this->getAuthentication();
1069 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
1070 StreamFile::send404Message( $params['src'], $flags );
1071 $status->fatal( 'backend-fail-stream', $params['src'] );
1072
1073 return $status;
1074 }
1075
1076 // If "headers" is set, we only want to send them if the file is there.
1077 // Do not bother checking if the file exists if headers are not set though.
1078 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1079 StreamFile::send404Message( $params['src'], $flags );
1080 $status->fatal( 'backend-fail-stream', $params['src'] );
1081
1082 return $status;
1083 }
1084
1085 // Send the requested additional headers
1086 foreach ( $params['headers'] as $header ) {
1087 header( $header ); // aways send
1088 }
1089
1090 if ( empty( $params['allowOB'] ) ) {
1091 // Cancel output buffering and gzipping if set
1092 call_user_func( $this->obResetFunc );
1093 }
1094
1095 $handle = fopen( 'php://output', 'wb' );
1096 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1097 'method' => 'GET',
1098 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1099 'headers' => $this->authTokenHeaders( $auth )
1100 + $this->headersFromParams( $params ) + $params['options'],
1101 'stream' => $handle,
1102 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1103 ] );
1104
1105 if ( $rcode >= 200 && $rcode <= 299 ) {
1106 // good
1107 } elseif ( $rcode === 404 ) {
1108 $status->fatal( 'backend-fail-stream', $params['src'] );
1109 // Per T43113, nasty things can happen if bad cache entries get
1110 // stuck in cache. It's also possible that this error can come up
1111 // with simple race conditions. Clear out the stat cache to be safe.
1112 $this->clearCache( [ $params['src'] ] );
1113 $this->deleteFileCache( $params['src'] );
1114 } else {
1115 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1116 }
1117
1118 return $status;
1119 }
1120
1121 protected function doGetLocalCopyMulti( array $params ) {
1122 /** @var TempFSFile[] $tmpFiles */
1123 $tmpFiles = [];
1124
1125 $auth = $this->getAuthentication();
1126
1127 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1128 // Blindly create tmp files and stream to them, catching any exception if the file does
1129 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1130 $reqs = []; // (path => op)
1131
1132 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1133 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1134 if ( $srcRel === null || !$auth ) {
1135 $tmpFiles[$path] = null;
1136 continue;
1137 }
1138 // Get source file extension
1139 $ext = FileBackend::extensionFromPath( $path );
1140 // Create a new temporary file...
1141 $tmpFile = TempFSFile::factory( 'localcopy_', $ext, $this->tmpDirectory );
1142 if ( $tmpFile ) {
1143 $handle = fopen( $tmpFile->getPath(), 'wb' );
1144 if ( $handle ) {
1145 $reqs[$path] = [
1146 'method' => 'GET',
1147 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1148 'headers' => $this->authTokenHeaders( $auth )
1149 + $this->headersFromParams( $params ),
1150 'stream' => $handle,
1151 ];
1152 } else {
1153 $tmpFile = null;
1154 }
1155 }
1156 $tmpFiles[$path] = $tmpFile;
1157 }
1158
1159 $isLatest = ( $this->isRGW || !empty( $params['latest'] ) );
1160 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1161 $reqs = $this->http->runMulti( $reqs, $opts );
1162 foreach ( $reqs as $path => $op ) {
1163 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1164 fclose( $op['stream'] ); // close open handle
1165 if ( $rcode >= 200 && $rcode <= 299 ) {
1166 $size = $tmpFiles[$path] ? $tmpFiles[$path]->getSize() : 0;
1167 // Double check that the disk is not full/broken
1168 if ( $size != $rhdrs['content-length'] ) {
1169 $tmpFiles[$path] = null;
1170 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1171 $this->onError( null, __METHOD__,
1172 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1173 }
1174 // Set the file stat process cache in passing
1175 $stat = $this->getStatFromHeaders( $rhdrs );
1176 $stat['latest'] = $isLatest;
1177 $this->cheapCache->set( $path, 'stat', $stat );
1178 } elseif ( $rcode === 404 ) {
1179 $tmpFiles[$path] = false;
1180 } else {
1181 $tmpFiles[$path] = null;
1182 $this->onError( null, __METHOD__,
1183 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1184 }
1185 }
1186
1187 return $tmpFiles;
1188 }
1189
1190 public function getFileHttpUrl( array $params ) {
1191 if ( $this->swiftTempUrlKey != '' ||
1192 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1193 ) {
1194 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1195 if ( $srcRel === null ) {
1196 return null; // invalid path
1197 }
1198
1199 $auth = $this->getAuthentication();
1200 if ( !$auth ) {
1201 return null;
1202 }
1203
1204 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1205 $expires = time() + $ttl;
1206
1207 if ( $this->swiftTempUrlKey != '' ) {
1208 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1209 // Swift wants the signature based on the unencoded object name
1210 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1211 $signature = hash_hmac( 'sha1',
1212 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1213 $this->swiftTempUrlKey
1214 );
1215
1216 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1217 } else { // give S3 API URL for rgw
1218 // Path for signature starts with the bucket
1219 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1220 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1221 // Calculate the hash
1222 $signature = base64_encode( hash_hmac(
1223 'sha1',
1224 "GET\n\n\n{$expires}\n{$spath}",
1225 $this->rgwS3SecretKey,
1226 true // raw
1227 ) );
1228 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1229 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1230 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1231 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1232 '?' .
1233 http_build_query( [
1234 'Signature' => $signature,
1235 'Expires' => $expires,
1236 'AWSAccessKeyId' => $this->rgwS3AccessKey
1237 ] );
1238 }
1239 }
1240
1241 return null;
1242 }
1243
1244 protected function directoriesAreVirtual() {
1245 return true;
1246 }
1247
1248 /**
1249 * Get headers to send to Swift when reading a file based
1250 * on a FileBackend params array, e.g. that of getLocalCopy().
1251 * $params is currently only checked for a 'latest' flag.
1252 *
1253 * @param array $params
1254 * @return array
1255 */
1256 protected function headersFromParams( array $params ) {
1257 $hdrs = [];
1258 if ( !empty( $params['latest'] ) ) {
1259 $hdrs['x-newest'] = 'true';
1260 }
1261
1262 return $hdrs;
1263 }
1264
1265 /**
1266 * @param FileBackendStoreOpHandle[] $fileOpHandles
1267 *
1268 * @return StatusValue[]
1269 */
1270 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1271 /** @var StatusValue[] $statuses */
1272 $statuses = [];
1273
1274 $auth = $this->getAuthentication();
1275 if ( !$auth ) {
1276 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1277 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name );
1278 }
1279
1280 return $statuses;
1281 }
1282
1283 // Split the HTTP requests into stages that can be done concurrently
1284 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1285 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1286 /** @var SwiftFileOpHandle $fileOpHandle */
1287 $reqs = $fileOpHandle->httpOp;
1288 // Convert the 'url' parameter to an actual URL using $auth
1289 foreach ( $reqs as $stage => &$req ) {
1290 list( $container, $relPath ) = $req['url'];
1291 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1292 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : [];
1293 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1294 $httpReqsByStage[$stage][$index] = $req;
1295 }
1296 $statuses[$index] = $this->newStatus();
1297 }
1298
1299 // Run all requests for the first stage, then the next, and so on
1300 $reqCount = count( $httpReqsByStage );
1301 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1302 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1303 foreach ( $httpReqs as $index => $httpReq ) {
1304 // Run the callback for each request of this operation
1305 $callback = $fileOpHandles[$index]->callback;
1306 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1307 // On failure, abort all remaining requests for this operation
1308 // (e.g. abort the DELETE request if the COPY request fails for a move)
1309 if ( !$statuses[$index]->isOK() ) {
1310 $stages = count( $fileOpHandles[$index]->httpOp );
1311 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1312 unset( $httpReqsByStage[$s][$index] );
1313 }
1314 }
1315 }
1316 }
1317
1318 return $statuses;
1319 }
1320
1321 /**
1322 * Set read/write permissions for a Swift container.
1323 *
1324 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1325 *
1326 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1327 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1328 *
1329 * @param string $container Resolved Swift container
1330 * @param array $readUsers List of the possible criteria for a request to have
1331 * access to read a container. Each item is one of the following formats:
1332 * - account:user : Grants access if the request is by the given user
1333 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1334 * matches the expression and the request is not for a listing.
1335 * Setting this to '*' effectively makes a container public.
1336 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1337 * matches the expression and the request is for a listing.
1338 * @param array $writeUsers A list of the possible criteria for a request to have
1339 * access to write to a container. Each item is of the following format:
1340 * - account:user : Grants access if the request is by the given user
1341 * @return StatusValue
1342 */
1343 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1344 $status = $this->newStatus();
1345 $auth = $this->getAuthentication();
1346
1347 if ( !$auth ) {
1348 $status->fatal( 'backend-fail-connect', $this->name );
1349
1350 return $status;
1351 }
1352
1353 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1354 'method' => 'POST',
1355 'url' => $this->storageUrl( $auth, $container ),
1356 'headers' => $this->authTokenHeaders( $auth ) + [
1357 'x-container-read' => implode( ',', $readUsers ),
1358 'x-container-write' => implode( ',', $writeUsers )
1359 ]
1360 ] );
1361
1362 if ( $rcode != 204 && $rcode !== 202 ) {
1363 $status->fatal( 'backend-fail-internal', $this->name );
1364 $this->logger->error( __METHOD__ . ': unexpected rcode value (' . $rcode . ')' );
1365 }
1366
1367 return $status;
1368 }
1369
1370 /**
1371 * Get a Swift container stat array, possibly from process cache.
1372 * Use $reCache if the file count or byte count is needed.
1373 *
1374 * @param string $container Container name
1375 * @param bool $bypassCache Bypass all caches and load from Swift
1376 * @return array|bool|null False on 404, null on failure
1377 */
1378 protected function getContainerStat( $container, $bypassCache = false ) {
1379 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1380
1381 if ( $bypassCache ) { // purge cache
1382 $this->containerStatCache->clear( $container );
1383 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1384 $this->primeContainerCache( [ $container ] ); // check persistent cache
1385 }
1386 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1387 $auth = $this->getAuthentication();
1388 if ( !$auth ) {
1389 return null;
1390 }
1391
1392 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1393 'method' => 'HEAD',
1394 'url' => $this->storageUrl( $auth, $container ),
1395 'headers' => $this->authTokenHeaders( $auth )
1396 ] );
1397
1398 if ( $rcode === 204 ) {
1399 $stat = [
1400 'count' => $rhdrs['x-container-object-count'],
1401 'bytes' => $rhdrs['x-container-bytes-used']
1402 ];
1403 if ( $bypassCache ) {
1404 return $stat;
1405 } else {
1406 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1407 $this->setContainerCache( $container, $stat ); // update persistent cache
1408 }
1409 } elseif ( $rcode === 404 ) {
1410 return false;
1411 } else {
1412 $this->onError( null, __METHOD__,
1413 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1414
1415 return null;
1416 }
1417 }
1418
1419 return $this->containerStatCache->get( $container, 'stat' );
1420 }
1421
1422 /**
1423 * Create a Swift container
1424 *
1425 * @param string $container Container name
1426 * @param array $params
1427 * @return StatusValue
1428 */
1429 protected function createContainer( $container, array $params ) {
1430 $status = $this->newStatus();
1431
1432 $auth = $this->getAuthentication();
1433 if ( !$auth ) {
1434 $status->fatal( 'backend-fail-connect', $this->name );
1435
1436 return $status;
1437 }
1438
1439 // @see SwiftFileBackend::setContainerAccess()
1440 if ( empty( $params['noAccess'] ) ) {
1441 $readUsers = array_merge( $this->readUsers, [ '.r:*', $this->swiftUser ] ); // public
1442 } else {
1443 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser ] ); // private
1444 }
1445
1446 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] ); // sanity
1447
1448 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1449 'method' => 'PUT',
1450 'url' => $this->storageUrl( $auth, $container ),
1451 'headers' => $this->authTokenHeaders( $auth ) + [
1452 'x-container-read' => implode( ',', $readUsers ),
1453 'x-container-write' => implode( ',', $writeUsers )
1454 ]
1455 ] );
1456
1457 if ( $rcode === 201 ) { // new
1458 // good
1459 } elseif ( $rcode === 202 ) { // already there
1460 // this shouldn't really happen, but is OK
1461 } else {
1462 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1463 }
1464
1465 return $status;
1466 }
1467
1468 /**
1469 * Delete a Swift container
1470 *
1471 * @param string $container Container name
1472 * @param array $params
1473 * @return StatusValue
1474 */
1475 protected function deleteContainer( $container, array $params ) {
1476 $status = $this->newStatus();
1477
1478 $auth = $this->getAuthentication();
1479 if ( !$auth ) {
1480 $status->fatal( 'backend-fail-connect', $this->name );
1481
1482 return $status;
1483 }
1484
1485 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1486 'method' => 'DELETE',
1487 'url' => $this->storageUrl( $auth, $container ),
1488 'headers' => $this->authTokenHeaders( $auth )
1489 ] );
1490
1491 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1492 $this->containerStatCache->clear( $container ); // purge
1493 } elseif ( $rcode === 404 ) { // not there
1494 // this shouldn't really happen, but is OK
1495 } elseif ( $rcode === 409 ) { // not empty
1496 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1497 } else {
1498 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1499 }
1500
1501 return $status;
1502 }
1503
1504 /**
1505 * Get a list of objects under a container.
1506 * Either just the names or a list of stdClass objects with details can be returned.
1507 *
1508 * @param string $fullCont
1509 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1510 * @param int $limit
1511 * @param string|null $after
1512 * @param string|null $prefix
1513 * @param string|null $delim
1514 * @return StatusValue With the list as value
1515 */
1516 private function objectListing(
1517 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1518 ) {
1519 $status = $this->newStatus();
1520
1521 $auth = $this->getAuthentication();
1522 if ( !$auth ) {
1523 $status->fatal( 'backend-fail-connect', $this->name );
1524
1525 return $status;
1526 }
1527
1528 $query = [ 'limit' => $limit ];
1529 if ( $type === 'info' ) {
1530 $query['format'] = 'json';
1531 }
1532 if ( $after !== null ) {
1533 $query['marker'] = $after;
1534 }
1535 if ( $prefix !== null ) {
1536 $query['prefix'] = $prefix;
1537 }
1538 if ( $delim !== null ) {
1539 $query['delimiter'] = $delim;
1540 }
1541
1542 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1543 'method' => 'GET',
1544 'url' => $this->storageUrl( $auth, $fullCont ),
1545 'query' => $query,
1546 'headers' => $this->authTokenHeaders( $auth )
1547 ] );
1548
1549 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1550 if ( $rcode === 200 ) { // good
1551 if ( $type === 'info' ) {
1552 $status->value = FormatJson::decode( trim( $rbody ) );
1553 } else {
1554 $status->value = explode( "\n", trim( $rbody ) );
1555 }
1556 } elseif ( $rcode === 204 ) {
1557 $status->value = []; // empty container
1558 } elseif ( $rcode === 404 ) {
1559 $status->value = []; // no container
1560 } else {
1561 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1562 }
1563
1564 return $status;
1565 }
1566
1567 protected function doPrimeContainerCache( array $containerInfo ) {
1568 foreach ( $containerInfo as $container => $info ) {
1569 $this->containerStatCache->set( $container, 'stat', $info );
1570 }
1571 }
1572
1573 protected function doGetFileStatMulti( array $params ) {
1574 $stats = [];
1575
1576 $auth = $this->getAuthentication();
1577
1578 $reqs = [];
1579 foreach ( $params['srcs'] as $path ) {
1580 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1581 if ( $srcRel === null ) {
1582 $stats[$path] = false;
1583 continue; // invalid storage path
1584 } elseif ( !$auth ) {
1585 $stats[$path] = null;
1586 continue;
1587 }
1588
1589 // (a) Check the container
1590 $cstat = $this->getContainerStat( $srcCont );
1591 if ( $cstat === false ) {
1592 $stats[$path] = false;
1593 continue; // ok, nothing to do
1594 } elseif ( !is_array( $cstat ) ) {
1595 $stats[$path] = null;
1596 continue;
1597 }
1598
1599 $reqs[$path] = [
1600 'method' => 'HEAD',
1601 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1602 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1603 ];
1604 }
1605
1606 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1607 $reqs = $this->http->runMulti( $reqs, $opts );
1608
1609 foreach ( $params['srcs'] as $path ) {
1610 if ( array_key_exists( $path, $stats ) ) {
1611 continue; // some sort of failure above
1612 }
1613 // (b) Check the file
1614 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1615 if ( $rcode === 200 || $rcode === 204 ) {
1616 // Update the object if it is missing some headers
1617 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1618 // Load the stat array from the headers
1619 $stat = $this->getStatFromHeaders( $rhdrs );
1620 if ( $this->isRGW ) {
1621 $stat['latest'] = true; // strong consistency
1622 }
1623 } elseif ( $rcode === 404 ) {
1624 $stat = false;
1625 } else {
1626 $stat = null;
1627 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1628 }
1629 $stats[$path] = $stat;
1630 }
1631
1632 return $stats;
1633 }
1634
1635 /**
1636 * @param array $rhdrs
1637 * @return array
1638 */
1639 protected function getStatFromHeaders( array $rhdrs ) {
1640 // Fetch all of the custom metadata headers
1641 $metadata = $this->getMetadata( $rhdrs );
1642 // Fetch all of the custom raw HTTP headers
1643 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1644
1645 return [
1646 // Convert various random Swift dates to TS_MW
1647 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1648 // Empty objects actually return no content-length header in Ceph
1649 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1650 'sha1' => isset( $metadata['sha1base36'] ) ? $metadata['sha1base36'] : null,
1651 // Note: manifiest ETags are not an MD5 of the file
1652 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1653 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1654 ];
1655 }
1656
1657 /**
1658 * @return array|null Credential map
1659 */
1660 protected function getAuthentication() {
1661 if ( $this->authErrorTimestamp !== null ) {
1662 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1663 return null; // failed last attempt; don't bother
1664 } else { // actually retry this time
1665 $this->authErrorTimestamp = null;
1666 }
1667 }
1668 // Session keys expire after a while, so we renew them periodically
1669 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1670 // Authenticate with proxy and get a session key...
1671 if ( !$this->authCreds || $reAuth ) {
1672 $this->authSessionTimestamp = 0;
1673 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1674 $creds = $this->srvCache->get( $cacheKey ); // credentials
1675 // Try to use the credential cache
1676 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1677 $this->authCreds = $creds;
1678 // Skew the timestamp for worst case to avoid using stale credentials
1679 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1680 } else { // cache miss
1681 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1682 'method' => 'GET',
1683 'url' => "{$this->swiftAuthUrl}/v1.0",
1684 'headers' => [
1685 'x-auth-user' => $this->swiftUser,
1686 'x-auth-key' => $this->swiftKey
1687 ]
1688 ] );
1689
1690 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1691 $this->authCreds = [
1692 'auth_token' => $rhdrs['x-auth-token'],
1693 'storage_url' => ( $this->swiftStorageUrl !== null )
1694 ? $this->swiftStorageUrl
1695 : $rhdrs['x-storage-url']
1696 ];
1697
1698 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1699 $this->authSessionTimestamp = time();
1700 } elseif ( $rcode === 401 ) {
1701 $this->onError( null, __METHOD__, [], "Authentication failed.", $rcode );
1702 $this->authErrorTimestamp = time();
1703
1704 return null;
1705 } else {
1706 $this->onError( null, __METHOD__, [], "HTTP return code: $rcode", $rcode );
1707 $this->authErrorTimestamp = time();
1708
1709 return null;
1710 }
1711 }
1712 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1713 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1714 $this->isRGW = true; // take advantage of strong consistency in Ceph
1715 }
1716 }
1717
1718 return $this->authCreds;
1719 }
1720
1721 /**
1722 * @param array $creds From getAuthentication()
1723 * @param string $container
1724 * @param string $object
1725 * @return string
1726 */
1727 protected function storageUrl( array $creds, $container = null, $object = null ) {
1728 $parts = [ $creds['storage_url'] ];
1729 if ( strlen( $container ) ) {
1730 $parts[] = rawurlencode( $container );
1731 }
1732 if ( strlen( $object ) ) {
1733 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1734 }
1735
1736 return implode( '/', $parts );
1737 }
1738
1739 /**
1740 * @param array $creds From getAuthentication()
1741 * @return array
1742 */
1743 protected function authTokenHeaders( array $creds ) {
1744 return [ 'x-auth-token' => $creds['auth_token'] ];
1745 }
1746
1747 /**
1748 * Get the cache key for a container
1749 *
1750 * @param string $username
1751 * @return string
1752 */
1753 private function getCredsCacheKey( $username ) {
1754 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1755 }
1756
1757 /**
1758 * Log an unexpected exception for this backend.
1759 * This also sets the StatusValue object to have a fatal error.
1760 *
1761 * @param StatusValue|null $status
1762 * @param string $func
1763 * @param array $params
1764 * @param string $err Error string
1765 * @param int $code HTTP status
1766 * @param string $desc HTTP StatusValue description
1767 */
1768 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1769 if ( $status instanceof StatusValue ) {
1770 $status->fatal( 'backend-fail-internal', $this->name );
1771 }
1772 if ( $code == 401 ) { // possibly a stale token
1773 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1774 }
1775 $this->logger->error(
1776 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1777 ( $err ? ": $err" : "" )
1778 );
1779 }
1780 }
1781
1782 /**
1783 * @see FileBackendStoreOpHandle
1784 */
1785 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1786 /** @var array List of Requests for MultiHttpClient */
1787 public $httpOp;
1788 /** @var Closure */
1789 public $callback;
1790
1791 /**
1792 * @param SwiftFileBackend $backend
1793 * @param Closure $callback Function that takes (HTTP request array, status)
1794 * @param array $httpOp MultiHttpClient op
1795 */
1796 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1797 $this->backend = $backend;
1798 $this->callback = $callback;
1799 $this->httpOp = $httpOp;
1800 }
1801 }
1802
1803 /**
1804 * SwiftFileBackend helper class to page through listings.
1805 * Swift also has a listing limit of 10,000 objects for sanity.
1806 * Do not use this class from places outside SwiftFileBackend.
1807 *
1808 * @ingroup FileBackend
1809 */
1810 abstract class SwiftFileBackendList implements Iterator {
1811 /** @var array List of path or (path,stat array) entries */
1812 protected $bufferIter = [];
1813
1814 /** @var string List items *after* this path */
1815 protected $bufferAfter = null;
1816
1817 /** @var int */
1818 protected $pos = 0;
1819
1820 /** @var array */
1821 protected $params = [];
1822
1823 /** @var SwiftFileBackend */
1824 protected $backend;
1825
1826 /** @var string Container name */
1827 protected $container;
1828
1829 /** @var string Storage directory */
1830 protected $dir;
1831
1832 /** @var int */
1833 protected $suffixStart;
1834
1835 const PAGE_SIZE = 9000; // file listing buffer size
1836
1837 /**
1838 * @param SwiftFileBackend $backend
1839 * @param string $fullCont Resolved container name
1840 * @param string $dir Resolved directory relative to container
1841 * @param array $params
1842 */
1843 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1844 $this->backend = $backend;
1845 $this->container = $fullCont;
1846 $this->dir = $dir;
1847 if ( substr( $this->dir, -1 ) === '/' ) {
1848 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1849 }
1850 if ( $this->dir == '' ) { // whole container
1851 $this->suffixStart = 0;
1852 } else { // dir within container
1853 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1854 }
1855 $this->params = $params;
1856 }
1857
1858 /**
1859 * @see Iterator::key()
1860 * @return int
1861 */
1862 public function key() {
1863 return $this->pos;
1864 }
1865
1866 /**
1867 * @see Iterator::next()
1868 */
1869 public function next() {
1870 // Advance to the next file in the page
1871 next( $this->bufferIter );
1872 ++$this->pos;
1873 // Check if there are no files left in this page and
1874 // advance to the next page if this page was not empty.
1875 if ( !$this->valid() && count( $this->bufferIter ) ) {
1876 $this->bufferIter = $this->pageFromList(
1877 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1878 ); // updates $this->bufferAfter
1879 }
1880 }
1881
1882 /**
1883 * @see Iterator::rewind()
1884 */
1885 public function rewind() {
1886 $this->pos = 0;
1887 $this->bufferAfter = null;
1888 $this->bufferIter = $this->pageFromList(
1889 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1890 ); // updates $this->bufferAfter
1891 }
1892
1893 /**
1894 * @see Iterator::valid()
1895 * @return bool
1896 */
1897 public function valid() {
1898 if ( $this->bufferIter === null ) {
1899 return false; // some failure?
1900 } else {
1901 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1902 }
1903 }
1904
1905 /**
1906 * Get the given list portion (page)
1907 *
1908 * @param string $container Resolved container name
1909 * @param string $dir Resolved path relative to container
1910 * @param string &$after
1911 * @param int $limit
1912 * @param array $params
1913 * @return Traversable|array
1914 */
1915 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1916 }
1917
1918 /**
1919 * Iterator for listing directories
1920 */
1921 class SwiftFileBackendDirList extends SwiftFileBackendList {
1922 /**
1923 * @see Iterator::current()
1924 * @return string|bool String (relative path) or false
1925 */
1926 public function current() {
1927 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1928 }
1929
1930 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1931 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1932 }
1933 }
1934
1935 /**
1936 * Iterator for listing regular files
1937 */
1938 class SwiftFileBackendFileList extends SwiftFileBackendList {
1939 /**
1940 * @see Iterator::current()
1941 * @return string|bool String (relative path) or false
1942 */
1943 public function current() {
1944 list( $path, $stat ) = current( $this->bufferIter );
1945 $relPath = substr( $path, $this->suffixStart );
1946 if ( is_array( $stat ) ) {
1947 $storageDir = rtrim( $this->params['dir'], '/' );
1948 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1949 }
1950
1951 return $relPath;
1952 }
1953
1954 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1955 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1956 }
1957 }