Passed
Push — master ( 1716c0...401a94 )
by Ankit
02:42
created

Server::verifyChecksum()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace TusPhp\Tus;
4
5
use TusPhp\File;
6
use Carbon\Carbon;
7
use TusPhp\Request;
8
use TusPhp\Response;
9
use Ramsey\Uuid\Uuid;
10
use TusPhp\Cache\Cacheable;
11
use TusPhp\Exception\FileException;
12
use TusPhp\Exception\ConnectionException;
13
use TusPhp\Exception\OutOfRangeException;
14
use Illuminate\Http\Request as HttpRequest;
15
use Illuminate\Http\Response as HttpResponse;
16
use Symfony\Component\HttpFoundation\BinaryFileResponse;
17
18
class Server extends AbstractTus
19
{
20
    /** @const string Tus Creation Extension */
21
    const TUS_EXTENSION_CREATION = 'creation';
22
23
    /** @const string Tus Termination Extension */
24
    const TUS_EXTENSION_TERMINATION = 'termination';
25
26
    /** @const string Tus Checksum Extension */
27
    const TUS_EXTENSION_CHECKSUM = 'checksum';
28
29
    /** @const string Tus Expiration Extension */
30
    const TUS_EXTENSION_EXPIRATION = 'expiration';
31
32
    /** @const string Tus Concatenation Extension */
33
    const TUS_EXTENSION_CONCATENATION = 'concatenation';
34
35
    /** @const array All supported tus extensions */
36
    const TUS_EXTENSIONS = [
37
        self::TUS_EXTENSION_CREATION,
38
        self::TUS_EXTENSION_TERMINATION,
39
        self::TUS_EXTENSION_CHECKSUM,
40
        self::TUS_EXTENSION_EXPIRATION,
41
        self::TUS_EXTENSION_CONCATENATION,
42
    ];
43
44
    /** @const int 460 Checksum Mismatch */
45
    const HTTP_CHECKSUM_MISMATCH = 460;
46
47
    /** @const string Default checksum algorithm */
48
    const DEFAULT_CHECKSUM_ALGORITHM = 'sha256';
49
50
    /** @const int 24 hours access control max age header */
51
    const HEADER_ACCESS_CONTROL_MAX_AGE = 86400;
52
53
    /** @var Request */
54
    protected $request;
55
56
    /** @var Response */
57
    protected $response;
58
59
    /** @var string */
60
    protected $uploadDir;
61
62
    /** @var string */
63
    protected $uploadKey;
64
65
    /** @var array */
66
    protected $globalHeaders;
67
68
    /**
69
     * @var int Max upload size in bytes
70
     *          Default 0, no restriction.
71
     */
72
    protected $maxUploadSize = 0;
73
74
    /**
75
     * TusServer constructor.
76
     *
77
     * @param Cacheable|string $cacheAdapter
78
     */
79 3
    public function __construct($cacheAdapter = 'file')
80
    {
81 3
        $this->request   = new Request;
82 3
        $this->response  = new Response;
83 3
        $this->uploadDir = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'uploads';
84
85 3
        $this->globalHeaders = [
86 3
            'Access-Control-Allow-Origin' => $this->request->header('Origin'),
87 3
            'Access-Control-Allow-Methods' => implode(',', $this->getRequest()->allowedHttpVerbs()),
88 3
            'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Content-Length, Upload-Key, Upload-Checksum, Upload-Length, Upload-Offset, Tus-Version, Tus-Resumable, Upload-Metadata',
89 3
            'Access-Control-Expose-Headers' => 'Upload-Key, Upload-Checksum, Upload-Length, Upload-Offset, Upload-Metadata, Tus-Version, Tus-Resumable, Tus-Extension, Location',
90 3
            'Access-Control-Max-Age' => self::HEADER_ACCESS_CONTROL_MAX_AGE,
91 3
            'X-Content-Type-Options' => 'nosniff',
92
        ];
93
94 3
        $this->setCache($cacheAdapter);
95 3
    }
96
97
    /**
98
     * Set upload dir.
99
     *
100
     * @param string $path
101
     *
102
     * @return Server
103
     */
104 2
    public function setUploadDir(string $path) : self
105
    {
106 2
        $this->uploadDir = $path;
107
108 2
        return $this;
109
    }
110
111
    /**
112
     * Get upload dir.
113
     *
114
     * @return string
115
     */
116 1
    public function getUploadDir() : string
117
    {
118 1
        return $this->uploadDir;
119
    }
120
121
    /**
122
     * Get request.
123
     *
124
     * @return Request
125
     */
126 1
    public function getRequest() : Request
127
    {
128 1
        return $this->request;
129
    }
130
131
    /**
132
     * Get request.
133
     *
134
     * @return Response
135
     */
136 1
    public function getResponse() : Response
137
    {
138 1
        return $this->response;
139
    }
140
141
    /**
142
     * Get file checksum.
143
     *
144
     * @param string $filePath
145
     *
146
     * @return string
147
     */
148 1
    public function getServerChecksum(string $filePath) : string
149
    {
150 1
        return hash_file($this->getChecksumAlgorithm(), $filePath);
151
    }
152
153
    /**
154
     * Get checksum algorithm.
155
     *
156
     * @return string|null
157
     */
158 1
    public function getChecksumAlgorithm()
159
    {
160 1
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
161
162 1
        if (empty($checksumHeader)) {
163 1
            return self::DEFAULT_CHECKSUM_ALGORITHM;
164
        }
165
166 1
        list($checksumAlgorithm) = explode(' ', $checksumHeader);
167
168 1
        return $checksumAlgorithm;
169
    }
170
171
    /**
172
     * Set upload key.
173
     *
174
     * @param string $key
175
     *
176
     * @return Server
177
     */
178 1
    public function setUploadKey(string $key) : self
179
    {
180 1
        $this->uploadKey = $key;
181
182 1
        return $this;
183
    }
184
185
    /**
186
     * Get upload key from header.
187
     *
188
     * @return string|HttpResponse
189
     */
190 4
    public function getUploadKey()
191
    {
192 4
        if ( ! empty($this->uploadKey)) {
193 1
            return $this->uploadKey;
194
        }
195
196 3
        $key = $this->getRequest()->header('Upload-Key') ?? Uuid::uuid4()->toString();
197
198 3
        if (empty($key)) {
199 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
200
        }
201
202 2
        $this->uploadKey = $key;
203
204 2
        return $this->uploadKey;
205
    }
206
207
    /**
208
     * Set max upload size.
209
     *
210
     * @param int $uploadSize
211
     *
212
     * @return Server
213
     */
214 2
    public function setMaxUploadSize(int $uploadSize) : self
215
    {
216 2
        $this->maxUploadSize = $uploadSize;
217
218 2
        return $this;
219
    }
220
221
    /**
222
     * Get max upload size.
223
     *
224
     * @return int
225
     */
226 1
    public function getMaxUploadSize() : int
227
    {
228 1
        return $this->maxUploadSize;
229
    }
230
231
    /**
232
     * Set or get global headers.
233
     *
234
     * @param array $headers
235
     *
236
     * @return Server|array
237
     */
238 1
    public function headers(array $headers = [])
239
    {
240 1
        if (empty($headers)) {
241 1
            return $this->globalHeaders;
242
        }
243
244 1
        $this->globalHeaders = $headers + $this->globalHeaders;
245
246 1
        return $this;
247
    }
248
249
    /**
250
     * Handle all HTTP request.
251
     *
252
     * @return null|HttpResponse
253
     */
254 2
    public function serve()
255
    {
256 2
        $requestMethod = $this->getRequest()->method();
257 2
        $globalHeaders = $this->headers();
258
259 2
        if (HttpRequest::METHOD_OPTIONS !== $requestMethod) {
260 2
            $globalHeaders += ['Tus-Resumable' => self::TUS_PROTOCOL_VERSION];
261
        }
262
263 2
        $this->getResponse()->setHeaders($globalHeaders);
264
265 2
        if ( ! in_array($requestMethod, $this->getRequest()->allowedHttpVerbs())) {
266 1
            return $this->response->send(null, HttpResponse::HTTP_METHOD_NOT_ALLOWED);
267
        }
268
269 1
        $method = 'handle' . ucfirst(strtolower($requestMethod));
270
271 1
        $this->{$method}();
272
273 1
        $this->exit();
274 1
    }
275
276
    /**
277
     * Exit from current php process.
278
     *
279
     * @codeCoverageIgnore
280
     */
281
    protected function exit()
282
    {
283
        exit(0);
284
    }
285
286
    /**
287
     * Handle OPTIONS request.
288
     *
289
     * @return HttpResponse
290
     */
291 2
    protected function handleOptions() : HttpResponse
292
    {
293
        $headers = [
294 2
            'Allow' => implode(',', $this->request->allowedHttpVerbs()),
295 2
            'Tus-Version' => self::TUS_PROTOCOL_VERSION,
296 2
            'Tus-Extension' => implode(',', self::TUS_EXTENSIONS),
297 2
            'Tus-Checksum-Algorithm' => $this->getSupportedHashAlgorithms(),
298
        ];
299
300 2
        $maxUploadSize = $this->getMaxUploadSize();
301
302 2
        if ($maxUploadSize > 0) {
303 1
            $headers['Tus-Max-Size'] = $maxUploadSize;
304
        }
305
306 2
        return $this->response->send(null, HttpResponse::HTTP_OK, $headers);
307
    }
308
309
    /**
310
     * Handle HEAD request.
311
     *
312
     * @return HttpResponse
313
     */
314 5
    protected function handleHead() : HttpResponse
315
    {
316 5
        $key = $this->request->key();
317
318 5
        if ( ! $fileMeta = $this->cache->get($key)) {
319 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
320
        }
321
322 4
        $offset = $fileMeta['offset'] ?? false;
323
324 4
        if (false === $offset) {
325 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
326
        }
327
328 3
        return $this->response->send(null, HttpResponse::HTTP_OK, $this->getHeadersForHeadRequest($fileMeta));
329
    }
330
331
    /**
332
     * Handle POST request.
333
     *
334
     * @return HttpResponse
335
     */
336 5
    protected function handlePost() : HttpResponse
337
    {
338 5
        $fileName   = $this->getRequest()->extractFileName();
339 5
        $uploadType = self::UPLOAD_TYPE_NORMAL;
340
341 5
        if (empty($fileName)) {
342 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
343
        }
344
345 4
        if ( ! $this->verifyUploadSize()) {
346 1
            return $this->response->send(null, HttpResponse::HTTP_REQUEST_ENTITY_TOO_LARGE);
347
        }
348
349 3
        $uploadKey = $this->getUploadKey();
350 3
        $filePath  = $this->uploadDir . DIRECTORY_SEPARATOR . $fileName;
351
352 3
        if ($this->getRequest()->isFinal()) {
353 1
            return $this->handleConcatenation($fileName, $filePath);
354
        }
355
356 2
        if ($this->getRequest()->isPartial()) {
357 1
            $filePath   = $this->getPathForPartialUpload($uploadKey) . $fileName;
358 1
            $uploadType = self::UPLOAD_TYPE_PARTIAL;
359
        }
360
361 2
        $checksum = $this->getClientChecksum();
362 2
        $location = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
363
364 2
        $file = $this->buildFile([
365 2
            'name' => $fileName,
366 2
            'offset' => 0,
367 2
            'size' => $this->getRequest()->header('Upload-Length'),
368 2
            'file_path' => $filePath,
369 2
            'location' => $location,
370 2
        ])->setChecksum($checksum);
371
372 2
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => $uploadType]);
373
374 2
        return $this->response->send(
375 2
            ['data' => ['checksum' => $checksum]],
376 2
            HttpResponse::HTTP_CREATED,
377
            [
378 2
                'Location' => $location,
379 2
                'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
380
            ]
381
        );
