SwiftFileBackend.php 61 KB

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