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