382
    }
383
384
    /**
385
     * Handle file concatenation.
386
     *
387
     * @param string $fileName
388
     * @param string $filePath
389
     *
390
     * @return HttpResponse
391
     */
392 2
    protected function handleConcatenation(string $fileName, string $filePath) : HttpResponse
393
    {
394 2
        $partials  = $this->getRequest()->extractPartials();
395 2
        $uploadKey = $this->getUploadKey();
396 2
        $files     = $this->getPartialsMeta($partials);
397 2
        $filePaths = array_column($files, 'file_path');
398 2
        $location  = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
399
400 2
        $file = $this->buildFile([
401 2
            'name' => $fileName,
402 2
            'offset' => 0,
403 2
            'size' => 0,
404 2
            'file_path' => $filePath,
405 2
            'location' => $location,
406 2
        ])->setFilePath($filePath);
407
408 2
        $file->setOffset($file->merge($files));
409
410
        // Verify checksum.
411 2
        $checksum = $this->getServerChecksum($filePath);
412
413 2
        if ($checksum !== $this->getClientChecksum()) {
414 1
            return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
415
        }
416
417 1
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => self::UPLOAD_TYPE_FINAL]);
418
419
        // Cleanup.
420 1
        if ($file->delete($filePaths, true)) {
421 1
            $this->cache->deleteAll($partials);
422
        }
