Connection::read()   B
last analyzed

Complexity

Conditions 9
Paths 33

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 12.6885

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 9
cts 14
cp 0.6429
rs 8.0555
c 0
b 0
f 0
cc 9
nc 33
nop 1
crap 12.6885
1
<?php
2
/**
3
 * Copyright (c) 2014 Robin Appelman <[email protected]>
4
 * This file is licensed under the Licensed under the MIT license:
5
 * http://opensource.org/licenses/MIT
6
 */
7
8
namespace Icewind\SMB\Wrapped;
9
10
use Icewind\SMB\Exception\AccessDeniedException;
11
use Icewind\SMB\Exception\AuthenticationException;
12
use Icewind\SMB\Exception\ConnectException;
13
use Icewind\SMB\Exception\ConnectionException;
14
use Icewind\SMB\Exception\ConnectionRefusedException;
15
use Icewind\SMB\Exception\InvalidHostException;
16
use Icewind\SMB\Exception\NoLoginServerException;
17
18
class Connection extends RawConnection {
19
	const DELIMITER = 'smb:';
20
	const DELIMITER_LENGTH = 4;
21
22
	/** @var Parser */
23
	private $parser;
24 486
25 486
	/**
26 486
	 * @param string $command
27 486
	 * @param Parser $parser
28
	 * @param array<string, string> $env
29
	 */
30
	public function __construct(string $command, Parser $parser, array $env = []) {
31
		parent::__construct($command, $env);
32
		$this->parser = $parser;
33
	}
34 486
35 486
	/**
36
	 * send input to smbclient
37
	 *
38
	 * @param string $input
39
	 */
40
	public function write(string $input) {
41 486
		return parent::write($input . PHP_EOL);
42 486
	}
43
44 486
	/**
45 486
	 * @throws ConnectException
46 486
	 */
47 486
	public function clearTillPrompt(): void {
48
		$this->write('');
49
		do {
50 486
			$promptLine = $this->readLine();
51 486
			if ($promptLine === false) {
52
				break;
53
			}
54
			$this->parser->checkConnectionError($promptLine);
55
		} while (!$this->isPrompt($promptLine));
56
		if ($this->write('') === false) {
57
			throw new ConnectionRefusedException();
58
		}
59
		$this->readLine();
60
	}
61
62
	/**
63
	 * get all unprocessed output from smbclient until the next prompt
64 484
	 *
65 484
	 * @param (callable(string):bool)|null $callback (optional) callback to call for every line read
0 ignored issues
show
Documentation introduced by
The doc-type (callable(string):bool)|null could not be parsed: Expected ")" at position 2, but found "(". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
66
	 * @return string[]
67
	 * @throws AuthenticationException
68 484
	 * @throws ConnectException
69 484
	 * @throws ConnectionException
70
	 * @throws InvalidHostException
71 484
	 * @throws NoLoginServerException
72 484
	 * @throws AccessDeniedException
73 2
	 */
74
	public function read(callable $callback = null): array {
75 484
		if (!$this->isValid()) {
76
			throw new ConnectionException('Connection not valid');
77 484
		}
78
		$promptLine = $this->readLine(); //first line is prompt
79
		if ($promptLine === false) {
80 484
			$this->unknownError($promptLine);
81 484
		}
82
		$this->parser->checkConnectionError($promptLine);
0 ignored issues
show
Security Bug introduced by
It seems like $promptLine defined by $this->readLine() on line 78 can also be of type false; however, Icewind\SMB\Wrapped\Parser::checkConnectionError() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
83
84
		$output = [];
85
		if (!$this->isPrompt($promptLine)) {
0 ignored issues
show
Security Bug introduced by
It seems like $promptLine defined by $this->readLine() on line 78 can also be of type false; however, Icewind\SMB\Wrapped\Connection::isPrompt() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
86
			$line = $promptLine;
87
		} else {
88 484
			$line = $this->readLine();
89
		}
90 484
		if ($line === false) {
91
			$this->unknownError($promptLine);
92 484
		}
93
		while ($line !== false && !$this->isPrompt($line)) { //next prompt functions as delimiter
94
			if (is_callable($callback)) {
95
				$result = $callback($line);
96
				if ($result === false) { // allow the callback to close the connection for infinite running commands
97
					$this->close(true);
98
					break;
99
				}
100
			} else {
101 486
				$output[] = $line;
102 486
			}
103
			$line = $this->readLine();
104
		}
105
		return $output;
106
	}
107
108
	private function isPrompt(string $line): bool {
109
		return mb_substr($line, 0, self::DELIMITER_LENGTH) === self::DELIMITER;
110
	}
111
112
	/**
113
	 * @param string|bool $promptLine (optional) prompt line that might contain some info about the error
114
	 * @throws ConnectException
115
	 * @return no-return
0 ignored issues
show
Documentation introduced by
The doc-type no-return could not be parsed: Unknown type name "no-return" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
116
	 */
117
	private function unknownError($promptLine = '') {
118
		if ($promptLine) { //maybe we have some error we missed on the previous line
119
			throw new ConnectException('Unknown error (' . $promptLine . ')');
120
		} else {
121
			$error = $this->readError(); // maybe something on stderr
122 486
			if ($error) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
123 486
				throw new ConnectException('Unknown error (' . $error . ')');
124
			} else {
125 486
				throw new ConnectException('Unknown error');
126
			}
127 486
		}
128 486
	}
129
130
	public function close(bool $terminate = true): void {
131
		if (get_resource_type($this->getInputStream()) === 'stream') {
132
			// ignore any errors while trying to send the close command, the process might already be dead
133
			@$this->write('close' . PHP_EOL);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
134
		}
135
		parent::close($terminate);
136
	}
137
}
138