MediaWiki  master
Command.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Shell;
22 
23 use Exception;
26 use Profiler;
30 
36 class Command {
37  use LoggerAwareTrait;
38 
40  protected $command = '';
41 
43  private $limits = [
44  // seconds
45  'time' => 180,
46  // seconds
47  'walltime' => 180,
48  // KB
49  'memory' => 307200,
50  // KB
51  'filesize' => 102400,
52  ];
53 
55  private $env = [];
56 
58  private $method;
59 
61  private $inputString;
62 
64  private $doIncludeStderr = false;
65 
67  private $doLogStderr = false;
68 
70  private $everExecuted = false;
71 
73  private $cgroup = false;
74 
80  protected $restrictions = 0;
81 
87  public function __construct() {
88  if ( Shell::isDisabled() ) {
89  throw new ShellDisabledError();
90  }
91 
92  $this->setLogger( new NullLogger() );
93  }
94 
98  public function __destruct() {
99  if ( !$this->everExecuted ) {
100  $context = [ 'command' => $this->command ];
101  $message = __CLASS__ . " was instantiated, but execute() was never called.";
102  if ( $this->method ) {
103  $message .= ' Calling method: {method}.';
104  $context['method'] = $this->method;
105  }
106  $message .= ' Command: {command}';
107  $this->logger->warning( $message, $context );
108  }
109  }
110 
118  public function params( ...$args ): Command {
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 );
123  }
124  $this->command = trim( $this->command . ' ' . Shell::escape( $args ) );
125 
126  return $this;
127  }
128 
136  public function unsafeParams( ...$args ): Command {
137  if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
138  // If only one argument has been passed, and that argument is an array,
139  // treat it as a list of arguments
140  $args = reset( $args );
141  }
142  $args = array_filter( $args,
143  function ( $value ) {
144  return $value !== null;
145  }
146  );
147  $this->command = trim( $this->command . ' ' . implode( ' ', $args ) );
148 
149  return $this;
150  }
151 
159  public function limits( array $limits ): Command {
160  if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
161  // Emulate the behavior of old wfShellExec() where walltime fell back on time
162  // if the latter was overridden and the former wasn't
163  $limits['walltime'] = $limits['time'];
164  }
165  $this->limits = $limits + $this->limits;
166 
167  return $this;
168  }
169 
176  public function environment( array $env ): Command {
177  $this->env = $env;
178 
179  return $this;
180  }
181 
188  public function profileMethod( $method ): Command {
189  $this->method = $method;
190 
191  return $this;
192  }
193 
200  public function input( $inputString ): Command {
201  $this->inputString = is_null( $inputString ) ? null : (string)$inputString;
202 
203  return $this;
204  }
205 
213  public function includeStderr( $yesno = true ): Command {
214  $this->doIncludeStderr = $yesno;
215 
216  return $this;
217  }
218 
225  public function logStderr( $yesno = true ): Command {
226  $this->doLogStderr = $yesno;
227 
228  return $this;
229  }
230 
237  public function cgroup( $cgroup ): Command {
238  $this->cgroup = $cgroup;
239 
240  return $this;
241  }
242 
250  public function restrict( $restrictions ): Command {
251  $this->restrictions |= $restrictions;
252 
253  return $this;
254  }
255 
263  protected function hasRestriction( $restriction ) {
264  return ( $this->restrictions & $restriction ) === $restriction;
265  }
266 
277  public function whitelistPaths( array $paths ): Command {
278  // Default implementation is a no-op
279  return $this;
280  }
281 
289  protected function buildFinalCommand( $command ) {
290  $envcmd = '';
291  foreach ( $this->env as $k => $v ) {
292  if ( wfIsWindows() ) {
293  /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
294  * appear in the environment variable, so we must use carat escaping as documented in
295  * https://technet.microsoft.com/en-us/library/cc723564.aspx
296  * Note however that the quote isn't listed there, but is needed, and the parentheses
297  * are listed there but doesn't appear to need it.
298  */
299  $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
300  } else {
301  /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
302  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
303  */
304  $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
305  }
306  }
307 
308  $useLogPipe = false;
309  $cmd = $envcmd . trim( $command );
310 
311  if ( is_executable( '/bin/bash' ) ) {
312  $time = intval( $this->limits['time'] );
313  $wallTime = intval( $this->limits['walltime'] );
314  $mem = intval( $this->limits['memory'] );
315  $filesize = intval( $this->limits['filesize'] );
316 
317  if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
318  $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
319  escapeshellarg( $cmd ) . ' ' .
320  escapeshellarg(
321  "MW_INCLUDE_STDERR=" . ( $this->doIncludeStderr ? '1' : '' ) . ';' .
322  "MW_CPU_LIMIT=$time; " .
323  'MW_CGROUP=' . escapeshellarg( $this->cgroup ) . '; ' .
324  "MW_MEM_LIMIT=$mem; " .
325  "MW_FILE_SIZE_LIMIT=$filesize; " .
326  "MW_WALL_CLOCK_LIMIT=$wallTime; " .
327  "MW_USE_LOG_PIPE=yes"
328  );
329  $useLogPipe = true;
330  }
331  }
332  if ( !$useLogPipe && $this->doIncludeStderr ) {
333  $cmd .= ' 2>&1';
334  }
335 
336  return [ $cmd, $useLogPipe ];
337  }
338 
348  public function execute() {
349  $this->everExecuted = true;
350 
351  $profileMethod = $this->method ?: wfGetCaller();
352 
353  list( $cmd, $useLogPipe ) = $this->buildFinalCommand( $this->command );
354 
355  $this->logger->debug( __METHOD__ . ": $cmd" );
356 
357  // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
358  // Other platforms may be more accomodating, but we don't want to be
359  // accomodating, because very long commands probably include user
360  // input. See T129506.
361  if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
362  throw new Exception( __METHOD__ .
363  '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
364  }
365 
366  $desc = [
367  0 => $this->inputString === null ? [ 'file', 'php://stdin', 'r' ] : [ 'pipe', 'r' ],
368  1 => [ 'pipe', 'w' ],
369  2 => [ 'pipe', 'w' ],
370  ];
371  if ( $useLogPipe ) {
372  $desc[3] = [ 'pipe', 'w' ];
373  }
374  $pipes = null;
375  $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
376  $proc = proc_open( $cmd, $desc, $pipes );
377  if ( !$proc ) {
378  $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
379  throw new ProcOpenError();
380  }
381 
382  $buffers = [
383  0 => $this->inputString, // input
384  1 => '', // stdout
385  2 => null, // stderr
386  3 => '', // log
387  ];
388  $emptyArray = [];
389  $status = false;
390  $logMsg = false;
391 
392  /* According to the documentation, it is possible for stream_select()
393  * to fail due to EINTR. I haven't managed to induce this in testing
394  * despite sending various signals. If it did happen, the error
395  * message would take the form:
396  *
397  * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
398  *
399  * where [4] is the value of the macro EINTR and "Interrupted system
400  * call" is string which according to the Linux manual is "possibly"
401  * localised according to LC_MESSAGES.
402  */
403  $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
404  $eintrMessage = "stream_select(): unable to select [$eintr]";
405 
406  /* The select(2) system call only guarantees a "sufficiently small write"
407  * can be made without blocking. And on Linux the read might block too
408  * in certain cases, although I don't know if any of them can occur here.
409  * Regardless, set all the pipes to non-blocking to avoid T184171.
410  */
411  foreach ( $pipes as $pipe ) {
412  stream_set_blocking( $pipe, false );
413  }
414 
415  $running = true;
416  $timeout = null;
417  $numReadyPipes = 0;
418 
419  while ( $pipes && ( $running === true || $numReadyPipes !== 0 ) ) {
420  if ( $running ) {
421  $status = proc_get_status( $proc );
422  // If the process has terminated, switch to nonblocking selects
423  // for getting any data still waiting to be read.
424  if ( !$status['running'] ) {
425  $running = false;
426  $timeout = 0;
427  }
428  }
429 
430  error_clear_last();
431 
432  $readPipes = array_filter( $pipes, function ( $fd ) use ( $desc ) {
433  return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'r';
434  }, ARRAY_FILTER_USE_KEY );
435  $writePipes = array_filter( $pipes, function ( $fd ) use ( $desc ) {
436  return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'w';
437  }, ARRAY_FILTER_USE_KEY );
438  // stream_select parameter names are from the POV of us being able to do the operation;
439  // proc_open desriptor types are from the POV of the process doing it.
440  // So $writePipes is passed as the $read parameter and $readPipes as $write.
441  AtEase::suppressWarnings();
442  $numReadyPipes = stream_select( $writePipes, $readPipes, $emptyArray, $timeout );
443  AtEase::restoreWarnings();
444  if ( $numReadyPipes === false ) {
445  $error = error_get_last();
446  if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
447  continue;
448  } else {
449  trigger_error( $error['message'], E_USER_WARNING );
450  $logMsg = $error['message'];
451  break;
452  }
453  }
454  foreach ( $writePipes + $readPipes as $fd => $pipe ) {
455  // True if a pipe is unblocked for us to write into, false if for reading from
456  $isWrite = array_key_exists( $fd, $readPipes );
457 
458  if ( $isWrite ) {
459  // Don't bother writing if the buffer is empty
460  if ( $buffers[$fd] === '' ) {
461  fclose( $pipes[$fd] );
462  unset( $pipes[$fd] );
463  continue;
464  }
465  $res = fwrite( $pipe, $buffers[$fd], 65536 );
466  } else {
467  $res = fread( $pipe, 65536 );
468  }
469 
470  if ( $res === false ) {
471  $logMsg = 'Error ' . ( $isWrite ? 'writing to' : 'reading from' ) . ' pipe';
472  break 2;
473  }
474 
475  if ( $res === '' || $res === 0 ) {
476  // End of file?
477  if ( feof( $pipe ) ) {
478  fclose( $pipes[$fd] );
479  unset( $pipes[$fd] );
480  }
481  } elseif ( $isWrite ) {
482  $buffers[$fd] = (string)substr( $buffers[$fd], $res );
483  if ( $buffers[$fd] === '' ) {
484  fclose( $pipes[$fd] );
485  unset( $pipes[$fd] );
486  }
487  } else {
488  $buffers[$fd] .= $res;
489  if ( $fd === 3 && strpos( $res, "\n" ) !== false ) {
490  // For the log FD, every line is a separate log entry.
491  $lines = explode( "\n", $buffers[3] );
492  $buffers[3] = array_pop( $lines );
493  foreach ( $lines as $line ) {
494  $this->logger->info( $line );
495  }
496  }
497  }
498  }
499  }
500 
501  foreach ( $pipes as $pipe ) {
502  fclose( $pipe );
503  }
504 
505  // Use the status previously collected if possible, since proc_get_status()
506  // just calls waitpid() which will not return anything useful the second time.
507  if ( $running ) {
508  $status = proc_get_status( $proc );
509  }
510 
511  if ( $logMsg !== false ) {
512  // Read/select error
513  $retval = -1;
514  proc_close( $proc );
515  } elseif ( $status['signaled'] ) {
516  $logMsg = "Exited with signal {$status['termsig']}";
517  $retval = 128 + $status['termsig'];
518  proc_close( $proc );
519  } else {
520  if ( $status['running'] ) {
521  $retval = proc_close( $proc );
522  } else {
523  $retval = $status['exitcode'];
524  proc_close( $proc );
525  }
526  if ( $retval == 127 ) {
527  $logMsg = "Possibly missing executable file";
528  } elseif ( $retval >= 129 && $retval <= 192 ) {
529  $logMsg = "Probably exited with signal " . ( $retval - 128 );
530  }
531  }
532 
533  if ( $logMsg !== false ) {
534  $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
535  }
536 
537  if ( $buffers[2] && $this->doLogStderr ) {
538  $this->logger->error( "Error running {command}: {error}", [
539  'command' => $cmd,
540  'error' => $buffers[2],
541  'exitcode' => $retval,
542  'exception' => new Exception( 'Shell error' ),
543  ] );
544  }
545 
546  return new Result( $retval, $buffers[1], $buffers[2] );
547  }
548 
556  public function __toString() {
557  return "#Command: {$this->command}";
558  }
559 }
execute()
Executes command.
Definition: Command.php:348
cgroup( $cgroup)
Sets cgroup for this command.
Definition: Command.php:237
whitelistPaths(array $paths)
If called, only the files/directories that are whitelisted will be available to the shell command...
Definition: Command.php:277
restrict( $restrictions)
Set additional restrictions for this request.
Definition: Command.php:250
static escape(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: Shell.php:163
static instance()
Singleton.
Definition: Profiler.php:63
params(... $args)
Adds parameters to the command.
Definition: Command.php:118
limits(array $limits)
Sets execution limits.
Definition: Command.php:159
string null $inputString
Definition: Command.php:61
unsafeParams(... $args)
Adds unsafe parameters to the command.
Definition: Command.php:136
__destruct()
Makes sure the programmer didn&#39;t forget to execute the command after all.
Definition: Command.php:98
hasRestriction( $restriction)
Bitfield helper on whether a specific restriction is enabled.
Definition: Command.php:263
wfIsWindows()
Check if the operating system is Windows.
int $restrictions
Bitfield with restrictions.
Definition: Command.php:80
includeStderr( $yesno=true)
Controls whether stderr should be included in stdout, including errors from limit.sh.
Definition: Command.php:213
array string [] $env
Definition: Command.php:55
if( $line===false) $args
Definition: cdb.php:64
__toString()
Returns the final command line before environment/limiting, etc are applied.
Definition: Command.php:556
const SHELL_MAX_ARG_STRLEN
Definition: Defines.php:250
IContextSource $context
Definition: MediaWiki.php:37
Class used for executing shell commands.
Definition: Command.php:36
logStderr( $yesno=true)
When enabled, text sent to stderr will be logged with a level of &#39;error&#39;.
Definition: Command.php:225
Returned by MediaWiki\Shell\Command::execute()
Definition: Result.php:28
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
input( $inputString)
Sends the provided input to the command.
Definition: Command.php:200
$lines
Definition: router.php:61
environment(array $env)
Sets environment variables which should be added to the executed command environment.
Definition: Command.php:176
$line
Definition: cdb.php:59
__construct()
Don&#39;t call directly, instead use Shell::command()
Definition: Command.php:87
buildFinalCommand( $command)
String together all the options and build the final command to execute.
Definition: Command.php:289
Copyright (C) 2017 Kunal Mehta legoktm@member.fsf.org
Definition: Command.php:21
static isDisabled()
Check if this class is effectively disabled via php.ini config.
Definition: Shell.php:137
string false $cgroup
Definition: Command.php:73
profileMethod( $method)
Sets calling function for profiler.
Definition: Command.php:188