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