Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/S3Transfer/Utils/FileDownloadHandler.php

raw symbols SCIP
1 <?php
2
3 namespace Aws\S3\S3Transfer\Utils;
4
5 use Aws\S3\ApplyChecksumMiddleware;
6 use Aws\S3\S3Transfer\AbstractMultipartDownloader;
7 use Aws\S3\S3Transfer\Exception\FileDownloadException;
8 use Aws\S3\S3Transfer\Progress\AbstractTransferListener;
9
10 final class FileDownloadHandler extends AbstractDownloadHandler
11 implements ResumableDownloadHandlerInterface
12 {
13 private const IDENTIFIER_LENGTH = 8;
14 private const TEMP_INFIX = '.s3tmp.';
15 private const RESUME_SUFFIX = '.resume';
16 private const MAX_UNIQUE_ID_ATTEMPTS = 100;
17
18 /** @var string */
19 private string $destination;
20
21 /** @var bool */
22 private bool $failsWhenDestinationExists;
23
24 /** @var string|null */
25 private ?string $temporaryFilePath;
26
27 /** @var int|null */
28 private ?int $fixedPartSize;
29
30 /** @var bool */
31 private bool $resumeEnabled;
32
33 /** @var mixed|null */
34 private mixed $handle;
35
36 /** @var bool */
37 private bool $transferFailed;
38
39 /**
40 * @param string $destination
41 * @param bool $failsWhenDestinationExists
42 * @param bool $resumeEnabled
43 * @param string|null $temporaryFilePath
44 * @param int|null $fixedPartSize
45 */
46 public function __construct(
47 string $destination,
48 bool $failsWhenDestinationExists,
49 bool $resumeEnabled = false,
50 ?string $temporaryFilePath = null,
51 ?int $fixedPartSize = null,
52 ) {
53 $this->destination = $destination;
54 $this->failsWhenDestinationExists = $failsWhenDestinationExists;
55 $this->resumeEnabled = $resumeEnabled;
56 $this->temporaryFilePath = $temporaryFilePath;
57 $this->fixedPartSize = $fixedPartSize;
58 $this->handle = null;
59 $this->transferFailed = false;
60 }
61
62 /**
63 * @return string
64 */
65 public function getDestination(): string
66 {
67 return $this->destination;
68 }
69
70 /**
71 * @return bool
72 */
73 public function isFailsWhenDestinationExists(): bool
74 {
75 return $this->failsWhenDestinationExists;
76 }
77
78 /**
79 * @param array $context
80 *
81 * @return void
82 */
83 public function transferInitiated(array $context): void
84 {
85 $this->validateDestination();
86 $this->ensureDirectoryExists();
87 // temporary destination may have been set by resume
88 if (empty($this->temporaryFilePath)) {
89 $this->temporaryFilePath = $this->generateTemporaryFilePath();
90 } else {
91 $this->openExistingFile();
92 }
93 }
94
95 /**
96 * Open an existing temporary file for resuming.
97 * Opens in 'r+' mode which allows reading and writing without truncating.
98 *
99 * @return void
100 */
101 private function openExistingFile(): void
102 {
103 if ($this->handle !== null) {
104 return;
105 }
106
107 $handle = fopen($this->temporaryFilePath, 'r+');
108
109 if ($handle === false) {
110 throw new FileDownloadException(
111 "Failed to open existing temporary file '{$this->temporaryFilePath}' for resuming."
112 );
113 }
114
115 $this->handle = $handle;
116 }
117
118 /**
119 * @param array $context
120 *
121 * @return bool
122 */
123 public function bytesTransferred(array $context): bool
124 {
125 if ($this->transferFailed) {
126 return false;
127 }
128
129 $snapshot = $context[AbstractTransferListener::PROGRESS_SNAPSHOT_KEY];
130 $response = $snapshot->getResponse();
131
132 if ($this->handle === null) {
133 $this->fixedPartSize = $response['ContentLength'];
134 $this->initializeDestination($response);
135 }
136
137 if ($this->handle === null) {
138 throw new FileDownloadException(
139 "Failed to initialize destination for downloading."
140 );
141 }
142
143 return $this->writePartToDestinationHandle($response);
144 }
145
146 /**
147 * @param array $context
148 *
149 * @return void
150 */
151 public function transferComplete(array $context): void
152 {
153 $this->closeDestinationHandle();
154 $this->replaceDestinationFile();
155 }
156
157 /**
158 * @param array $context
159 *
160 * @return void
161 */
162 public function transferFail(array $context): void
163 {
164 $this->transferFailed = true;
165 $this->closeDestinationHandle();
166 $this->cleanupAfterFailure($context);
167 }
168
169 /**
170 * @param array $response
171 *
172 * @return void
173 */
174 public function initializeDestination(array $response): void
175 {
176 $objectSize = AbstractMultipartDownloader::computeObjectSizeFromContentRange(
177 $response['ContentRange'] ?? ""
178 );
179
180 $this->createTruncatedFile($objectSize);
181 }
182
183 /**
184 * @param array $response
185 *
186 * @return bool
187 */
188 private function writePartToDestinationHandle(array $response): bool
189 {
190 $contentRange = $response['ContentRange'] ?? null;
191 if ($contentRange === null) {
192 throw new FileDownloadException(
193 "Unable to get content range from response."
194 );
195 }
196
197 $partNo = (int) ceil(
198 AbstractMultipartDownloader::getRangeTo($contentRange) / $this->fixedPartSize
199 );
200 $position = ($partNo - 1) * $this->fixedPartSize;
201
202 if (!flock($this->handle, LOCK_EX)) {
203 throw new FileDownloadException("Failed to acquire file lock.");
204 }
205
206 try {
207 fseek($this->handle, $position);
208
209 $body = $response['Body'];
210 // In case body was already consumed by another process
211 if ($body->isSeekable()) {
212 $body->rewind();
213 }
214
215 // Try to validate a checksum when writting to disk
216 $checksumParameter = ApplyChecksumMiddleware::filterChecksum(
217 $response
218 );
219 $hashContext = null;
220 if ($checksumParameter !== null) {
221 $checksumAlgorithm = strtolower(
222 str_replace(
223 "Checksum",
224 "",
225 $checksumParameter
226 )
227 );
228 $checksumAlgorithm = $checksumAlgorithm === 'crc32'
229 ? 'crc32b'
230 : $checksumAlgorithm;
231 $hashContext = hash_init($checksumAlgorithm);
232 }
233
234 while (!$body->eof()) {
235 $chunk = $body->read(self::READ_BUFFER_SIZE);
236
237 if (fwrite($this->handle, $chunk) === false) {
238 throw new FileDownloadException("Failed to write data to temporary file.");
239 }
240
241 if ($hashContext !== null) {
242 hash_update($hashContext, $chunk);
243 }
244 }
245
246 if ($hashContext !== null) {
247 $calculatedChecksum = base64_encode(
248 hash_final($hashContext, true)
249 );
250 if ($calculatedChecksum !== $response[$checksumParameter]) {
251 throw new FileDownloadException(
252 "Checksum mismatch when writing part to destination file."
253 );
254 }
255 }
256
257 fflush($this->handle);
258
259 return true;
260 } finally {
261 flock($this->handle, LOCK_UN);
262 }
263 }
264
265 /**
266 * @return void
267 */
268 private function closeDestinationHandle(): void
269 {
270 if (is_resource($this->handle)) {
271 fclose($this->handle);
272 $this->handle = null;
273 }
274 }
275
276 /**
277 * @return string
278 */
279 public function getHandlerResult(): string
280 {
281 return $this->destination;
282 }
283
284 /**
285 * @return void
286 */
287 private function validateDestination(): void
288 {
289 if ($this->failsWhenDestinationExists && file_exists($this->destination)) {
290 throw new FileDownloadException(
291 "The destination '{$this->destination}' already exists."
292 );
293 }
294
295 if (is_dir($this->destination)) {
296 throw new FileDownloadException(
297 "The destination '{$this->destination}' can't be a directory."
298 );
299 }
300 }
301
302 /**
303 * @return void
304 */
305 private function ensureDirectoryExists(): void
306 {
307 $directory = dirname($this->destination);
308
309 if (!is_dir($directory) && !mkdir($directory, 0755, true)
310 && !is_dir($directory)) {
311 throw new FileDownloadException(
312 "Failed to create directory '{$directory}'."
313 );
314 }
315 }
316
317 /**
318 * @return string
319 */
320 private function generateTemporaryFilePath(): string
321 {
322 for ($attempt = 0; $attempt < self::MAX_UNIQUE_ID_ATTEMPTS; $attempt++) {
323 $uniqueId = $this->generateUniqueIdentifier();
324 $temporaryPath = $this->destination . self::TEMP_INFIX . $uniqueId;
325
326 if (!file_exists($temporaryPath)) {
327 return $temporaryPath;
328 }
329 }
330
331 throw new FileDownloadException(
332 "Unable to generate a unique temporary file name after " . self::MAX_UNIQUE_ID_ATTEMPTS . " attempts."
333 );
334 }
335
336 /**
337 * @return string
338 */
339 private function generateUniqueIdentifier(): string
340 {
341 $uniqueId = uniqid();
342
343 if (strlen($uniqueId) > self::IDENTIFIER_LENGTH) {
344 return substr($uniqueId, 0, self::IDENTIFIER_LENGTH);
345 }
346
347 return str_pad($uniqueId, self::IDENTIFIER_LENGTH, "0");
348 }
349
350 /**
351 * @param int $size
352 *
353 * @return void
354 */
355 private function createTruncatedFile(int $size): void
356 {
357 $handle = fopen($this->temporaryFilePath, 'w+');
358
359 if ($handle === false) {
360 throw new FileDownloadException(
361 "Failed to open temporary file '{$this->temporaryFilePath}' for writing."
362 );
363 }
364
365 $this->handle = $handle;
366
367 if (!ftruncate($this->handle, $size)) {
368 throw new FileDownloadException(
369 "Failed to allocate {$size} bytes for temporary file."
370 );
371 }
372 }
373
374 /**
375 * @return void
376 */
377 private function replaceDestinationFile(): void
378 {
379 if (file_exists($this->destination)) {
380 if ($this->failsWhenDestinationExists) {
381 throw new FileDownloadException(
382 "The destination '{$this->destination}' already exists."
383 );
384 }
385
386 if (!unlink($this->destination)) {
387 throw new FileDownloadException(
388 "Failed to delete existing file '{$this->destination}'."
389 );
390 }
391 }
392
393 if (!rename($this->temporaryFilePath, $this->destination)) {
394 throw new FileDownloadException(
395 "Unable to rename the file '{$this->temporaryFilePath}' to '{$this->destination}'."
396 );
397 }
398 }
399
400 /**
401 * @param array $context
402 *
403 * @return void
404 */
405 private function cleanupAfterFailure(array $context): void
406 {
407 if (!$this->resumeEnabled && file_exists($this->temporaryFilePath)) {
408 unlink($this->temporaryFilePath);
409 return;
410 }
411
412 $reason = $context[self::REASON_KEY] ?? '';
413 $isDestinationExistsError = str_contains(
414 $reason,
415 "The destination '{$this->destination}' already exists."
416 );
417
418 if (file_exists($this->destination) && !$isDestinationExistsError) {
419 unlink($this->destination);
420 }
421 }
422
423 /**
424 * @inheritDoc
425 */
426 public function isConcurrencySupported(): bool
427 {
428 return true;
429 }
430
431 /**
432 * @return string
433 */
434 public function getResumeFilePath(): string
435 {
436 return $this->temporaryFilePath . self::RESUME_SUFFIX;
437 }
438
439 /**
440 * @return string
441 */
442 public function getTemporaryFilePath(): string
443 {
444 return $this->temporaryFilePath;
445 }
446
447 /**
448 * @return int
449 */
450 public function getFixedPartSize(): int
451 {
452 return $this->fixedPartSize;
453 }
454 }