423
424 1
        return $this->response->send(
425 1
            ['data' => ['checksum' => $checksum]],
426 1
            HttpResponse::HTTP_CREATED,
427
            [
428 1
                'Location' => $location,
429
            ]
430
        );
431
    }
432
433
    /**
434
     * Handle PATCH request.
435
     *
436
     * @return HttpResponse
437
     */
438 7
    protected function handlePatch() : HttpResponse
439
    {
440 7
        $uploadKey = $this->request->key();
441
442 7
        if ( ! $meta = $this->cache->get($uploadKey)) {
443 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
444
        }
445
446 6
        if (self::UPLOAD_TYPE_FINAL === $meta['upload_type']) {
447 1
            return $this->response->send(null, HttpResponse::HTTP_FORBIDDEN);
448
        }
449
450 5
        $file     = $this->buildFile($meta);
451 5
        $checksum = $meta['checksum'];
452
453
        try {
454 5
            $fileSize = $file->getFileSize();
455 5
            $offset   = $file->setKey($uploadKey)->setChecksum($checksum)->upload($fileSize);
456
457
            // If upload is done, verify checksum.
458 2
            if ($offset === $fileSize && ! $this->verifyChecksum($checksum, $meta['file_path'])) {
459 2
                return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
460
            }
461 3
        } catch (FileException $e) {
462 1
            return $this->response->send($e->getMessage(), HttpResponse::HTTP_UNPROCESSABLE_ENTITY);
463 2
        } catch (OutOfRangeException $e) {
464 1
            return $this->response->send(null, HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
465 1
        } catch (ConnectionException $e) {
466 1
            return $this->response->send(null, HttpResponse::HTTP_CONTINUE);
467
        }
468
469 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
470 1
            'Content-Type' => 'application/offset+octet-stream',
471 1
            'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
472 1
            'Upload-Offset' => $offset,
473
        ]);
