Merge "Revert "Log the reason why revision->getContent() returns null""
[lhc/web/wiklou.git] / includes / shell / Command.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Shell;
22
23 use Exception;
24 use MediaWiki\ProcOpenError;
25 use MediaWiki\ShellDisabledError;
26 use Profiler;
27 use Psr\Log\LoggerAwareTrait;
28 use Psr\Log\NullLogger;
29
30 /**
31 * Class used for executing shell commands
32 *
33 * @since 1.30
34 */
35 class Command {
36 use LoggerAwareTrait;
37
38 /** @var string */
39 protected $command = '';
40
41 /** @var array */
42 private $limits = [
43 // seconds
44 'time' => 180,
45 // seconds
46 'walltime' => 180,
47 // KB
48 'memory' => 307200,
49 // KB
50 'filesize' => 102400,
51 ];
52
53 /** @var string[] */
54 private $env = [];
55
56 /** @var string */
57 private $method;
58
59 /** @var string|null */
60 private $inputString;
61
62 /** @var bool */
63 private $doIncludeStderr = false;
64
65 /** @var bool */
66 private $doLogStderr = false;
67
68 /** @var bool */
69 private $everExecuted = false;
70
71 /** @var string|false */
72 private $cgroup = false;
73
74 /**
75 * bitfield with restrictions
76 *
77 * @var int
78 */
79 protected $restrictions = 0;
80
81 /**
82 * Constructor. Don't call directly, instead use Shell::command()
83 *
84 * @throws ShellDisabledError
85 */
86 public function __construct() {
87 if ( Shell::isDisabled() ) {
88 throw new ShellDisabledError();
89 }
90
91 $this->setLogger( new NullLogger() );
92 }
93
94 /**
95 * Destructor. Makes sure programmer didn't forget to execute the command after all
96 */
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;
104 }
105 $message .= ' Command: {command}';
106 $this->logger->warning( $message, $context );
107 }
108 }
109
110 /**
111 * Adds parameters to the command. All parameters are sanitized via Shell::escape().
112 * Null values are ignored.
113 *
114 * @param string|string[] $args,...
115 * @return $this
116 */
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 );
123 }
124 $this->command = trim( $this->command . ' ' . Shell::escape( $args ) );
125
126 return $this;
127 }
128
129 /**
130 * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
131 * Null values are ignored.
132 *
133 * @param string|string[] $args,...
134 * @return $this
135 */
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 );
142 }
143 $args = array_filter( $args,
144 function ( $value ) {
145 return $value !== null;
146 }
147 );
148 $this->command = trim( $this->command . ' ' . implode( ' ', $args ) );
149
150 return $this;
151 }
152
153 /**
154 * Sets execution limits
155 *
156 * @param array $limits Associative array of limits. Keys (all optional):
157 * filesize (for ulimit -f), memory, time, walltime.
158 * @return $this
159 */
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'];
165 }
166 $this->limits = $limits + $this->limits;
167
168 return $this;
169 }
170
171 /**
172 * Sets environment variables which should be added to the executed command environment
173 *
174 * @param string[] $env array of variable name => value
175 * @return $this
176 */
177 public function environment( array $env ) {
178 $this->env = $env;
179
180 return $this;
181 }
182
183 /**
184 * Sets calling function for profiler. By default, the caller for execute() will be used.
185 *
186 * @param string $method
187 * @return $this
188 */
189 public function profileMethod( $method ) {
190 $this->method = $method;
191
192 return $this;
193 }
194
195 /**
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
199 * @return $this
200 */
201 public function input( $inputString ) {
202 $this->inputString = is_null( $inputString ) ? null : (string)$inputString;
203
204 return $this;
205 }
206
207 /**
208 * Controls whether stderr should be included in stdout, including errors from limit.sh.
209 * Default: don't include.
210 *
211 * @param bool $yesno
212 * @return $this
213 */
214 public function includeStderr( $yesno = true ) {
215 $this->doIncludeStderr = $yesno;
216
217 return $this;
218 }
219
220 /**
221 * When enabled, text sent to stderr will be logged with a level of 'error'.
222 *
223 * @param bool $yesno
224 * @return $this
225 */
226 public function logStderr( $yesno = true ) {
227 $this->doLogStderr = $yesno;
228
229 return $this;
230 }
231
232 /**
233 * Sets cgroup for this command
234 *
235 * @param string|false $cgroup Absolute file path to the cgroup, or false to not use a cgroup
236 * @return $this
237 */
238 public function cgroup( $cgroup ) {
239 $this->cgroup = $cgroup;
240
241 return $this;
242 }
243
244 /**
245 * Set additional restrictions for this request
246 *
247 * @since 1.31
248 * @param int $restrictions
249 * @return $this
250 */
251 public function restrict( $restrictions ) {
252 $this->restrictions |= $restrictions;
253
254 return $this;
255 }
256
257 /**
258 * Bitfield helper on whether a specific restriction is enabled
259 *
260 * @param int $restriction
261 *
262 * @return bool
263 */
264 protected function hasRestriction( $restriction ) {
265 return ( $this->restrictions & $restriction ) === $restriction;
266 }
267
268 /**
269 * If called, only the files/directories that are
270 * whitelisted will be available to the shell command.
271 *
272 * limit.sh will always be whitelisted
273 *
274 * @param string[] $paths
275 *
276 * @return $this
277 */
278 public function whitelistPaths( array $paths ) {
279 // Default implementation is a no-op
280 return $this;
281 }
282
283 /**
284 * String together all the options and build the final command
285 * to execute
286 *
287 * @param string $command Already-escaped command to run
288 * @return array [ command, whether to use log pipe ]
289 */
290 protected function buildFinalCommand( $command ) {
291 $envcmd = '';
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.
299 */
300 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
301 } else {
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
304 */
305 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
306 }
307 }
308
309 $useLogPipe = false;
310 $cmd = $envcmd . trim( $command );
311
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'] );
317
318 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
319 $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
320 escapeshellarg( $cmd ) . ' ' .
321 escapeshellarg(
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"
329 );
330 $useLogPipe = true;
331 }
332 }
333 if ( !$useLogPipe && $this->doIncludeStderr ) {
334 $cmd .= ' 2>&1';
335 }
336
337 return [ $cmd, $useLogPipe ];
338 }
339
340 /**
341 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
342 * results.
343 *
344 * @return Result
345 * @throws Exception
346 * @throws ProcOpenError
347 * @throws ShellDisabledError
348 */
349 public function execute() {
350 $this->everExecuted = true;
351
352 $profileMethod = $this->method ?: wfGetCaller();
353
354 list( $cmd, $useLogPipe ) = $this->buildFinalCommand( $this->command );
355
356 $this->logger->debug( __METHOD__ . ": $cmd" );
357
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' );
365 }
366
367 $desc = [
368 0 => $this->inputString === null ? [ 'file', 'php://stdin', 'r' ] : [ 'pipe', 'r' ],
369 1 => [ 'pipe', 'w' ],
370 2 => [ 'pipe', 'w' ],
371 ];
372 if ( $useLogPipe ) {
373 $desc[3] = [ 'pipe', 'w' ];
374 }
375 $pipes = null;
376 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
377 $proc = proc_open( $cmd, $desc, $pipes );
378 if ( !$proc ) {
379 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
380 throw new ProcOpenError();
381 }
382
383 $buffers = [
384 0 => $this->inputString, // input
385 1 => '', // stdout
386 2 => null, // stderr
387 3 => '', // log
388 ];
389 $emptyArray = [];
390 $status = false;
391 $logMsg = false;
392
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:
397 *
398 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
399 *
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.
403 */
404 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
405 $eintrMessage = "stream_select(): unable to select [$eintr]";
406
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.
411 */
412 foreach ( $pipes as $pipe ) {
413 stream_set_blocking( $pipe, false );
414 }
415
416 $running = true;
417 $timeout = null;
418 $numReadyPipes = 0;
419
420 while ( $pipes && ( $running === true || $numReadyPipes !== 0 ) ) {
421 if ( $running ) {
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'] ) {
426 $running = false;
427 $timeout = 0;
428 }
429 }
430
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 () {
435 }, 0 );
436 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
437 @trigger_error( '' );
438 restore_error_handler();
439
440 $readPipes = wfArrayFilterByKey( $pipes, function ( $fd ) use ( $desc ) {
441 return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'r';
442 } );
443 $writePipes = wfArrayFilterByKey( $pipes, function ( $fd ) use ( $desc ) {
444 return $desc[$fd][0] === 'pipe' && $desc[$fd][1] === 'w';
445 } );
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 ) {
454 continue;
455 } else {
456 trigger_error( $error['message'], E_USER_WARNING );
457 $logMsg = $error['message'];
458 break;
459 }
460 }
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 );
464
465 if ( $isWrite ) {
466 // Don't bother writing if the buffer is empty
467 if ( $buffers[$fd] === '' ) {
468 fclose( $pipes[$fd] );
469 unset( $pipes[$fd] );
470 continue;
471 }
472 $res = fwrite( $pipe, $buffers[$fd], 65536 );
473 } else {
474 $res = fread( $pipe, 65536 );
475 }
476
477 if ( $res === false ) {
478 $logMsg = 'Error ' . ( $isWrite ? 'writing to' : 'reading from' ) . ' pipe';
479 break 2;
480 }
481
482 if ( $res === '' || $res === 0 ) {
483 // End of file?
484 if ( feof( $pipe ) ) {
485 fclose( $pipes[$fd] );
486 unset( $pipes[$fd] );
487 }
488 } elseif ( $isWrite ) {
489 $buffers[$fd] = (string)substr( $buffers[$fd], $res );
490 if ( $buffers[$fd] === '' ) {
491 fclose( $pipes[$fd] );
492 unset( $pipes[$fd] );
493 }
494 } else {
495 $buffers[$fd] .= $res;
496 if ( $fd === 3 && strpos( $res, "\n" ) !== false ) {
497 // For the log FD, every line is a separate log entry.
498 $lines = explode( "\n", $buffers[3] );
499 $buffers[3] = array_pop( $lines );
500 foreach ( $lines as $line ) {
501 $this->logger->info( $line );
502 }
503 }
504 }
505 }
506 }
507
508 foreach ( $pipes as $pipe ) {
509 fclose( $pipe );
510 }
511
512 // Use the status previously collected if possible, since proc_get_status()
513 // just calls waitpid() which will not return anything useful the second time.
514 if ( $running ) {
515 $status = proc_get_status( $proc );
516 }
517
518 if ( $logMsg !== false ) {
519 // Read/select error
520 $retval = -1;
521 proc_close( $proc );
522 } elseif ( $status['signaled'] ) {
523 $logMsg = "Exited with signal {$status['termsig']}";
524 $retval = 128 + $status['termsig'];
525 proc_close( $proc );
526 } else {
527 if ( $status['running'] ) {
528 $retval = proc_close( $proc );
529 } else {
530 $retval = $status['exitcode'];
531 proc_close( $proc );
532 }
533 if ( $retval == 127 ) {
534 $logMsg = "Possibly missing executable file";
535 } elseif ( $retval >= 129 && $retval <= 192 ) {
536 $logMsg = "Probably exited with signal " . ( $retval - 128 );
537 }
538 }
539
540 if ( $logMsg !== false ) {
541 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
542 }
543
544 if ( $buffers[2] && $this->doLogStderr ) {
545 $this->logger->error( "Error running {command}: {error}", [
546 'command' => $cmd,
547 'error' => $buffers[2],
548 'exitcode' => $retval,
549 'exception' => new Exception( 'Shell error' ),
550 ] );
551 }
552
553 return new Result( $retval, $buffers[1], $buffers[2] );
554 }
555 }