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