Debian Codegraph @

vendor/wikimedia/shellbox/src/Command/UnboxedExecutor.php

raw
1 <?php
2
3 namespace Shellbox\Command;
4
5 use Psr\Log\LoggerInterface;
6 use Psr\Log\NullLogger;
7 use Shellbox\FileUtils;
8 use Shellbox\Shellbox;
9 use Shellbox\ShellboxError;
10 use Shellbox\TempDirManager;
11
12 /**
13 * A concrete class for executing UnboxedCommand objects
14 */
15 class UnboxedExecutor {
16 /** @var LoggerInterface */
17 protected $logger;
18 /** @var Wrapper[] */
19 private $wrappers = [];
20
21 /** @var string|null */
22 private $stdoutPath;
23
24 /** @var string|null */
25 private $stderrPath;
26
27 /** @var string|null */
28 private $tempDirBase;
29
30 /** @var TempDirManager|null */
31 private $tempDirManager;
32
33 /**
34 * @param string|null $tempDirBase The parent directory of the temporary
35 * directory to use if the command is run on Windows. For example /tmp.
36 * If this is null, sys_get_temp_dir() will be used. The temporary
37 * directory may also be overridden later using setTempDirManager().
38 */
39 public function __construct( $tempDirBase = null ) {
40 $this->logger = new NullLogger;
41 $this->tempDirBase = $tempDirBase;
42 }
43
44 /**
45 * Create a Command linked to this executor.
46 *
47 * @return UnboxedCommand
48 */
49 public function createCommand() {
50 return new UnboxedCommand( $this );
51 }
52
53 /**
54 * Get a TempDirManager with optional lazy initialisation
55 *
56 * @return TempDirManager
57 */
58 protected function getTempDirManager() {
59 if ( !$this->tempDirManager ) {
60 $tempDirBase = $this->tempDirBase;
61 if ( $tempDirBase === null ) {
62 $tempDirBase = sys_get_temp_dir();
63 }
64
65 $this->tempDirManager = new TempDirManager(
66 $tempDirBase . '/shellbox-' . Shellbox::getUniqueString()
67 );
68 }
69 return $this->tempDirManager;
70 }
71
72 /**
73 * Explicitly set a TempDirManager, overriding lazy initialisation config
74 *
75 * @param TempDirManager $manager
76 */
77 public function setTempDirManager( TempDirManager $manager ) {
78 $this->tempDirManager = $manager;
79 }
80
81 /**
82 * Set the logger.
83 *
84 * @param LoggerInterface $logger
85 */
86 public function setLogger( LoggerInterface $logger ) {
87 $this->logger = $logger;
88 foreach ( $this->wrappers as $wrapper ) {
89 $wrapper->setLogger( $logger );
90 }
91 }
92
93 /**
94 * Add a Wrapper, which modifies the Command, typically providing more
95 * security.
96 *
97 * @param Wrapper $wrapper
98 */
99 public function addWrapper( Wrapper $wrapper ) {
100 $wrapper->setLogger( $this->logger );
101 $this->wrappers[] = $wrapper;
102 }
103
104 /**
105 * Add wrappers based on a configuration array
106 *
107 * @param array $config Associative array of configuration parameters:
108 * - useSystemd: If true, systemd-run will be used
109 * - useBashWrapper: If true, limit.sh will be used
110 * - useFirejail: If true, firejail will be used
111 * - firejailPath: The path to the firejail binary
112 * - firejailProfile: The path to the firejail profile
113 * - cgroup: A writable cgroup path which can be used for manual memory
114 * limiting
115 */
116 public function addWrappersFromConfiguration( $config ) {
117 $isWindows = PHP_OS_FAMILY === 'Windows';
118 $useSystemd = !empty( $config['useSystemd'] );
119 if ( isset( $config['useBashWrapper'] ) ) {
120 $useBashWrapper = $config['useBashWrapper'];
121 } elseif ( $isWindows || $useSystemd ) {
122 $useBashWrapper = false;
123 } else {
124 $useBashWrapper = is_executable( '/bin/bash' );
125 }
126
127 if ( $useBashWrapper ) {
128 $this->addWrapper( new BashWrapper( $config['cgroup'] ?? '' ) );
129 }
130 if ( !empty( $config['useFirejail'] ) ) {
131 $this->addWrapper( new FirejailWrapper(
132 $config['firejailPath'] ?? '/usr/bin/firejail',
133 $config['firejailProfile'] ?? __DIR__ . '/firejail.profile'
134 ) );
135 }
136 if ( $useSystemd ) {
137 $this->addWrapper( new SystemdWrapper );
138 }
139 if ( $isWindows ) {
140 $this->addWrapper( new WindowsWrapper );
141 }
142 }
143
144 /**
145 * Get pipe descriptors for proc_open()
146 *
147 * @param Command $command
148 * @return array
149 */
150 private function getPipeDescriptors( Command $command ) {
151 $desc = [
152 0 => $command->getPassStdin() ? [ 'file', 'php://stdin', 'r' ] : [ 'pipe', 'r' ]
153 ];
154 if ( PHP_OS_FAMILY === 'Windows' ) {
155 // PHP's view of Windows anonymous pipes is too broken to be usable
156 $this->stdoutPath = $this->getTempDirManager()->preparePath( 'sb-stdout' );
157 $this->stderrPath = $this->getTempDirManager()->preparePath( 'sb-stderr' );
158 $desc[1] = [ 'file', $this->stdoutPath, 'wb' ];
159 $desc[2] = [ 'file', $this->stderrPath, 'wb' ];
160 } else {
161 $desc[1] = $desc[2] = [ 'pipe', 'w' ];
162 }
163 if ( $command->getUseLogPipe() ) {
164 $desc[3] = [ 'pipe', 'w' ];
165 }
166 return $desc;
167 }
168
169 /**
170 * Get the environment to be passed through to the subprocess. In CLI mode
171 * this uses getenv() because that is backwards compatible and relatively
172 * sensible. In the other SAPIs, there's no way to get the real environment
173 * short of shell_exec('env'), but it's usually near-empty anyway. We add
174 * PATH for convenience.
175 *
176 * In the FastCGI SAPI, $_ENV and getenv() return CGI-like variables sent
177 * from the web server. So the PATH here is typically inherited from Apache
178 * not PHP-FPM.
179 *
180 * @return array
181 */
182 private function getParentEnvironment() {
183 if ( PHP_SAPI === 'cli' ) {
184 return getenv();
185 } elseif ( isset( $_ENV['PATH'] ) ) {
186 return [ 'PATH' => $_ENV['PATH'] ];
187 } else {
188 return [];
189 }
190 }
191
192 /**
193 * If the environment contains an unsafe character set, filter out the
194 * variable.
195 *
196 * @param array &$env
197 */
198 private function fixLocaleEnvironment( array &$env ) {
199 if ( PHP_OS_FAMILY === 'Windows' ) {
200 // Probably OK?
201 return;
202 }
203 foreach ( [ 'LC_CTYPE', 'LC_ALL', 'LANG' ] as $name ) {
204 if ( isset( $env[$name] )
205 && preg_match( '/\.(gb\w*)/i', $env[$name] )
206 ) {
207 $this->logger->warning( "Filtering out unsafe environment variable " .
208 "$name={$env[$name]}" );
209 unset( $env[$name] );
210 }
211 }
212 }
213
214 /**
215 * @param Command $command
216 * @return UnboxedResult
217 * @throws ShellboxError
218 */
219 public function execute( Command $command ) {
220 $command = clone $command;
221 $this->buildFinalCommand( $command );
222 $cmd = $command->getCommandString();
223
224 $this->logger->info( "Executing: $cmd" );
225
226 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
227 // Other platforms may be more accomodating, but we don't want to be
228 // accomodating, because very long commands probably include user
229 // input. See T129506.
230 if ( strlen( $cmd ) > Shellbox::getMaxCmdLength() ) {
231 throw new ShellboxError( 'Total length of $cmd must not exceed MAX_ARG_STRLEN' );
232 }
233
234 $desc = $this->getPipeDescriptors( $command );
235
236 $cmd = $command->getCommandString();
237 $options = $command->getProcOpenOptions();
238
239 $combinedEnvironment = $command->getEnvironment() + $this->getParentEnvironment();
240 $this->fixLocaleEnvironment( $combinedEnvironment );
241 $env = [];
242 foreach ( $combinedEnvironment as $name => $value ) {
243 $env[] = "$name=$value";
244 }
245 $pipes = null;
246 $proc = proc_open( $cmd, $desc, $pipes,
247 $command->getWorkingDirectory(), $env, $options );
248
249 if ( !$proc ) {
250 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
251 throw new ShellboxError( 'proc_open() failed' );
252 }
253
254 $buffers = [
255 0 => $command->getStdin(), // input
256 1 => '', // stdout
257 2 => '', // stderr
258 3 => '', // log
259 ];
260 $emptyArray = [];
261 $status = false;
262 $logMsg = false;
263
264 /* According to the documentation, it is possible for stream_select()
265 * to fail due to EINTR. I haven't managed to induce this in testing
266 * despite sending various signals. If it did happen, the error
267 * message would take the form:
268 *
269 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
270 *
271 * where [4] is the value of the macro EINTR and "Interrupted system
272 * call" is string which according to the Linux manual is "possibly"
273 * localised according to LC_MESSAGES.
274 */
275 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
276 $eintrMessage = "stream_select(): unable to select [$eintr]";
277
278 /* The select(2) system call only guarantees a "sufficiently small write"
279 * can be made without blocking. And on Linux the read might block too
280 * in certain cases, although I don't know if any of them can occur here.
281 * Regardless, set all the pipes to non-blocking to avoid T184171.
282 */
283 foreach ( $pipes as $pipe ) {
284 stream_set_blocking( $pipe, false );
285 }
286
287 $running = true;
288 $timeout = null;
289 $numReadyPipes = 0;
290
291 while ( $pipes && ( $running === true || $numReadyPipes !== 0 ) ) {
292 if ( $running ) {
293 $status = proc_get_status( $proc );
294 // If the process has terminated, switch to nonblocking selects
295 // for getting any data still waiting to be read.
296 if ( !$status['running'] ) {
297 $running = false;
298 $timeout = 0;
299 }
300 }
301
302 error_clear_last();
303
304 $readPipes = array_filter( $pipes, static function ( $fd ) use ( $desc ) {
305 return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'r';
306 }, ARRAY_FILTER_USE_KEY );
307 $writePipes = array_filter( $pipes, static function ( $fd ) use ( $desc ) {
308 return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'w';
309 }, ARRAY_FILTER_USE_KEY );
310 // stream_select parameter names are from the POV of us being able to do the operation;
311 // proc_open descriptor types are from the POV of the process doing it.
312 // So $writePipes is passed as the $read parameter and $readPipes as $write.
313 // phpcs:ignore Generic.PHP.NoSilencedErrors
314 $numReadyPipes = @stream_select( $writePipes, $readPipes, $emptyArray, $timeout );
315 if ( $numReadyPipes === false ) {
316 $error = error_get_last();
317 if ( !$error ) {
318 $logMsg = 'unknown error';
319 break;
320 } elseif ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
321 continue;
322 } else {
323 $logMsg = $error['message'];
324 break;
325 }
326 }
327 foreach ( $writePipes + $readPipes as $fd => $pipe ) {
328 // True if a pipe is unblocked for us to write into, false if for reading from
329 $isWrite = array_key_exists( $fd, $readPipes );
330
331 if ( $isWrite ) {
332 // Don't bother writing if the buffer is empty
333 if ( $buffers[$fd] === '' ) {
334 fclose( $pipes[$fd] );
335 unset( $pipes[$fd] );
336 continue;
337 }
338 $res = fwrite( $pipe, $buffers[$fd], 65536 );
339 } else {
340 $res = fread( $pipe, 65536 );
341 }
342
343 if ( $res === false ) {
344 $logMsg = 'Error ' . ( $isWrite ? 'writing to' : 'reading from' ) . ' pipe';
345 break 2;
346 }
347
348 if ( $res === '' || $res === 0 ) {
349 // End of file?
350 if ( feof( $pipe ) ) {
351 fclose( $pipes[$fd] );
352 unset( $pipes[$fd] );
353 }
354 } elseif ( $isWrite ) {
355 $buffers[$fd] = (string)substr( $buffers[$fd], $res );
356 if ( $buffers[$fd] === '' ) {
357 fclose( $pipes[$fd] );
358 unset( $pipes[$fd] );
359 }
360 } else {
361 $buffers[$fd] .= $res;
362 if ( $fd === 3 && strpos( $res, "\n" ) !== false ) {
363 // For the log FD, every line is a separate log entry.
364 $lines = explode( "\n", $buffers[3] );
365 $buffers[3] = array_pop( $lines );
366 foreach ( $lines as $line ) {
367 $this->logger->info( $line );
368 }
369 }
370 }
371 }
372 }
373
374 foreach ( $pipes as $pipe ) {
375 fclose( $pipe );
376 }
377
378 // Use the status previously collected if possible, since proc_get_status()
379 // just calls waitpid() which will not return anything useful the second time.
380 if ( $running ) {
381 $status = proc_get_status( $proc );
382 }
383
384 if ( $logMsg !== false ) {
385 // Read/select error
386 $retval = -1;
387 proc_close( $proc );
388 } elseif ( $status['signaled'] ) {
389 $logMsg = "Exited with signal {$status['termsig']}";
390 // Use the shell convention of setting the exit status to 128 + the signal number
391 $retval = 128 + $status['termsig'];
392 proc_close( $proc );
393 } else {
394 if ( $status['running'] ) {
395 $retval = proc_close( $proc );
396 } else {
397 $retval = $status['exitcode'];
398 proc_close( $proc );
399 }
400 if ( $retval == 127 ) {
401 $logMsg = "Possibly missing executable file";
402 } elseif ( $retval >= 129 && $retval <= 192 ) {
403 // Per the shell convention
404 $logMsg = "Probably exited with signal " . ( $retval - 128 );
405 }
406 }
407
408 if ( $logMsg !== false ) {
409 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
410 }
411
412 if ( $this->stdoutPath !== null ) {
413 $stdout = FileUtils::getContents( $this->stdoutPath );
414 } else {
415 $stdout = $buffers[1];
416 }
417 if ( $this->stderrPath !== null ) {
418 $stderr = FileUtils::getContents( $this->stderrPath );
419 } else {
420 $stderr = $buffers[2];
421 }
422 if ( $stderr !== '' && $command->getForwardStderr() ) {
423 fwrite( STDERR, $stderr );
424 }
425 if ( $stderr !== '' && $command->getLogStderr() ) {
426 $this->logger->error( "Error running {command}: {error}", [
427 'command' => $cmd,
428 'error' => $stderr,
429 'exitcode' => $retval,
430 'exception' => new ShellboxError( 'Shell error' ),
431 ] );
432 }
433
434 return ( new UnboxedResult )
435 ->exitCode( $retval )
436 ->stdout( $stdout )
437 ->stderr( $stderr );
438 }
439
440 /**
441 * Modify the command by running wrappers on it.
442 *
443 * @param Command $command
444 */
445 protected function buildFinalCommand( Command $command ) {
446 $wrappers = $this->wrappers;
447 usort( $wrappers, static function ( Wrapper $a, Wrapper $b ) {
448 return $a->getPriority() <=> $b->getPriority();
449 } );
450 foreach ( $wrappers as $wrapper ) {
451 $wrapper->wrap( $command );
452 }
453
454 if ( $command->getIncludeStderr() ) {
455 $command->unsafeCommand( $command->getCommandString() . ' 2>&1' );
456 }
457 }
458 }