Merge "Skin: Make skins aware of their registered skin name"
[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 }
249 }
250 if ( !$useLogPipe && $this->useStderr ) {
251 $cmd .= ' 2>&1';
252 }
253 wfDebug( __METHOD__ . ": $cmd\n" );
254
255 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
256 // Other platforms may be more accomodating, but we don't want to be
257 // accomodating, because very long commands probably include user
258 // input. See T129506.
259 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
260 throw new Exception( __METHOD__ .
261 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
262 }
263
264 $desc = [
265 0 => [ 'file', 'php://stdin', 'r' ],
266 1 => [ 'pipe', 'w' ],
267 2 => [ 'pipe', 'w' ],
268 ];
269 if ( $useLogPipe ) {
270 $desc[3] = [ 'pipe', 'w' ];
271 }
272 $pipes = null;
273 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
274 $proc = proc_open( $cmd, $desc, $pipes );
275 if ( !$proc ) {
276 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
277 throw new ProcOpenError();
278 }
279 $outBuffer = $logBuffer = '';
280 $errBuffer = null;
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 get_last_error without actually raising an error
317 // from http://php.net/manual/en/function.error-get-last.php#113518
318 // TODO replace with clear_last_error when requirements are bumped to PHP7
319 set_error_handler( function () {
320 }, 0 );
321 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
322 @trigger_error( '' );
323 // @codingStandardsIgnoreEnd
324 restore_error_handler();
325
326 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
327 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
328 // @codingStandardsIgnoreEnd
329 if ( $numReadyPipes === false ) {
330 $error = error_get_last();
331 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
332 continue;
333 } else {
334 trigger_error( $error['message'], E_USER_WARNING );
335 $logMsg = $error['message'];
336 break;
337 }
338 }
339 foreach ( $readyPipes as $fd => $pipe ) {
340 $block = fread( $pipe, 65536 );
341 if ( $block === '' ) {
342 // End of file
343 fclose( $pipes[$fd] );
344 unset( $pipes[$fd] );
345 if ( !$pipes ) {
346 break 2;
347 }
348 } elseif ( $block === false ) {
349 // Read error
350 $logMsg = "Error reading from pipe";
351 break 2;
352 } elseif ( $fd == 1 ) {
353 // From stdout
354 $outBuffer .= $block;
355 } elseif ( $fd == 2 ) {
356 // From stderr
357 $errBuffer .= $block;
358 } elseif ( $fd == 3 ) {
359 // From log FD
360 $logBuffer .= $block;
361 if ( strpos( $block, "\n" ) !== false ) {
362 $lines = explode( "\n", $logBuffer );
363 $logBuffer = array_pop( $lines );
364 foreach ( $lines as $line ) {
365 $this->logger->info( $line );
366 }
367 }
368 }
369 }
370 }
371
372 foreach ( $pipes as $pipe ) {
373 fclose( $pipe );
374 }
375
376 // Use the status previously collected if possible, since proc_get_status()
377 // just calls waitpid() which will not return anything useful the second time.
378 if ( $running ) {
379 $status = proc_get_status( $proc );
380 }
381
382 if ( $logMsg !== false ) {
383 // Read/select error
384 $retval = -1;
385 proc_close( $proc );
386 } elseif ( $status['signaled'] ) {
387 $logMsg = "Exited with signal {$status['termsig']}";
388 $retval = 128 + $status['termsig'];
389 proc_close( $proc );
390 } else {
391 if ( $status['running'] ) {
392 $retval = proc_close( $proc );
393 } else {
394 $retval = $status['exitcode'];
395 proc_close( $proc );
396 }
397 if ( $retval == 127 ) {
398 $logMsg = "Possibly missing executable file";
399 } elseif ( $retval >= 129 && $retval <= 192 ) {
400 $logMsg = "Probably exited with signal " . ( $retval - 128 );
401 }
402 }
403
404 if ( $logMsg !== false ) {
405 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
406 }
407
408 return new Result( $retval, $outBuffer, $errBuffer );
409 }
410 }