Debian Codegraph @

vendor/wikimedia/shellbox/src/Shellbox.php

raw
1 <?php
2
3 namespace Shellbox;
4
5 use Psr\Http\Client\ClientInterface;
6 use Psr\Log\LoggerInterface;
7 use Shellbox\Command\LocalBoxedExecutor;
8 use Shellbox\Command\UnboxedExecutor;
9
10 /**
11 * Static factories and miscellaneous utility functions
12 */
13 class Shellbox {
14 /**
15 * Create a LocalBoxedExecutor from a configuration array. This can be used
16 * to run commands locally, without the client/server split.
17 *
18 * @param array $config Associative array of configuration parameters:
19 * - tempDir: The parent directory in which a temporary directory may be created
20 * - useSystemd: If true, systemd-run will be used
21 * - useBashWrapper: If true, limit.sh will be used
22 * - useFirejail: If true, firejail will be used
23 * - firejailPath: The path to the firejail binary
24 * - firejailProfile: The path to the firejail profile
25 * - cgroup: A writable cgroup path which can be used for manual memory
26 * limiting
27 * - urlFileConcurrency: The maximum number of HTTP requests to have in
28 * flight, if BoxedCommand::inputFileFromUrl() and outputFileToUrl() were
29 * used.
30 * @param LoggerInterface|null $logger
31 * @param ClientInterface|null $urlFileClient An HTTP client to use to
32 * implement BoxedCommand::inputFileFromUrl() and outputFileToUrl().
33 * If this is null, using those features will result in an exception
34 * being thrown.
35 * @return LocalBoxedExecutor
36 */
37 public static function createBoxedExecutor(
38 $config = [],
39 ?LoggerInterface $logger = null,
40 ?ClientInterface $urlFileClient = null
41 ) {
42 $tempDirManager = self::createTempDirManager( $config['tempDir'] ?? null );
43 $unboxedExecutor = new UnboxedExecutor;
44 $unboxedExecutor->setTempDirManager( $tempDirManager );
45 $unboxedExecutor->addWrappersFromConfiguration( $config );
46 $executor = new LocalBoxedExecutor( $unboxedExecutor, $tempDirManager );
47 if ( $logger ) {
48 $executor->setLogger( $logger );
49 $unboxedExecutor->setLogger( $logger );
50 $tempDirManager->setLogger( $logger );
51 }
52 if ( $urlFileClient ) {
53 $executor->setUrlFileClient(
54 $urlFileClient,
55 [
56 'concurrency' => $config['urlFileConcurrency'] ?? 1
57 ]
58 );
59 }
60 return $executor;
61 }
62
63 /**
64 * Create an UnboxedExecutor from a configuration array. This can be used
65 * to run commands locally, without temporary directory setup or the
66 * client/server split.
67 *
68 * A temporary directory is only needed if the command runs on Windows.
69 *
70 * @param array $config Associative array of configuration parameters:
71 * - tempDir: The parent directory in which a temporary directory may be created
72 * - useSystemd: If true, systemd-run will be used
73 * - useBashWrapper: If true, limit.sh will be used
74 * - useFirejail: If true, firejail will be used
75 * - firejailPath: The path to the firejail binary
76 * - firejailProfile: The path to the firejail profile
77 * - cgroup: A writable cgroup path which can be used for manual memory
78 * limiting
79 * @param LoggerInterface|null $logger
80 * @return UnboxedExecutor
81 */
82 public static function createUnboxedExecutor( $config = [], ?LoggerInterface $logger = null ) {
83 $executor = new UnboxedExecutor( $config['tempDir'] ?? null );
84 $executor->addWrappersFromConfiguration( $config );
85 if ( $logger ) {
86 $executor->setLogger( $logger );
87 }
88 return $executor;
89 }
90
91 /**
92 * Create a TempDirManager from a shared base path (e.g. /tmp)
93 *
94 * @param string|null $tempDirBase
95 * @return TempDirManager
96 */
97 public static function createTempDirManager( $tempDirBase = null ) {
98 if ( $tempDirBase === null ) {
99 $tempDirBase = sys_get_temp_dir();
100 }
101 return new TempDirManager(
102 $tempDirBase . '/shellbox-' . self::getUniqueString()
103 );
104 }
105
106 /**
107 * Escape arguments for the shell
108 *
109 * @param mixed|mixed[] ...$args strings to escape and glue together, or a single
110 * array of strings parameter. Null values are ignored.
111 * @return string
112 */
113 public static function escape( ...$args ): string {
114 if ( count( $args ) === 1 && is_array( $args[0] ) ) {
115 // If only one argument has been passed, and that argument is an array,
116 // treat it as a list of arguments
117 $args = $args[0];
118 }
119
120 $first = true;
121 $retVal = '';
122 foreach ( $args as $arg ) {
123 if ( $arg === null ) {
124 continue;
125 }
126 $arg = (string)$arg;
127 if ( !$first ) {
128 $retVal .= ' ';
129 } else {
130 $first = false;
131 }
132
133 if ( PHP_OS_FAMILY === 'Windows' ) {
134 // Escaping for an MSVC-style command line parser and CMD.EXE
135 // Refs:
136 // * phpcs:ignore Generic.Files.LineLength.TooLong
137 // * https://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
138 // * https://technet.microsoft.com/en-us/library/cc723564.aspx
139 // * T15518
140 // * CR r63214
141 // Double the backslashes before any double quotes. Escape the double quotes.
142 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
143 $arg = '';
144 $iteration = 0;
145 foreach ( $tokens as $token ) {
146 if ( $iteration % 2 == 1 ) {
147 // Delimiter, a double quote preceded by zero or more slashes
148 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
149 } elseif ( $iteration % 4 == 2 ) {
150 // ^ in $token will be outside quotes, need to be escaped
151 $arg .= str_replace( '^', '^^', $token );
152 } else { // $iteration % 4 == 0
153 // ^ in $token will appear inside double quotes, so leave as is
154 $arg .= $token;
155 }
156 $iteration++;
157 }
158 // Double the backslashes before the end of the string, because
159 // we will soon add a quote
160 $m = [];
161 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
162 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
163 }
164
165 // Add surrounding quotes
166 $retVal .= '"' . $arg . '"';
167 } else {
168 // In PHP 8.0+, the locale is "C" unless setlocale() has been
169 // called, regardless of the environment. So escapeshellarg()
170 // will strip non-ASCII bytes to avoid misinterpretation by a
171 // shell that uses GBK or a similar character set. So we roll
172 // our own, but UnboxedExecutor will filter the environment to
173 // avoid misinterpretation.
174 $retVal .= "'" . str_replace( "'", "'\\''", $arg ) . "'";
175 }
176 }
177 return $retVal;
178 }
179
180 /**
181 * Get the platform's maximum command length in bytes, minus a safety margin.
182 *
183 * @return int
184 */
185 public static function getMaxCmdLength() {
186 if ( PHP_OS_FAMILY === 'Windows' ) {
187 // phpcs:ignore Generic.Files.LineLength.TooLong
188 // Ref: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa
189 $max = 32767;
190 } else {
191 // Ref: MAX_ARG_STRLEN in linux/binfmts.h
192 $max = 131072;
193 }
194 // In case there is a hidden extra wrapper
195 $max -= 200;
196 return $max;
197 }
198
199 /**
200 * Get a random string from a CSPRNG.
201 *
202 * @return string
203 * @throws \Exception
204 */
205 public static function getUniqueString() {
206 return bin2hex( random_bytes( 8 ) );
207 }
208
209 /**
210 * JSON encode with our preferred options
211 * @param mixed $value
212 * @return string
213 */
214 public static function jsonEncode( $value ) {
215 $json = json_encode( $value,
216 JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES |
217 JSON_UNESCAPED_UNICODE );
218 if ( $json === false ) {
219 throw new ShellboxError( "The supplied value cannot be converted " .
220 "to JSON. Try transferring it as a file." );
221 }
222 $json .= "\n";
223 return $json;
224 }
225
226 /**
227 * Throwing wrapper for JSON decode with our preferred options.
228 *
229 * @param string $json
230 * @return mixed
231 */
232 public static function jsonDecode( $json ) {
233 // phpcs:ignore Generic.PHP.NoSilencedErrors
234 $value = @json_decode( $json, true, 512 );
235 if ( $value === null ) {
236 throw new ShellboxError( 'Received invalid JSON: ' .
237 json_last_error_msg() );
238 }
239 return $value;
240 }
241
242 /**
243 * Validate a relative path for path traversal safety and cross-platform
244 * file name compliance. Under Windows, the path may contain backslashes,
245 * which will be replaced with slashes.
246 *
247 * @param string $path
248 * @return string
249 * @throws ShellboxError
250 */
251 public static function normalizePath( $path ) {
252 $windowsReservedNames = [
253 'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4',
254 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3',
255 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
256 ];
257
258 if ( DIRECTORY_SEPARATOR === '\\' ) {
259 $path = str_replace( '\\', '/', $path );
260 }
261 if ( preg_match( '/[\\x00-\x1f\x7f-\xff<>:"|?*$!\[\];&(){}\\\'\0]/', $path ) ) {
262 throw new ShellboxError( "Relative path contains invalid characters" );
263 }
264 foreach ( explode( '/', $path ) as $component ) {
265 if ( $component === ''
266 || $component === '.'
267 || $component === '..'
268 || substr( $component, -1 ) === ':'
269 ) {
270 throw new ShellboxError( "Invalid relative file path \"$path\"" );
271 }
272 $firstPart = substr( $component, 0, strcspn( $component, '.' ) );
273 if ( in_array( strtoupper( $firstPart ), $windowsReservedNames ) ) {
274 throw new ShellboxError( "Relative path contains Windows reserved name" );
275 }
276 }
277 return $path;
278 }
279
280 /**
281 * Check an extension for path traversal safety and cross-platform file
282 * name compliance. Throw an exception if it is not acceptable.
283 *
284 * @since 4.1.0
285 * @param string $extension
286 * @throws ShellboxError
287 */
288 public static function checkExtension( $extension ) {
289 if ( !preg_match( '/^[0-9a-zA-Z\-_]*$/', $extension ) ) {
290 throw new ShellboxError( "invalid extension \"$extension\"" );
291 }
292 }
293
294 }