FileCorruptionAnalyzer::isCorrupted()   C
last analyzed

Complexity

Conditions 15
Paths 156

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 15
eloc 32
c 2
b 0
f 0
nc 156
nop 1
dl 0
loc 53
rs 5.4499

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @copyright Copyright (c) 2017 Matthias Held <[email protected]>
5
 * @author Matthias Held <[email protected]>
6
 * @license GNU AGPL version 3 or any later version
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License as
10
 * published by the Free Software Foundation, either version 3 of the
11
 * License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License
19
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
namespace OCA\RansomwareDetection\Analyzer;
23
24
use OCA\RansomwareDetection\AppInfo\Application;
25
use OCA\RansomwareDetection\FileSignatures;
26
use OCP\Files\IRootFolder;
0 ignored issues
show
Bug introduced by
The type OCP\Files\IRootFolder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use OCP\Files\NotFoundException;
0 ignored issues
show
Bug introduced by
The type OCP\Files\NotFoundException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
use OCP\Files\File;
0 ignored issues
show
Bug introduced by
The type OCP\Files\File was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
use OCP\ILogger;
0 ignored issues
show
Bug introduced by
The type OCP\ILogger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
31
class FileCorruptionAnalyzer
32
{
33
    /** @var ILogger */
34
    private $logger;
35
36
    /** @var IRootFolder */
37
    private $rootFolder;
38
39
    /** @var string */
40
    private $userId;
41
42
    /**
43
     * @param ILogger     $logger
44
     * @param IRootFolder $rootFolder
45
     * @param string      $userId
46
     */
47
    public function __construct(
48
        ILogger $logger,
49
        IRootFolder $rootFolder,
50
        $userId
51
    ) {
52
        $this->logger = $logger;
53
        $this->rootFolder = $rootFolder;
54
        $this->userId = $userId;
55
    }
56
57
    /**
58
     * Analysis a file if it's corrupted or not.
59
     *
60
     * @param  File $node
61
     * @return FileCorruptionResult
62
     */
63
    public function analyze($node)
64
    {
65
        return $this->isCorrupted($node);
66
    }
67
68
    /**
69
     * Checks the file for existing file header informations and compares them,
70
     * if found, to the file extension.
71
     *
72
     * @param  File    $node
73
     * @return FileCorruptionResult
74
     */
75
    protected function isCorrupted(File $node)
76
    {
77
        $signatures = FileSignatures::getSignatures();
78
79
        try {
80
            // get the first 1024 bytes
81
            $handle = $node->fopen('r');
82
            $data = fread($handle, 1024);
83
            fclose($handle);
84
85
            $pathInfo = pathinfo($node->getPath());
86
            foreach ($signatures as $signature) {
87
                $isFileCorrupted = true;
88
                if (isset($pathInfo['extension']) && in_array(strtolower($pathInfo['extension']), $signature['extensions'])) {
89
                    // txt file extension has no signature, but is not corrupted
90
                    if (array_key_exists('exists', $signature['signature'])) {
91
                        if ($signature['signature']['exists'] === false) {
92
                            return new FileCorruptionResult(false);
93
                        }
94
                    }
95
                    // starting byte sequence
96
                    if (array_key_exists('starting', $signature['signature'])) {
97
						foreach ($signature['signature']['starting']['bytes'] as $bytes) {
98
							if (preg_match($bytes, strtolower(bin2hex(substr($data, $signature['signature']['starting']['offset'], strlen($bytes) / 2))))) {
99
									$isFileCorrupted = false;
100
							}
101
						}
102
                    }
103
                    // trailing byte sequence
104
                    if (array_key_exists('trailing', $signature['signature'])) {
105
                        $trailingIsNotMatching = true;
106
						foreach ($signature['signature']['trailing']['bytes'] as $bytes) {
107
							$trailingOffset = strlen($data) - $signature['signature']['trailing']['offset'] - strlen($bytes) / 2;
108
							if (preg_match($bytes, strtolower(bin2hex(substr($data, $trailingOffset, strlen($bytes) / 2))))) {
109
									$trailingIsNotMatching = false;
110
							}
111
						}
112
						$isFileCorrupted = $isFileCorrupted || $trailingIsNotMatching;
113
                        return new FileCorruptionResult($isFileCorrupted);
114
                    }
115
                    return new FileCorruptionResult($isFileCorrupted);
116
                }
117
            }
118
119
            return new FileCorruptionResult(false);
120
        } catch (\OCP\Files\NotPermittedException $exception) {
0 ignored issues
show
Bug introduced by
The type OCP\Files\NotPermittedException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
121
            $this->logger->debug('isCorrupted: Not permitted.', array('app' => Application::APP_ID));
122
123
            return new FileCorruptionResult(false);
124
        } catch (\OCP\Lock\LockedException $exception) {
0 ignored issues
show
Bug introduced by
The type OCP\Lock\LockedException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
125
            $this->logger->debug('isCorrupted: File is locked.', array('app' => Application::APP_ID));
126
127
            return new FileCorruptionResult(false);
128
        }
129
    }
130
}
131