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 private $command = '';
60 private $useStderr = false;
63 private $everExecuted = false;
65 /** @var string|false */
66 private $cgroup = false;
69 * Constructor. Don't call directly, instead use Shell::command()
71 * @throws ShellDisabledError
73 public function __construct() {
74 if ( Shell
::isDisabled() ) {
75 throw new ShellDisabledError();
78 $this->setLogger( new NullLogger() );
82 * Destructor. Makes sure programmer didn't forget to execute the command after all
84 public function __destruct() {
85 if ( !$this->everExecuted
) {
86 $context = [ 'command' => $this->command
];
87 $message = __CLASS__
. " was instantiated, but execute() was never called.";
88 if ( $this->method
) {
89 $message .= ' Calling method: {method}.';
90 $context['method'] = $this->method
;
92 $message .= ' Command: {command}';
93 $this->logger
->warning( $message, $context );
98 * Adds parameters to the command. All parameters are sanitized via Shell::escape().
100 * @param string|string[] $args,...
103 public function params( /* ... */ ) {
104 $args = func_get_args();
105 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
106 // If only one argument has been passed, and that argument is an array,
107 // treat it as a list of arguments
108 $args = reset( $args );
110 $this->command
.= ' ' . Shell
::escape( $args );
116 * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
118 * @param string|string[] $args,...
121 public function unsafeParams( /* ... */ ) {
122 $args = func_get_args();
123 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
124 // If only one argument has been passed, and that argument is an array,
125 // treat it as a list of arguments
126 $args = reset( $args );
128 $this->command
.= implode( ' ', $args );
134 * Sets execution limits
136 * @param array $limits Associative array of limits. Keys (all optional):
137 * filesize (for ulimit -f), memory, time, walltime.
140 public function limits( array $limits ) {
141 if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
142 // Emulate the behavior of old wfShellExec() where walltime fell back on time
143 // if the latter was overridden and the former wasn't
144 $limits['walltime'] = $limits['time'];
146 $this->limits
= $limits +
$this->limits
;
152 * Sets environment variables which should be added to the executed command environment
154 * @param string[] $env array of variable name => value
157 public function environment( array $env ) {
164 * Sets calling function for profiler. By default, the caller for execute() will be used.
166 * @param string $method
169 public function profileMethod( $method ) {
170 $this->method
= $method;
176 * Controls whether stderr should be included in stdout, including errors from limit.sh.
177 * Default: don't include.
182 public function includeStderr( $yesno = true ) {
183 $this->useStderr
= $yesno;
189 * Sets cgroup for this command
191 * @param string|false $cgroup Absolute file path to the cgroup, or false to not use a cgroup
194 public function cgroup( $cgroup ) {
195 $this->cgroup
= $cgroup;
201 * String together all the options and build the final command
204 * @return array [ command, whether to use log pipe ]
206 protected function buildFinalCommand() {
208 foreach ( $this->env
as $k => $v ) {
209 if ( wfIsWindows() ) {
210 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
211 * appear in the environment variable, so we must use carat escaping as documented in
212 * https://technet.microsoft.com/en-us/library/cc723564.aspx
213 * Note however that the quote isn't listed there, but is needed, and the parentheses
214 * are listed there but doesn't appear to need it.
216 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
218 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
219 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
221 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
226 $cmd = $envcmd . trim( $this->command
);
228 if ( is_executable( '/bin/bash' ) ) {
229 $time = intval( $this->limits
['time'] );
230 $wallTime = intval( $this->limits
['walltime'] );
231 $mem = intval( $this->limits
['memory'] );
232 $filesize = intval( $this->limits
['filesize'] );
234 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
235 $cmd = '/bin/bash ' . escapeshellarg( __DIR__
. '/limit.sh' ) . ' ' .
236 escapeshellarg( $cmd ) . ' ' .
238 "MW_INCLUDE_STDERR=" . ( $this->useStderr ?
'1' : '' ) . ';' .
239 "MW_CPU_LIMIT=$time; " .
240 'MW_CGROUP=' . escapeshellarg( $this->cgroup
) . '; ' .
241 "MW_MEM_LIMIT=$mem; " .
242 "MW_FILE_SIZE_LIMIT=$filesize; " .
243 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
244 "MW_USE_LOG_PIPE=yes"
249 if ( !$useLogPipe && $this->useStderr
) {
253 return [ $cmd, $useLogPipe ];
257 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
262 * @throws ProcOpenError
263 * @throws ShellDisabledError
265 public function execute() {
266 $this->everExecuted
= true;
268 $profileMethod = $this->method ?
: wfGetCaller();
270 list( $cmd, $useLogPipe ) = $this->buildFinalCommand();
272 $this->logger
->debug( __METHOD__
. ": $cmd" );
274 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
275 // Other platforms may be more accomodating, but we don't want to be
276 // accomodating, because very long commands probably include user
277 // input. See T129506.
278 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN
) {
279 throw new Exception( __METHOD__
.
280 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
284 0 => [ 'file', 'php://stdin', 'r' ],
285 1 => [ 'pipe', 'w' ],
286 2 => [ 'pipe', 'w' ],
289 $desc[3] = [ 'pipe', 'w' ];
292 $scoped = Profiler
::instance()->scopedProfileIn( __FUNCTION__
. '-' . $profileMethod );
293 $proc = proc_open( $cmd, $desc, $pipes );
295 $this->logger
->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
296 throw new ProcOpenError();
298 $outBuffer = $logBuffer = '';
304 /* According to the documentation, it is possible for stream_select()
305 * to fail due to EINTR. I haven't managed to induce this in testing
306 * despite sending various signals. If it did happen, the error
307 * message would take the form:
309 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
311 * where [4] is the value of the macro EINTR and "Interrupted system
312 * call" is string which according to the Linux manual is "possibly"
313 * localised according to LC_MESSAGES.
315 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
316 $eintrMessage = "stream_select(): unable to select [$eintr]";
322 while ( $running === true ||
$numReadyPipes !== 0 ) {
324 $status = proc_get_status( $proc );
325 // If the process has terminated, switch to nonblocking selects
326 // for getting any data still waiting to be read.
327 if ( !$status['running'] ) {
333 $readyPipes = $pipes;
335 // clear get_last_error without actually raising an error
336 // from http://php.net/manual/en/function.error-get-last.php#113518
337 // TODO replace with clear_last_error when requirements are bumped to PHP7
338 set_error_handler( function () {
340 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
341 @trigger_error
( '' );
342 // @codingStandardsIgnoreEnd
343 restore_error_handler();
345 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
346 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
347 // @codingStandardsIgnoreEnd
348 if ( $numReadyPipes === false ) {
349 $error = error_get_last();
350 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
353 trigger_error( $error['message'], E_USER_WARNING
);
354 $logMsg = $error['message'];
358 foreach ( $readyPipes as $fd => $pipe ) {
359 $block = fread( $pipe, 65536 );
360 if ( $block === '' ) {
362 fclose( $pipes[$fd] );
363 unset( $pipes[$fd] );
367 } elseif ( $block === false ) {
369 $logMsg = "Error reading from pipe";
371 } elseif ( $fd == 1 ) {
373 $outBuffer .= $block;
374 } elseif ( $fd == 2 ) {
376 $errBuffer .= $block;
377 } elseif ( $fd == 3 ) {
379 $logBuffer .= $block;
380 if ( strpos( $block, "\n" ) !== false ) {
381 $lines = explode( "\n", $logBuffer );
382 $logBuffer = array_pop( $lines );
383 foreach ( $lines as $line ) {
384 $this->logger
->info( $line );
391 foreach ( $pipes as $pipe ) {
395 // Use the status previously collected if possible, since proc_get_status()
396 // just calls waitpid() which will not return anything useful the second time.
398 $status = proc_get_status( $proc );
401 if ( $logMsg !== false ) {
405 } elseif ( $status['signaled'] ) {
406 $logMsg = "Exited with signal {$status['termsig']}";
407 $retval = 128 +
$status['termsig'];
410 if ( $status['running'] ) {
411 $retval = proc_close( $proc );
413 $retval = $status['exitcode'];
416 if ( $retval == 127 ) {
417 $logMsg = "Possibly missing executable file";
418 } elseif ( $retval >= 129 && $retval <= 192 ) {
419 $logMsg = "Probably exited with signal " . ( $retval - 128 );
423 if ( $logMsg !== false ) {
424 $this->logger
->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
427 return new Result( $retval, $outBuffer, $errBuffer );