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