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