-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClamAvAdapter.php
105 lines (90 loc) · 2.73 KB
/
ClamAvAdapter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace CL\Tissue\Adapter\ClamAv;
use CL\Tissue\Adapter\AbstractAdapter;
use CL\Tissue\Exception\AdapterException;
use CL\Tissue\Model\Detection;
use Symfony\Component\Process\Process;
class ClamAvAdapter extends AbstractAdapter
{
/**
* @var string
*/
protected $clamScanPath;
/**
* @var string
*/
protected $databasePath;
/**
* @param string $clamScanPath
* @param string|null $databasePath
*
* @throws AdapterException If the given path to clamscan (or clamdscan) is not executable
*/
public function __construct(string $clamScanPath, string $databasePath = null)
{
if (!is_executable($clamScanPath)) {
throw new AdapterException(sprintf(
'The path to `clamscan` or `clamdscan` could not be found or is not executable (path: %s)',
$clamScanPath
));
}
$this->clamScanPath = $clamScanPath;
$this->databasePath = $databasePath;
}
/**
* {@inheritdoc}
*
* @throws \CL\Tissue\Exception\AdapterException
*/
protected function detect(string $path): ?Detection
{
$process = $this->createProcess(
$this->prepareCommand($path)
);
$returnCode = $process->run();
$output = trim($process->getOutput());
if (0 !== $returnCode && false === strpos($output, ' FOUND')) {
throw AdapterException::fromProcess($process);
}
foreach (explode("\n", $output) as $line) {
if (' FOUND' === substr($line, -6)) {
$file = substr($line, 0, strrpos($line, ':'));
$description = substr(substr($line, strrpos($line, ':') + 2), 0, -6);
return $this->createDetection($file, Detection::TYPE_VIRUS, $description);
}
}
return null;
}
/**
* Prepare the process command.
*
* @param string $path
*
* @return array
*/
private function prepareCommand(string $path): array
{
$cmd = [
$this->clamScanPath,
'--no-summary',
];
if ($this->usesDaemon($this->clamScanPath)) {
// Pass filedescriptor to clamd (useful if clamd is running as a different user)
$cmd[] = '--fdpass';
} elseif (null !== $this->databasePath) {
// Only the (isolated) binary version can change the signature-database used
$cmd[] = sprintf('--database=%s', $this->databasePath);
}
$cmd[] = $path;
return $cmd;
}
/**
* @param string $path
*
* @return bool
*/
private function usesDaemon(string $path): bool
{
return 'clamdscan' === substr($path, -9);
}
}