-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathexecute.php
192 lines (168 loc) · 6.7 KB
/
execute.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php
declare(strict_types=1);
namespace Psl\Shell;
use Psl\DateTime\Duration;
use Psl\Dict;
use Psl\Env;
use Psl\Filesystem;
use Psl\IO;
use Psl\OS;
use Psl\Regex;
use Psl\SecureRandom;
use Psl\Str;
use Psl\Vec;
use function is_resource;
use function pack;
use function proc_close;
use function proc_open;
use function strpbrk;
/**
* Execute an external program.
*
* @param non-empty-string $command The command to execute.
* @param list<string> $arguments The command arguments listed as separate entries.
* @param null|non-empty-string $working_directory The initial working directory for the command.
* This must be an absolute directory path, or null if you want to
* use the default value ( the current directory )
* @param array<string, string> $environment A dict with the environment variables for the command that
* will be run.
*
* @psalm-taint-sink shell $command
*
* @throws Exception\FailedExecutionException In case the command resulted in an exit code other than 0.
* @throws Exception\PossibleAttackException In case the command being run is suspicious ( e.g: contains NULL byte ).
* @throws Exception\RuntimeException In case $working_directory doesn't exist, or unable to create a new process.
* @throws Exception\TimeoutException If $timeout is reached before being able to read the process stream.
*
* @mago-expect best-practices/no-boolean-literal-comparison
* @mago-expect best-practices/no-else-clause
*/
function execute(
string $command,
array $arguments = [],
null|string $working_directory = null,
array $environment = [],
ErrorOutputBehavior $error_output_behavior = ErrorOutputBehavior::Discard,
null|Duration $timeout = null,
): string {
$arguments = Vec\map($arguments, Internal\escape_argument(...));
$commandline = Str\join([$command, ...$arguments], ' ');
/** @psalm-suppress MissingThrowsDocblock - safe ( $offset is within-of-bounds ) */
if (Str\contains($commandline, "\0")) {
throw new Exception\PossibleAttackException('NULL byte detected.');
}
$environment = Dict\merge(Env\get_vars(), $environment);
$working_directory ??= Env\current_dir();
if (!Filesystem\is_directory($working_directory)) {
throw new Exception\RuntimeException('$working_directory does not exist.');
}
$options = [];
// @codeCoverageIgnoreStart
if (OS\is_windows()) {
$variable_cache = [];
$variable_count = 0;
/** @psalm-suppress MissingThrowsDocblock */
$identifier = 'PHP_STANDARD_LIBRARY_TMP_ENV_' . SecureRandom\string(6);
/** @psalm-suppress MissingThrowsDocblock */
$commandline = Regex\replace_with(
$commandline,
'/"(?:([^"%!^]*+(?:(?:!LF!|"(?:\^[%!^])?+")[^"%!^]*+)++)|[^"]*+ )"/x',
/**
* @param array<array-key, string> $m
*
* @return string
*/
static function (array $m) use (&$environment, &$variable_cache, &$variable_count, $identifier): string {
if (!isset($m[1])) {
return $m[0];
}
if (isset($variable_cache[$m[0]])) {
/** @var string */
return $variable_cache[$m[0]];
}
$value = $m[1];
if (Str\Byte\contains($value, "\0")) {
$value = Str\Byte\replace($value, "\0", '?');
}
if (false === strpbrk($value, "\"%!\n")) {
return '"' . $value . '"';
}
$var = $identifier . ((string) ++$variable_count);
$environment[$var] =
'"' .
Regex\replace(
Str\Byte\replace_every($value, [
'!LF!' => "\n",
'"^!"' => '!',
'"^%"' => '%',
'"^^"' => '^',
'""' => '"',
]),
'/(\\\\*)"/',
'$1$1\\"',
) .
'"';
/** @var string */
return $variable_cache[$m[0]] = '!' . $var . '!';
},
);
$commandline = 'cmd /V:ON /E:ON /D /C (' . Str\Byte\replace($commandline, "\n", ' ') . ')';
$options = [
'bypass_shell' => true,
'blocking_pipes' => false,
];
} else {
$commandline = Str\format('exec %s', $commandline);
}
// @codeCoverageIgnoreEnd
$descriptor = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($commandline, $descriptor, $pipes, $working_directory, $environment, $options);
// @codeCoverageIgnoreStart
// not sure how to replicate this, but it can happen \_o.o_/
if (!is_resource($process)) {
throw new Exception\RuntimeException('Failed to open a new process.');
}
// @codeCoverageIgnoreEnd
$stdout = new IO\CloseReadStreamHandle($pipes[1]);
$stderr = new IO\CloseReadStreamHandle($pipes[2]);
try {
$result = '';
/** @psalm-suppress MissingThrowsDocblock */
foreach (IO\streaming([1 => $stdout, 2 => $stderr], $timeout) as $type => $chunk) {
if ($chunk) {
$result .= pack('C1N1', $type, Str\Byte\length($chunk)) . $chunk;
}
}
} catch (IO\Exception\TimeoutException $previous) {
throw new Exception\TimeoutException(
'reached timeout while the process output is still not readable.',
0,
$previous,
);
} finally {
/** @psalm-suppress MissingThrowsDocblock */
$stdout->close();
/** @psalm-suppress MissingThrowsDocblock */
$stderr->close();
$code = proc_close($process);
}
if ($code !== 0) {
/** @psalm-suppress MissingThrowsDocblock */
[$stdout_content, $stderr_content] = namespace\unpack($result);
throw new Exception\FailedExecutionException($commandline, $stdout_content, $stderr_content, $code);
}
if (ErrorOutputBehavior::Packed === $error_output_behavior) {
return $result;
}
/** @psalm-suppress MissingThrowsDocblock */
[$stdout_content, $stderr_content] = namespace\unpack($result);
return match ($error_output_behavior) {
ErrorOutputBehavior::Prepend => $stderr_content . $stdout_content,
ErrorOutputBehavior::Append => $stdout_content . $stderr_content,
ErrorOutputBehavior::Replace => $stderr_content,
ErrorOutputBehavior::Discard => $stdout_content,
};
}