Merge "Add attributes parameter to ShowSearchHitTitle"
[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 private $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 bool */
60 private $doIncludeStderr = false;
61
62 /** @var bool */
63 private $doLogStderr = false;
64
65 /** @var bool */
66 private $everExecuted = false;
67
68 /** @var string|false */
69 private $cgroup = false;
70
71 /**
72 * Constructor. Don't call directly, instead use Shell::command()
73 *
74 * @throws ShellDisabledError
75 */
76 public function __construct() {
77 if ( Shell::isDisabled() ) {
78 throw new ShellDisabledError();
79 }
80
81 $this->setLogger( new NullLogger() );
82 }
83
84 /**
85 * Destructor. Makes sure programmer didn't forget to execute the command after all
86 */
87 public function __destruct() {
88 if ( !$this->everExecuted ) {
89 $context = [ 'command' => $this->command ];
90 $message = __CLASS__ . " was instantiated, but execute() was never called.";
91 if ( $this->method ) {
92 $message .= ' Calling method: {method}.';
93 $context['method'] = $this->method;
94 }
95 $message .= ' Command: {command}';
96 $this->logger->warning( $message, $context );
97 }
98 }
99
100 /**
101 * Adds parameters to the command. All parameters are sanitized via Shell::escape().
102 *
103 * @param string|string[] $args,...
104 * @return $this
105 */
106 public function params( /* ... */ ) {
107 $args = func_get_args();
108 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
109 // If only one argument has been passed, and that argument is an array,
110 // treat it as a list of arguments
111 $args = reset( $args );
112 }
113 $this->command .= ' ' . Shell::escape( $args );
114
115 return $this;
116 }
117
118 /**
119 * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
120 *
121 * @param string|string[] $args,...
122 * @return $this
123 */
124 public function unsafeParams( /* ... */ ) {
125 $args = func_get_args();
126 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
127 // If only one argument has been passed, and that argument is an array,
128 // treat it as a list of arguments
129 $args = reset( $args );
130 }
131 $this->command .= implode( ' ', $args );
132
133 return $this;
134 }
135
136 /**
137 * Sets execution limits
138 *
139 * @param array $limits Associative array of limits. Keys (all optional):
140 * filesize (for ulimit -f), memory, time, walltime.
141 * @return $this
142 */
143 public function limits( array $limits ) {
144 if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
145 // Emulate the behavior of old wfShellExec() where walltime fell back on time
146 // if the latter was overridden and the former wasn't
147 $limits['walltime'] = $limits['time'];
148 }
149 $this->limits = $limits + $this->limits;
150
151 return $this;
152 }
153
154 /**
155 * Sets environment variables which should be added to the executed command environment
156 *
157 * @param string[] $env array of variable name => value
158 * @return $this
159 */
160 public function environment( array $env ) {
161 $this->env = $env;
162
163 return $this;
164 }
165
166 /**
167 * Sets calling function for profiler. By default, the caller for execute() will be used.
168 *
169 * @param string $method
170 * @return $this
171 */
172 public function profileMethod( $method ) {
173 $this->method = $method;
174
175 return $this;
176 }
177
178 /**
179 * Controls whether stderr should be included in stdout, including errors from limit.sh.
180 * Default: don't include.
181 *
182 * @param bool $yesno
183 * @return $this
184 */
185 public function includeStderr( $yesno = true ) {
186 $this->doIncludeStderr = $yesno;
187
188 return $this;
189 }
190
191 /**
192 * When enabled, text sent to stderr will be logged with a level of 'error'.
193 *
194 * @param bool $yesno
195 * @return $this
196 */
197 public function logStderr( $yesno = true ) {
198 $this->doLogStderr = $yesno;
199
200 return $this;
201 }
202
203 /**
204 * Sets cgroup for this command
205 *
206 * @param string|false $cgroup Absolute file path to the cgroup, or false to not use a cgroup
207 * @return $this
208 */
209 public function cgroup( $cgroup ) {
210 $this->cgroup = $cgroup;
211
212 return $this;
213 }
214
215 /**
216 * String together all the options and build the final command
217 * to execute
218 *
219 * @return array [ command, whether to use log pipe ]
220 */
221 protected function buildFinalCommand() {
222 $envcmd = '';
223 foreach ( $this->env as $k => $v ) {
224 if ( wfIsWindows() ) {
225 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
226 * appear in the environment variable, so we must use carat escaping as documented in
227 * https://technet.microsoft.com/en-us/library/cc723564.aspx
228 * Note however that the quote isn't listed there, but is needed, and the parentheses
229 * are listed there but doesn't appear to need it.
230 */
231 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
232 } else {
233 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
234 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
235 */
236 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
237 }
238 }
239
240 $useLogPipe = false;
241 $cmd = $envcmd . trim( $this->command );
242
243 if ( is_executable( '/bin/bash' ) ) {
244 $time = intval( $this->limits['time'] );
245 $wallTime = intval( $this->limits['walltime'] );
246 $mem = intval( $this->limits['memory'] );
247 $filesize = intval( $this->limits['filesize'] );
248
249 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
250 $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
251 escapeshellarg( $cmd ) . ' ' .
252 escapeshellarg(
253 "MW_INCLUDE_STDERR=" . ( $this->doIncludeStderr ? '1' : '' ) . ';' .
254 "MW_CPU_LIMIT=$time; " .
255 'MW_CGROUP=' . escapeshellarg( $this->cgroup ) . '; ' .
256 "MW_MEM_LIMIT=$mem; " .
257 "MW_FILE_SIZE_LIMIT=$filesize; " .
258 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
259 "MW_USE_LOG_PIPE=yes"
260 );
261 $useLogPipe = true;
262 }
263 }
264 if ( !$useLogPipe && $this->doIncludeStderr ) {
265 $cmd .= ' 2>&1';
266 }
267
268 return [ $cmd, $useLogPipe ];
269 }
270
271 /**
272 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
273 * results.
274 *
275 * @return Result
276 * @throws Exception
277 * @throws ProcOpenError
278 * @throws ShellDisabledError
279 */
280 public function execute() {
281 $this->everExecuted = true;
282
283 $profileMethod = $this->method ?: wfGetCaller();
284
285 list( $cmd, $useLogPipe ) = $this->buildFinalCommand();
286
287 $this->logger->debug( __METHOD__ . ": $cmd" );
288
289 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
290 // Other platforms may be more accomodating, but we don't want to be
291 // accomodating, because very long commands probably include user
292 // input. See T129506.
293 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
294 throw new Exception( __METHOD__ .
295 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
296 }
297
298 $desc = [
299 0 => [ 'file', 'php://stdin', 'r' ],
300 1 => [ 'pipe', 'w' ],
301 2 => [ 'pipe', 'w' ],
302 ];
303 if ( $useLogPipe ) {
304 $desc[3] = [ 'pipe', 'w' ];
305 }
306 $pipes = null;
307 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
308 $proc = proc_open( $cmd, $desc, $pipes );
309 if ( !$proc ) {
310 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
311 throw new ProcOpenError();
312 }
313 $outBuffer = $logBuffer = '';
314 $errBuffer = null;
315 $emptyArray = [];
316 $status = false;
317 $logMsg = false;
318
319 /* According to the documentation, it is possible for stream_select()
320 * to fail due to EINTR. I haven't managed to induce this in testing
321 * despite sending various signals. If it did happen, the error
322 * message would take the form:
323 *
324 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
325 *
326 * where [4] is the value of the macro EINTR and "Interrupted system
327 * call" is string which according to the Linux manual is "possibly"
328 * localised according to LC_MESSAGES.
329 */
330 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
331 $eintrMessage = "stream_select(): unable to select [$eintr]";
332
333 $running = true;
334 $timeout = null;
335 $numReadyPipes = 0;
336
337 while ( $running === true || $numReadyPipes !== 0 ) {
338 if ( $running ) {
339 $status = proc_get_status( $proc );
340 // If the process has terminated, switch to nonblocking selects
341 // for getting any data still waiting to be read.
342 if ( !$status['running'] ) {
343 $running = false;
344 $timeout = 0;
345 }
346 }
347
348 $readyPipes = $pipes;
349
350 // clear get_last_error without actually raising an error
351 // from http://php.net/manual/en/function.error-get-last.php#113518
352 // TODO replace with clear_last_error when requirements are bumped to PHP7
353 set_error_handler( function () {
354 }, 0 );
355 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
356 @trigger_error( '' );
357 // @codingStandardsIgnoreEnd
358 restore_error_handler();
359
360 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
361 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
362 // @codingStandardsIgnoreEnd
363 if ( $numReadyPipes === false ) {
364 $error = error_get_last();
365 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
366 continue;
367 } else {
368 trigger_error( $error['message'], E_USER_WARNING );
369 $logMsg = $error['message'];
370 break;
371 }
372 }
373 foreach ( $readyPipes as $fd => $pipe ) {
374 $block = fread( $pipe, 65536 );
375 if ( $block === '' ) {
376 // End of file
377 fclose( $pipes[$fd] );
378 unset( $pipes[$fd] );
379 if ( !$pipes ) {
380 break 2;
381 }
382 } elseif ( $block === false ) {
383 // Read error
384 $logMsg = "Error reading from pipe";
385 break 2;
386 } elseif ( $fd == 1 ) {
387 // From stdout
388 $outBuffer .= $block;
389 } elseif ( $fd == 2 ) {
390 // From stderr
391 $errBuffer .= $block;
392 } elseif ( $fd == 3 ) {
393 // From log FD
394 $logBuffer .= $block;
395 if ( strpos( $block, "\n" ) !== false ) {
396 $lines = explode( "\n", $logBuffer );
397 $logBuffer = array_pop( $lines );
398 foreach ( $lines as $line ) {
399 $this->logger->info( $line );
400 }
401 }
402 }
403 }
404 }
405
406 foreach ( $pipes as $pipe ) {
407 fclose( $pipe );
408 }
409
410 // Use the status previously collected if possible, since proc_get_status()
411 // just calls waitpid() which will not return anything useful the second time.
412 if ( $running ) {
413 $status = proc_get_status( $proc );
414 }
415
416 if ( $logMsg !== false ) {
417 // Read/select error
418 $retval = -1;
419 proc_close( $proc );
420 } elseif ( $status['signaled'] ) {
421 $logMsg = "Exited with signal {$status['termsig']}";
422 $retval = 128 + $status['termsig'];
423 proc_close( $proc );
424 } else {
425 if ( $status['running'] ) {
426 $retval = proc_close( $proc );
427 } else {
428 $retval = $status['exitcode'];
429 proc_close( $proc );
430 }
431 if ( $retval == 127 ) {
432 $logMsg = "Possibly missing executable file";
433 } elseif ( $retval >= 129 && $retval <= 192 ) {
434 $logMsg = "Probably exited with signal " . ( $retval - 128 );
435 }
436 }
437
438 if ( $logMsg !== false ) {
439 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
440 }
441
442 if ( $errBuffer && $this->doLogStderr ) {
443 $this->logger->error( "Error running {command}: {error}", [
444 'command' => $cmd,
445 'error' => $errBuffer,
446 'exitcode' => $retval,
447 'exception' => new Exception( 'Shell error' ),
448 ] );
449 }
450
451 return new Result( $retval, $outBuffer, $errBuffer );
452 }
453 }