474
    }
475
476
    /**
477
     * Handle GET request.
478
     *
479
     * @return BinaryFileResponse|HttpResponse
480
     */
481 4
    protected function handleGet()
482
    {
483 4
        $key = $this->request->key();
484
485 4
        if (empty($key)) {
486 1
            return $this->response->send('400 bad request.', HttpResponse::HTTP_BAD_REQUEST);
487
        }
488
489 3
        if ( ! $fileMeta = $this->cache->get($key)) {
490 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
491
        }
492
493 2
        $resource = $fileMeta['file_path'] ?? null;
494 2
        $fileName = $fileMeta['name'] ?? null;
495
496 2
        if ( ! $resource || ! file_exists($resource)) {
497 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
498
        }
499
500 1
        return $this->response->download($resource, $fileName);
501
    }
502
503
    /**
504
     * Handle DELETE request.
505
     *
506
     * @return HttpResponse
507
     */
508 3
    protected function handleDelete() : HttpResponse
509
    {
510 3
        $key      = $this->request->key();
511 3
        $fileMeta = $this->cache->get($key);
512 3
        $resource = $fileMeta['file_path'] ?? null;
513
514 3
        if ( ! $resource) {
515 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
516
        }
517
518 2
        $isDeleted = $this->cache->delete($key);
519
520 2
        if ( ! $isDeleted || ! file_exists($resource)) {
521 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
522
        }
523
524 1
        unlink($resource);
525
526 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
527 1
            'Tus-Extension' => self::TUS_EXTENSION_TERMINATION,
528
        ]);
529
    }
530
531
    /**
532
     * Get required headers for head request.
533
     *
534
     * @param array $fileMeta
535
     *
536
     * @return array
537
     */
538 4
    protected function getHeadersForHeadRequest(array $fileMeta) : array
539
    {
540
        $headers = [
541 4
            'Upload-Length' => (int) $fileMeta['size'],
542 4
            'Upload-Offset' => (int) $fileMeta['offset'],
543 4
            'Cache-Control' => 'no-store',
544
        ];
545
546 4
        if (self::UPLOAD_TYPE_FINAL === $fileMeta['upload_type'] && $fileMeta['size'] !== $fileMeta['offset']) {
547 2
            unset($headers['Upload-Offset']);
548
        }
549
550 4
        if (self::UPLOAD_TYPE_NORMAL !== $fileMeta['upload_type']) {
551 3
            $headers += ['Upload-Concat' => $fileMeta['upload_type']];
552
        }
553
554 4
        return $headers;
555
    }
556
557
    /**
558
     * Build file object.
559
     *
560
     * @param array $meta
561
     *
562
     * @return File
563
     */
564 1
    protected function buildFile(array $meta) : File
565
    {
566 1
        $file = new File($meta['name'], $this->cache);
567
568 1
        if (array_key_exists('offset', $meta)) {
569 1
            $file->setMeta($meta['offset'], $meta['size'], $meta['file_path'], $meta['location']);
570
        }
571
572 1
        return $file;
573
    }
574
575
    /**
576
     * Get list of supported hash algorithms.
577
     *
578
     * @return string
579
     */
580 1
    protected function getSupportedHashAlgorithms() : string
