xref: /PHP-8.4/ext/standard/exec.c (revision 5853cdb7)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: Rasmus Lerdorf <rasmus@php.net>                              |
14    |         Ilia Alshanetsky <iliaa@php.net>                             |
15    +----------------------------------------------------------------------+
16  */
17 
18 #include <stdio.h>
19 #include "php.h"
20 #include <ctype.h>
21 #include "php_string.h"
22 #include "ext/standard/file.h"
23 #include "basic_functions.h"
24 #include "exec.h"
25 #include "SAPI.h"
26 
27 #ifdef HAVE_SYS_WAIT_H
28 #include <sys/wait.h>
29 #endif
30 
31 #include <signal.h>
32 
33 #ifdef HAVE_SYS_TYPES_H
34 #include <sys/types.h>
35 #endif
36 #ifdef HAVE_SYS_STAT_H
37 #include <sys/stat.h>
38 #endif
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #endif
42 
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 
47 #include <limits.h>
48 
49 #ifdef PHP_WIN32
50 # include "win32/nice.h"
51 #endif
52 
53 static size_t cmd_max_len;
54 
55 /* {{{ PHP_MINIT_FUNCTION(exec) */
PHP_MINIT_FUNCTION(exec)56 PHP_MINIT_FUNCTION(exec)
57 {
58 #ifdef _SC_ARG_MAX
59 	cmd_max_len = sysconf(_SC_ARG_MAX);
60 	if ((size_t)-1 == cmd_max_len) {
61 #ifdef _POSIX_ARG_MAX
62 		cmd_max_len = _POSIX_ARG_MAX;
63 #else
64 		cmd_max_len = 4096;
65 #endif
66 	}
67 #elif defined(ARG_MAX)
68 	cmd_max_len = ARG_MAX;
69 #elif defined(PHP_WIN32)
70 	/* Executed commands will run through cmd.exe. As long as it's the case,
71 		it's just the constant limit.*/
72 	cmd_max_len = 8192;
73 #else
74 	/* This is just an arbitrary value for the fallback case. */
75 	cmd_max_len = 4096;
76 #endif
77 
78 	return SUCCESS;
79 }
80 /* }}} */
81 
strip_trailing_whitespace(char * buf,size_t bufl)82 static size_t strip_trailing_whitespace(char *buf, size_t bufl) {
83 	size_t l = bufl;
84 	while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
85 	if (l != (bufl - 1)) {
86 		bufl = l + 1;
87 		buf[bufl] = '\0';
88 	}
89 	return bufl;
90 }
91 
handle_line(int type,zval * array,char * buf,size_t bufl)92 static size_t handle_line(int type, zval *array, char *buf, size_t bufl) {
93 	if (type == 1) {
94 		PHPWRITE(buf, bufl);
95 		if (php_output_get_level() < 1) {
96 			sapi_flush();
97 		}
98 	} else if (type == 2) {
99 		bufl = strip_trailing_whitespace(buf, bufl);
100 		add_next_index_stringl(array, buf, bufl);
101 	}
102 	return bufl;
103 }
104 
105 /* {{{ php_exec
106  * If type==0, only last line of output is returned (exec)
107  * If type==1, all lines will be printed and last lined returned (system)
108  * If type==2, all lines will be saved to given array (exec with &$array)
109  * If type==3, output will be printed binary, no lines will be saved or returned (passthru)
110  *
111  */
php_exec(int type,const char * cmd,zval * array,zval * return_value)112 PHPAPI int php_exec(int type, const char *cmd, zval *array, zval *return_value)
113 {
114 	FILE *fp;
115 	char *buf;
116 	int pclose_return;
117 	char *b, *d=NULL;
118 	php_stream *stream;
119 	size_t buflen, bufl = 0;
120 #if PHP_SIGCHILD
121 	void (*sig_handler)() = NULL;
122 #endif
123 
124 #if PHP_SIGCHILD
125 	sig_handler = signal (SIGCHLD, SIG_DFL);
126 #endif
127 
128 #ifdef PHP_WIN32
129 	fp = VCWD_POPEN(cmd, "rb");
130 #else
131 	fp = VCWD_POPEN(cmd, "r");
132 #endif
133 	if (!fp) {
134 		php_error_docref(NULL, E_WARNING, "Unable to fork [%s]", cmd);
135 		goto err;
136 	}
137 
138 	stream = php_stream_fopen_from_pipe(fp, "rb");
139 
140 	buf = (char *) emalloc(EXEC_INPUT_BUF);
141 	buflen = EXEC_INPUT_BUF;
142 
143 	if (type != 3) {
144 		b = buf;
145 
146 		while (php_stream_get_line(stream, b, EXEC_INPUT_BUF, &bufl)) {
147 			/* no new line found, let's read some more */
148 			if (b[bufl - 1] != '\n' && !php_stream_eof(stream)) {
149 				if (buflen < (bufl + (b - buf) + EXEC_INPUT_BUF)) {
150 					bufl += b - buf;
151 					buflen = bufl + EXEC_INPUT_BUF;
152 					buf = erealloc(buf, buflen);
153 					b = buf + bufl;
154 				} else {
155 					b += bufl;
156 				}
157 				continue;
158 			} else if (b != buf) {
159 				bufl += b - buf;
160 			}
161 
162 			bufl = handle_line(type, array, buf, bufl);
163 			b = buf;
164 		}
165 		if (bufl) {
166 			if (buf != b) {
167 				/* Process remaining output */
168 				bufl = handle_line(type, array, buf, bufl);
169 			}
170 
171 			/* Return last line from the shell command */
172 			bufl = strip_trailing_whitespace(buf, bufl);
173 			RETVAL_STRINGL(buf, bufl);
174 		} else { /* should return NULL, but for BC we return "" */
175 			RETVAL_EMPTY_STRING();
176 		}
177 	} else {
178 		ssize_t read;
179 		while ((read = php_stream_read(stream, buf, EXEC_INPUT_BUF)) > 0) {
180 			PHPWRITE(buf, read);
181 		}
182 	}
183 
184 	pclose_return = php_stream_close(stream);
185 	efree(buf);
186 
187 done:
188 #if PHP_SIGCHILD
189 	if (sig_handler) {
190 		signal(SIGCHLD, sig_handler);
191 	}
192 #endif
193 	if (d) {
194 		efree(d);
195 	}
196 	return pclose_return;
197 err:
198 	pclose_return = -1;
199 	RETVAL_FALSE;
200 	goto done;
201 }
202 /* }}} */
203 
php_exec_ex(INTERNAL_FUNCTION_PARAMETERS,int mode)204 static void php_exec_ex(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
205 {
206 	char *cmd;
207 	size_t cmd_len;
208 	zval *ret_code=NULL, *ret_array=NULL;
209 	int ret;
210 
211 	ZEND_PARSE_PARAMETERS_START(1, (mode ? 2 : 3))
212 		Z_PARAM_STRING(cmd, cmd_len)
213 		Z_PARAM_OPTIONAL
214 		if (!mode) {
215 			Z_PARAM_ZVAL(ret_array)
216 		}
217 		Z_PARAM_ZVAL(ret_code)
218 	ZEND_PARSE_PARAMETERS_END();
219 
220 	if (!cmd_len) {
221 		zend_argument_must_not_be_empty_error(1);
222 		RETURN_THROWS();
223 	}
224 	if (strlen(cmd) != cmd_len) {
225 		zend_argument_value_error(1, "must not contain any null bytes");
226 		RETURN_THROWS();
227 	}
228 
229 	if (!ret_array) {
230 		ret = php_exec(mode, cmd, NULL, return_value);
231 	} else {
232 		if (Z_TYPE_P(Z_REFVAL_P(ret_array)) == IS_ARRAY) {
233 			ZVAL_DEREF(ret_array);
234 			SEPARATE_ARRAY(ret_array);
235 		} else {
236 			ret_array = zend_try_array_init(ret_array);
237 			if (!ret_array) {
238 				RETURN_THROWS();
239 			}
240 		}
241 
242 		ret = php_exec(2, cmd, ret_array, return_value);
243 	}
244 	if (ret_code) {
245 		ZEND_TRY_ASSIGN_REF_LONG(ret_code, ret);
246 	}
247 }
248 /* }}} */
249 
250 /* {{{ Execute an external program */
PHP_FUNCTION(exec)251 PHP_FUNCTION(exec)
252 {
253 	php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
254 }
255 /* }}} */
256 
257 /* {{{ Execute an external program and display output */
PHP_FUNCTION(system)258 PHP_FUNCTION(system)
259 {
260 	php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
261 }
262 /* }}} */
263 
264 /* {{{ Execute an external program and display raw output */
PHP_FUNCTION(passthru)265 PHP_FUNCTION(passthru)
266 {
267 	php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3);
268 }
269 /* }}} */
270 
271 /* {{{ php_escape_shell_cmd
272    Escape all chars that could possibly be used to
273    break out of a shell command
274 
275    This function emalloc's a string and returns the pointer.
276    Remember to efree it when done with it.
277 
278    *NOT* safe for binary strings
279 */
php_escape_shell_cmd(const zend_string * unescaped_cmd)280 PHPAPI zend_string *php_escape_shell_cmd(const zend_string *unescaped_cmd)
281 {
282 	size_t x, y;
283 	zend_string *cmd;
284 #ifndef PHP_WIN32
285 	char *p = NULL;
286 #endif
287 
288 	ZEND_ASSERT(ZSTR_LEN(unescaped_cmd) == strlen(ZSTR_VAL(unescaped_cmd)) && "Must be a binary safe string");
289 	size_t l = ZSTR_LEN(unescaped_cmd);
290 	const char *str = ZSTR_VAL(unescaped_cmd);
291 
292 	uint64_t estimate = (2 * (uint64_t)l) + 1;
293 
294 	/* max command line length - two single quotes - \0 byte length */
295 	if (l > cmd_max_len - 2 - 1) {
296 		zend_value_error("Command exceeds the allowed length of %zu bytes", cmd_max_len);
297 		return ZSTR_EMPTY_ALLOC();
298 	}
299 
300 	cmd = zend_string_safe_alloc(2, l, 0, 0);
301 
302 	for (x = 0, y = 0; x < l; x++) {
303 		int mb_len = php_mblen(str + x, (l - x));
304 
305 		/* skip non-valid multibyte characters */
306 		if (mb_len < 0) {
307 			continue;
308 		} else if (mb_len > 1) {
309 			memcpy(ZSTR_VAL(cmd) + y, str + x, mb_len);
310 			y += mb_len;
311 			x += mb_len - 1;
312 			continue;
313 		}
314 
315 		switch (str[x]) {
316 #ifndef PHP_WIN32
317 			case '"':
318 			case '\'':
319 				if (!p && (p = memchr(str + x + 1, str[x], l - x - 1))) {
320 					/* noop */
321 				} else if (p && *p == str[x]) {
322 					p = NULL;
323 				} else {
324 					ZSTR_VAL(cmd)[y++] = '\\';
325 				}
326 				ZSTR_VAL(cmd)[y++] = str[x];
327 				break;
328 #else
329 			/* % is Windows specific for environmental variables, ^%PATH% will
330 				output PATH while ^%PATH^% will not. escapeshellcmd->val will escape all % and !.
331 			*/
332 			case '%':
333 			case '!':
334 			case '"':
335 			case '\'':
336 #endif
337 			case '#': /* This is character-set independent */
338 			case '&':
339 			case ';':
340 			case '`':
341 			case '|':
342 			case '*':
343 			case '?':
344 			case '~':
345 			case '<':
346 			case '>':
347 			case '^':
348 			case '(':
349 			case ')':
350 			case '[':
351 			case ']':
352 			case '{':
353 			case '}':
354 			case '$':
355 			case '\\':
356 			case '\x0A': /* excluding these two */
357 			case '\xFF':
358 #ifdef PHP_WIN32
359 				ZSTR_VAL(cmd)[y++] = '^';
360 #else
361 				ZSTR_VAL(cmd)[y++] = '\\';
362 #endif
363 				ZEND_FALLTHROUGH;
364 			default:
365 				ZSTR_VAL(cmd)[y++] = str[x];
366 
367 		}
368 	}
369 	ZSTR_VAL(cmd)[y] = '\0';
370 
371 	if (y > cmd_max_len + 1) {
372 		zend_value_error("Escaped command exceeds the allowed length of %zu bytes", cmd_max_len);
373 		zend_string_release_ex(cmd, 0);
374 		return ZSTR_EMPTY_ALLOC();
375 	}
376 
377 	if ((estimate - y) > 4096) {
378 		/* realloc if the estimate was way overill
379 		 * Arbitrary cutoff point of 4096 */
380 		cmd = zend_string_truncate(cmd, y, 0);
381 	}
382 
383 	ZSTR_LEN(cmd) = y;
384 
385 	return cmd;
386 }
387 /* }}} */
388 
389 /* {{{ php_escape_shell_arg */
php_escape_shell_arg(const zend_string * unescaped_arg)390 PHPAPI zend_string *php_escape_shell_arg(const zend_string *unescaped_arg)
391 {
392 	size_t x, y = 0;
393 	zend_string *cmd;
394 
395 	ZEND_ASSERT(ZSTR_LEN(unescaped_arg) == strlen(ZSTR_VAL(unescaped_arg)) && "Must be a binary safe string");
396 	size_t l = ZSTR_LEN(unescaped_arg);
397 	const char *str = ZSTR_VAL(unescaped_arg);
398 
399 	uint64_t estimate = (4 * (uint64_t)l) + 3;
400 
401 	/* max command line length - two single quotes - \0 byte length */
402 	if (l > cmd_max_len - 2 - 1) {
403 		zend_value_error("Argument exceeds the allowed length of %zu bytes", cmd_max_len);
404 		return ZSTR_EMPTY_ALLOC();
405 	}
406 
407 	cmd = zend_string_safe_alloc(4, l, 2, 0); /* worst case */
408 
409 #ifdef PHP_WIN32
410 	ZSTR_VAL(cmd)[y++] = '"';
411 #else
412 	ZSTR_VAL(cmd)[y++] = '\'';
413 #endif
414 
415 	for (x = 0; x < l; x++) {
416 		int mb_len = php_mblen(str + x, (l - x));
417 
418 		/* skip non-valid multibyte characters */
419 		if (mb_len < 0) {
420 			continue;
421 		} else if (mb_len > 1) {
422 			memcpy(ZSTR_VAL(cmd) + y, str + x, mb_len);
423 			y += mb_len;
424 			x += mb_len - 1;
425 			continue;
426 		}
427 
428 		switch (str[x]) {
429 #ifdef PHP_WIN32
430 		case '"':
431 		case '%':
432 		case '!':
433 			ZSTR_VAL(cmd)[y++] = ' ';
434 			break;
435 #else
436 		case '\'':
437 			ZSTR_VAL(cmd)[y++] = '\'';
438 			ZSTR_VAL(cmd)[y++] = '\\';
439 			ZSTR_VAL(cmd)[y++] = '\'';
440 #endif
441 			ZEND_FALLTHROUGH;
442 		default:
443 			ZSTR_VAL(cmd)[y++] = str[x];
444 		}
445 	}
446 #ifdef PHP_WIN32
447 	if (y > 0 && '\\' == ZSTR_VAL(cmd)[y - 1]) {
448 		int k = 0, n = y - 1;
449 		for (; n >= 0 && '\\' == ZSTR_VAL(cmd)[n]; n--, k++);
450 		if (k % 2) {
451 			ZSTR_VAL(cmd)[y++] = '\\';
452 		}
453 	}
454 
455 	ZSTR_VAL(cmd)[y++] = '"';
456 #else
457 	ZSTR_VAL(cmd)[y++] = '\'';
458 #endif
459 	ZSTR_VAL(cmd)[y] = '\0';
460 
461 	if (y > cmd_max_len + 1) {
462 		zend_value_error("Escaped argument exceeds the allowed length of %zu bytes", cmd_max_len);
463 		zend_string_release_ex(cmd, 0);
464 		return ZSTR_EMPTY_ALLOC();
465 	}
466 
467 	if ((estimate - y) > 4096) {
468 		/* realloc if the estimate was way overill
469 		 * Arbitrary cutoff point of 4096 */
470 		cmd = zend_string_truncate(cmd, y, 0);
471 	}
472 	ZSTR_LEN(cmd) = y;
473 	return cmd;
474 }
475 /* }}} */
476 
477 /* {{{ Escape shell metacharacters */
PHP_FUNCTION(escapeshellcmd)478 PHP_FUNCTION(escapeshellcmd)
479 {
480 	zend_string *command;
481 
482 	ZEND_PARSE_PARAMETERS_START(1, 1)
483 		Z_PARAM_PATH_STR(command)
484 	ZEND_PARSE_PARAMETERS_END();
485 
486 	if (ZSTR_LEN(command)) {
487 		RETVAL_STR(php_escape_shell_cmd(command));
488 	} else {
489 		RETVAL_EMPTY_STRING();
490 	}
491 }
492 /* }}} */
493 
494 /* {{{ Quote and escape an argument for use in a shell command */
PHP_FUNCTION(escapeshellarg)495 PHP_FUNCTION(escapeshellarg)
496 {
497 	zend_string *argument;
498 
499 	ZEND_PARSE_PARAMETERS_START(1, 1)
500 		Z_PARAM_PATH_STR(argument)
501 	ZEND_PARSE_PARAMETERS_END();
502 
503 	RETVAL_STR(php_escape_shell_arg(argument));
504 }
505 /* }}} */
506 
507 /* {{{ Execute command via shell and return complete output as string */
PHP_FUNCTION(shell_exec)508 PHP_FUNCTION(shell_exec)
509 {
510 	FILE *in;
511 	char *command;
512 	size_t command_len;
513 	zend_string *ret;
514 	php_stream *stream;
515 
516 	ZEND_PARSE_PARAMETERS_START(1, 1)
517 		Z_PARAM_PATH(command, command_len)
518 	ZEND_PARSE_PARAMETERS_END();
519 
520 	if (!command_len) {
521 		zend_argument_must_not_be_empty_error(1);
522 		RETURN_THROWS();
523 	}
524 
525 #ifdef PHP_WIN32
526 	if ((in=VCWD_POPEN(command, "rt"))==NULL) {
527 #else
528 	if ((in=VCWD_POPEN(command, "r"))==NULL) {
529 #endif
530 		php_error_docref(NULL, E_WARNING, "Unable to execute '%s'", command);
531 		RETURN_FALSE;
532 	}
533 
534 	stream = php_stream_fopen_from_pipe(in, "rb");
535 	ret = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0);
536 	php_stream_close(stream);
537 
538 	if (ret && ZSTR_LEN(ret) > 0) {
539 		RETVAL_STR(ret);
540 	}
541 }
542 /* }}} */
543 
544 #ifdef HAVE_NICE
545 /* {{{ Change the priority of the current process */
546 PHP_FUNCTION(proc_nice)
547 {
548 	zend_long pri;
549 
550 	ZEND_PARSE_PARAMETERS_START(1, 1)
551 		Z_PARAM_LONG(pri)
552 	ZEND_PARSE_PARAMETERS_END();
553 
554 	errno = 0;
555 	php_ignore_value(nice(pri));
556 	if (errno) {
557 #ifdef PHP_WIN32
558 		char *err = php_win_err();
559 		php_error_docref(NULL, E_WARNING, "%s", err);
560 		php_win_err_free(err);
561 #else
562 		php_error_docref(NULL, E_WARNING, "Only a super user may attempt to increase the priority of a process");
563 #endif
564 		RETURN_FALSE;
565 	}
566 
567 	RETURN_TRUE;
568 }
569 /* }}} */
570 #endif
571