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