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