Shell\Command: Move code that builds final shell command into separate method
[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 * String together all the options and build the final command
202 * to execute
203 *
204 * @return array [ command, whether to use log pipe ]
205 */
206 protected function buildFinalCommand() {
207 $envcmd = '';
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.
215 */
216 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
217 } else {
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
220 */
221 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
222 }
223 }
224
225 $useLogPipe = false;
226 $cmd = $envcmd . trim( $this->command );
227
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'] );
233
234 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
235 $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
236 escapeshellarg( $cmd ) . ' ' .
237 escapeshellarg(
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"
245 );
246 $useLogPipe = true;
247 }
248 }
249 if ( !$useLogPipe && $this->useStderr ) {
250 $cmd .= ' 2>&1';
251 }
252
253 return [ $cmd, $useLogPipe ];
254 }
255
256 /**
257 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
258 * results.
259 *
260 * @return Result
261 * @throws Exception
262 * @throws ProcOpenError
263 * @throws ShellDisabledError
264 */
265 public function execute() {
266 $this->everExecuted = true;
267
268 $profileMethod = $this->method ?: wfGetCaller();
269
270 list( $cmd, $useLogPipe ) = $this->buildFinalCommand();
271
272 $this->logger->debug( __METHOD__ . ": $cmd" );
273
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' );
281 }
282
283 $desc = [
284 0 => [ 'file', 'php://stdin', 'r' ],
285 1 => [ 'pipe', 'w' ],
286 2 => [ 'pipe', 'w' ],
287 ];
288 if ( $useLogPipe ) {
289 $desc[3] = [ 'pipe', 'w' ];
290 }
291 $pipes = null;
292 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
293 $proc = proc_open( $cmd, $desc, $pipes );
294 if ( !$proc ) {
295 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
296 throw new ProcOpenError();
297 }
298 $outBuffer = $logBuffer = '';
299 $errBuffer = null;
300 $emptyArray = [];
301 $status = false;
302 $logMsg = false;
303
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:
308 *
309 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
310 *
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.
314 */
315 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
316 $eintrMessage = "stream_select(): unable to select [$eintr]";
317
318 $running = true;
319 $timeout = null;
320 $numReadyPipes = 0;
321
322 while ( $running === true || $numReadyPipes !== 0 ) {
323 if ( $running ) {
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'] ) {
328 $running = false;
329 $timeout = 0;
330 }
331 }
332
333 $readyPipes = $pipes;
334
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 () {
339 }, 0 );
340 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
341 @trigger_error( '' );
342 // @codingStandardsIgnoreEnd
343 restore_error_handler();
344
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 ) {
351 continue;
352 } else {
353 trigger_error( $error['message'], E_USER_WARNING );
354 $logMsg = $error['message'];
355 break;
356 }
357 }
358 foreach ( $readyPipes as $fd => $pipe ) {
359 $block = fread( $pipe, 65536 );
360 if ( $block === '' ) {
361 // End of file
362 fclose( $pipes[$fd] );
363 unset( $pipes[$fd] );
364 if ( !$pipes ) {
365 break 2;
366 }
367 } elseif ( $block === false ) {
368 // Read error
369 $logMsg = "Error reading from pipe";
370 break 2;
371 } elseif ( $fd == 1 ) {
372 // From stdout
373 $outBuffer .= $block;
374 } elseif ( $fd == 2 ) {
375 // From stderr
376 $errBuffer .= $block;
377 } elseif ( $fd == 3 ) {
378 // From log FD
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 );
385 }
386 }
387 }
388 }
389 }
390
391 foreach ( $pipes as $pipe ) {
392 fclose( $pipe );
393 }
394
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.
397 if ( $running ) {
398 $status = proc_get_status( $proc );
399 }
400
401 if ( $logMsg !== false ) {
402 // Read/select error
403 $retval = -1;
404 proc_close( $proc );
405 } elseif ( $status['signaled'] ) {
406 $logMsg = "Exited with signal {$status['termsig']}";
407 $retval = 128 + $status['termsig'];
408 proc_close( $proc );
409 } else {
410 if ( $status['running'] ) {
411 $retval = proc_close( $proc );
412 } else {
413 $retval = $status['exitcode'];
414 proc_close( $proc );
415 }
416 if ( $retval == 127 ) {
417 $logMsg = "Possibly missing executable file";
418 } elseif ( $retval >= 129 && $retval <= 192 ) {
419 $logMsg = "Probably exited with signal " . ( $retval - 128 );
420 }
421 }
422
423 if ( $logMsg !== false ) {
424 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
425 }
426
427 return new Result( $retval, $outBuffer, $errBuffer );
428 }
429 }