3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Shell
;
24 use MediaWiki\ProcOpenError
;
25 use MediaWiki\ShellDisabledError
;
27 use Psr\Log\LoggerAwareTrait
;
28 use Psr\Log\NullLogger
;
31 * Class used for executing shell commands
39 protected $command = '';
59 /** @var string|null */
63 private $doIncludeStderr = false;
66 private $doLogStderr = false;
69 private $everExecuted = false;
71 /** @var string|false */
72 private $cgroup = false;
75 * bitfield with restrictions
79 protected $restrictions = 0;
82 * Constructor. Don't call directly, instead use Shell::command()
84 * @throws ShellDisabledError
86 public function __construct() {
87 if ( Shell
::isDisabled() ) {
88 throw new ShellDisabledError();
91 $this->setLogger( new NullLogger() );
95 * Destructor. Makes sure programmer didn't forget to execute the command after all
97 public function __destruct() {
98 if ( !$this->everExecuted
) {
99 $context = [ 'command' => $this->command
];
100 $message = __CLASS__
. " was instantiated, but execute() was never called.";
101 if ( $this->method
) {
102 $message .= ' Calling method: {method}.';
103 $context['method'] = $this->method
;
105 $message .= ' Command: {command}';
106 $this->logger
->warning( $message, $context );
111 * Adds parameters to the command. All parameters are sanitized via Shell::escape().
112 * Null values are ignored.
114 * @param string|string[] $args,...
117 public function params( /* ... */ ) {
118 $args = func_get_args();
119 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
120 // If only one argument has been passed, and that argument is an array,
121 // treat it as a list of arguments
122 $args = reset( $args );
124 $this->command
= trim( $this->command
. ' ' . Shell
::escape( $args ) );
130 * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
131 * Null values are ignored.
133 * @param string|string[] $args,...
136 public function unsafeParams( /* ... */ ) {
137 $args = func_get_args();
138 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
139 // If only one argument has been passed, and that argument is an array,
140 // treat it as a list of arguments
141 $args = reset( $args );
143 $args = array_filter( $args,
144 function ( $value ) {
145 return $value !== null;
148 $this->command
= trim( $this->command
. ' ' . implode( ' ', $args ) );
154 * Sets execution limits
156 * @param array $limits Associative array of limits. Keys (all optional):
157 * filesize (for ulimit -f), memory, time, walltime.
160 public function limits( array $limits ) {
161 if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
162 // Emulate the behavior of old wfShellExec() where walltime fell back on time
163 // if the latter was overridden and the former wasn't
164 $limits['walltime'] = $limits['time'];
166 $this->limits
= $limits +
$this->limits
;
172 * Sets environment variables which should be added to the executed command environment
174 * @param string[] $env array of variable name => value
177 public function environment( array $env ) {
184 * Sets calling function for profiler. By default, the caller for execute() will be used.
186 * @param string $method
189 public function profileMethod( $method ) {
190 $this->method
= $method;
196 * Sends the provided input to the command.
197 * When set to null (default), the command will use the standard input.
198 * @param string|null $inputString
201 public function input( $inputString ) {
202 $this->inputString
= is_null( $inputString ) ?
null : (string)$inputString;
208 * Controls whether stderr should be included in stdout, including errors from limit.sh.
209 * Default: don't include.
214 public function includeStderr( $yesno = true ) {
215 $this->doIncludeStderr
= $yesno;
221 * When enabled, text sent to stderr will be logged with a level of 'error'.
226 public function logStderr( $yesno = true ) {
227 $this->doLogStderr
= $yesno;
233 * Sets cgroup for this command
235 * @param string|false $cgroup Absolute file path to the cgroup, or false to not use a cgroup
238 public function cgroup( $cgroup ) {
239 $this->cgroup
= $cgroup;
245 * Set additional restrictions for this request
248 * @param int $restrictions
251 public function restrict( $restrictions ) {
252 $this->restrictions |
= $restrictions;
258 * Bitfield helper on whether a specific restriction is enabled
260 * @param int $restriction
264 protected function hasRestriction( $restriction ) {
265 return ( $this->restrictions
& $restriction ) === $restriction;
269 * If called, only the files/directories that are
270 * whitelisted will be available to the shell command.
272 * limit.sh will always be whitelisted
274 * @param string[] $paths
278 public function whitelistPaths( array $paths ) {
279 // Default implementation is a no-op
284 * String together all the options and build the final command
287 * @param string $command Already-escaped command to run
288 * @return array [ command, whether to use log pipe ]
290 protected function buildFinalCommand( $command ) {
292 foreach ( $this->env
as $k => $v ) {
293 if ( wfIsWindows() ) {
294 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
295 * appear in the environment variable, so we must use carat escaping as documented in
296 * https://technet.microsoft.com/en-us/library/cc723564.aspx
297 * Note however that the quote isn't listed there, but is needed, and the parentheses
298 * are listed there but doesn't appear to need it.
300 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
302 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
303 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
305 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
310 $cmd = $envcmd . trim( $command );
312 if ( is_executable( '/bin/bash' ) ) {
313 $time = intval( $this->limits
['time'] );
314 $wallTime = intval( $this->limits
['walltime'] );
315 $mem = intval( $this->limits
['memory'] );
316 $filesize = intval( $this->limits
['filesize'] );
318 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
319 $cmd = '/bin/bash ' . escapeshellarg( __DIR__
. '/limit.sh' ) . ' ' .
320 escapeshellarg( $cmd ) . ' ' .
322 "MW_INCLUDE_STDERR=" . ( $this->doIncludeStderr ?
'1' : '' ) . ';' .
323 "MW_CPU_LIMIT=$time; " .
324 'MW_CGROUP=' . escapeshellarg( $this->cgroup
) . '; ' .
325 "MW_MEM_LIMIT=$mem; " .
326 "MW_FILE_SIZE_LIMIT=$filesize; " .
327 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
328 "MW_USE_LOG_PIPE=yes"
333 if ( !$useLogPipe && $this->doIncludeStderr
) {
337 return [ $cmd, $useLogPipe ];
341 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
346 * @throws ProcOpenError
347 * @throws ShellDisabledError
349 public function execute() {
350 $this->everExecuted
= true;
352 $profileMethod = $this->method ?
: wfGetCaller();
354 list( $cmd, $useLogPipe ) = $this->buildFinalCommand( $this->command
);
356 $this->logger
->debug( __METHOD__
. ": $cmd" );
358 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
359 // Other platforms may be more accomodating, but we don't want to be
360 // accomodating, because very long commands probably include user
361 // input. See T129506.
362 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN
) {
363 throw new Exception( __METHOD__
.
364 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
368 0 => $this->inputString
=== null ?
[ 'file', 'php://stdin', 'r' ] : [ 'pipe', 'r' ],
369 1 => [ 'pipe', 'w' ],
370 2 => [ 'pipe', 'w' ],
373 $desc[3] = [ 'pipe', 'w' ];
376 $scoped = Profiler
::instance()->scopedProfileIn( __FUNCTION__
. '-' . $profileMethod );
377 $proc = proc_open( $cmd, $desc, $pipes );
379 $this->logger
->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
380 throw new ProcOpenError();
384 0 => $this->inputString
, // input
393 /* According to the documentation, it is possible for stream_select()
394 * to fail due to EINTR. I haven't managed to induce this in testing
395 * despite sending various signals. If it did happen, the error
396 * message would take the form:
398 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
400 * where [4] is the value of the macro EINTR and "Interrupted system
401 * call" is string which according to the Linux manual is "possibly"
402 * localised according to LC_MESSAGES.
404 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
405 $eintrMessage = "stream_select(): unable to select [$eintr]";
407 /* The select(2) system call only guarantees a "sufficiently small write"
408 * can be made without blocking. And on Linux the read might block too
409 * in certain cases, although I don't know if any of them can occur here.
410 * Regardless, set all the pipes to non-blocking to avoid T184171.
412 foreach ( $pipes as $pipe ) {
413 stream_set_blocking( $pipe, false );
420 while ( $pipes && ( $running === true ||
$numReadyPipes !== 0 ) ) {
422 $status = proc_get_status( $proc );
423 // If the process has terminated, switch to nonblocking selects
424 // for getting any data still waiting to be read.
425 if ( !$status['running'] ) {
431 // clear get_last_error without actually raising an error
432 // from http://php.net/manual/en/function.error-get-last.php#113518
433 // TODO replace with clear_last_error when requirements are bumped to PHP7
434 set_error_handler( function () {
436 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
437 @trigger_error
( '' );
438 restore_error_handler();
440 $readPipes = wfArrayFilterByKey( $pipes, function ( $fd ) use ( $desc ) {
441 return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'r';
443 $writePipes = wfArrayFilterByKey( $pipes, function ( $fd ) use ( $desc ) {
444 return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'w';
446 // stream_select parameter names are from the POV of us being able to do the operation;
447 // proc_open desriptor types are from the POV of the process doing it.
448 // So $writePipes is passed as the $read parameter and $readPipes as $write.
449 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
450 $numReadyPipes = @stream_select
( $writePipes, $readPipes, $emptyArray, $timeout );
451 if ( $numReadyPipes === false ) {
452 $error = error_get_last();
453 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
456 trigger_error( $error['message'], E_USER_WARNING
);
457 $logMsg = $error['message'];
461 foreach ( $writePipes +
$readPipes as $fd => $pipe ) {
462 // True if a pipe is unblocked for us to write into, false if for reading from
463 $isWrite = array_key_exists( $fd, $readPipes );
466 $res = fwrite( $pipe, $buffers[$fd], 65536 );
468 $res = fread( $pipe, 65536 );
471 if ( $res === false ) {
472 $logMsg = 'Error ' . ( $isWrite ?
'writing to' : 'reading from' ) . ' pipe';
476 if ( $res === '' ||
$res === 0 ) {
478 if ( feof( $pipe ) ) {
479 fclose( $pipes[$fd] );
480 unset( $pipes[$fd] );
482 } elseif ( $isWrite ) {
483 $buffers[$fd] = (string)substr( $buffers[$fd], $res );
484 if ( $buffers[$fd] === '' ) {
485 fclose( $pipes[$fd] );
486 unset( $pipes[$fd] );
489 $buffers[$fd] .= $res;
490 if ( $fd === 3 && strpos( $res, "\n" ) !== false ) {
491 // For the log FD, every line is a separate log entry.
492 $lines = explode( "\n", $buffers[3] );
493 $buffers[3] = array_pop( $lines );
494 foreach ( $lines as $line ) {
495 $this->logger
->info( $line );
502 foreach ( $pipes as $pipe ) {
506 // Use the status previously collected if possible, since proc_get_status()
507 // just calls waitpid() which will not return anything useful the second time.
509 $status = proc_get_status( $proc );
512 if ( $logMsg !== false ) {
516 } elseif ( $status['signaled'] ) {
517 $logMsg = "Exited with signal {$status['termsig']}";
518 $retval = 128 +
$status['termsig'];
521 if ( $status['running'] ) {
522 $retval = proc_close( $proc );
524 $retval = $status['exitcode'];
527 if ( $retval == 127 ) {
528 $logMsg = "Possibly missing executable file";
529 } elseif ( $retval >= 129 && $retval <= 192 ) {
530 $logMsg = "Probably exited with signal " . ( $retval - 128 );
534 if ( $logMsg !== false ) {
535 $this->logger
->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
538 if ( $buffers[2] && $this->doLogStderr
) {
539 $this->logger
->error( "Error running {command}: {error}", [
541 'error' => $buffers[2],
542 'exitcode' => $retval,
543 'exception' => new Exception( 'Shell error' ),
547 return new Result( $retval, $buffers[1], $buffers[2] );