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: 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_str.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 zend_string_release_ex(proc->command, false);
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 bool 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_str(return_value, "command", zend_string_copy(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, ©, 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_str * str,size_t num_bs)488 static void append_backslashes(smart_str *str, size_t num_bs)
489 {
490 for (size_t i = 0; i < num_bs; i++) {
491 smart_str_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_str * str,zend_string * arg)496 static void append_win_escaped_arg(smart_str *str, zend_string *arg)
497 {
498 size_t num_bs = 0;
499
500 smart_str_appendc(str, '"');
501 for (size_t i = 0; i < ZSTR_LEN(arg); ++i) {
502 char c = ZSTR_VAL(arg)[i];
503 if (c == '\\') {
504 num_bs++;
505 continue;
506 }
507
508 if (c == '"') {
509 /* Backslashes before " need to be doubled. */
510 num_bs = num_bs * 2 + 1;
511 }
512 append_backslashes(str, num_bs);
513 smart_str_appendc(str, c);
514 num_bs = 0;
515 }
516 append_backslashes(str, num_bs * 2);
517 smart_str_appendc(str, '"');
518 }
519
create_win_command_from_args(HashTable * args)520 static zend_string *create_win_command_from_args(HashTable *args)
521 {
522 smart_str str = {0};
523 zval *arg_zv;
524 bool is_prog_name = 1;
525 int elem_num = 0;
526
527 ZEND_HASH_FOREACH_VAL(args, arg_zv) {
528 zend_string *arg_str = get_valid_arg_string(arg_zv, ++elem_num);
529 if (!arg_str) {
530 smart_str_free(&str);
531 return NULL;
532 }
533
534 if (!is_prog_name) {
535 smart_str_appendc(&str, ' ');
536 }
537
538 append_win_escaped_arg(&str, arg_str);
539
540 is_prog_name = 0;
541 zend_string_release(arg_str);
542 } ZEND_HASH_FOREACH_END();
543 smart_str_0(&str);
544 return str.s;
545 }
546
547 /* Get a boolean option from the `other_options` array which can be passed to `proc_open`.
548 * (Currently, all options apply on Windows only.) */
get_option(zval * other_options,char * opt_name,size_t opt_name_len)549 static bool get_option(zval *other_options, char *opt_name, size_t opt_name_len)
550 {
551 HashTable *opt_ary = Z_ARRVAL_P(other_options);
552 zval *item = zend_hash_str_find_deref(opt_ary, opt_name, opt_name_len);
553 return item != NULL &&
554 (Z_TYPE_P(item) == IS_TRUE ||
555 ((Z_TYPE_P(item) == IS_LONG) && Z_LVAL_P(item)));
556 }
557
558 /* Initialize STARTUPINFOW struct, used on Windows when spawning a process.
559 * Ref: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfow */
init_startup_info(STARTUPINFOW * si,descriptorspec_item * descriptors,int ndesc)560 static void init_startup_info(STARTUPINFOW *si, descriptorspec_item *descriptors, int ndesc)
561 {
562 memset(si, 0, sizeof(STARTUPINFOW));
563 si->cb = sizeof(STARTUPINFOW);
564 si->dwFlags = STARTF_USESTDHANDLES;
565
566 si->hStdInput = GetStdHandle(STD_INPUT_HANDLE);
567 si->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
568 si->hStdError = GetStdHandle(STD_ERROR_HANDLE);
569
570 /* redirect stdin/stdout/stderr if requested */
571 for (int i = 0; i < ndesc; i++) {
572 switch (descriptors[i].index) {
573 case 0:
574 si->hStdInput = descriptors[i].childend;
575 break;
576 case 1:
577 si->hStdOutput = descriptors[i].childend;
578 break;
579 case 2:
580 si->hStdError = descriptors[i].childend;
581 break;
582 }
583 }
584 }
585
init_process_info(PROCESS_INFORMATION * pi)586 static void init_process_info(PROCESS_INFORMATION *pi)
587 {
588 memset(&pi, 0, sizeof(pi));
589 }
590
convert_command_to_use_shell(wchar_t ** cmdw,size_t cmdw_len)591 static zend_result convert_command_to_use_shell(wchar_t **cmdw, size_t cmdw_len)
592 {
593 size_t len = sizeof(COMSPEC_NT) + sizeof(" /s /c ") + cmdw_len + 3;
594 wchar_t *cmdw_shell = (wchar_t *)malloc(len * sizeof(wchar_t));
595
596 if (cmdw_shell == NULL) {
597 php_error_docref(NULL, E_WARNING, "Command conversion failed");
598 return FAILURE;
599 }
600
601 if (_snwprintf(cmdw_shell, len, L"%hs /s /c \"%s\"", COMSPEC_NT, *cmdw) == -1) {
602 free(cmdw_shell);
603 php_error_docref(NULL, E_WARNING, "Command conversion failed");
604 return FAILURE;
605 }
606
607 free(*cmdw);
608 *cmdw = cmdw_shell;
609
610 return SUCCESS;
611 }
612 #endif
613
614 /* 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)615 static zend_string* get_command_from_array(HashTable *array, char ***argv, int num_elems)
616 {
617 zval *arg_zv;
618 zend_string *command = NULL;
619 int i = 0;
620
621 *argv = safe_emalloc(sizeof(char *), num_elems + 1, 0);
622
623 ZEND_HASH_FOREACH_VAL(array, arg_zv) {
624 zend_string *arg_str = get_valid_arg_string(arg_zv, i + 1);
625 if (!arg_str) {
626 /* Terminate with NULL so exit_fail code knows how many entries to free */
627 (*argv)[i] = NULL;
628 if (command != NULL) {
629 zend_string_release_ex(command, false);
630 }
631 return NULL;
632 }
633
634 if (i == 0) {
635 command = zend_string_copy(arg_str);
636 }
637
638 (*argv)[i++] = estrdup(ZSTR_VAL(arg_str));
639 zend_string_release(arg_str);
640 } ZEND_HASH_FOREACH_END();
641
642 (*argv)[i] = NULL;
643 return command;
644 }
645
alloc_descriptor_array(HashTable * descriptorspec)646 static descriptorspec_item* alloc_descriptor_array(HashTable *descriptorspec)
647 {
648 uint32_t ndescriptors = zend_hash_num_elements(descriptorspec);
649 return ecalloc(sizeof(descriptorspec_item), ndescriptors);
650 }
651
get_string_parameter(zval * array,int index,char * param_name)652 static zend_string* get_string_parameter(zval *array, int index, char *param_name)
653 {
654 zval *array_item;
655 if ((array_item = zend_hash_index_find(Z_ARRVAL_P(array), index)) == NULL) {
656 zend_value_error("Missing %s", param_name);
657 return NULL;
658 }
659 return zval_try_get_string(array_item);
660 }
661
set_proc_descriptor_to_blackhole(descriptorspec_item * desc)662 static zend_result set_proc_descriptor_to_blackhole(descriptorspec_item *desc)
663 {
664 #ifdef PHP_WIN32
665 desc->childend = CreateFileA("nul", GENERIC_READ | GENERIC_WRITE,
666 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
667 if (desc->childend == NULL) {
668 php_error_docref(NULL, E_WARNING, "Failed to open nul");
669 return FAILURE;
670 }
671 #else
672 desc->childend = open("/dev/null", O_RDWR);
673 if (desc->childend < 0) {
674 php_error_docref(NULL, E_WARNING, "Failed to open /dev/null: %s", strerror(errno));
675 return FAILURE;
676 }
677 #endif
678 return SUCCESS;
679 }
680
set_proc_descriptor_to_pty(descriptorspec_item * desc,int * master_fd,int * slave_fd)681 static zend_result set_proc_descriptor_to_pty(descriptorspec_item *desc, int *master_fd, int *slave_fd)
682 {
683 #if HAVE_OPENPTY
684 /* All FDs set to PTY in the child process will go to the slave end of the same PTY.
685 * Likewise, all the corresponding entries in `$pipes` in the parent will all go to the master
686 * end of the same PTY.
687 * If this is the first descriptorspec set to 'pty', find an available PTY and get master and
688 * slave FDs. */
689 if (*master_fd == -1) {
690 if (openpty(master_fd, slave_fd, NULL, NULL, NULL)) {
691 php_error_docref(NULL, E_WARNING, "Could not open PTY (pseudoterminal): %s", strerror(errno));
692 return FAILURE;
693 }
694 }
695
696 desc->type = DESCRIPTOR_TYPE_PIPE;
697 desc->childend = dup(*slave_fd);
698 desc->parentend = dup(*master_fd);
699 desc->mode_flags = O_RDWR;
700 return SUCCESS;
701 #else
702 php_error_docref(NULL, E_WARNING, "PTY (pseudoterminal) not supported on this system");
703 return FAILURE;
704 #endif
705 }
706
707 /* Mark the descriptor close-on-exec, so it won't be inherited by children */
make_descriptor_cloexec(php_file_descriptor_t fd)708 static php_file_descriptor_t make_descriptor_cloexec(php_file_descriptor_t fd)
709 {
710 #ifdef PHP_WIN32
711 return dup_handle(fd, FALSE, TRUE);
712 #else
713 #if defined(F_SETFD) && defined(FD_CLOEXEC)
714 fcntl(fd, F_SETFD, FD_CLOEXEC);
715 #endif
716 return fd;
717 #endif
718 }
719
set_proc_descriptor_to_pipe(descriptorspec_item * desc,zend_string * zmode)720 static zend_result set_proc_descriptor_to_pipe(descriptorspec_item *desc, zend_string *zmode)
721 {
722 php_file_descriptor_t newpipe[2];
723
724 if (pipe(newpipe)) {
725 php_error_docref(NULL, E_WARNING, "Unable to create pipe %s", strerror(errno));
726 return FAILURE;
727 }
728
729 desc->type = DESCRIPTOR_TYPE_PIPE;
730
731 if (strncmp(ZSTR_VAL(zmode), "w", 1) != 0) {
732 desc->parentend = newpipe[1];
733 desc->childend = newpipe[0];
734 desc->mode_flags = O_WRONLY;
735 } else {
736 desc->parentend = newpipe[0];
737 desc->childend = newpipe[1];
738 desc->mode_flags = O_RDONLY;
739 }
740
741 desc->parentend = make_descriptor_cloexec(desc->parentend);
742
743 #ifdef PHP_WIN32
744 if (ZSTR_LEN(zmode) >= 2 && ZSTR_VAL(zmode)[1] == 'b')
745 desc->mode_flags |= O_BINARY;
746 #endif
747
748 return SUCCESS;
749 }
750
751 #ifdef PHP_WIN32
752 #define create_socketpair(socks) socketpair_win32(AF_INET, SOCK_STREAM, 0, (socks), 0)
753 #else
754 #define create_socketpair(socks) socketpair(AF_UNIX, SOCK_STREAM, 0, (socks))
755 #endif
756
set_proc_descriptor_to_socket(descriptorspec_item * desc)757 static zend_result set_proc_descriptor_to_socket(descriptorspec_item *desc)
758 {
759 php_socket_t sock[2];
760
761 if (create_socketpair(sock)) {
762 zend_string *err = php_socket_error_str(php_socket_errno());
763 php_error_docref(NULL, E_WARNING, "Unable to create socket pair: %s", ZSTR_VAL(err));
764 zend_string_release(err);
765 return FAILURE;
766 }
767
768 desc->type = DESCRIPTOR_TYPE_SOCKET;
769 desc->parentend = make_descriptor_cloexec((php_file_descriptor_t) sock[0]);
770
771 /* Pass sock[1] to child because it will never use overlapped IO on Windows. */
772 desc->childend = (php_file_descriptor_t) sock[1];
773
774 return SUCCESS;
775 }
776
set_proc_descriptor_to_file(descriptorspec_item * desc,zend_string * file_path,zend_string * file_mode)777 static zend_result set_proc_descriptor_to_file(descriptorspec_item *desc, zend_string *file_path,
778 zend_string *file_mode)
779 {
780 php_socket_t fd;
781
782 /* try a wrapper */
783 php_stream *stream = php_stream_open_wrapper(ZSTR_VAL(file_path), ZSTR_VAL(file_mode),
784 REPORT_ERRORS|STREAM_WILL_CAST, NULL);
785 if (stream == NULL) {
786 return FAILURE;
787 }
788
789 /* force into an fd */
790 if (php_stream_cast(stream, PHP_STREAM_CAST_RELEASE|PHP_STREAM_AS_FD, (void **)&fd,
791 REPORT_ERRORS) == FAILURE) {
792 return FAILURE;
793 }
794
795 #ifdef PHP_WIN32
796 desc->childend = dup_fd_as_handle((int)fd);
797 _close((int)fd);
798
799 /* Simulate the append mode by fseeking to the end of the file
800 * This introduces a potential race condition, but it is the best we can do */
801 if (strchr(ZSTR_VAL(file_mode), 'a')) {
802 SetFilePointer(desc->childend, 0, NULL, FILE_END);
803 }
804 #else
805 desc->childend = fd;
806 #endif
807 return SUCCESS;
808 }
809
dup_proc_descriptor(php_file_descriptor_t from,php_file_descriptor_t * to,zend_ulong nindex)810 static zend_result dup_proc_descriptor(php_file_descriptor_t from, php_file_descriptor_t *to,
811 zend_ulong nindex)
812 {
813 #ifdef PHP_WIN32
814 *to = dup_handle(from, TRUE, FALSE);
815 if (*to == NULL) {
816 php_error_docref(NULL, E_WARNING, "Failed to dup() for descriptor " ZEND_LONG_FMT, nindex);
817 return FAILURE;
818 }
819 #else
820 *to = dup(from);
821 if (*to < 0) {
822 php_error_docref(NULL, E_WARNING, "Failed to dup() for descriptor " ZEND_LONG_FMT ": %s",
823 nindex, strerror(errno));
824 return FAILURE;
825 }
826 #endif
827 return SUCCESS;
828 }
829
redirect_proc_descriptor(descriptorspec_item * desc,int target,descriptorspec_item * descriptors,int ndesc,int nindex)830 static zend_result redirect_proc_descriptor(descriptorspec_item *desc, int target,
831 descriptorspec_item *descriptors, int ndesc, int nindex)
832 {
833 php_file_descriptor_t redirect_to = PHP_INVALID_FD;
834
835 for (int i = 0; i < ndesc; i++) {
836 if (descriptors[i].index == target) {
837 redirect_to = descriptors[i].childend;
838 break;
839 }
840 }
841
842 if (redirect_to == PHP_INVALID_FD) { /* Didn't find the index we wanted */
843 if (target < 0 || target > 2) {
844 php_error_docref(NULL, E_WARNING, "Redirection target %d not found", target);
845 return FAILURE;
846 }
847
848 /* Support referring to a stdin/stdout/stderr pipe adopted from the parent,
849 * which happens whenever an explicit override is not provided. */
850 #ifndef PHP_WIN32
851 redirect_to = target;
852 #else
853 switch (target) {
854 case 0: redirect_to = GetStdHandle(STD_INPUT_HANDLE); break;
855 case 1: redirect_to = GetStdHandle(STD_OUTPUT_HANDLE); break;
856 case 2: redirect_to = GetStdHandle(STD_ERROR_HANDLE); break;
857 EMPTY_SWITCH_DEFAULT_CASE()
858 }
859 #endif
860 }
861
862 return dup_proc_descriptor(redirect_to, &desc->childend, nindex);
863 }
864
865 /* 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)866 static zend_result set_proc_descriptor_from_array(zval *descitem, descriptorspec_item *descriptors,
867 int ndesc, int nindex, int *pty_master_fd, int *pty_slave_fd) {
868 zend_string *ztype = get_string_parameter(descitem, 0, "handle qualifier");
869 if (!ztype) {
870 return FAILURE;
871 }
872
873 zend_string *zmode = NULL, *zfile = NULL;
874 zend_result retval = FAILURE;
875
876 if (zend_string_equals_literal(ztype, "pipe")) {
877 /* Set descriptor to pipe */
878 zmode = get_string_parameter(descitem, 1, "mode parameter for 'pipe'");
879 if (zmode == NULL) {
880 goto finish;
881 }
882 retval = set_proc_descriptor_to_pipe(&descriptors[ndesc], zmode);
883 } else if (zend_string_equals_literal(ztype, "socket")) {
884 /* Set descriptor to socketpair */
885 retval = set_proc_descriptor_to_socket(&descriptors[ndesc]);
886 } else if (zend_string_equals_literal(ztype, "file")) {
887 /* Set descriptor to file */
888 if ((zfile = get_string_parameter(descitem, 1, "file name parameter for 'file'")) == NULL) {
889 goto finish;
890 }
891 if ((zmode = get_string_parameter(descitem, 2, "mode parameter for 'file'")) == NULL) {
892 goto finish;
893 }
894 retval = set_proc_descriptor_to_file(&descriptors[ndesc], zfile, zmode);
895 } else if (zend_string_equals_literal(ztype, "redirect")) {
896 /* Redirect descriptor to whatever another descriptor is set to */
897 zval *ztarget = zend_hash_index_find_deref(Z_ARRVAL_P(descitem), 1);
898 if (!ztarget) {
899 zend_value_error("Missing redirection target");
900 goto finish;
901 }
902 if (Z_TYPE_P(ztarget) != IS_LONG) {
903 zend_value_error("Redirection target must be of type int, %s given", zend_zval_type_name(ztarget));
904 goto finish;
905 }
906
907 retval = redirect_proc_descriptor(
908 &descriptors[ndesc], (int)Z_LVAL_P(ztarget), descriptors, ndesc, nindex);
909 } else if (zend_string_equals_literal(ztype, "null")) {
910 /* Set descriptor to blackhole (discard all data written) */
911 retval = set_proc_descriptor_to_blackhole(&descriptors[ndesc]);
912 } else if (zend_string_equals_literal(ztype, "pty")) {
913 /* Set descriptor to slave end of PTY */
914 retval = set_proc_descriptor_to_pty(&descriptors[ndesc], pty_master_fd, pty_slave_fd);
915 } else {
916 php_error_docref(NULL, E_WARNING, "%s is not a valid descriptor spec/mode", ZSTR_VAL(ztype));
917 goto finish;
918 }
919
920 finish:
921 if (zmode) zend_string_release(zmode);
922 if (zfile) zend_string_release(zfile);
923 zend_string_release(ztype);
924 return retval;
925 }
926
set_proc_descriptor_from_resource(zval * resource,descriptorspec_item * desc,int nindex)927 static zend_result set_proc_descriptor_from_resource(zval *resource, descriptorspec_item *desc, int nindex)
928 {
929 /* Should be a stream - try and dup the descriptor */
930 php_stream *stream = (php_stream*)zend_fetch_resource(Z_RES_P(resource), "stream",
931 php_file_le_stream());
932 if (stream == NULL) {
933 return FAILURE;
934 }
935
936 php_socket_t fd;
937 zend_result status = php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, REPORT_ERRORS);
938 if (status == FAILURE) {
939 return FAILURE;
940 }
941
942 #ifdef PHP_WIN32
943 php_file_descriptor_t fd_t = (php_file_descriptor_t)_get_osfhandle(fd);
944 #else
945 php_file_descriptor_t fd_t = fd;
946 #endif
947 return dup_proc_descriptor(fd_t, &desc->childend, nindex);
948 }
949
950 #ifndef PHP_WIN32
close_parentends_of_pipes(descriptorspec_item * descriptors,int ndesc)951 static zend_result close_parentends_of_pipes(descriptorspec_item *descriptors, int ndesc)
952 {
953 /* We are running in child process
954 * Close the 'parent end' of pipes which were opened before forking/spawning
955 * Also, dup() the child end of all pipes as necessary so they will use the FD
956 * number which the user requested */
957 for (int i = 0; i < ndesc; i++) {
958 if (descriptors[i].type != DESCRIPTOR_TYPE_STD) {
959 close(descriptors[i].parentend);
960 }
961 if (descriptors[i].childend != descriptors[i].index) {
962 if (dup2(descriptors[i].childend, descriptors[i].index) < 0) {
963 php_error_docref(NULL, E_WARNING, "Unable to copy file descriptor %d (for pipe) into " \
964 "file descriptor %d: %s", descriptors[i].childend, descriptors[i].index, strerror(errno));
965 return FAILURE;
966 }
967 close(descriptors[i].childend);
968 }
969 }
970
971 return SUCCESS;
972 }
973 #endif
974
close_all_descriptors(descriptorspec_item * descriptors,int ndesc)975 static void close_all_descriptors(descriptorspec_item *descriptors, int ndesc)
976 {
977 for (int i = 0; i < ndesc; i++) {
978 close_descriptor(descriptors[i].childend);
979 if (descriptors[i].parentend)
980 close_descriptor(descriptors[i].parentend);
981 }
982 }
983
efree_argv(char ** argv)984 static void efree_argv(char **argv)
985 {
986 if (argv) {
987 char **arg = argv;
988 while (*arg != NULL) {
989 efree(*arg);
990 arg++;
991 }
992 efree(argv);
993 }
994 }
995
996 /* {{{ Execute a command, with specified files used for input/output */
PHP_FUNCTION(proc_open)997 PHP_FUNCTION(proc_open)
998 {
999 zend_string *command_str;
1000 HashTable *command_ht;
1001 HashTable *descriptorspec; /* Mandatory argument */
1002 zval *pipes; /* Mandatory argument */
1003 char *cwd = NULL; /* Optional argument */
1004 size_t cwd_len = 0; /* Optional argument */
1005 zval *environment = NULL, *other_options = NULL; /* Optional arguments */
1006
1007 php_process_env env;
1008 int ndesc = 0;
1009 int i;
1010 zval *descitem = NULL;
1011 zend_string *str_index;
1012 zend_ulong nindex;
1013 descriptorspec_item *descriptors = NULL;
1014 #ifdef PHP_WIN32
1015 PROCESS_INFORMATION pi;
1016 HANDLE childHandle;
1017 STARTUPINFOW si;
1018 BOOL newprocok;
1019 DWORD dwCreateFlags = 0;
1020 UINT old_error_mode;
1021 char cur_cwd[MAXPATHLEN];
1022 wchar_t *cmdw = NULL, *cwdw = NULL, *envpw = NULL;
1023 size_t cmdw_len;
1024 bool suppress_errors = 0;
1025 bool bypass_shell = 0;
1026 bool blocking_pipes = 0;
1027 bool create_process_group = 0;
1028 bool create_new_console = 0;
1029 #else
1030 char **argv = NULL;
1031 #endif
1032 int pty_master_fd = -1, pty_slave_fd = -1;
1033 php_process_id_t child;
1034 php_process_handle *proc;
1035
1036 ZEND_PARSE_PARAMETERS_START(3, 6)
1037 Z_PARAM_ARRAY_HT_OR_STR(command_ht, command_str)
1038 Z_PARAM_ARRAY_HT(descriptorspec)
1039 Z_PARAM_ZVAL(pipes)
1040 Z_PARAM_OPTIONAL
1041 Z_PARAM_STRING_OR_NULL(cwd, cwd_len)
1042 Z_PARAM_ARRAY_OR_NULL(environment)
1043 Z_PARAM_ARRAY_OR_NULL(other_options)
1044 ZEND_PARSE_PARAMETERS_END();
1045
1046 memset(&env, 0, sizeof(env));
1047
1048 if (command_ht) {
1049 uint32_t num_elems = zend_hash_num_elements(command_ht);
1050 if (num_elems == 0) {
1051 zend_argument_value_error(1, "must have at least one element");
1052 RETURN_THROWS();
1053 }
1054
1055 #ifdef PHP_WIN32
1056 /* Automatically bypass shell if command is given as an array */
1057 bypass_shell = 1;
1058 command_str = create_win_command_from_args(command_ht);
1059 #else
1060 command_str = get_command_from_array(command_ht, &argv, num_elems);
1061 #endif
1062
1063 if (!command_str) {
1064 #ifndef PHP_WIN32
1065 efree_argv(argv);
1066 #endif
1067 RETURN_FALSE;
1068 }
1069 } else {
1070 zend_string_addref(command_str);
1071 }
1072
1073 #ifdef PHP_WIN32
1074 if (other_options) {
1075 suppress_errors = get_option(other_options, "suppress_errors", strlen("suppress_errors"));
1076 /* TODO: Deprecate in favor of array command? */
1077 bypass_shell = bypass_shell || get_option(other_options, "bypass_shell", strlen("bypass_shell"));
1078 blocking_pipes = get_option(other_options, "blocking_pipes", strlen("blocking_pipes"));
1079 create_process_group = get_option(other_options, "create_process_group", strlen("create_process_group"));
1080 create_new_console = get_option(other_options, "create_new_console", strlen("create_new_console"));
1081 }
1082 #endif
1083
1084 if (environment) {
1085 env = _php_array_to_envp(environment);
1086 }
1087
1088 descriptors = alloc_descriptor_array(descriptorspec);
1089
1090 /* Walk the descriptor spec and set up files/pipes */
1091 ZEND_HASH_FOREACH_KEY_VAL(descriptorspec, nindex, str_index, descitem) {
1092 if (str_index) {
1093 zend_argument_value_error(2, "must be an integer indexed array");
1094 goto exit_fail;
1095 }
1096
1097 descriptors[ndesc].index = (int)nindex;
1098
1099 if (Z_TYPE_P(descitem) == IS_RESOURCE) {
1100 if (set_proc_descriptor_from_resource(descitem, &descriptors[ndesc], ndesc) == FAILURE) {
1101 goto exit_fail;
1102 }
1103 } else if (Z_TYPE_P(descitem) == IS_ARRAY) {
1104 if (set_proc_descriptor_from_array(descitem, descriptors, ndesc, (int)nindex,
1105 &pty_master_fd, &pty_slave_fd) == FAILURE) {
1106 goto exit_fail;
1107 }
1108 } else {
1109 zend_argument_value_error(2, "must only contain arrays and streams");
1110 goto exit_fail;
1111 }
1112 ndesc++;
1113 } ZEND_HASH_FOREACH_END();
1114
1115 #ifdef PHP_WIN32
1116 if (cwd == NULL) {
1117 char *getcwd_result = VCWD_GETCWD(cur_cwd, MAXPATHLEN);
1118 if (!getcwd_result) {
1119 php_error_docref(NULL, E_WARNING, "Cannot get current directory");
1120 goto exit_fail;
1121 }
1122 cwd = cur_cwd;
1123 }
1124 cwdw = php_win32_cp_any_to_w(cwd);
1125 if (!cwdw) {
1126 php_error_docref(NULL, E_WARNING, "CWD conversion failed");
1127 goto exit_fail;
1128 }
1129
1130 init_startup_info(&si, descriptors, ndesc);
1131 init_process_info(&pi);
1132
1133 if (suppress_errors) {
1134 old_error_mode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
1135 }
1136
1137 dwCreateFlags = NORMAL_PRIORITY_CLASS;
1138 if(strcmp(sapi_module.name, "cli") != 0) {
1139 dwCreateFlags |= CREATE_NO_WINDOW;
1140 }
1141 if (create_process_group) {
1142 dwCreateFlags |= CREATE_NEW_PROCESS_GROUP;
1143 }
1144 if (create_new_console) {
1145 dwCreateFlags |= CREATE_NEW_CONSOLE;
1146 }
1147 envpw = php_win32_cp_env_any_to_w(env.envp);
1148 if (envpw) {
1149 dwCreateFlags |= CREATE_UNICODE_ENVIRONMENT;
1150 } else {
1151 if (env.envp) {
1152 php_error_docref(NULL, E_WARNING, "ENV conversion failed");
1153 goto exit_fail;
1154 }
1155 }
1156
1157 cmdw = php_win32_cp_conv_any_to_w(ZSTR_VAL(command_str), ZSTR_LEN(command_str), &cmdw_len);
1158 if (!cmdw) {
1159 php_error_docref(NULL, E_WARNING, "Command conversion failed");
1160 goto exit_fail;
1161 }
1162
1163 if (!bypass_shell) {
1164 if (convert_command_to_use_shell(&cmdw, cmdw_len) == FAILURE) {
1165 goto exit_fail;
1166 }
1167 }
1168 newprocok = CreateProcessW(NULL, cmdw, &php_proc_open_security,
1169 &php_proc_open_security, TRUE, dwCreateFlags, envpw, cwdw, &si, &pi);
1170
1171 if (suppress_errors) {
1172 SetErrorMode(old_error_mode);
1173 }
1174
1175 if (newprocok == FALSE) {
1176 DWORD dw = GetLastError();
1177 close_all_descriptors(descriptors, ndesc);
1178 php_error_docref(NULL, E_WARNING, "CreateProcess failed, error code: %u", dw);
1179 goto exit_fail;
1180 }
1181
1182 childHandle = pi.hProcess;
1183 child = pi.dwProcessId;
1184 CloseHandle(pi.hThread);
1185 #elif HAVE_FORK
1186 /* the Unix way */
1187 child = fork();
1188
1189 if (child == 0) {
1190 /* This is the child process */
1191
1192 if (close_parentends_of_pipes(descriptors, ndesc) == FAILURE) {
1193 /* We are already in child process and can't do anything to make
1194 * `proc_open` return an error in the parent
1195 * All we can do is exit with a non-zero (error) exit code */
1196 _exit(127);
1197 }
1198
1199 if (cwd) {
1200 php_ignore_value(chdir(cwd));
1201 }
1202
1203 if (argv) {
1204 /* execvpe() is non-portable, use environ instead. */
1205 if (env.envarray) {
1206 environ = env.envarray;
1207 }
1208 execvp(ZSTR_VAL(command_str), argv);
1209 } else {
1210 if (env.envarray) {
1211 execle("/bin/sh", "sh", "-c", ZSTR_VAL(command_str), NULL, env.envarray);
1212 } else {
1213 execl("/bin/sh", "sh", "-c", ZSTR_VAL(command_str), NULL);
1214 }
1215 }
1216
1217 /* If execvp/execle/execl are successful, we will never reach here
1218 * Display error and exit with non-zero (error) status code */
1219 php_error_docref(NULL, E_WARNING, "Exec failed: %s", strerror(errno));
1220 _exit(127);
1221 } else if (child < 0) {
1222 /* Failed to fork() */
1223 close_all_descriptors(descriptors, ndesc);
1224 php_error_docref(NULL, E_WARNING, "Fork failed: %s", strerror(errno));
1225 goto exit_fail;
1226 }
1227 #else
1228 # error You lose (configure should not have let you get here)
1229 #endif
1230
1231 /* We forked/spawned and this is the parent */
1232
1233 pipes = zend_try_array_init(pipes);
1234 if (!pipes) {
1235 goto exit_fail;
1236 }
1237
1238 proc = (php_process_handle*) emalloc(sizeof(php_process_handle));
1239 proc->command = zend_string_copy(command_str);
1240 proc->pipes = emalloc(sizeof(zend_resource *) * ndesc);
1241 proc->npipes = ndesc;
1242 proc->child = child;
1243 #ifdef PHP_WIN32
1244 proc->childHandle = childHandle;
1245 #endif
1246 proc->env = env;
1247
1248 /* Clean up all the child ends and then open streams on the parent
1249 * ends, where appropriate */
1250 for (i = 0; i < ndesc; i++) {
1251 php_stream *stream = NULL;
1252
1253 close_descriptor(descriptors[i].childend);
1254
1255 if (descriptors[i].type == DESCRIPTOR_TYPE_PIPE) {
1256 char *mode_string = NULL;
1257
1258 switch (descriptors[i].mode_flags) {
1259 #ifdef PHP_WIN32
1260 case O_WRONLY|O_BINARY:
1261 mode_string = "wb";
1262 break;
1263 case O_RDONLY|O_BINARY:
1264 mode_string = "rb";
1265 break;
1266 #endif
1267 case O_WRONLY:
1268 mode_string = "w";
1269 break;
1270 case O_RDONLY:
1271 mode_string = "r";
1272 break;
1273 case O_RDWR:
1274 mode_string = "r+";
1275 break;
1276 }
1277
1278 #ifdef PHP_WIN32
1279 stream = php_stream_fopen_from_fd(_open_osfhandle((zend_intptr_t)descriptors[i].parentend,
1280 descriptors[i].mode_flags), mode_string, NULL);
1281 php_stream_set_option(stream, PHP_STREAM_OPTION_PIPE_BLOCKING, blocking_pipes, NULL);
1282 #else
1283 stream = php_stream_fopen_from_fd(descriptors[i].parentend, mode_string, NULL);
1284 #endif
1285 } else if (descriptors[i].type == DESCRIPTOR_TYPE_SOCKET) {
1286 stream = php_stream_sock_open_from_socket((php_socket_t) descriptors[i].parentend, NULL);
1287 } else {
1288 proc->pipes[i] = NULL;
1289 }
1290
1291 if (stream) {
1292 zval retfp;
1293
1294 /* nasty hack; don't copy it */
1295 stream->flags |= PHP_STREAM_FLAG_NO_SEEK;
1296
1297 php_stream_to_zval(stream, &retfp);
1298 add_index_zval(pipes, descriptors[i].index, &retfp);
1299
1300 proc->pipes[i] = Z_RES(retfp);
1301 Z_ADDREF(retfp);
1302 }
1303 }
1304
1305 if (1) {
1306 RETVAL_RES(zend_register_resource(proc, le_proc_open));
1307 } else {
1308 exit_fail:
1309 _php_free_envp(env);
1310 RETVAL_FALSE;
1311 }
1312
1313 zend_string_release_ex(command_str, false);
1314 #ifdef PHP_WIN32
1315 free(cwdw);
1316 free(cmdw);
1317 free(envpw);
1318 #else
1319 efree_argv(argv);
1320 #endif
1321 #if HAVE_OPENPTY
1322 if (pty_master_fd != -1) {
1323 close(pty_master_fd);
1324 }
1325 if (pty_slave_fd != -1) {
1326 close(pty_slave_fd);
1327 }
1328 #endif
1329 if (descriptors) {
1330 efree(descriptors);
1331 }
1332 }
1333 /* }}} */
1334
1335 #endif /* PHP_CAN_SUPPORT_PROC_OPEN */
1336