]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/shell/Command.php
MediaWiki 1.30.2-scripts2
[autoinstallsdev/mediawiki.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          * Null values are ignored.
100          *
101          * @param string|string[] $args,...
102          * @return $this
103          */
104         public function params( /* ... */ ) {
105                 $args = func_get_args();
106                 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
107                         // If only one argument has been passed, and that argument is an array,
108                         // treat it as a list of arguments
109                         $args = reset( $args );
110                 }
111                 $this->command = trim( $this->command . ' ' . Shell::escape( $args ) );
112
113                 return $this;
114         }
115
116         /**
117          * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
118          * Null values are ignored.
119          *
120          * @param string|string[] $args,...
121          * @return $this
122          */
123         public function unsafeParams( /* ... */ ) {
124                 $args = func_get_args();
125                 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
126                         // If only one argument has been passed, and that argument is an array,
127                         // treat it as a list of arguments
128                         $args = reset( $args );
129                 }
130                 $args = array_filter( $args,
131                         function ( $value ) {
132                                 return $value !== null;
133                         }
134                 );
135                 $this->command = trim( $this->command . ' ' . implode( ' ', $args ) );
136
137                 return $this;
138         }
139
140         /**
141          * Sets execution limits
142          *
143          * @param array $limits Associative array of limits. Keys (all optional):
144          *   filesize (for ulimit -f), memory, time, walltime.
145          * @return $this
146          */
147         public function limits( array $limits ) {
148                 if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
149                         // Emulate the behavior of old wfShellExec() where walltime fell back on time
150                         // if the latter was overridden and the former wasn't
151                         $limits['walltime'] = $limits['time'];
152                 }
153                 $this->limits = $limits + $this->limits;
154
155                 return $this;
156         }
157
158         /**
159          * Sets environment variables which should be added to the executed command environment
160          *
161          * @param string[] $env array of variable name => value
162          * @return $this
163          */
164         public function environment( array $env ) {
165                 $this->env = $env;
166
167                 return $this;
168         }
169
170         /**
171          * Sets calling function for profiler. By default, the caller for execute() will be used.
172          *
173          * @param string $method
174          * @return $this
175          */
176         public function profileMethod( $method ) {
177                 $this->method = $method;
178
179                 return $this;
180         }
181
182         /**
183          * Controls whether stderr should be included in stdout, including errors from limit.sh.
184          * Default: don't include.
185          *
186          * @param bool $yesno
187          * @return $this
188          */
189         public function includeStderr( $yesno = true ) {
190                 $this->useStderr = $yesno;
191
192                 return $this;
193         }
194
195         /**
196          * Sets cgroup for this command
197          *
198          * @param string|false $cgroup Absolute file path to the cgroup, or false to not use a cgroup
199          * @return $this
200          */
201         public function cgroup( $cgroup ) {
202                 $this->cgroup = $cgroup;
203
204                 return $this;
205         }
206
207         /**
208          * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
209          * results.
210          *
211          * @return Result
212          * @throws Exception
213          * @throws ProcOpenError
214          * @throws ShellDisabledError
215          */
216         public function execute() {
217                 $this->everExecuted = true;
218
219                 $profileMethod = $this->method ?: wfGetCaller();
220
221                 $envcmd = '';
222                 foreach ( $this->env as $k => $v ) {
223                         if ( wfIsWindows() ) {
224                                 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
225                                  * appear in the environment variable, so we must use carat escaping as documented in
226                                  * https://technet.microsoft.com/en-us/library/cc723564.aspx
227                                  * Note however that the quote isn't listed there, but is needed, and the parentheses
228                                  * are listed there but doesn't appear to need it.
229                                  */
230                                 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
231                         } else {
232                                 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
233                                  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
234                                  */
235                                 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
236                         }
237                 }
238
239                 $cmd = $envcmd . trim( $this->command );
240
241                 $useLogPipe = false;
242                 if ( is_executable( '/bin/bash' ) ) {
243                         $time = intval( $this->limits['time'] );
244                         $wallTime = intval( $this->limits['walltime'] );
245                         $mem = intval( $this->limits['memory'] );
246                         $filesize = intval( $this->limits['filesize'] );
247
248                         if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
249                                 $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
250                                            escapeshellarg( $cmd ) . ' ' .
251                                            escapeshellarg(
252                                                    "MW_INCLUDE_STDERR=" . ( $this->useStderr ? '1' : '' ) . ';' .
253                                                    "MW_CPU_LIMIT=$time; " .
254                                                    'MW_CGROUP=' . escapeshellarg( $this->cgroup ) . '; ' .
255                                                    "MW_MEM_LIMIT=$mem; " .
256                                                    "MW_FILE_SIZE_LIMIT=$filesize; " .
257                                                    "MW_WALL_CLOCK_LIMIT=$wallTime; " .
258                                                    "MW_USE_LOG_PIPE=yes"
259                                            );
260                                 $useLogPipe = true;
261                         } elseif ( $this->useStderr ) {
262                                 $cmd .= ' 2>&1';
263                         }
264                 } elseif ( $this->useStderr ) {
265                         $cmd .= ' 2>&1';
266                 }
267                 wfDebug( __METHOD__ . ": $cmd\n" );
268
269                 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
270                 // Other platforms may be more accomodating, but we don't want to be
271                 // accomodating, because very long commands probably include user
272                 // input. See T129506.
273                 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
274                         throw new Exception( __METHOD__ .
275                                                                  '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
276                 }
277
278                 $desc = [
279                         0 => [ 'file', 'php://stdin', 'r' ],
280                         1 => [ 'pipe', 'w' ],
281                         2 => [ 'file', 'php://stderr', 'w' ],
282                 ];
283                 if ( $useLogPipe ) {
284                         $desc[3] = [ 'pipe', 'w' ];
285                 }
286                 $pipes = null;
287                 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
288                 $proc = proc_open( $cmd, $desc, $pipes );
289                 if ( !$proc ) {
290                         $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
291                         throw new ProcOpenError();
292                 }
293                 $outBuffer = $logBuffer = '';
294                 $emptyArray = [];
295                 $status = false;
296                 $logMsg = false;
297
298                 /* According to the documentation, it is possible for stream_select()
299                  * to fail due to EINTR. I haven't managed to induce this in testing
300                  * despite sending various signals. If it did happen, the error
301                  * message would take the form:
302                  *
303                  * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
304                  *
305                  * where [4] is the value of the macro EINTR and "Interrupted system
306                  * call" is string which according to the Linux manual is "possibly"
307                  * localised according to LC_MESSAGES.
308                  */
309                 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
310                 $eintrMessage = "stream_select(): unable to select [$eintr]";
311
312                 $running = true;
313                 $timeout = null;
314                 $numReadyPipes = 0;
315
316                 while ( $running === true || $numReadyPipes !== 0 ) {
317                         if ( $running ) {
318                                 $status = proc_get_status( $proc );
319                                 // If the process has terminated, switch to nonblocking selects
320                                 // for getting any data still waiting to be read.
321                                 if ( !$status['running'] ) {
322                                         $running = false;
323                                         $timeout = 0;
324                                 }
325                         }
326
327                         $readyPipes = $pipes;
328
329                         \MediaWiki\suppressWarnings();
330                         trigger_error( '' );
331                         $numReadyPipes = stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
332                         \MediaWiki\restoreWarnings();
333
334                         if ( $numReadyPipes === false ) {
335                                 // @codingStandardsIgnoreEnd
336                                 $error = error_get_last();
337                                 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
338                                         continue;
339                                 } else {
340                                         trigger_error( $error['message'], E_USER_WARNING );
341                                         $logMsg = $error['message'];
342                                         break;
343                                 }
344                         }
345                         foreach ( $readyPipes as $fd => $pipe ) {
346                                 $block = fread( $pipe, 65536 );
347                                 if ( $block === '' ) {
348                                         // End of file
349                                         fclose( $pipes[$fd] );
350                                         unset( $pipes[$fd] );
351                                         if ( !$pipes ) {
352                                                 break 2;
353                                         }
354                                 } elseif ( $block === false ) {
355                                         // Read error
356                                         $logMsg = "Error reading from pipe";
357                                         break 2;
358                                 } elseif ( $fd == 1 ) {
359                                         // From stdout
360                                         $outBuffer .= $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 );
412         }
413 }