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'] ) ? StreamFile::STREAM_HEADLESS : 0;
1094
1095 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1096 if ( $srcRel === null ) {
1097 StreamFile::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 StreamFile::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 StreamFile::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 StatusValue[] $statuses */
1305 $statuses = [];
1306
1307 $auth = $this->getAuthentication();
1308 if ( !$auth ) {
1309 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1310 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name );
1311 }
1312
1313 return $statuses;
1314 }
1315
1316 // Split the HTTP requests into stages that can be done concurrently
1317 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1318 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1319 /** @var SwiftFileOpHandle $fileOpHandle */
1320 $reqs = $fileOpHandle->httpOp;
1321 // Convert the 'url' parameter to an actual URL using $auth
1322 foreach ( $reqs as $stage => &$req ) {
1323 list( $container, $relPath ) = $req['url'];
1324 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1325 $req['headers'] = $req['headers'] ?? [];
1326 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1327 $httpReqsByStage[$stage][$index] = $req;
1328 }
1329 $statuses[$index] = $this->newStatus();
1330 }
1331
1332 // Run all requests for the first stage, then the next, and so on
1333 $reqCount = count( $httpReqsByStage );
1334 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1335 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1336 foreach ( $httpReqs as $index => $httpReq ) {
1337 /** @var SwiftFileOpHandle $fileOpHandle */
1338 $fileOpHandle = $fileOpHandles[$index];
1339 // Run the callback for each request of this operation
1340 $status = $statuses[$index];
1341 ( $fileOpHandle->callback )( $httpReq, $status );
1342 // On failure, abort all remaining requests for this operation. This is used
1343 // in "move" operations to abort the DELETE request if the PUT request fails.
1344 if (
1345 !$status->isOK() ||
1346 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1347 ) {
1348 $stages = count( $fileOpHandle->httpOp );
1349 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1350 unset( $httpReqsByStage[$s][$index] );
1351 }
1352 }
1353 }
1354 }
1355
1356 return $statuses;
1357 }
1358
1359 /**
1360 * Set read/write permissions for a Swift container.
1361 *
1362 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1363 *
1364 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1365 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1366 *
1367 * @param string $container Resolved Swift container
1368 * @param array $readUsers List of the possible criteria for a request to have
1369 * access to read a container. Each item is one of the following formats:
1370 * - account:user : Grants access if the request is by the given user
1371 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1372 * matches the expression and the request is not for a listing.
1373 * Setting this to '*' effectively makes a container public.
1374 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1375 * matches the expression and the request is for a listing.
1376 * @param array $writeUsers A list of the possible criteria for a request to have
1377 * access to write to a container. Each item is of the following format:
1378 * - account:user : Grants access if the request is by the given user
1379 * @return StatusValue
1380 */
1381 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1382 $status = $this->newStatus();
1383 $auth = $this->getAuthentication();
1384
1385 if ( !$auth ) {
1386 $status->fatal( 'backend-fail-connect', $this->name );
1387
1388 return $status;
1389 }
1390
1391 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1392 'method' => 'POST',
1393 'url' => $this->storageUrl( $auth, $container ),
1394 'headers' => $this->authTokenHeaders( $auth ) + [
1395 'x-container-read' => implode( ',', $readUsers ),
1396 'x-container-write' => implode( ',', $writeUsers )
1397 ]
1398 ] );
1399
1400 if ( $rcode != 204 && $rcode !== 202 ) {
1401 $status->fatal( 'backend-fail-internal', $this->name );
1402 $this->logger->error( __METHOD__ . ': unexpected rcode value ({rcode})',
1403 [ 'rcode' => $rcode ] );
1404 }
1405
1406 return $status;
1407 }
1408
1409 /**
1410 * Get a Swift container stat array, possibly from process cache.
1411 * Use $reCache if the file count or byte count is needed.
1412 *
1413 * @param string $container Container name
1414 * @param bool $bypassCache Bypass all caches and load from Swift
1415 * @return array|bool|null False on 404, null on failure
1416 */
1417 protected function getContainerStat( $container, $bypassCache = false ) {
1418 /** @noinspection PhpUnusedLocalVariableInspection */
1419 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1420
1421 if ( $bypassCache ) { // purge cache
1422 $this->containerStatCache->clear( $container );
1423 } elseif ( !$this->containerStatCache->hasField( $container, 'stat' ) ) {
1424 $this->primeContainerCache( [ $container ] ); // check persistent cache
1425 }
1426 if ( !$this->containerStatCache->hasField( $container, 'stat' ) ) {
1427 $auth = $this->getAuthentication();
1428 if ( !$auth ) {
1429 return self::$RES_ERROR;
1430 }
1431
1432 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1433 'method' => 'HEAD',
1434 'url' => $this->storageUrl( $auth, $container ),
1435 'headers' => $this->authTokenHeaders( $auth )
1436 ] );
1437
1438 if ( $rcode === 204 ) {
1439 $stat = [
1440 'count' => $rhdrs['x-container-object-count'],
1441 'bytes' => $rhdrs['x-container-bytes-used']
1442 ];
1443 if ( $bypassCache ) {
1444 return $stat;
1445 } else {
1446 $this->containerStatCache->setField( $container, 'stat', $stat ); // cache it
1447 $this->setContainerCache( $container, $stat ); // update persistent cache
1448 }
1449 } elseif ( $rcode === 404 ) {
1450 return self::$RES_ABSENT;
1451 } else {
1452 $this->onError( null, __METHOD__,
1453 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1454
1455 return self::$RES_ERROR;
1456 }
1457 }
1458
1459 return $this->containerStatCache->getField( $container, 'stat' );
1460 }
1461
1462 /**
1463 * Create a Swift container
1464 *
1465 * @param string $container Container name
1466 * @param array $params
1467 * @return StatusValue
1468 */
1469 protected function createContainer( $container, array $params ) {
1470 $status = $this->newStatus();
1471
1472 $auth = $this->getAuthentication();
1473 if ( !$auth ) {
1474 $status->fatal( 'backend-fail-connect', $this->name );
1475
1476 return $status;
1477 }
1478
1479 // @see SwiftFileBackend::setContainerAccess()
1480 if ( empty( $params['noAccess'] ) ) {
1481 // public
1482 $readUsers = array_merge( $this->readUsers, [ '.r:*', $this->swiftUser ] );
1483 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1484 } else {
1485 // private
1486 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1487 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1488 }
1489
1490 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1491 'method' => 'PUT',
1492 'url' => $this->storageUrl( $auth, $container ),
1493 'headers' => $this->authTokenHeaders( $auth ) + [
1494 'x-container-read' => implode( ',', $readUsers ),
1495 'x-container-write' => implode( ',', $writeUsers )
1496 ]
1497 ] );
1498
1499 if ( $rcode === 201 ) { // new
1500 // good
1501 } elseif ( $rcode === 202 ) { // already there
1502 // this shouldn't really happen, but is OK
1503 } else {
1504 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1505 }
1506
1507 return $status;
1508 }
1509
1510 /**
1511 * Delete a Swift container
1512 *
1513 * @param string $container Container name
1514 * @param array $params
1515 * @return StatusValue
1516 */
1517 protected function deleteContainer( $container, array $params ) {
1518 $status = $this->newStatus();
1519
1520 $auth = $this->getAuthentication();
1521 if ( !$auth ) {
1522 $status->fatal( 'backend-fail-connect', $this->name );
1523
1524 return $status;
1525 }
1526
1527 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1528 'method' => 'DELETE',
1529 'url' => $this->storageUrl( $auth, $container ),
1530 'headers' => $this->authTokenHeaders( $auth )
1531 ] );
1532
1533 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1534 $this->containerStatCache->clear( $container ); // purge
1535 } elseif ( $rcode === 404 ) { // not there
1536 // this shouldn't really happen, but is OK
1537 } elseif ( $rcode === 409 ) { // not empty
1538 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1539 } else {
1540 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1541 }
1542
1543 return $status;
1544 }
1545
1546 /**
1547 * Get a list of objects under a container.
1548 * Either just the names or a list of stdClass objects with details can be returned.
1549 *
1550 * @param string $fullCont
1551 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1552 * @param int $limit
1553 * @param string|null $after
1554 * @param string|null $prefix
1555 * @param string|null $delim
1556 * @return StatusValue With the list as value
1557 */
1558 private function objectListing(
1559 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1560 ) {
1561 $status = $this->newStatus();
1562
1563 $auth = $this->getAuthentication();
1564 if ( !$auth ) {
1565 $status->fatal( 'backend-fail-connect', $this->name );
1566
1567 return $status;
1568 }
1569
1570 $query = [ 'limit' => $limit ];
1571 if ( $type === 'info' ) {
1572 $query['format'] = 'json';
1573 }
1574 if ( $after !== null ) {
1575 $query['marker'] = $after;
1576 }
1577 if ( $prefix !== null ) {
1578 $query['prefix'] = $prefix;
1579 }
1580 if ( $delim !== null ) {
1581 $query['delimiter'] = $delim;
1582 }
1583
1584 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1585 'method' => 'GET',
1586 'url' => $this->storageUrl( $auth, $fullCont ),
1587 'query' => $query,
1588 'headers' => $this->authTokenHeaders( $auth )
1589 ] );
1590
1591 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1592 if ( $rcode === 200 ) { // good
1593 if ( $type === 'info' ) {
1594 $status->value = FormatJson::decode( trim( $rbody ) );
1595 } else {
1596 $status->value = explode( "\n", trim( $rbody ) );
1597 }
1598 } elseif ( $rcode === 204 ) {
1599 $status->value = []; // empty container
1600 } elseif ( $rcode === 404 ) {
1601 $status->value = []; // no container
1602 } else {
1603 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1604 }
1605
1606 return $status;
1607 }
1608
1609 protected function doPrimeContainerCache( array $containerInfo ) {
1610 foreach ( $containerInfo as $container => $info ) {
1611 $this->containerStatCache->setField( $container, 'stat', $info );
1612 }
1613 }
1614
1615 protected function doGetFileStatMulti( array $params ) {
1616 $stats = [];
1617
1618 $auth = $this->getAuthentication();
1619
1620 $reqs = []; // (path => op)
1621 // (a) Check the containers of the paths...
1622 foreach ( $params['srcs'] as $path ) {
1623 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1624 if ( $srcRel === null || !$auth ) {
1625 $stats[$path] = self::$RES_ERROR;
1626 continue; // invalid storage path or auth error
1627 }
1628
1629 $cstat = $this->getContainerStat( $srcCont );
1630 if ( $cstat === self::$RES_ABSENT ) {
1631 $stats[$path] = self::$RES_ABSENT;
1632 continue; // ok, nothing to do
1633 } elseif ( !is_array( $cstat ) ) {
1634 $stats[$path] = self::$RES_ERROR;
1635 continue;
1636 }
1637
1638 $reqs[$path] = [
1639 'method' => 'HEAD',
1640 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1641 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1642 ];
1643 }
1644
1645 // (b) Check the files themselves...
1646 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1647 $reqs = $this->http->runMulti( $reqs, $opts );
1648 foreach ( $reqs as $path => $op ) {
1649 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1650 if ( $rcode === 200 || $rcode === 204 ) {
1651 // Update the object if it is missing some headers
1652 if ( !empty( $params['requireSHA1'] ) ) {
1653 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1654 }
1655 // Load the stat array from the headers
1656 $stat = $this->getStatFromHeaders( $rhdrs );
1657 if ( $this->isRGW ) {
1658 $stat['latest'] = true; // strong consistency
1659 }
1660 } elseif ( $rcode === 404 ) {
1661 $stat = self::$RES_ABSENT;
1662 } else {
1663 $stat = self::$RES_ERROR;
1664 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1665 }
1666 $stats[$path] = $stat;
1667 }
1668
1669 return $stats;
1670 }
1671
1672 /**
1673 * @param array $rhdrs
1674 * @return array
1675 */
1676 protected function getStatFromHeaders( array $rhdrs ) {
1677 // Fetch all of the custom metadata headers
1678 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1679 // Fetch all of the custom raw HTTP headers
1680 $headers = $this->extractMutableContentHeaders( $rhdrs );
1681
1682 return [
1683 // Convert various random Swift dates to TS_MW
1684 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1685 // Empty objects actually return no content-length header in Ceph
1686 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1687 'sha1' => $metadata['sha1base36'] ?? null,
1688 // Note: manifiest ETags are not an MD5 of the file
1689 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1690 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1691 ];
1692 }
1693
1694 /**
1695 * @return array|null Credential map
1696 */
1697 protected function getAuthentication() {
1698 if ( $this->authErrorTimestamp !== null ) {
1699 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1700 return null; // failed last attempt; don't bother
1701 } else { // actually retry this time
1702 $this->authErrorTimestamp = null;
1703 }
1704 }
1705 // Session keys expire after a while, so we renew them periodically
1706 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1707 // Authenticate with proxy and get a session key...
1708 if ( !$this->authCreds || $reAuth ) {
1709 $this->authSessionTimestamp = 0;
1710 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1711 $creds = $this->srvCache->get( $cacheKey ); // credentials
1712 // Try to use the credential cache
1713 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1714 $this->authCreds = $creds;
1715 // Skew the timestamp for worst case to avoid using stale credentials
1716 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1717 } else { // cache miss
1718 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1719 'method' => 'GET',
1720 'url' => "{$this->swiftAuthUrl}/v1.0",
1721 'headers' => [
1722 'x-auth-user' => $this->swiftUser,
1723 'x-auth-key' => $this->swiftKey
1724 ]
1725 ] );
1726
1727 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1728 $this->authCreds = [
1729 'auth_token' => $rhdrs['x-auth-token'],
1730 'storage_url' => $this->swiftStorageUrl ?? $rhdrs['x-storage-url']
1731 ];
1732
1733 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1734 $this->authSessionTimestamp = time();
1735 } elseif ( $rcode === 401 ) {
1736 $this->onError( null, __METHOD__, [], "Authentication failed.", $rcode );
1737 $this->authErrorTimestamp = time();
1738
1739 return null;
1740 } else {
1741 $this->onError( null, __METHOD__, [], "HTTP return code: $rcode", $rcode );
1742 $this->authErrorTimestamp = time();
1743
1744 return null;
1745 }
1746 }
1747 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1748 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1749 $this->isRGW = true; // take advantage of strong consistency in Ceph
1750 }
1751 }
1752
1753 return $this->authCreds;
1754 }
1755
1756 /**
1757 * @param array $creds From getAuthentication()
1758 * @param string|null $container
1759 * @param string|null $object
1760 * @return string
1761 */
1762 protected function storageUrl( array $creds, $container = null, $object = null ) {
1763 $parts = [ $creds['storage_url'] ];
1764 if ( strlen( $container ) ) {
1765 $parts[] = rawurlencode( $container );
1766 }
1767 if ( strlen( $object ) ) {
1768 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1769 }
1770
1771 return implode( '/', $parts );
1772 }
1773
1774 /**
1775 * @param array $creds From getAuthentication()
1776 * @return array
1777 */
1778 protected function authTokenHeaders( array $creds ) {
1779 return [ 'x-auth-token' => $creds['auth_token'] ];
1780 }
1781
1782 /**
1783 * Get the cache key for a container
1784 *
1785 * @param string $username
1786 * @return string
1787 */
1788 private function getCredsCacheKey( $username ) {
1789 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1790 }
1791
1792 /**
1793 * Log an unexpected exception for this backend.
1794 * This also sets the StatusValue object to have a fatal error.
1795 *
1796 * @param StatusValue|null $status
1797 * @param string $func
1798 * @param array $params
1799 * @param string $err Error string
1800 * @param int $code HTTP status
1801 * @param string $desc HTTP StatusValue description
1802 */
1803 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1804 if ( $status instanceof StatusValue ) {
1805 $status->fatal( 'backend-fail-internal', $this->name );
1806 }
1807 if ( $code == 401 ) { // possibly a stale token
1808 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1809 }
1810 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1811 $msgParams = [
1812 'code' => $code,
1813 'desc' => $desc,
1814 'func' => $func,
1815 'req_params' => FormatJson::encode( $params ),
1816 ];
1817 if ( $err ) {
1818 $msg .= ': {err}';
1819 $msgParams['err'] = $err;
1820 }
1821 $this->logger->error( $msg, $msgParams );
1822 }
1823 }