xref: /PHP-8.0/ext/standard/proc_open.c (revision 240d0611)
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    | http://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: Wez Furlong <wez@thebrainroom.com>                           |
14    +----------------------------------------------------------------------+
15  */
16 
17 #include "php.h"
18 #include <stdio.h>
19 #include <ctype.h>
20 #include <signal.h>
21 #include "php_string.h"
22 #include "ext/standard/head.h"
23 #include "ext/standard/basic_functions.h"
24 #include "ext/standard/file.h"
25 #include "exec.h"
26 #include "php_globals.h"
27 #include "SAPI.h"
28 #include "main/php_network.h"
29 #include "zend_smart_string.h"
30 
31 #if HAVE_SYS_WAIT_H
32 #include <sys/wait.h>
33 #endif
34 
35 #if HAVE_FCNTL_H
36 #include <fcntl.h>
37 #endif
38 
39 /* This symbol is defined in ext/standard/config.m4.
40  * Essentially, it is set if you HAVE_FORK || PHP_WIN32
41  * Other platforms may modify that configure check and add suitable #ifdefs
42  * around the alternate code. */
43 #ifdef PHP_CAN_SUPPORT_PROC_OPEN
44 
45 #if HAVE_OPENPTY
46 # if HAVE_PTY_H
47 #  include <pty.h>
48 # elif defined(__FreeBSD__)
49 /* FreeBSD defines `openpty` in <libutil.h> */
50 #  include <libutil.h>
51 # elif defined(__NetBSD__) || defined(__DragonFly__)
52 /* On recent NetBSD/DragonFlyBSD releases the emalloc, estrdup ... calls had been introduced in libutil */
53 #  if defined(__NetBSD__)
54 #    include <sys/termios.h>
55 #  else
56 #    include <termios.h>
57 #  endif
58 extern int openpty(int *, int *, char *, struct termios *, struct winsize *);
59 # elif defined(__sun)
60 #    include <termios.h>
61 # else
62 /* Mac OS X (and some BSDs) define `openpty` in <util.h> */
63 #  include <util.h>
64 # endif
65 #elif defined(__sun)
66 # include <fcntl.h>
67 # include <stropts.h>
68 # include <termios.h>
69 # define HAVE_OPENPTY 1
70 
71 /* Solaris before version 11.4 and Illumos do not have any openpty implementation */
openpty(int * master,int * slave,char * name,struct termios * termp,struct winsize * winp)72 int openpty(int *master, int *slave, char *name, struct termios *termp, struct winsize *winp)
73 {
74 	int fd, sd;
75 	const char *slaveid;
76 
77 	assert(master);
78 	assert(slave);
79 
80 	sd = *master = *slave = -1;
81 	fd = open("/dev/ptmx", O_NOCTTY|O_RDWR);
82 	if (fd == -1) {
83 		return -1;
84 	}
85 	/* Checking if we can have to the pseudo terminal */
86 	if (grantpt(fd) != 0 || unlockpt(fd) != 0) {
87 		goto fail;
88 	}
89 	slaveid = ptsname(fd);
90 	if (!slaveid) {
91 		goto fail;
92 	}
93 
94 	/* Getting the slave path and pushing pseudo terminal */
95 	sd = open(slaveid, O_NOCTTY|O_RDONLY);
96 	if (sd == -1 || ioctl(sd, I_PUSH, "ptem") == -1) {
97 		goto fail;
98 	}
99 	if (termp) {
100 		if (tcgetattr(sd, termp) < 0) {
101 			goto fail;
102 		}
103 	}
104 	if (winp) {
105 		if (ioctl(sd, TIOCSWINSZ, winp) == -1) {
106 			goto fail;
107 		}
108 	}
109 
110 	*slave = sd;
111 	*master = fd;
112 	return 0;
113 fail:
114 	if (sd != -1) {
115 		close(sd);
116 	}
117 	if (fd != -1) {
118 		close(fd);
119 	}
120 	return -1;
121 }
122 #endif
123 
124 #include "proc_open.h"
125 
126 static int le_proc_open; /* Resource number for `proc` resources */
127 
128 /* {{{ _php_array_to_envp
129  * Process the `environment` argument to `proc_open`
130  * Convert into data structures which can be passed to underlying OS APIs like `exec` on POSIX or
131  * `CreateProcessW` on Win32 */
_php_array_to_envp(zval * environment)132 static php_process_env _php_array_to_envp(zval *environment)
133 {
134 	zval *element;
135 	php_process_env env;
136 	zend_string *key, *str;
137 #ifndef PHP_WIN32
138 	char **ep;
139 #endif
140 	char *p;
141 	size_t sizeenv = 0;
142 	HashTable *env_hash; /* temporary PHP array used as helper */
143 
144 	memset(&env, 0, sizeof(env));
145 
146 	if (!environment) {
147 		return env;
148 	}
149 
150 	uint32_t cnt = zend_hash_num_elements(Z_ARRVAL_P(environment));
151 
152 	if (cnt < 1) {
153 #ifndef PHP_WIN32
154 		env.envarray = (char **) ecalloc(1, sizeof(char *));
155 #endif
156 		env.envp = (char *) ecalloc(4, 1);
157 		return env;
158 	}
159 
160 	ALLOC_HASHTABLE(env_hash);
161 	zend_hash_init(env_hash, cnt, NULL, NULL, 0);
162 
163 	/* first, we have to get the size of all the elements in the hash */
164 	ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(environment), key, element) {
165 		str = zval_get_string(element);
166 
167 		if (ZSTR_LEN(str) == 0) {
168 			zend_string_release_ex(str, 0);
169 			continue;
170 		}
171 
172 		sizeenv += ZSTR_LEN(str) + 1;
173 
174 		if (key && ZSTR_LEN(key)) {
175 			sizeenv += ZSTR_LEN(key) + 1;
176 			zend_hash_add_ptr(env_hash, key, str);
177 		} else {
178 			zend_hash_next_index_insert_ptr(env_hash, str);
179 		}
180 	} ZEND_HASH_FOREACH_END();
181 
182 #ifndef PHP_WIN32
183 	ep = env.envarray = (char **) ecalloc(cnt + 1, sizeof(char *));
184 #endif
185 	p = env.envp = (char *) ecalloc(sizeenv + 4, 1);
186 
187 	ZEND_HASH_FOREACH_STR_KEY_PTR(env_hash, key, str) {
188 #ifndef PHP_WIN32
189 		*ep = p;
190 		++ep;
191 #endif
192 
193 		if (key) {
194 			memcpy(p, ZSTR_VAL(key), ZSTR_LEN(key));
195 			p += ZSTR_LEN(key);
196 			*p++ = '=';
197 		}
198 
199 		memcpy(p, ZSTR_VAL(str), ZSTR_LEN(str));
200 		p += ZSTR_LEN(str);
201 		*p++ = '\0';
202 		zend_string_release_ex(str, 0);
203 	} ZEND_HASH_FOREACH_END();
204 
205 	assert((uint32_t)(p - env.envp) <= sizeenv);
206 
207 	zend_hash_destroy(env_hash);
208 	FREE_HASHTABLE(env_hash);
209 
210 	return env;
211 }
212 /* }}} */
213 
214 /* {{{ _php_free_envp
215  * Free the structures allocated by `_php_array_to_envp` */
_php_free_envp(php_process_env env)216 static void _php_free_envp(php_process_env env)
217 {
218 #ifndef PHP_WIN32
219 	if (env.envarray) {
220 		efree(env.envarray);
221 	}
222 #endif
223 	if (env.envp) {
224 		efree(env.envp);
225 	}
226 }
227 /* }}} */
228 
229 /* {{{ proc_open_rsrc_dtor
230  * Free `proc` resource, either because all references to it were dropped or because `pclose` or
231  * `proc_close` were called */
proc_open_rsrc_dtor(zend_resource * rsrc)232 static void proc_open_rsrc_dtor(zend_resource *rsrc)
233 {
234 	php_process_handle *proc = (php_process_handle*)rsrc->ptr;
235 #ifdef PHP_WIN32
236 	DWORD wstatus;
237 #elif HAVE_SYS_WAIT_H
238 	int wstatus;
239 	int waitpid_options = 0;
240 	pid_t wait_pid;
241 #endif
242 
243 	/* Close all handles to avoid a deadlock */
244 	for (int i = 0; i < proc->npipes; i++) {
245 		if (proc->pipes[i] != NULL) {
246 			GC_DELREF(proc->pipes[i]);
247 			zend_list_close(proc->pipes[i]);
248 			proc->pipes[i] = NULL;
249 		}
250 	}
251 
252 	/* `pclose_wait` tells us: Are we freeing this resource because `pclose` or `proc_close` were
253 	 * called? If so, we need to wait until the child process exits, because its exit code is
254 	 * needed as the return value of those functions.
255 	 * But if we're freeing the resource because of GC, don't wait. */
256 #ifdef PHP_WIN32
257 	if (FG(pclose_wait)) {
258 		WaitForSingleObject(proc->childHandle, INFINITE);
259 	}
260 	GetExitCodeProcess(proc->childHandle, &wstatus);
261 	if (wstatus == STILL_ACTIVE) {
262 		FG(pclose_ret) = -1;
263 	} else {
264 		FG(pclose_ret) = wstatus;
265 	}
266 	CloseHandle(proc->childHandle);
267 
268 #elif HAVE_SYS_WAIT_H
269 	if (!FG(pclose_wait)) {
270 		waitpid_options = WNOHANG;
271 	}
272 	do {
273 		wait_pid = waitpid(proc->child, &wstatus, waitpid_options);
274 	} while (wait_pid == -1 && errno == EINTR);
275 
276 	if (wait_pid <= 0) {
277 		FG(pclose_ret) = -1;
278 	} else {
279 		if (WIFEXITED(wstatus)) {
280 			wstatus = WEXITSTATUS(wstatus);
281 		}
282 		FG(pclose_ret) = wstatus;
283 	}
284 
285 #else
286 	FG(pclose_ret) = -1;
287 #endif
288 
289 	_php_free_envp(proc->env);
290 	efree(proc->pipes);
291 	efree(proc->command);
292 	efree(proc);
293 }
294 /* }}} */
295 
296 /* {{{ PHP_MINIT_FUNCTION(proc_open) */
PHP_MINIT_FUNCTION(proc_open)297 PHP_MINIT_FUNCTION(proc_open)
298 {
299 	le_proc_open = zend_register_list_destructors_ex(proc_open_rsrc_dtor, NULL, "process",
300 		module_number);
301 	return SUCCESS;
302 }
303 /* }}} */
304 
305 /* {{{ Kill a process opened by `proc_open` */
PHP_FUNCTION(proc_terminate)306 PHP_FUNCTION(proc_terminate)
307 {
308 	zval *zproc;
309 	php_process_handle *proc;
310 	zend_long sig_no = SIGTERM;
311 
312 	ZEND_PARSE_PARAMETERS_START(1, 2)
313 		Z_PARAM_RESOURCE(zproc)
314 		Z_PARAM_OPTIONAL
315 		Z_PARAM_LONG(sig_no)
316 	ZEND_PARSE_PARAMETERS_END();
317 
318 	proc = (php_process_handle*)zend_fetch_resource(Z_RES_P(zproc), "process", le_proc_open);
319 	if (proc == NULL) {
320 		RETURN_THROWS();
321 	}
322 
323 #ifdef PHP_WIN32
324 	RETURN_BOOL(TerminateProcess(proc->childHandle, 255));
325 #else
326 	RETURN_BOOL(kill(proc->child, sig_no) == 0);
327 #endif
328 }
329 /* }}} */
330 
331 /* {{{ Close a process opened by `proc_open` */
PHP_FUNCTION(proc_close)332 PHP_FUNCTION(proc_close)
333 {
334 	zval *zproc;
335 	php_process_handle *proc;
336 
337 	ZEND_PARSE_PARAMETERS_START(1, 1)
338 		Z_PARAM_RESOURCE(zproc)
339 	ZEND_PARSE_PARAMETERS_END();
340 
341 	proc = (php_process_handle*)zend_fetch_resource(Z_RES_P(zproc), "process", le_proc_open);
342 	if (proc == NULL) {
343 		RETURN_THROWS();
344 	}
345 
346 	FG(pclose_wait) = 1; /* See comment in `proc_open_rsrc_dtor` */
347 	zend_list_close(Z_RES_P(zproc));
348 	FG(pclose_wait) = 0;
349 	RETURN_LONG(FG(pclose_ret));
350 }
351 /* }}} */
352 
353 /* {{{ Get information about a process opened by `proc_open` */
PHP_FUNCTION(proc_get_status)354 PHP_FUNCTION(proc_get_status)
355 {
356 	zval *zproc;
357 	php_process_handle *proc;
358 #ifdef PHP_WIN32
359 	DWORD wstatus;
360 #elif HAVE_SYS_WAIT_H
361 	int wstatus;
362 	pid_t wait_pid;
363 #endif
364 	int running = 1, signaled = 0, stopped = 0;
365 	int exitcode = -1, termsig = 0, stopsig = 0;
366 
367 	ZEND_PARSE_PARAMETERS_START(1, 1)
368 		Z_PARAM_RESOURCE(zproc)
369 	ZEND_PARSE_PARAMETERS_END();
370 
371 	proc = (php_process_handle*)zend_fetch_resource(Z_RES_P(zproc), "process", le_proc_open);
372 	if (proc == NULL) {
373 		RETURN_THROWS();
374 	}
375 
376 	array_init(return_value);
377 	add_assoc_string(return_value, "command", proc->command);
378 	add_assoc_long(return_value, "pid", (zend_long)proc->child);
379 
380 #ifdef PHP_WIN32
381 	GetExitCodeProcess(proc->childHandle, &wstatus);
382 	running = wstatus == STILL_ACTIVE;
383 	exitcode = running ? -1 : wstatus;
384 
385 #elif HAVE_SYS_WAIT_H
386 	wait_pid = waitpid(proc->child, &wstatus, WNOHANG|WUNTRACED);
387 
388 	if (wait_pid == proc->child) {
389 		if (WIFEXITED(wstatus)) {
390 			running = 0;
391 			exitcode = WEXITSTATUS(wstatus);
392 		}
393 		if (WIFSIGNALED(wstatus)) {
394 			running = 0;
395 			signaled = 1;
396 			termsig = WTERMSIG(wstatus);
397 		}
398 		if (WIFSTOPPED(wstatus)) {
399 			stopped = 1;
400 			stopsig = WSTOPSIG(wstatus);
401 		}
402 	} else if (wait_pid == -1) {
403 		/* The only error which could occur here is ECHILD, which means that the PID we were
404 		 * looking for either does not exist or is not a child of this process */
405 		running = 0;
406 	}
407 #endif
408 
409 	add_assoc_bool(return_value, "running", running);
410 	add_assoc_bool(return_value, "signaled", signaled);
411 	add_assoc_bool(return_value, "stopped", stopped);
412 	add_assoc_long(return_value, "exitcode", exitcode);
413 	add_assoc_long(return_value, "termsig", termsig);
414 	add_assoc_long(return_value, "stopsig", stopsig);
415 }
416 /* }}} */
417 
418 #ifdef PHP_WIN32
419 
420 /* We use this to allow child processes to inherit handles
421  * One static instance can be shared and used for all calls to `proc_open`, since the values are
422  * never changed */
423 SECURITY_ATTRIBUTES php_proc_open_security = {
424 	.nLength = sizeof(SECURITY_ATTRIBUTES),
425 	.lpSecurityDescriptor = NULL,
426 	.bInheritHandle = TRUE
427 };
428 
429 # define pipe(pair)		(CreatePipe(&pair[0], &pair[1], &php_proc_open_security, 0) ? 0 : -1)
430 
431 # define COMSPEC_NT	"cmd.exe"
432 
dup_handle(HANDLE src,BOOL inherit,BOOL closeorig)433 static inline HANDLE dup_handle(HANDLE src, BOOL inherit, BOOL closeorig)
434 {
435 	HANDLE copy, self = GetCurrentProcess();
436 
437 	if (!DuplicateHandle(self, src, self, &copy, 0, inherit, DUPLICATE_SAME_ACCESS |
438 				(closeorig ? DUPLICATE_CLOSE_SOURCE : 0)))
439 		return NULL;
440 	return copy;
441 }
442 
dup_fd_as_handle(int fd)443 static inline HANDLE dup_fd_as_handle(int fd)
444 {
445 	return dup_handle((HANDLE)_get_osfhandle(fd), TRUE, FALSE);
446 }
447 
448 # define close_descriptor(fd)	CloseHandle(fd)
449 #else /* !PHP_WIN32 */
450 # define close_descriptor(fd)	close(fd)
451 #endif
452 
453 /* Determines the type of a descriptor item. */
454 typedef enum _descriptor_type {
455 	DESCRIPTOR_TYPE_STD,
456 	DESCRIPTOR_TYPE_PIPE,
457 	DESCRIPTOR_TYPE_SOCKET
458 } descriptor_type;
459 
460 /* One instance of this struct is created for each item in `$descriptorspec` argument to `proc_open`
461  * They are used within `proc_open` and freed before it returns */
462 typedef struct _descriptorspec_item {
463 	int index;                       /* desired FD # in child process */
464 	descriptor_type type;
465 	php_file_descriptor_t childend;  /* FD # opened for use in child
466 	                                  * (will be copied to `index` in child) */
467 	php_file_descriptor_t parentend; /* FD # opened for use in parent
468 	                                  * (for pipes only; will be 0 otherwise) */
469 	int mode_flags;                  /* mode for opening FDs: r/o, r/w, binary (on Win32), etc */
470 } descriptorspec_item;
471 
get_valid_arg_string(zval * zv,int elem_num)472 static zend_string *get_valid_arg_string(zval *zv, int elem_num) {
473 	zend_string *str = zval_get_string(zv);
474 	if (!str) {
475 		return NULL;
476 	}
477 
478 	if (strlen(ZSTR_VAL(str)) != ZSTR_LEN(str)) {
479 		zend_value_error("Command array element %d contains a null byte", elem_num);
480 		zend_string_release(str);
481 		return NULL;
482 	}
483 
484 	return str;
485 }
486 
487 #ifdef PHP_WIN32
append_backslashes(smart_string * str,size_t num_bs)488 static void append_backslashes(smart_string *str, size_t num_bs)
489 {
490 	for (size_t i = 0; i < num_bs; i++) {
491 		smart_string_appendc(str, '\\');
492 	}
493 }
494 
495 /* See https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments */
append_win_escaped_arg(smart_string * str,char * arg)496 static void append_win_escaped_arg(smart_string *str, char *arg)
497 {
498 	char c;
499 	size_t num_bs = 0;
500 	smart_string_appendc(str, '"');
501 	while ((c = *arg)) {
502 		if (c == '\\') {
503 			num_bs++;
504 		} else {
505 			if (c == '"') {
506 				/* Backslashes before " need to be doubled. */
507 				num_bs = num_bs * 2 + 1;
508 			}
509 			append_backslashes(str, num_bs);
510 			smart_string_appendc(str, c);
511 			num_bs = 0;
512 		}
513 		arg++;
514 	}
515 	append_backslashes(str, num_bs * 2);
516 	smart_string_appendc(str, '"');
517 }
518 
create_win_command_from_args(HashTable * args)519 static char *create_win_command_from_args(HashTable *args)
520 {
521 	smart_string str = {0};
522 	zval *arg_zv;
523 	zend_bool is_prog_name = 1;
524 	int elem_num = 0;
525 
526 	ZEND_HASH_FOREACH_VAL(args, arg_zv) {
527 		zend_string *arg_str = get_valid_arg_string(arg_zv, ++elem_num);
528 		if (!arg_str) {
529 			smart_string_free(&str);
530 			return NULL;
531 		}
532 
533 		if (!is_prog_name) {
534 			smart_string_appendc(&str, ' ');
535 		}
536 
537 		append_win_escaped_arg(&str, ZSTR_VAL(arg_str));
538 
539 		is_prog_name = 0;
540 		zend_string_release(arg_str);
541 	} ZEND_HASH_FOREACH_END();
542 	smart_string_0(&str);
543 	return str.c;
544 }
545 
546 /* Get a boolean option from the `other_options` array which can be passed to `proc_open`.
547  * (Currently, all options apply on Windows only.) */
get_option(zval * other_options,char * opt_name)548 static int get_option(zval *other_options, char *opt_name)
549 {
550 	HashTable *opt_ary = Z_ARRVAL_P(other_options);
551 	zval *item = zend_hash_str_find_deref(opt_ary, opt_name, strlen(opt_name));
552 	return item != NULL &&
553 		(Z_TYPE_P(item) == IS_TRUE ||
554 		((Z_TYPE_P(item) == IS_LONG) && Z_LVAL_P(item)));
555 }
556 
557 /* Initialize STARTUPINFOW struct, used on Windows when spawning a process.
558  * Ref: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfow */
init_startup_info(STARTUPINFOW * si,descriptorspec_item * descriptors,int ndesc)559 static void init_startup_info(STARTUPINFOW *si, descriptorspec_item *descriptors, int ndesc)
560 {
561 	memset(si, 0, sizeof(STARTUPINFOW));
562 	si->cb = sizeof(STARTUPINFOW);
563 	si->dwFlags = STARTF_USESTDHANDLES;
564 
565 	si->hStdInput  = GetStdHandle(STD_INPUT_HANDLE);
566 	si->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
567 	si->hStdError  = GetStdHandle(STD_ERROR_HANDLE);
568 
569 	/* redirect stdin/stdout/stderr if requested */
570 	for (int i = 0; i < ndesc; i++) {
571 		switch (descriptors[i].index) {
572 			case 0:
573 				si->hStdInput = descriptors[i].childend;
574 				break;
575 			case 1:
576 				si->hStdOutput = descriptors[i].childend;
577 				break;
578 			case 2:
579 				si->hStdError = descriptors[i].childend;
580 				break;
581 		}
582 	}
583 }
584 
init_process_info(PROCESS_INFORMATION * pi)585 static void init_process_info(PROCESS_INFORMATION *pi)
586 {
587 	memset(&pi, 0, sizeof(pi));
588 }
589 
convert_command_to_use_shell(wchar_t ** cmdw,size_t cmdw_len)590 static int convert_command_to_use_shell(wchar_t **cmdw, size_t cmdw_len)
591 {
592 	size_t len = sizeof(COMSPEC_NT) + sizeof(" /s /c ") + cmdw_len + 3;
593 	wchar_t *cmdw_shell = (wchar_t *)malloc(len * sizeof(wchar_t));
594 
595 	if (cmdw_shell == NULL) {
596 		php_error_docref(NULL, E_WARNING, "Command conversion failed");
597 		return FAILURE;
598 	}
599 
600 	if (_snwprintf(cmdw_shell, len, L"%hs /s /c \"%s\"", COMSPEC_NT, *cmdw) == -1) {
601 		free(cmdw_shell);
602 		php_error_docref(NULL, E_WARNING, "Command conversion failed");
603 		return FAILURE;
604 	}
605 
606 	free(*cmdw);
607 	*cmdw = cmdw_shell;
608 
609 	return SUCCESS;
610 }
611 #endif
612 
613 /* Convert command parameter array passed as first argument to `proc_open` into command string */
get_command_from_array(HashTable * array,char *** argv,int num_elems)614 static char* get_command_from_array(HashTable *array, char ***argv, int num_elems)
615 {
616 	zval *arg_zv;
617 	char *command = NULL;
618 	int i = 0;
619 
620 	*argv = safe_emalloc(sizeof(char *), num_elems + 1, 0);
621 
622 	ZEND_HASH_FOREACH_VAL(array, arg_zv) {
623 		zend_string *arg_str = get_valid_arg_string(arg_zv, i + 1);
624 		if (!arg_str) {
625 			/* Terminate with NULL so exit_fail code knows how many entries to free */
626 			(*argv)[i] = NULL;
627 			if (command != NULL) {
628 				efree(command);
629 			}
630 			return NULL;
631 		}
632 
633 		if (i == 0) {
634 			command = estrdup(ZSTR_VAL(arg_str));
635 		}
636 
637 		(*argv)[i++] = estrdup(ZSTR_VAL(arg_str));
638 		zend_string_release(arg_str);
639 	} ZEND_HASH_FOREACH_END();
640 
641 	(*argv)[i] = NULL;
642 	return command;
643 }
644 
alloc_descriptor_array(zval * descriptorspec)645 static descriptorspec_item* alloc_descriptor_array(zval *descriptorspec)
646 {
647 	int ndescriptors = zend_hash_num_elements(Z_ARRVAL_P(descriptorspec));
648 	return ecalloc(sizeof(descriptorspec_item), ndescriptors);
649 }
650 
get_string_parameter(zval * array,int index,char * param_name)651 static zend_string* get_string_parameter(zval *array, int index, char *param_name)
652 {
653 	zval *array_item;
654 	if ((array_item = zend_hash_index_find(Z_ARRVAL_P(array), index)) == NULL) {
655 		zend_value_error("Missing %s", param_name);
656 		return NULL;
657 	}
658 	return zval_try_get_string(array_item);
659 }
660 
set_proc_descriptor_to_blackhole(descriptorspec_item * desc)661 static int set_proc_descriptor_to_blackhole(descriptorspec_item *desc)
662 {
663 #ifdef PHP_WIN32
664 	desc->childend = CreateFileA("nul", GENERIC_READ | GENERIC_WRITE,
665 		FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
666 	if (desc->childend == NULL) {
667 		php_error_docref(NULL, E_WARNING, "Failed to open nul");
668 		return FAILURE;
669 	}
670 #else
671 	desc->childend = open("/dev/null", O_RDWR);
672 	if (desc->childend < 0) {
673 		php_error_docref(NULL, E_WARNING, "Failed to open /dev/null: %s", strerror(errno));
674 		return FAILURE;
675 	}
676 #endif
677 	return SUCCESS;
678 }
679 
set_proc_descriptor_to_pty(descriptorspec_item * desc,int * master_fd,int * slave_fd)680 static int set_proc_descriptor_to_pty(descriptorspec_item *desc, int *master_fd, int *slave_fd)
681 {
682 #if HAVE_OPENPTY
683 	/* All FDs set to PTY in the child process will go to the slave end of the same PTY.
684 	 * Likewise, all the corresponding entries in `$pipes` in the parent will all go to the master
685 	 * end of the same PTY.
686 	 * If this is the first descriptorspec set to 'pty', find an available PTY and get master and
687 	 * slave FDs. */
688 	if (*master_fd == -1) {
689 		if (openpty(master_fd, slave_fd, NULL, NULL, NULL)) {
690 			php_error_docref(NULL, E_WARNING, "Could not open PTY (pseudoterminal): %s", strerror(errno));
691 			return FAILURE;
692 		}
693 	}
694 
695 	desc->type       = DESCRIPTOR_TYPE_PIPE;
696 	desc->childend   = dup(*slave_fd);
697 	desc->parentend  = dup(*master_fd);
698 	desc->mode_flags = O_RDWR;
699 	return SUCCESS;
700 #else
701 	php_error_docref(NULL, E_WARNING, "PTY (pseudoterminal) not supported on this system");
702 	return FAILURE;
703 #endif
704 }
705 
706 /* Mark the descriptor close-on-exec, so it won't be inherited by children */
make_descriptor_cloexec(php_file_descriptor_t fd)707 static php_file_descriptor_t make_descriptor_cloexec(php_file_descriptor_t fd)
708 {
709 #ifdef PHP_WIN32
710 	return dup_handle(fd, FALSE, TRUE);
711 #else
712 #if defined(F_SETFD) && defined(FD_CLOEXEC)
713 	fcntl(fd, F_SETFD, FD_CLOEXEC);
714 #endif
715 	return fd;
716 #endif
717 }
718 
set_proc_descriptor_to_pipe(descriptorspec_item * desc,zend_string * zmode)719 static int set_proc_descriptor_to_pipe(descriptorspec_item *desc, zend_string *zmode)
720 {
721 	php_file_descriptor_t newpipe[2];
722 
723 	if (pipe(newpipe)) {
724 		php_error_docref(NULL, E_WARNING, "Unable to create pipe %s", strerror(errno));
725 		return FAILURE;
726 	}
727 
728 	desc->type = DESCRIPTOR_TYPE_PIPE;
729 
730 	if (strncmp(ZSTR_VAL(zmode), "w", 1) != 0) {
731 		desc->parentend = newpipe[1];
732 		desc->childend = newpipe[0];
733 		desc->mode_flags = O_WRONLY;
734 	} else {
735 		desc->parentend = newpipe[0];
736 		desc->childend = newpipe[1];
737 		desc->mode_flags = O_RDONLY;
738 	}
739 
740 	desc->parentend = make_descriptor_cloexec(desc->parentend);
741 
742 #ifdef PHP_WIN32
743 	if (ZSTR_LEN(zmode) >= 2 && ZSTR_VAL(zmode)[1] == 'b')
744 		desc->mode_flags |= O_BINARY;
745 #endif
746 
747 	return SUCCESS;
748 }
749 
750 #ifdef PHP_WIN32
751 #define create_socketpair(socks) socketpair_win32(AF_INET, SOCK_STREAM, 0, (socks), 0)
752 #else
753 #define create_socketpair(socks) socketpair(AF_UNIX, SOCK_STREAM, 0, (socks))
754 #endif
755 
set_proc_descriptor_to_socket(descriptorspec_item * desc)756 static int set_proc_descriptor_to_socket(descriptorspec_item *desc)
757 {
758 	php_socket_t sock[2];
759 
760 	if (create_socketpair(sock)) {
761 		zend_string *err = php_socket_error_str(php_socket_errno());
762 		php_error_docref(NULL, E_WARNING, "Unable to create socket pair: %s", ZSTR_VAL(err));
763 		zend_string_release(err);
764 		return FAILURE;
765 	}
766 
767 	desc->type = DESCRIPTOR_TYPE_SOCKET;
768 	desc->parentend = make_descriptor_cloexec((php_file_descriptor_t) sock[0]);
769 
770 	/* Pass sock[1] to child because it will never use overlapped IO on Windows. */
771 	desc->childend = (php_file_descriptor_t) sock[1];
772 
773 	return SUCCESS;
774 }
775 
set_proc_descriptor_to_file(descriptorspec_item * desc,zend_string * file_path,zend_string * file_mode)776 static int set_proc_descriptor_to_file(descriptorspec_item *desc, zend_string *file_path,
777 	zend_string *file_mode)
778 {
779 	php_socket_t fd;
780 
781 	/* try a wrapper */
782 	php_stream *stream = php_stream_open_wrapper(ZSTR_VAL(file_path), ZSTR_VAL(file_mode),
783 		REPORT_ERRORS|STREAM_WILL_CAST, NULL);
784 	if (stream == NULL) {
785 		return FAILURE;
786 	}
787 
788 	/* force into an fd */
789 	if (php_stream_cast(stream, PHP_STREAM_CAST_RELEASE|PHP_STREAM_AS_FD, (void **)&fd,
790 		REPORT_ERRORS) == FAILURE) {
791 		return FAILURE;
792 	}
793 
794 #ifdef PHP_WIN32
795 	desc->childend = dup_fd_as_handle((int)fd);
796 	_close((int)fd);
797 
798 	/* Simulate the append mode by fseeking to the end of the file
799 	 * This introduces a potential race condition, but it is the best we can do */
800 	if (strchr(ZSTR_VAL(file_mode), 'a')) {
801 		SetFilePointer(desc->childend, 0, NULL, FILE_END);
802 	}
803 #else
804 	desc->childend = fd;
805 #endif
806 	return SUCCESS;
807 }
808 
dup_proc_descriptor(php_file_descriptor_t from,php_file_descriptor_t * to,zend_ulong nindex)809 static int dup_proc_descriptor(php_file_descriptor_t from, php_file_descriptor_t *to,
810 	zend_ulong nindex)
811 {
812 #ifdef PHP_WIN32
813 	*to = dup_handle(from, TRUE, FALSE);
814 	if (*to == NULL) {
815 		php_error_docref(NULL, E_WARNING, "Failed to dup() for descriptor " ZEND_LONG_FMT, nindex);
816 		return FAILURE;
817 	}
818 #else
819 	*to = dup(from);
820 	if (*to < 0) {
821 		php_error_docref(NULL, E_WARNING, "Failed to dup() for descriptor " ZEND_LONG_FMT ": %s",
822 			nindex, strerror(errno));
823 		return FAILURE;
824 	}
825 #endif
826 	return SUCCESS;
827 }
828 
redirect_proc_descriptor(descriptorspec_item * desc,int target,descriptorspec_item * descriptors,int ndesc,int nindex)829 static int redirect_proc_descriptor(descriptorspec_item *desc, int target,
830 	descriptorspec_item *descriptors, int ndesc, int nindex)
831 {
832 	php_file_descriptor_t redirect_to = PHP_INVALID_FD;
833 
834 	for (int i = 0; i < ndesc; i++) {
835 		if (descriptors[i].index == target) {
836 			redirect_to = descriptors[i].childend;
837 			break;
838 		}
839 	}
840 
841 	if (redirect_to == PHP_INVALID_FD) { /* Didn't find the index we wanted */
842 		if (target < 0 || target > 2) {
843 			php_error_docref(NULL, E_WARNING, "Redirection target %d not found", target);
844 			return FAILURE;
845 		}
846 
847 		/* Support referring to a stdin/stdout/stderr pipe adopted from the parent,
848 		 * which happens whenever an explicit override is not provided. */
849 #ifndef PHP_WIN32
850 		redirect_to = target;
851 #else
852 		switch (target) {
853 			case 0: redirect_to = GetStdHandle(STD_INPUT_HANDLE); break;
854 			case 1: redirect_to = GetStdHandle(STD_OUTPUT_HANDLE); break;
855 			case 2: redirect_to = GetStdHandle(STD_ERROR_HANDLE); break;
856 			EMPTY_SWITCH_DEFAULT_CASE()
857 		}
858 #endif
859 	}
860 
861 	return dup_proc_descriptor(redirect_to, &desc->childend, nindex);
862 }
863 
864 /* Process one item from `$descriptorspec` argument to `proc_open` */
set_proc_descriptor_from_array(zval * descitem,descriptorspec_item * descriptors,int ndesc,int nindex,int * pty_master_fd,int * pty_slave_fd)865 static int set_proc_descriptor_from_array(zval *descitem, descriptorspec_item *descriptors,
866 	int ndesc, int nindex, int *pty_master_fd, int *pty_slave_fd) {
867 	zend_string *ztype = get_string_parameter(descitem, 0, "handle qualifier");
868 	if (!ztype) {
869 		return FAILURE;
870 	}
871 
872 	zend_string *zmode = NULL, *zfile = NULL;
873 	int retval = FAILURE;
874 	if (zend_string_equals_literal(ztype, "pipe")) {
875 		/* Set descriptor to pipe */
876 		zmode = get_string_parameter(descitem, 1, "mode parameter for 'pipe'");
877 		if (zmode == NULL) {
878 			goto finish;
879 		}
880 		retval = set_proc_descriptor_to_pipe(&descriptors[ndesc], zmode);
881 	} else if (zend_string_equals_literal(ztype, "socket")) {
882 		/* Set descriptor to socketpair */
883 		retval = set_proc_descriptor_to_socket(&descriptors[ndesc]);
884 	} else if (zend_string_equals_literal(ztype, "file")) {
885 		/* Set descriptor to file */
886 		if ((zfile = get_string_parameter(descitem, 1, "file name parameter for 'file'")) == NULL) {
887 			goto finish;
888 		}
889 		if ((zmode = get_string_parameter(descitem, 2, "mode parameter for 'file'")) == NULL) {
890 			goto finish;
891 		}
892 		retval = set_proc_descriptor_to_file(&descriptors[ndesc], zfile, zmode);
893 	} else if (zend_string_equals_literal(ztype, "redirect")) {
894 		/* Redirect descriptor to whatever another descriptor is set to */
895 		zval *ztarget = zend_hash_index_find_deref(Z_ARRVAL_P(descitem), 1);
896 		if (!ztarget) {
897 			zend_value_error("Missing redirection target");
898 			goto finish;
899 		}
900 		if (Z_TYPE_P(ztarget) != IS_LONG) {
901 			zend_value_error("Redirection target must be of type int, %s given", zend_zval_type_name(ztarget));
902 			goto finish;
903 		}
904 
905 		retval = redirect_proc_descriptor(
906 			&descriptors[ndesc], (int)Z_LVAL_P(ztarget), descriptors, ndesc, nindex);
907 	} else if (zend_string_equals_literal(ztype, "null")) {
908 		/* Set descriptor to blackhole (discard all data written) */
909 		retval = set_proc_descriptor_to_blackhole(&descriptors[ndesc]);
910 	} else if (zend_string_equals_literal(ztype, "pty")) {
911 		/* Set descriptor to slave end of PTY */
912 		retval = set_proc_descriptor_to_pty(&descriptors[ndesc], pty_master_fd, pty_slave_fd);
913 	} else {
914 		php_error_docref(NULL, E_WARNING, "%s is not a valid descriptor spec/mode", ZSTR_VAL(ztype));
915 		goto finish;
916 	}
917 
918 finish:
919 	if (zmode) zend_string_release(zmode);
920 	if (zfile) zend_string_release(zfile);
921 	zend_string_release(ztype);
922 	return retval;
923 }
924 
set_proc_descriptor_from_resource(zval * resource,descriptorspec_item * desc,int nindex)925 static int set_proc_descriptor_from_resource(zval *resource, descriptorspec_item *desc, int nindex)
926 {
927 	/* Should be a stream - try and dup the descriptor */
928 	php_stream *stream = (php_stream*)zend_fetch_resource(Z_RES_P(resource), "stream",
929 		php_file_le_stream());
930 	if (stream == NULL) {
931 		return FAILURE;
932 	}
933 
934 	php_socket_t fd;
935 	int status = php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, REPORT_ERRORS);
936 	if (status == FAILURE) {
937 		return FAILURE;
938 	}
939 
940 #ifdef PHP_WIN32
941 	php_file_descriptor_t fd_t = (php_file_descriptor_t)_get_osfhandle(fd);
942 #else
943 	php_file_descriptor_t fd_t = fd;
944 #endif
945 	if (dup_proc_descriptor(fd_t, &desc->childend, nindex) == FAILURE) {
946 		return FAILURE;
947 	}
948 
949 	return SUCCESS;
950 }
951 
952 #ifndef PHP_WIN32
close_parentends_of_pipes(descriptorspec_item * descriptors,int ndesc)953 static int close_parentends_of_pipes(descriptorspec_item *descriptors, int ndesc)
954 {
955 	/* We are running in child process
956 	 * Close the 'parent end' of pipes which were opened before forking/spawning
957 	 * Also, dup() the child end of all pipes as necessary so they will use the FD
958 	 * number which the user requested */
959 	for (int i = 0; i < ndesc; i++) {
960 		if (descriptors[i].type != DESCRIPTOR_TYPE_STD) {
961 			close(descriptors[i].parentend);
962 		}
963 		if (descriptors[i].childend != descriptors[i].index) {
964 			if (dup2(descriptors[i].childend, descriptors[i].index) < 0) {
965 				php_error_docref(NULL, E_WARNING, "Unable to copy file descriptor %d (for pipe) into " \
966 					"file descriptor %d: %s", descriptors[i].childend, descriptors[i].index, strerror(errno));
967 				return FAILURE;
968 			}
969 			close(descriptors[i].childend);
970 		}
971 	}
972 
973 	return SUCCESS;
974 }
975 #endif
976 
close_all_descriptors(descriptorspec_item * descriptors,int ndesc)977 static void close_all_descriptors(descriptorspec_item *descriptors, int ndesc)
978 {
979 	for (int i = 0; i < ndesc; i++) {
980 		close_descriptor(descriptors[i].childend);
981 		if (descriptors[i].parentend)
982 			close_descriptor(descriptors[i].parentend);
983 	}
984 }
985 
efree_argv(char ** argv)986 static void efree_argv(char **argv)
987 {
988 	if (argv) {
989 		char **arg = argv;
990 		while (*arg != NULL) {
991 			efree(*arg);
992 			arg++;
993 		}
994 		efree(argv);
995 	}
996 }
997 
998 /* {{{ Execute a command, with specified files used for input/output */
PHP_FUNCTION(proc_open)999 PHP_FUNCTION(proc_open)
1000 {
1001 	zend_string *command_str;
1002 	HashTable *command_ht;
1003 	zval *descriptorspec, *pipes;       /* Mandatory arguments */
1004 	char *cwd = NULL;                                /* Optional argument */
1005 	size_t cwd_len = 0;                              /* Optional argument */
1006 	zval *environment = NULL, *other_options = NULL; /* Optional arguments */
1007 
1008 	char *command = NULL;
1009 	php_process_env env;
1010 	int ndesc = 0;
1011 	int i;
1012 	zval *descitem = NULL;
1013 	zend_string *str_index;
1014 	zend_ulong nindex;
1015 	descriptorspec_item *descriptors = NULL;
1016 #ifdef PHP_WIN32
1017 	PROCESS_INFORMATION pi;
1018 	HANDLE childHandle;
1019 	STARTUPINFOW si;
1020 	BOOL newprocok;
1021 	DWORD dwCreateFlags = 0;
1022 	UINT old_error_mode;
1023 	char cur_cwd[MAXPATHLEN];
1024 	wchar_t *cmdw = NULL, *cwdw = NULL, *envpw = NULL;
1025 	size_t cmdw_len;
1026 	int suppress_errors = 0;
1027 	int bypass_shell = 0;
1028 	int blocking_pipes = 0;
1029 	int create_process_group = 0;
1030 	int create_new_console = 0;
1031 #else
1032 	char **argv = NULL;
1033 #endif
1034 	int pty_master_fd = -1, pty_slave_fd = -1;
1035 	php_process_id_t child;
1036 	php_process_handle *proc;
1037 
1038 	ZEND_PARSE_PARAMETERS_START(3, 6)
1039 		Z_PARAM_ARRAY_HT_OR_STR(command_ht, command_str)
1040 		Z_PARAM_ARRAY(descriptorspec)
1041 		Z_PARAM_ZVAL(pipes)
1042 		Z_PARAM_OPTIONAL
1043 		Z_PARAM_STRING_OR_NULL(cwd, cwd_len)
1044 		Z_PARAM_ARRAY_OR_NULL(environment)
1045 		Z_PARAM_ARRAY_OR_NULL(other_options)
1046 	ZEND_PARSE_PARAMETERS_END();
1047 
1048 	memset(&env, 0, sizeof(env));
1049 
1050 	if (command_ht) {
1051 		uint32_t num_elems = zend_hash_num_elements(command_ht);
1052 		if (num_elems == 0) {
1053 			zend_argument_value_error(1, "must have at least one element");
1054 			RETURN_THROWS();
1055 		}
1056 
1057 #ifdef PHP_WIN32
1058 		/* Automatically bypass shell if command is given as an array */
1059 		bypass_shell = 1;
1060 		command = create_win_command_from_args(command_ht);
1061 		if (!command) {
1062 			RETURN_FALSE;
1063 		}
1064 #else
1065 		command = get_command_from_array(command_ht, &argv, num_elems);
1066 		if (command == NULL) {
1067 			goto exit_fail;
1068 		}
1069 #endif
1070 	} else {
1071 		command = estrdup(ZSTR_VAL(command_str));
1072 	}
1073 
1074 #ifdef PHP_WIN32
1075 	if (other_options) {
1076 		suppress_errors      = get_option(other_options, "suppress_errors");
1077 		/* TODO: Deprecate in favor of array command? */
1078 		bypass_shell         = bypass_shell || get_option(other_options, "bypass_shell");
1079 		blocking_pipes       = get_option(other_options, "blocking_pipes");
1080 		create_process_group = get_option(other_options, "create_process_group");
1081 		create_new_console   = get_option(other_options, "create_new_console");
1082 	}
1083 #endif
1084 
1085 	if (environment) {
1086 		env = _php_array_to_envp(environment);
1087 	}
1088 
1089 	descriptors = alloc_descriptor_array(descriptorspec);
1090 
1091 	/* Walk the descriptor spec and set up files/pipes */
1092 	ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(descriptorspec), nindex, str_index, descitem) {
1093 		if (str_index) {
1094 			zend_argument_value_error(2, "must be an integer indexed array");
1095 			goto exit_fail;
1096 		}
1097 
1098 		descriptors[ndesc].index = (int)nindex;
1099 
1100 		if (Z_TYPE_P(descitem) == IS_RESOURCE) {
1101 			if (set_proc_descriptor_from_resource(descitem, &descriptors[ndesc], ndesc) == FAILURE) {
1102 				goto exit_fail;
1103 			}
1104 		} else if (Z_TYPE_P(descitem) == IS_ARRAY) {
1105 			if (set_proc_descriptor_from_array(descitem, descriptors, ndesc, (int)nindex,
1106 				&pty_master_fd, &pty_slave_fd) == FAILURE) {
1107 				goto exit_fail;
1108 			}
1109 		} else {
1110 			zend_argument_value_error(2, "must only contain arrays and streams");
1111 			goto exit_fail;
1112 		}
1113 		ndesc++;
1114 	} ZEND_HASH_FOREACH_END();
1115 
1116 #ifdef PHP_WIN32
1117 	if (cwd == NULL) {
1118 		char *getcwd_result = VCWD_GETCWD(cur_cwd, MAXPATHLEN);
1119 		if (!getcwd_result) {
1120 			php_error_docref(NULL, E_WARNING, "Cannot get current directory");
1121 			goto exit_fail;
1122 		}
1123 		cwd = cur_cwd;
1124 	}
1125 	cwdw = php_win32_cp_any_to_w(cwd);
1126 	if (!cwdw) {
1127 		php_error_docref(NULL, E_WARNING, "CWD conversion failed");
1128 		goto exit_fail;
1129 	}
1130 
1131 	init_startup_info(&si, descriptors, ndesc);
1132 	init_process_info(&pi);
1133 
1134 	if (suppress_errors) {
1135 		old_error_mode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
1136 	}
1137 
1138 	dwCreateFlags = NORMAL_PRIORITY_CLASS;
1139 	if(strcmp(sapi_module.name, "cli") != 0) {
1140 		dwCreateFlags |= CREATE_NO_WINDOW;
1141 	}
1142 	if (create_process_group) {
1143 		dwCreateFlags |= CREATE_NEW_PROCESS_GROUP;
1144 	}
1145 	if (create_new_console) {
1146 		dwCreateFlags |= CREATE_NEW_CONSOLE;
1147 	}
1148 	envpw = php_win32_cp_env_any_to_w(env.envp);
1149 	if (envpw) {
1150 		dwCreateFlags |= CREATE_UNICODE_ENVIRONMENT;
1151 	} else  {
1152 		if (env.envp) {
1153 			php_error_docref(NULL, E_WARNING, "ENV conversion failed");
1154 			goto exit_fail;
1155 		}
1156 	}
1157 
1158 	cmdw = php_win32_cp_conv_any_to_w(command, strlen(command), &cmdw_len);
1159 	if (!cmdw) {
1160 		php_error_docref(NULL, E_WARNING, "Command conversion failed");
1161 		goto exit_fail;
1162 	}
1163 
1164 	if (!bypass_shell) {
1165 		if (convert_command_to_use_shell(&cmdw, cmdw_len) == FAILURE) {
1166 			goto exit_fail;
1167 		}
1168 	}
1169 	newprocok = CreateProcessW(NULL, cmdw, &php_proc_open_security,
1170 		&php_proc_open_security, TRUE, dwCreateFlags, envpw, cwdw, &si, &pi);
1171 
1172 	if (suppress_errors) {
1173 		SetErrorMode(old_error_mode);
1174 	}
1175 
1176 	if (newprocok == FALSE) {
1177 		DWORD dw = GetLastError();
1178 		close_all_descriptors(descriptors, ndesc);
1179 		php_error_docref(NULL, E_WARNING, "CreateProcess failed, error code: %u", dw);
1180 		goto exit_fail;
1181 	}
1182 
1183 	childHandle = pi.hProcess;
1184 	child       = pi.dwProcessId;
1185 	CloseHandle(pi.hThread);
1186 #elif HAVE_FORK
1187 	/* the Unix way */
1188 	child = fork();
1189 
1190 	if (child == 0) {
1191 		/* This is the child process */
1192 
1193 		if (close_parentends_of_pipes(descriptors, ndesc) == FAILURE) {
1194 			/* We are already in child process and can't do anything to make
1195 			 * `proc_open` return an error in the parent
1196 			 * All we can do is exit with a non-zero (error) exit code */
1197 			_exit(127);
1198 		}
1199 
1200 		if (cwd) {
1201 			php_ignore_value(chdir(cwd));
1202 		}
1203 
1204 		if (argv) {
1205 			/* execvpe() is non-portable, use environ instead. */
1206 			if (env.envarray) {
1207 				environ = env.envarray;
1208 			}
1209 			execvp(command, argv);
1210 		} else {
1211 			if (env.envarray) {
1212 				execle("/bin/sh", "sh", "-c", command, NULL, env.envarray);
1213 			} else {
1214 				execl("/bin/sh", "sh", "-c", command, NULL);
1215 			}
1216 		}
1217 
1218 		/* If execvp/execle/execl are successful, we will never reach here
1219 		 * Display error and exit with non-zero (error) status code */
1220 		php_error_docref(NULL, E_WARNING, "Exec failed: %s", strerror(errno));
1221 		_exit(127);
1222 	} else if (child < 0) {
1223 		/* Failed to fork() */
1224 		close_all_descriptors(descriptors, ndesc);
1225 		php_error_docref(NULL, E_WARNING, "Fork failed: %s", strerror(errno));
1226 		goto exit_fail;
1227 	}
1228 #else
1229 # error You lose (configure should not have let you get here)
1230 #endif
1231 
1232 	/* We forked/spawned and this is the parent */
1233 
1234 	pipes = zend_try_array_init(pipes);
1235 	if (!pipes) {
1236 		goto exit_fail;
1237 	}
1238 
1239 	proc = (php_process_handle*) emalloc(sizeof(php_process_handle));
1240 	proc->command = command;
1241 	proc->pipes = emalloc(sizeof(zend_resource *) * ndesc);
1242 	proc->npipes = ndesc;
1243 	proc->child = child;
1244 #ifdef PHP_WIN32
1245 	proc->childHandle = childHandle;
1246 #endif
1247 	proc->env = env;
1248 
1249 	/* Clean up all the child ends and then open streams on the parent
1250 	 *   ends, where appropriate */
1251 	for (i = 0; i < ndesc; i++) {
1252 		php_stream *stream = NULL;
1253 
1254 		close_descriptor(descriptors[i].childend);
1255 
1256 		if (descriptors[i].type == DESCRIPTOR_TYPE_PIPE) {
1257 			char *mode_string = NULL;
1258 
1259 			switch (descriptors[i].mode_flags) {
1260 #ifdef PHP_WIN32
1261 				case O_WRONLY|O_BINARY:
1262 					mode_string = "wb";
1263 					break;
1264 				case O_RDONLY|O_BINARY:
1265 					mode_string = "rb";
1266 					break;
1267 #endif
1268 				case O_WRONLY:
1269 					mode_string = "w";
1270 					break;
1271 				case O_RDONLY:
1272 					mode_string = "r";
1273 					break;
1274 				case O_RDWR:
1275 					mode_string = "r+";
1276 					break;
1277 			}
1278 
1279 #ifdef PHP_WIN32
1280 			stream = php_stream_fopen_from_fd(_open_osfhandle((zend_intptr_t)descriptors[i].parentend,
1281 						descriptors[i].mode_flags), mode_string, NULL);
1282 			php_stream_set_option(stream, PHP_STREAM_OPTION_PIPE_BLOCKING, blocking_pipes, NULL);
1283 #else
1284 			stream = php_stream_fopen_from_fd(descriptors[i].parentend, mode_string, NULL);
1285 #endif
1286 		} else if (descriptors[i].type == DESCRIPTOR_TYPE_SOCKET) {
1287 			stream = php_stream_sock_open_from_socket((php_socket_t) descriptors[i].parentend, NULL);
1288 		} else {
1289 			proc->pipes[i] = NULL;
1290 		}
1291 
1292 		if (stream) {
1293 			zval retfp;
1294 
1295 			/* nasty hack; don't copy it */
1296 			stream->flags |= PHP_STREAM_FLAG_NO_SEEK;
1297 
1298 			php_stream_to_zval(stream, &retfp);
1299 			add_index_zval(pipes, descriptors[i].index, &retfp);
1300 
1301 			proc->pipes[i] = Z_RES(retfp);
1302 			Z_ADDREF(retfp);
1303 		}
1304 	}
1305 
1306 	if (1) {
1307 		RETVAL_RES(zend_register_resource(proc, le_proc_open));
1308 	} else {
1309 exit_fail:
1310 		_php_free_envp(env);
1311 		if (command) {
1312 			efree(command);
1313 		}
1314 		RETVAL_FALSE;
1315 	}
1316 
1317 #ifdef PHP_WIN32
1318 	free(cwdw);
1319 	free(cmdw);
1320 	free(envpw);
1321 #else
1322 	efree_argv(argv);
1323 #endif
1324 #if HAVE_OPENPTY
1325 	if (pty_master_fd != -1) {
1326 		close(pty_master_fd);
1327 	}
1328 	if (pty_slave_fd != -1) {
1329 		close(pty_slave_fd);
1330 	}
1331 #endif
1332 	if (descriptors) {
1333 		efree(descriptors);
1334 	}
1335 }
1336 /* }}} */
1337 
1338 #endif /* PHP_CAN_SUPPORT_PROC_OPEN */
1339