MediaWiki  1.34.4
Command.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Shell;
22 
23 use Exception;
26 use Profiler;
27 use Psr\Log\LoggerAwareTrait;
28 use Psr\Log\NullLogger;
29 use Wikimedia\AtEase\AtEase;
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 
265  public function restrict( $restrictions ): Command {
266  $this->restrictions = $restrictions;
267 
268  return $this;
269  }
270 
278  protected function hasRestriction( $restriction ) {
279  return ( $this->restrictions & $restriction ) === $restriction;
280  }
281 
292  public function whitelistPaths( array $paths ): Command {
293  // Default implementation is a no-op
294  return $this;
295  }
296 
304  protected function buildFinalCommand( $command ) {
305  $envcmd = '';
306  foreach ( $this->env as $k => $v ) {
307  if ( wfIsWindows() ) {
308  /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
309  * appear in the environment variable, so we must use carat escaping as documented in
310  * https://technet.microsoft.com/en-us/library/cc723564.aspx
311  * Note however that the quote isn't listed there, but is needed, and the parentheses
312  * are listed there but doesn't appear to need it.
313  */
314  $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
315  } else {
316  /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
317  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
318  */
319  $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
320  }
321  }
322 
323  $useLogPipe = false;
324  $cmd = $envcmd . trim( $command );
325 
326  if ( is_executable( '/bin/bash' ) ) {
327  $time = intval( $this->limits['time'] );
328  $wallTime = intval( $this->limits['walltime'] );
329  $mem = intval( $this->limits['memory'] );
330  $filesize = intval( $this->limits['filesize'] );
331 
332  if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
333  $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
334  escapeshellarg( $cmd ) . ' ' .
335  escapeshellarg(
336  "MW_INCLUDE_STDERR=" . ( $this->doIncludeStderr ? '1' : '' ) . ';' .
337  "MW_CPU_LIMIT=$time; " .
338  'MW_CGROUP=' . escapeshellarg( $this->cgroup ) . '; ' .
339  "MW_MEM_LIMIT=$mem; " .
340  "MW_FILE_SIZE_LIMIT=$filesize; " .
341  "MW_WALL_CLOCK_LIMIT=$wallTime; " .
342  "MW_USE_LOG_PIPE=yes"
343  );
344  $useLogPipe = true;
345  }
346  }
347  if ( !$useLogPipe && $this->doIncludeStderr ) {
348  $cmd .= ' 2>&1';
349  }
350 
351  if ( wfIsWindows() ) {
352  $cmd = 'cmd.exe /c "' . $cmd . '"';
353  }
354 
355  return [ $cmd, $useLogPipe ];
356  }
357 
367  public function execute() {
368  $this->everExecuted = true;
369 
370  $profileMethod = $this->method ?: wfGetCaller();
371 
372  list( $cmd, $useLogPipe ) = $this->buildFinalCommand( $this->command );
373 
374  $this->logger->debug( __METHOD__ . ": $cmd" );
375 
376  // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
377  // Other platforms may be more accomodating, but we don't want to be
378  // accomodating, because very long commands probably include user
379  // input. See T129506.
380  if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
381  throw new Exception( __METHOD__ .
382  '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
383  }
384 
385  $desc = [
386  0 => $this->inputString === null ? [ 'file', 'php://stdin', 'r' ] : [ 'pipe', 'r' ],
387  1 => [ 'pipe', 'w' ],
388  2 => [ 'pipe', 'w' ],
389  ];
390  if ( $useLogPipe ) {
391  $desc[3] = [ 'pipe', 'w' ];
392  }
393  $pipes = null;
394  $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
395  $proc = null;
396 
397  if ( wfIsWindows() ) {
398  // Windows Shell bypassed, but command run is "cmd.exe /C "{$cmd}"
399  // This solves some shell parsing issues, see T207248
400  $proc = proc_open( $cmd, $desc, $pipes, null, null, [ 'bypass_shell' => true ] );
401  } else {
402  $proc = proc_open( $cmd, $desc, $pipes );
403  }
404 
405  if ( !$proc ) {
406  $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
407  throw new ProcOpenError();
408  }
409 
410  $buffers = [
411  0 => $this->inputString, // input
412  1 => '', // stdout
413  2 => null, // stderr
414  3 => '', // log
415  ];
416  $emptyArray = [];
417  $status = false;
418  $logMsg = false;
419 
420  /* According to the documentation, it is possible for stream_select()
421  * to fail due to EINTR. I haven't managed to induce this in testing
422  * despite sending various signals. If it did happen, the error
423  * message would take the form:
424  *
425  * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
426  *
427  * where [4] is the value of the macro EINTR and "Interrupted system
428  * call" is string which according to the Linux manual is "possibly"
429  * localised according to LC_MESSAGES.
430  */
431  $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
432  $eintrMessage = "stream_select(): unable to select [$eintr]";
433 
434  /* The select(2) system call only guarantees a "sufficiently small write"
435  * can be made without blocking. And on Linux the read might block too
436  * in certain cases, although I don't know if any of them can occur here.
437  * Regardless, set all the pipes to non-blocking to avoid T184171.
438  */
439  foreach ( $pipes as $pipe ) {
440  stream_set_blocking( $pipe, false );
441  }
442 
443  $running = true;
444  $timeout = null;
445  $numReadyPipes = 0;
446 
447  while ( $pipes && ( $running === true || $numReadyPipes !== 0 ) ) {
448  if ( $running ) {
449  $status = proc_get_status( $proc );
450  // If the process has terminated, switch to nonblocking selects
451  // for getting any data still waiting to be read.
452  if ( !$status['running'] ) {
453  $running = false;
454  $timeout = 0;
455  }
456  }
457 
458  // clear get_last_error without actually raising an error
459  // from https://www.php.net/manual/en/function.error-get-last.php#113518
460  // TODO replace with error_clear_last after dropping HHVM
461  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
462  set_error_handler( function () {
463  }, 0 );
464  AtEase::suppressWarnings();
465  trigger_error( '' );
466  AtEase::restoreWarnings();
467  restore_error_handler();
468 
469  $readPipes = array_filter( $pipes, function ( $fd ) use ( $desc ) {
470  return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'r';
471  }, ARRAY_FILTER_USE_KEY );
472  $writePipes = array_filter( $pipes, function ( $fd ) use ( $desc ) {
473  return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'w';
474  }, ARRAY_FILTER_USE_KEY );
475  // stream_select parameter names are from the POV of us being able to do the operation;
476  // proc_open desriptor types are from the POV of the process doing it.
477  // So $writePipes is passed as the $read parameter and $readPipes as $write.
478  AtEase::suppressWarnings();
479  $numReadyPipes = stream_select( $writePipes, $readPipes, $emptyArray, $timeout );
480  AtEase::restoreWarnings();
481  if ( $numReadyPipes === false ) {
482  $error = error_get_last();
483  if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
484  continue;
485  } else {
486  trigger_error( $error['message'], E_USER_WARNING );
487  $logMsg = $error['message'];
488  break;
489  }
490  }
491  foreach ( $writePipes + $readPipes as $fd => $pipe ) {
492  // True if a pipe is unblocked for us to write into, false if for reading from
493  $isWrite = array_key_exists( $fd, $readPipes );
494 
495  if ( $isWrite ) {
496  // Don't bother writing if the buffer is empty
497  if ( $buffers[$fd] === '' ) {
498  fclose( $pipes[$fd] );
499  unset( $pipes[$fd] );
500  continue;
501  }
502  $res = fwrite( $pipe, $buffers[$fd], 65536 );
503  } else {
504  $res = fread( $pipe, 65536 );
505  }
506 
507  if ( $res === false ) {
508  $logMsg = 'Error ' . ( $isWrite ? 'writing to' : 'reading from' ) . ' pipe';
509  break 2;
510  }
511 
512  if ( $res === '' || $res === 0 ) {
513  // End of file?
514  if ( feof( $pipe ) ) {
515  fclose( $pipes[$fd] );
516  unset( $pipes[$fd] );
517  }
518  } elseif ( $isWrite ) {
519  $buffers[$fd] = (string)substr( $buffers[$fd], $res );
520  if ( $buffers[$fd] === '' ) {
521  fclose( $pipes[$fd] );
522  unset( $pipes[$fd] );
523  }
524  } else {
525  $buffers[$fd] .= $res;
526  if ( $fd === 3 && strpos( $res, "\n" ) !== false ) {
527  // For the log FD, every line is a separate log entry.
528  $lines = explode( "\n", $buffers[3] );
529  $buffers[3] = array_pop( $lines );
530  foreach ( $lines as $line ) {
531  $this->logger->info( $line );
532  }
533  }
534  }
535  }
536  }
537 
538  foreach ( $pipes as $pipe ) {
539  fclose( $pipe );
540  }
541 
542  // Use the status previously collected if possible, since proc_get_status()
543  // just calls waitpid() which will not return anything useful the second time.
544  if ( $running ) {
545  $status = proc_get_status( $proc );
546  }
547 
548  if ( $logMsg !== false ) {
549  // Read/select error
550  $retval = -1;
551  proc_close( $proc );
552  } elseif ( $status['signaled'] ) {
553  $logMsg = "Exited with signal {$status['termsig']}";
554  $retval = 128 + $status['termsig'];
555  proc_close( $proc );
556  } else {
557  if ( $status['running'] ) {
558  $retval = proc_close( $proc );
559  } else {
560  $retval = $status['exitcode'];
561  proc_close( $proc );
562  }
563  if ( $retval == 127 ) {
564  $logMsg = "Possibly missing executable file";
565  } elseif ( $retval >= 129 && $retval <= 192 ) {
566  $logMsg = "Probably exited with signal " . ( $retval - 128 );
567  }
568  }
569 
570  if ( $logMsg !== false ) {
571  $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
572  }
573 
574  if ( $buffers[2] && $this->doLogStderr ) {
575  $this->logger->error( "Error running {command}: {error}", [
576  'command' => $cmd,
577  'error' => $buffers[2],
578  'exitcode' => $retval,
579  'exception' => new Exception( 'Shell error' ),
580  ] );
581  }
582 
583  return new Result( $retval, $buffers[1], $buffers[2] );
584  }
585 
593  public function __toString() {
594  return "#Command: {$this->command}";
595  }
596 }
MediaWiki\Shell\Command\$everExecuted
bool $everExecuted
Definition: Command.php:70
MediaWiki\Shell\Result
Returned by MediaWiki\Shell\Command::execute()
Definition: Result.php:28
MediaWiki\Shell\Command\$doIncludeStderr
bool $doIncludeStderr
Definition: Command.php:64
MediaWiki\Shell\Command\__destruct
__destruct()
Makes sure the programmer didn't forget to execute the command after all.
Definition: Command.php:98
MediaWiki\Shell\Command\unsafeParams
unsafeParams(... $args)
Adds unsafe parameters to the command.
Definition: Command.php:136
MediaWiki\ProcOpenError
Definition: ProcOpenError.php:25
MediaWiki\Shell\Command\profileMethod
profileMethod( $method)
Sets calling function for profiler.
Definition: Command.php:188
MediaWiki\Shell\Command\restrict
restrict( $restrictions)
Set restrictions for this request, overwriting any previously set restrictions.
Definition: Command.php:265
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:63
MediaWiki\Shell\Command
Class used for executing shell commands.
Definition: Command.php:36
MediaWiki\Shell\Command\$inputString
string null $inputString
Definition: Command.php:61
MediaWiki\Shell\Command\cgroup
cgroup( $cgroup)
Sets cgroup for this command.
Definition: Command.php:237
MediaWiki\Shell\Command\limits
limits(array $limits)
Sets execution limits.
Definition: Command.php:159
MediaWiki\Shell\Command\hasRestriction
hasRestriction( $restriction)
Bitfield helper on whether a specific restriction is enabled.
Definition: Command.php:278
MediaWiki\Shell\Command\$restrictions
int $restrictions
Bitfield with restrictions.
Definition: Command.php:80
$res
$res
Definition: testCompression.php:52
MediaWiki\Shell\Command\logStderr
logStderr( $yesno=true)
When enabled, text sent to stderr will be logged with a level of 'error'.
Definition: Command.php:225
Profiler
Profiler base class that defines the interface and some trivial functionality.
Definition: Profiler.php:33
SHELL_MAX_ARG_STRLEN
const SHELL_MAX_ARG_STRLEN
Definition: Defines.php:259
MediaWiki\Shell\Command\$env
string[] $env
Definition: Command.php:55
MediaWiki\Shell\Command\__toString
__toString()
Returns the final command line before environment/limiting, etc are applied.
Definition: Command.php:593
$lines
$lines
Definition: router.php:61
MediaWiki\Shell\Command\includeStderr
includeStderr( $yesno=true)
Controls whether stderr should be included in stdout, including errors from limit....
Definition: Command.php:213
MediaWiki\Shell\Command\environment
environment(array $env)
Sets environment variables which should be added to the executed command environment.
Definition: Command.php:176
MediaWiki\Shell\Shell\isDisabled
static isDisabled()
Check if this class is effectively disabled via php.ini config.
Definition: Shell.php:137
$line
$line
Definition: cdb.php:59
MediaWiki\Shell\Command\$command
string $command
Definition: Command.php:40
MediaWiki\Shell\Command\$doLogStderr
bool $doLogStderr
Definition: Command.php:67
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1887
MediaWiki\ShellDisabledError
Definition: ShellDisabledError.php:28
MediaWiki\Shell\Command\input
input( $inputString)
Sends the provided input to the command.
Definition: Command.php:200
MediaWiki\Shell\Shell\escape
static escape(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: Shell.php:163
$args
if( $line===false) $args
Definition: cdb.php:64
MediaWiki\Shell
Copyright (C) 2017 Kunal Mehta legoktm@member.fsf.org
Definition: Command.php:21
MediaWiki\Shell\Command\$limits
array $limits
Definition: Command.php:43
MediaWiki\Shell\Command\$cgroup
string false $cgroup
Definition: Command.php:73
MediaWiki\Shell\Command\$method
string $method
Definition: Command.php:58
MediaWiki\$context
IContextSource $context
Definition: MediaWiki.php:38
MediaWiki\Shell\Command\whitelistPaths
whitelistPaths(array $paths)
If called, only the files/directories that are whitelisted will be available to the shell command.
Definition: Command.php:292
MediaWiki\Shell\Command\buildFinalCommand
buildFinalCommand( $command)
String together all the options and build the final command to execute.
Definition: Command.php:304
MediaWiki\Shell\Command\execute
execute()
Executes command.
Definition: Command.php:367
wfGetCaller
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1434
MediaWiki\Shell\Command\__construct
__construct()
Don't call directly, instead use Shell::command()
Definition: Command.php:87
MediaWiki\Shell\Command\params
params(... $args)
Adds parameters to the command.
Definition: Command.php:118