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