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