581
    {
582 1
        $supportedAlgorithms = hash_algos();
583
584 1
        $algorithms = [];
585 1
        foreach ($supportedAlgorithms as $hashAlgo) {
586 1
            if (false !== strpos($hashAlgo, ',')) {
587 1
                $algorithms[] = "'{$hashAlgo}'";
588
            } else {
589 1
                $algorithms[] = $hashAlgo;
590
            }
591
        }
592
593 1
        return implode(',', $algorithms);
594
    }
595
596
    /**
597
     * Verify and get upload checksum from header.
598
     *
599
     * @return string|HttpResponse
600
     */
601 4
    protected function getClientChecksum()
602
    {
603 4
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
604
605 4
        if (empty($checksumHeader)) {
606 1
            return '';
607
        }
608
609 3
        list($checksumAlgorithm, $checksum) = explode(' ', $checksumHeader);
610
611 3
        $checksum = base64_decode($checksum);
612
613 3
        if ( ! in_array($checksumAlgorithm, hash_algos()) || false === $checksum) {
614 2
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
615
        }
616
617 1
        return $checksum;
618
    }
619
620
    /**
621
     * Get expired but incomplete uploads.
622
     *
623
     * @param array|null $contents
624
     *
625
     * @return bool
626
     */
627 3
    protected function isExpired($contents) : bool
628
    {
629 3
        $isExpired = empty($contents['expires_at']) || Carbon::parse($contents['expires_at'])->lt(Carbon::now());
630
631 3
        if ($isExpired && $contents['offset'] !== $contents['size']) {
632 3
            return true;
633
        }
634
635 2
        return false;
636
    }
637
638
    /**
639
     * Get path for partial upload.
640
     *
641
     * @param string $key
642
     *
643
     * @return string
644
     */
645 1
    protected function getPathForPartialUpload(string $key) : string
646
    {
647 1
        list($actualKey) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $key);
648
649 1
        $path = $this->uploadDir . DIRECTORY_SEPARATOR . $actualKey . DIRECTORY_SEPARATOR;
650
651 1
        if ( ! file_exists($path)) {
652 1
            mkdir($path);
653
        }
654
655 1
        return $path;
656
    }
657
658
    /**
659
     * Get metadata of partials.
660
     *
661
     * @param array $partials
662
     *
663
     * @return array
664
     */
665 3
    protected function getPartialsMeta(array $partials) : array
666
    {
667 3
        $files = [];
668
669 3
        foreach ($partials as $partial) {
670 3
            $fileMeta = $this->getCache()->get($partial);
671
672 3
            $files[] = $fileMeta;
673
        }
674
675 3
        return $files;
676
    }
677
678
    /**
679
     * Delete expired resources.
680
     *
681
     * @return array
682
     */
683 2
    public function handleExpiration() : array
684
    {
685 2
        $deleted   = [];
686 2
        $cacheKeys = $this->cache->keys();
687
688 2
        foreach ($cacheKeys as $key) {
689 2
            $fileMeta = $this->cache->get($key, true);
690
691 2
            if ( ! $this->isExpired($fileMeta)) {
692 1
                continue;
693
            }
694
695 2
            if ( ! $this->cache->delete($key)) {
696 1
                continue;
697
            }
698
699 1
            if (is_writable($fileMeta['file_path'])) {
700 1
                unlink($fileMeta['file_path']);
701
            }
702
703 1
            $deleted[] = $fileMeta;
704
        }
705
706 2
        return $deleted;
707
    }
708
709
    /**
710
     * Verify max upload size.
711
     *
712
     * @return bool
713
     */
714 1
    protected function verifyUploadSize() : bool
715
    {
716 1
        $maxUploadSize = $this->getMaxUploadSize();
717
718 1
        if ($maxUploadSize > 0 && $this->getRequest()->header('Upload-Length') > $maxUploadSize) {
719 1
            return false;
720
        }
721
722 1
        return true;
723
    }
724
725
    /**
726
     * Verify checksum if available.
727
     *
728
     * @param string $checksum
729
     * @param string $filePath
730
     *
731
     * @return bool
732
     */
733 1
    protected function verifyChecksum(string $checksum, string $filePath) : bool
734
    {
735
        // Skip if checksum is empty
736 1
        if (empty($checksum)) {
737 1
            return true;
738
        }
739
740 1
        return $checksum === $this->getServerChecksum($filePath);
741
    }
742
743
    /**
744
     * No other methods are allowed.
745
     *
746
     * @param string $method
747
     * @param array  $params
748
     *
749
     * @return HttpResponse|BinaryFileResponse
750
     */
751 1
    public function __call(string $method, array $params)
752
    {
753 1
        return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
754
    }
755
}
756