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