1 /*
2 +----------------------------------------------------------------------+
3 | PHP Version 5 |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 1997-2015 The PHP Group |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
15 | Author: Wez Furlong <wez@thebrainroom.com> |
16 +----------------------------------------------------------------------+
17 */
18 /* $Id$ */
19
20 #if 0 && (defined(__linux__) || defined(sun) || defined(__IRIX__))
21 # define _BSD_SOURCE /* linux wants this when XOPEN mode is on */
22 # define _BSD_COMPAT /* irix: uint */
23 # define _XOPEN_SOURCE 500 /* turn on Unix98 */
24 # define __EXTENSIONS__ 1 /* Solaris: uint */
25 #endif
26
27 #include "php.h"
28 #include <stdio.h>
29 #include <ctype.h>
30 #include "php_string.h"
31 #include "ext/standard/head.h"
32 #include "ext/standard/basic_functions.h"
33 #include "ext/standard/file.h"
34 #include "exec.h"
35 #include "php_globals.h"
36 #include "SAPI.h"
37
38 #ifdef NETWARE
39 #include <proc.h>
40 #include <library.h>
41 #endif
42
43 #if HAVE_SYS_WAIT_H
44 #include <sys/wait.h>
45 #endif
46 #if HAVE_SIGNAL_H
47 #include <signal.h>
48 #endif
49
50 #if HAVE_SYS_STAT_H
51 #include <sys/stat.h>
52 #endif
53 #if HAVE_FCNTL_H
54 #include <fcntl.h>
55 #endif
56
57 /* This symbol is defined in ext/standard/config.m4.
58 * Essentially, it is set if you HAVE_FORK || PHP_WIN32
59 * Other platforms may modify that configure check and add suitable #ifdefs
60 * around the alternate code.
61 * */
62 #ifdef PHP_CAN_SUPPORT_PROC_OPEN
63
64 #if 0 && HAVE_PTSNAME && HAVE_GRANTPT && HAVE_UNLOCKPT && HAVE_SYS_IOCTL_H && HAVE_TERMIOS_H
65 # include <sys/ioctl.h>
66 # include <termios.h>
67 # define PHP_CAN_DO_PTS 1
68 #endif
69
70 #include "proc_open.h"
71
72 static int le_proc_open;
73
74 /* {{{ _php_array_to_envp */
_php_array_to_envp(zval * environment,int is_persistent TSRMLS_DC)75 static php_process_env_t _php_array_to_envp(zval *environment, int is_persistent TSRMLS_DC)
76 {
77 zval **element;
78 php_process_env_t env;
79 char *string_key, *data;
80 #ifndef PHP_WIN32
81 char **ep;
82 #endif
83 char *p;
84 uint string_length, cnt, l, sizeenv=0, el_len;
85 ulong num_key;
86 HashTable *target_hash;
87 HashPosition pos;
88
89 memset(&env, 0, sizeof(env));
90
91 if (!environment) {
92 return env;
93 }
94
95 cnt = zend_hash_num_elements(Z_ARRVAL_P(environment));
96
97 if (cnt < 1) {
98 #ifndef PHP_WIN32
99 env.envarray = (char **) pecalloc(1, sizeof(char *), is_persistent);
100 #endif
101 env.envp = (char *) pecalloc(4, 1, is_persistent);
102 return env;
103 }
104
105 target_hash = HASH_OF(environment);
106 if (!target_hash) {
107 return env;
108 }
109
110 /* first, we have to get the size of all the elements in the hash */
111 for (zend_hash_internal_pointer_reset_ex(target_hash, &pos);
112 zend_hash_get_current_data_ex(target_hash, (void **) &element, &pos) == SUCCESS;
113 zend_hash_move_forward_ex(target_hash, &pos)) {
114
115 if (Z_TYPE_PP(element) != IS_STRING) {
116 zval tmp;
117
118 MAKE_COPY_ZVAL(element, &tmp);
119 convert_to_string(&tmp);
120 el_len = Z_STRLEN(tmp);
121
122 zval_dtor(&tmp);
123 } else {
124 el_len = Z_STRLEN_PP(element);
125 }
126 if (el_len == 0) {
127 continue;
128 }
129
130 sizeenv += el_len+1;
131
132 switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_length, &num_key, 0, &pos)) {
133 case HASH_KEY_IS_STRING:
134 if (string_length == 0) {
135 continue;
136 }
137 sizeenv += string_length;
138 break;
139 }
140 }
141
142 #ifndef PHP_WIN32
143 ep = env.envarray = (char **) pecalloc(cnt + 1, sizeof(char *), is_persistent);
144 #endif
145 p = env.envp = (char *) pecalloc(sizeenv + 4, 1, is_persistent);
146
147 for (zend_hash_internal_pointer_reset_ex(target_hash, &pos);
148 zend_hash_get_current_data_ex(target_hash, (void **) &element, &pos) == SUCCESS;
149 zend_hash_move_forward_ex(target_hash, &pos)) {
150 zval tmp;
151
152 if (Z_TYPE_PP(element) != IS_STRING) {
153 MAKE_COPY_ZVAL(element, &tmp);
154 convert_to_string(&tmp);
155 } else {
156 tmp = **element;
157 }
158
159 el_len = Z_STRLEN(tmp);
160
161 if (el_len == 0) {
162 goto next_element;
163 }
164
165 data = Z_STRVAL(tmp);
166 switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_length, &num_key, 0, &pos)) {
167 case HASH_KEY_IS_STRING:
168 if (string_length == 0) {
169 goto next_element;
170 }
171
172 l = string_length + el_len + 1;
173 memcpy(p, string_key, string_length);
174 strncat(p, "=", 1);
175 strncat(p, data, el_len);
176
177 #ifndef PHP_WIN32
178 *ep = p;
179 ++ep;
180 #endif
181 p += l;
182 break;
183 case HASH_KEY_IS_LONG:
184 memcpy(p,data,el_len);
185 #ifndef PHP_WIN32
186 *ep = p;
187 ++ep;
188 #endif
189 p += el_len + 1;
190 break;
191 case HASH_KEY_NON_EXISTENT:
192 break;
193 }
194
195 next_element:
196 if (Z_TYPE_PP(element) != IS_STRING) {
197 zval_dtor(&tmp);
198 }
199 }
200
201 assert((uint)(p - env.envp) <= sizeenv);
202
203 zend_hash_internal_pointer_reset_ex(target_hash, &pos);
204
205 return env;
206 }
207 /* }}} */
208
209 /* {{{ _php_free_envp */
_php_free_envp(php_process_env_t env,int is_persistent)210 static void _php_free_envp(php_process_env_t env, int is_persistent)
211 {
212 #ifndef PHP_WIN32
213 if (env.envarray) {
214 pefree(env.envarray, is_persistent);
215 }
216 #endif
217 if (env.envp) {
218 pefree(env.envp, is_persistent);
219 }
220 }
221 /* }}} */
222
223 /* {{{ proc_open_rsrc_dtor */
proc_open_rsrc_dtor(zend_rsrc_list_entry * rsrc TSRMLS_DC)224 static void proc_open_rsrc_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
225 {
226 struct php_process_handle *proc = (struct php_process_handle*)rsrc->ptr;
227 int i;
228 #ifdef PHP_WIN32
229 DWORD wstatus;
230 #elif HAVE_SYS_WAIT_H
231 int wstatus;
232 int waitpid_options = 0;
233 pid_t wait_pid;
234 #endif
235
236 /* Close all handles to avoid a deadlock */
237 for (i = 0; i < proc->npipes; i++) {
238 if (proc->pipes[i] != 0) {
239 zend_list_delete(proc->pipes[i]);
240 proc->pipes[i] = 0;
241 }
242 }
243
244 #ifdef PHP_WIN32
245 if (FG(pclose_wait)) {
246 WaitForSingleObject(proc->childHandle, INFINITE);
247 }
248 GetExitCodeProcess(proc->childHandle, &wstatus);
249 if (wstatus == STILL_ACTIVE) {
250 FG(pclose_ret) = -1;
251 } else {
252 FG(pclose_ret) = wstatus;
253 }
254 CloseHandle(proc->childHandle);
255
256 #elif HAVE_SYS_WAIT_H
257
258 if (!FG(pclose_wait)) {
259 waitpid_options = WNOHANG;
260 }
261 do {
262 wait_pid = waitpid(proc->child, &wstatus, waitpid_options);
263 } while (wait_pid == -1 && errno == EINTR);
264
265 if (wait_pid <= 0) {
266 FG(pclose_ret) = -1;
267 } else {
268 if (WIFEXITED(wstatus))
269 wstatus = WEXITSTATUS(wstatus);
270 FG(pclose_ret) = wstatus;
271 }
272
273 #else
274 FG(pclose_ret) = -1;
275 #endif
276 _php_free_envp(proc->env, proc->is_persistent);
277 pefree(proc->command, proc->is_persistent);
278 pefree(proc, proc->is_persistent);
279
280 }
281 /* }}} */
282
283 /* {{{ PHP_MINIT_FUNCTION(proc_open) */
PHP_MINIT_FUNCTION(proc_open)284 PHP_MINIT_FUNCTION(proc_open)
285 {
286 le_proc_open = zend_register_list_destructors_ex(proc_open_rsrc_dtor, NULL, "process", module_number);
287 return SUCCESS;
288 }
289 /* }}} */
290
291 /* {{{ proto bool proc_terminate(resource process [, long signal])
292 kill a process opened by proc_open */
PHP_FUNCTION(proc_terminate)293 PHP_FUNCTION(proc_terminate)
294 {
295 zval *zproc;
296 struct php_process_handle *proc;
297 long sig_no = SIGTERM;
298
299 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &zproc, &sig_no) == FAILURE) {
300 RETURN_FALSE;
301 }
302
303 ZEND_FETCH_RESOURCE(proc, struct php_process_handle *, &zproc, -1, "process", le_proc_open);
304
305 #ifdef PHP_WIN32
306 if (TerminateProcess(proc->childHandle, 255)) {
307 RETURN_TRUE;
308 } else {
309 RETURN_FALSE;
310 }
311 #else
312 if (kill(proc->child, sig_no) == 0) {
313 RETURN_TRUE;
314 } else {
315 RETURN_FALSE;
316 }
317 #endif
318 }
319 /* }}} */
320
321 /* {{{ proto int proc_close(resource process)
322 close a process opened by proc_open */
PHP_FUNCTION(proc_close)323 PHP_FUNCTION(proc_close)
324 {
325 zval *zproc;
326 struct php_process_handle *proc;
327
328 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zproc) == FAILURE) {
329 RETURN_FALSE;
330 }
331
332 ZEND_FETCH_RESOURCE(proc, struct php_process_handle *, &zproc, -1, "process", le_proc_open);
333
334 FG(pclose_wait) = 1;
335 zend_list_delete(Z_LVAL_P(zproc));
336 FG(pclose_wait) = 0;
337 RETURN_LONG(FG(pclose_ret));
338 }
339 /* }}} */
340
341 /* {{{ proto array proc_get_status(resource process)
342 get information about a process opened by proc_open */
PHP_FUNCTION(proc_get_status)343 PHP_FUNCTION(proc_get_status)
344 {
345 zval *zproc;
346 struct php_process_handle *proc;
347 #ifdef PHP_WIN32
348 DWORD wstatus;
349 #elif HAVE_SYS_WAIT_H
350 int wstatus;
351 pid_t wait_pid;
352 #endif
353 int running = 1, signaled = 0, stopped = 0;
354 int exitcode = -1, termsig = 0, stopsig = 0;
355
356 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zproc) == FAILURE) {
357 RETURN_FALSE;
358 }
359
360 ZEND_FETCH_RESOURCE(proc, struct php_process_handle *, &zproc, -1, "process", le_proc_open);
361
362 array_init(return_value);
363
364 add_assoc_string(return_value, "command", proc->command, 1);
365 add_assoc_long(return_value, "pid", (long) proc->child);
366
367 #ifdef PHP_WIN32
368
369 GetExitCodeProcess(proc->childHandle, &wstatus);
370
371 running = wstatus == STILL_ACTIVE;
372 exitcode = running ? -1 : wstatus;
373
374 #elif HAVE_SYS_WAIT_H
375
376 errno = 0;
377 wait_pid = waitpid(proc->child, &wstatus, WNOHANG|WUNTRACED);
378
379 if (wait_pid == proc->child) {
380 if (WIFEXITED(wstatus)) {
381 running = 0;
382 exitcode = WEXITSTATUS(wstatus);
383 }
384 if (WIFSIGNALED(wstatus)) {
385 running = 0;
386 signaled = 1;
387 #ifdef NETWARE
388 termsig = WIFTERMSIG(wstatus);
389 #else
390 termsig = WTERMSIG(wstatus);
391 #endif
392 }
393 if (WIFSTOPPED(wstatus)) {
394 stopped = 1;
395 stopsig = WSTOPSIG(wstatus);
396 }
397 } else if (wait_pid == -1) {
398 running = 0;
399 }
400 #endif
401
402 add_assoc_bool(return_value, "running", running);
403 add_assoc_bool(return_value, "signaled", signaled);
404 add_assoc_bool(return_value, "stopped", stopped);
405 add_assoc_long(return_value, "exitcode", exitcode);
406 add_assoc_long(return_value, "termsig", termsig);
407 add_assoc_long(return_value, "stopsig", stopsig);
408 }
409 /* }}} */
410
411 /* {{{ handy definitions for portability/readability */
412 #ifdef PHP_WIN32
413 # define pipe(pair) (CreatePipe(&pair[0], &pair[1], &security, 0) ? 0 : -1)
414
415 # define COMSPEC_NT "cmd.exe"
416
dup_handle(HANDLE src,BOOL inherit,BOOL closeorig)417 static inline HANDLE dup_handle(HANDLE src, BOOL inherit, BOOL closeorig)
418 {
419 HANDLE copy, self = GetCurrentProcess();
420
421 if (!DuplicateHandle(self, src, self, ©, 0, inherit, DUPLICATE_SAME_ACCESS |
422 (closeorig ? DUPLICATE_CLOSE_SOURCE : 0)))
423 return NULL;
424 return copy;
425 }
426
dup_fd_as_handle(int fd)427 static inline HANDLE dup_fd_as_handle(int fd)
428 {
429 return dup_handle((HANDLE)_get_osfhandle(fd), TRUE, FALSE);
430 }
431
432 # define close_descriptor(fd) CloseHandle(fd)
433 #else
434 # define close_descriptor(fd) close(fd)
435 #endif
436
437 #define DESC_PIPE 1
438 #define DESC_FILE 2
439 #define DESC_PARENT_MODE_WRITE 8
440
441 struct php_proc_open_descriptor_item {
442 int index; /* desired fd number in child process */
443 php_file_descriptor_t parentend, childend; /* fds for pipes in parent/child */
444 int mode; /* mode for proc_open code */
445 int mode_flags; /* mode flags for opening fds */
446 };
447 /* }}} */
448
449 /* {{{ proto resource proc_open(string command, array descriptorspec, array &pipes [, string cwd [, array env [, array other_options]]])
450 Run a process with more control over it's file descriptors */
PHP_FUNCTION(proc_open)451 PHP_FUNCTION(proc_open)
452 {
453 char *command, *cwd=NULL;
454 int command_len, cwd_len = 0;
455 zval *descriptorspec;
456 zval *pipes;
457 zval *environment = NULL;
458 zval *other_options = NULL;
459 php_process_env_t env;
460 int ndesc = 0;
461 int i;
462 zval **descitem = NULL;
463 HashPosition pos;
464 struct php_proc_open_descriptor_item descriptors[PHP_PROC_OPEN_MAX_DESCRIPTORS];
465 #ifdef PHP_WIN32
466 PROCESS_INFORMATION pi;
467 HANDLE childHandle;
468 STARTUPINFO si;
469 BOOL newprocok;
470 SECURITY_ATTRIBUTES security;
471 DWORD dwCreateFlags = 0;
472 char *command_with_cmd;
473 UINT old_error_mode;
474 char cur_cwd[MAXPATHLEN];
475 #endif
476 #ifdef NETWARE
477 char** child_argv = NULL;
478 char* command_dup = NULL;
479 char* orig_cwd = NULL;
480 int command_num_args = 0;
481 wiring_t channel;
482 #endif
483 php_process_id_t child;
484 struct php_process_handle *proc;
485 int is_persistent = 0; /* TODO: ensure that persistent procs will work */
486 #ifdef PHP_WIN32
487 int suppress_errors = 0;
488 int bypass_shell = 0;
489 #endif
490 #if PHP_CAN_DO_PTS
491 php_file_descriptor_t dev_ptmx = -1; /* master */
492 php_file_descriptor_t slave_pty = -1;
493 #endif
494
495 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "saz|s!a!a!", &command,
496 &command_len, &descriptorspec, &pipes, &cwd, &cwd_len, &environment,
497 &other_options) == FAILURE) {
498 RETURN_FALSE;
499 }
500
501 command = pestrdup(command, is_persistent);
502
503 #ifdef PHP_WIN32
504 if (other_options) {
505 zval **item;
506 if (SUCCESS == zend_hash_find(Z_ARRVAL_P(other_options), "suppress_errors", sizeof("suppress_errors"), (void**)&item)) {
507 if ((Z_TYPE_PP(item) == IS_BOOL || Z_TYPE_PP(item) == IS_LONG) &&
508 Z_LVAL_PP(item)) {
509 suppress_errors = 1;
510 }
511 }
512 if (SUCCESS == zend_hash_find(Z_ARRVAL_P(other_options), "bypass_shell", sizeof("bypass_shell"), (void**)&item)) {
513 if ((Z_TYPE_PP(item) == IS_BOOL || Z_TYPE_PP(item) == IS_LONG) &&
514 Z_LVAL_PP(item)) {
515 bypass_shell = 1;
516 }
517 }
518 }
519 #endif
520
521 command_len = strlen(command);
522
523 if (environment) {
524 env = _php_array_to_envp(environment, is_persistent TSRMLS_CC);
525 } else {
526 memset(&env, 0, sizeof(env));
527 }
528
529 memset(descriptors, 0, sizeof(descriptors));
530
531 #ifdef PHP_WIN32
532 /* we use this to allow the child to inherit handles */
533 memset(&security, 0, sizeof(security));
534 security.nLength = sizeof(security);
535 security.bInheritHandle = TRUE;
536 security.lpSecurityDescriptor = NULL;
537 #endif
538
539 /* walk the descriptor spec and set up files/pipes */
540 zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(descriptorspec), &pos);
541 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(descriptorspec), (void **)&descitem, &pos) == SUCCESS) {
542 char *str_index;
543 ulong nindex;
544 zval **ztype;
545
546 str_index = NULL;
547 zend_hash_get_current_key_ex(Z_ARRVAL_P(descriptorspec), &str_index, NULL, &nindex, 0, &pos);
548
549 if (str_index) {
550 php_error_docref(NULL TSRMLS_CC, E_WARNING, "descriptor spec must be an integer indexed array");
551 goto exit_fail;
552 }
553
554 descriptors[ndesc].index = nindex;
555
556 if (Z_TYPE_PP(descitem) == IS_RESOURCE) {
557 /* should be a stream - try and dup the descriptor */
558 php_stream *stream;
559 int fd;
560
561 php_stream_from_zval(stream, descitem);
562
563 if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, REPORT_ERRORS)) {
564 goto exit_fail;
565 }
566
567 #ifdef PHP_WIN32
568 descriptors[ndesc].childend = dup_fd_as_handle(fd);
569 if (descriptors[ndesc].childend == NULL) {
570 php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to dup File-Handle for descriptor %d", nindex);
571 goto exit_fail;
572 }
573 #else
574 descriptors[ndesc].childend = dup(fd);
575 if (descriptors[ndesc].childend < 0) {
576 php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to dup File-Handle for descriptor %ld - %s", nindex, strerror(errno));
577 goto exit_fail;
578 }
579 #endif
580 descriptors[ndesc].mode = DESC_FILE;
581
582 } else if (Z_TYPE_PP(descitem) != IS_ARRAY) {
583 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Descriptor item must be either an array or a File-Handle");
584 goto exit_fail;
585 } else {
586
587 if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 0, (void **)&ztype) == SUCCESS) {
588 convert_to_string_ex(ztype);
589 } else {
590 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing handle qualifier in array");
591 goto exit_fail;
592 }
593
594 if (strcmp(Z_STRVAL_PP(ztype), "pipe") == 0) {
595 php_file_descriptor_t newpipe[2];
596 zval **zmode;
597
598 if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 1, (void **)&zmode) == SUCCESS) {
599 convert_to_string_ex(zmode);
600 } else {
601 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing mode parameter for 'pipe'");
602 goto exit_fail;
603 }
604
605 descriptors[ndesc].mode = DESC_PIPE;
606
607 if (0 != pipe(newpipe)) {
608 php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to create pipe %s", strerror(errno));
609 goto exit_fail;
610 }
611
612 if (strncmp(Z_STRVAL_PP(zmode), "w", 1) != 0) {
613 descriptors[ndesc].parentend = newpipe[1];
614 descriptors[ndesc].childend = newpipe[0];
615 descriptors[ndesc].mode |= DESC_PARENT_MODE_WRITE;
616 } else {
617 descriptors[ndesc].parentend = newpipe[0];
618 descriptors[ndesc].childend = newpipe[1];
619 }
620 #ifdef PHP_WIN32
621 /* don't let the child inherit the parent side of the pipe */
622 descriptors[ndesc].parentend = dup_handle(descriptors[ndesc].parentend, FALSE, TRUE);
623 #endif
624 descriptors[ndesc].mode_flags = descriptors[ndesc].mode & DESC_PARENT_MODE_WRITE ? O_WRONLY : O_RDONLY;
625 #ifdef PHP_WIN32
626 if (Z_STRLEN_PP(zmode) >= 2 && Z_STRVAL_PP(zmode)[1] == 'b')
627 descriptors[ndesc].mode_flags |= O_BINARY;
628 #endif
629
630 } else if (strcmp(Z_STRVAL_PP(ztype), "file") == 0) {
631 zval **zfile, **zmode;
632 int fd;
633 php_stream *stream;
634
635 descriptors[ndesc].mode = DESC_FILE;
636
637 if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 1, (void **)&zfile) == SUCCESS) {
638 convert_to_string_ex(zfile);
639 } else {
640 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing file name parameter for 'file'");
641 goto exit_fail;
642 }
643
644 if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 2, (void **)&zmode) == SUCCESS) {
645 convert_to_string_ex(zmode);
646 } else {
647 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing mode parameter for 'file'");
648 goto exit_fail;
649 }
650
651 /* try a wrapper */
652 stream = php_stream_open_wrapper(Z_STRVAL_PP(zfile), Z_STRVAL_PP(zmode),
653 REPORT_ERRORS|STREAM_WILL_CAST, NULL);
654
655 /* force into an fd */
656 if (stream == NULL || FAILURE == php_stream_cast(stream,
657 PHP_STREAM_CAST_RELEASE|PHP_STREAM_AS_FD,
658 (void **)&fd, REPORT_ERRORS)) {
659 goto exit_fail;
660 }
661
662 #ifdef PHP_WIN32
663 descriptors[ndesc].childend = dup_fd_as_handle(fd);
664 _close(fd);
665
666 /* simulate the append mode by fseeking to the end of the file
667 this introduces a potential race-condition, but it is the best we can do, though */
668 if (strchr(Z_STRVAL_PP(zmode), 'a')) {
669 SetFilePointer(descriptors[ndesc].childend, 0, NULL, FILE_END);
670 }
671 #else
672 descriptors[ndesc].childend = fd;
673 #endif
674 } else if (strcmp(Z_STRVAL_PP(ztype), "pty") == 0) {
675 #if PHP_CAN_DO_PTS
676 if (dev_ptmx == -1) {
677 /* open things up */
678 dev_ptmx = open("/dev/ptmx", O_RDWR);
679 if (dev_ptmx == -1) {
680 php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to open /dev/ptmx, errno %d", errno);
681 goto exit_fail;
682 }
683 grantpt(dev_ptmx);
684 unlockpt(dev_ptmx);
685 slave_pty = open(ptsname(dev_ptmx), O_RDWR);
686
687 if (slave_pty == -1) {
688 php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to open slave pty, errno %d", errno);
689 goto exit_fail;
690 }
691 }
692 descriptors[ndesc].mode = DESC_PIPE;
693 descriptors[ndesc].childend = dup(slave_pty);
694 descriptors[ndesc].parentend = dup(dev_ptmx);
695 descriptors[ndesc].mode_flags = O_RDWR;
696 #else
697 php_error_docref(NULL TSRMLS_CC, E_WARNING, "pty pseudo terminal not supported on this system");
698 goto exit_fail;
699 #endif
700 } else {
701 php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s is not a valid descriptor spec/mode", Z_STRVAL_PP(ztype));
702 goto exit_fail;
703 }
704 }
705
706 zend_hash_move_forward_ex(Z_ARRVAL_P(descriptorspec), &pos);
707 if (++ndesc == PHP_PROC_OPEN_MAX_DESCRIPTORS)
708 break;
709 }
710
711 #ifdef PHP_WIN32
712 if (cwd == NULL) {
713 char *getcwd_result;
714 getcwd_result = VCWD_GETCWD(cur_cwd, MAXPATHLEN);
715 if (!getcwd_result) {
716 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot get current directory");
717 goto exit_fail;
718 }
719 cwd = cur_cwd;
720 }
721
722 memset(&si, 0, sizeof(si));
723 si.cb = sizeof(si);
724 si.dwFlags = STARTF_USESTDHANDLES;
725
726 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
727 si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
728 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
729
730 /* redirect stdin/stdout/stderr if requested */
731 for (i = 0; i < ndesc; i++) {
732 switch(descriptors[i].index) {
733 case 0:
734 si.hStdInput = descriptors[i].childend;
735 break;
736 case 1:
737 si.hStdOutput = descriptors[i].childend;
738 break;
739 case 2:
740 si.hStdError = descriptors[i].childend;
741 break;
742 }
743 }
744
745
746 memset(&pi, 0, sizeof(pi));
747
748 if (suppress_errors) {
749 old_error_mode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
750 }
751
752 dwCreateFlags = NORMAL_PRIORITY_CLASS;
753 if(strcmp(sapi_module.name, "cli") != 0) {
754 dwCreateFlags |= CREATE_NO_WINDOW;
755 }
756
757 if (bypass_shell) {
758 newprocok = CreateProcess(NULL, command, &security, &security, TRUE, dwCreateFlags, env.envp, cwd, &si, &pi);
759 } else {
760 spprintf(&command_with_cmd, 0, "%s /c %s", COMSPEC_NT, command);
761
762 newprocok = CreateProcess(NULL, command_with_cmd, &security, &security, TRUE, dwCreateFlags, env.envp, cwd, &si, &pi);
763
764 efree(command_with_cmd);
765 }
766
767 if (suppress_errors) {
768 SetErrorMode(old_error_mode);
769 }
770
771 if (FALSE == newprocok) {
772 DWORD dw = GetLastError();
773
774 /* clean up all the descriptors */
775 for (i = 0; i < ndesc; i++) {
776 CloseHandle(descriptors[i].childend);
777 if (descriptors[i].parentend) {
778 CloseHandle(descriptors[i].parentend);
779 }
780 }
781 php_error_docref(NULL TSRMLS_CC, E_WARNING, "CreateProcess failed, error code - %u", dw);
782 goto exit_fail;
783 }
784
785 childHandle = pi.hProcess;
786 child = pi.dwProcessId;
787 CloseHandle(pi.hThread);
788
789 #elif defined(NETWARE)
790 if (cwd) {
791 orig_cwd = getcwd(NULL, PATH_MAX);
792 chdir2(cwd);
793 }
794 channel.infd = descriptors[0].childend;
795 channel.outfd = descriptors[1].childend;
796 channel.errfd = -1;
797 /* Duplicate the command as processing downwards will modify it*/
798 command_dup = strdup(command);
799 if (!command_dup) {
800 goto exit_fail;
801 }
802 /* get a number of args */
803 construct_argc_argv(command_dup, NULL, &command_num_args, NULL);
804 child_argv = (char**) malloc((command_num_args + 1) * sizeof(char*));
805 if(!child_argv) {
806 free(command_dup);
807 if (cwd && orig_cwd) {
808 chdir2(orig_cwd);
809 free(orig_cwd);
810 }
811 }
812 /* fill the child arg vector */
813 construct_argc_argv(command_dup, NULL, &command_num_args, child_argv);
814 child_argv[command_num_args] = NULL;
815 child = procve(child_argv[0], PROC_DETACHED|PROC_INHERIT_CWD, NULL, &channel, NULL, NULL, 0, NULL, (const char**)child_argv);
816 free(child_argv);
817 free(command_dup);
818 if (cwd && orig_cwd) {
819 chdir2(orig_cwd);
820 free(orig_cwd);
821 }
822 if (child < 0) {
823 /* failed to fork() */
824 /* clean up all the descriptors */
825 for (i = 0; i < ndesc; i++) {
826 close(descriptors[i].childend);
827 if (descriptors[i].parentend)
828 close(descriptors[i].parentend);
829 }
830 php_error_docref(NULL TSRMLS_CC, E_WARNING, "procve failed - %s", strerror(errno));
831 goto exit_fail;
832 }
833 #elif HAVE_FORK
834 /* the unix way */
835 child = fork();
836
837 if (child == 0) {
838 /* this is the child process */
839
840 #if PHP_CAN_DO_PTS
841 if (dev_ptmx >= 0) {
842 int my_pid = getpid();
843
844 #ifdef TIOCNOTTY
845 /* detach from original tty. Might only need this if isatty(0) is true */
846 ioctl(0,TIOCNOTTY,NULL);
847 #else
848 setsid();
849 #endif
850 /* become process group leader */
851 setpgid(my_pid, my_pid);
852 tcsetpgrp(0, my_pid);
853 }
854 #endif
855
856 /* close those descriptors that we just opened for the parent stuff,
857 * dup new descriptors into required descriptors and close the original
858 * cruft */
859 for (i = 0; i < ndesc; i++) {
860 switch (descriptors[i].mode & ~DESC_PARENT_MODE_WRITE) {
861 case DESC_PIPE:
862 close(descriptors[i].parentend);
863 break;
864 }
865 if (dup2(descriptors[i].childend, descriptors[i].index) < 0)
866 perror("dup2");
867 if (descriptors[i].childend != descriptors[i].index)
868 close(descriptors[i].childend);
869 }
870
871 #if PHP_CAN_DO_PTS
872 if (dev_ptmx >= 0) {
873 close(dev_ptmx);
874 close(slave_pty);
875 }
876 #endif
877
878 if (cwd) {
879 php_ignore_value(chdir(cwd));
880 }
881
882 if (env.envarray) {
883 execle("/bin/sh", "sh", "-c", command, NULL, env.envarray);
884 } else {
885 execl("/bin/sh", "sh", "-c", command, NULL);
886 }
887 _exit(127);
888
889 } else if (child < 0) {
890 /* failed to fork() */
891
892 /* clean up all the descriptors */
893 for (i = 0; i < ndesc; i++) {
894 close(descriptors[i].childend);
895 if (descriptors[i].parentend)
896 close(descriptors[i].parentend);
897 }
898
899 php_error_docref(NULL TSRMLS_CC, E_WARNING, "fork failed - %s", strerror(errno));
900
901 goto exit_fail;
902
903 }
904 #else
905 # error You lose (configure should not have let you get here)
906 #endif
907 /* we forked/spawned and this is the parent */
908
909 proc = (struct php_process_handle*)pemalloc(sizeof(struct php_process_handle), is_persistent);
910 proc->is_persistent = is_persistent;
911 proc->command = command;
912 proc->npipes = ndesc;
913 proc->child = child;
914 #ifdef PHP_WIN32
915 proc->childHandle = childHandle;
916 #endif
917 proc->env = env;
918
919 if (pipes != NULL) {
920 zval_dtor(pipes);
921 }
922 array_init(pipes);
923
924 #if PHP_CAN_DO_PTS
925 if (dev_ptmx >= 0) {
926 close(dev_ptmx);
927 close(slave_pty);
928 }
929 #endif
930
931 /* clean up all the child ends and then open streams on the parent
932 * ends, where appropriate */
933 for (i = 0; i < ndesc; i++) {
934 char *mode_string=NULL;
935 php_stream *stream = NULL;
936
937 close_descriptor(descriptors[i].childend);
938
939 switch (descriptors[i].mode & ~DESC_PARENT_MODE_WRITE) {
940 case DESC_PIPE:
941 switch(descriptors[i].mode_flags) {
942 #ifdef PHP_WIN32
943 case O_WRONLY|O_BINARY:
944 mode_string = "wb";
945 break;
946 case O_RDONLY|O_BINARY:
947 mode_string = "rb";
948 break;
949 #endif
950 case O_WRONLY:
951 mode_string = "w";
952 break;
953 case O_RDONLY:
954 mode_string = "r";
955 break;
956 case O_RDWR:
957 mode_string = "r+";
958 break;
959 }
960 #ifdef PHP_WIN32
961 stream = php_stream_fopen_from_fd(_open_osfhandle((zend_intptr_t)descriptors[i].parentend,
962 descriptors[i].mode_flags), mode_string, NULL);
963 #else
964 stream = php_stream_fopen_from_fd(descriptors[i].parentend, mode_string, NULL);
965 # if defined(F_SETFD) && defined(FD_CLOEXEC)
966 /* mark the descriptor close-on-exec, so that it won't be inherited by potential other children */
967 fcntl(descriptors[i].parentend, F_SETFD, FD_CLOEXEC);
968 # endif
969 #endif
970 if (stream) {
971 zval *retfp;
972
973 /* nasty hack; don't copy it */
974 stream->flags |= PHP_STREAM_FLAG_NO_SEEK;
975
976 MAKE_STD_ZVAL(retfp);
977 php_stream_to_zval(stream, retfp);
978 add_index_zval(pipes, descriptors[i].index, retfp);
979
980 proc->pipes[i] = Z_LVAL_P(retfp);
981 }
982 break;
983 default:
984 proc->pipes[i] = 0;
985 }
986 }
987
988 ZEND_REGISTER_RESOURCE(return_value, proc, le_proc_open);
989 return;
990
991 exit_fail:
992 _php_free_envp(env, is_persistent);
993 pefree(command, is_persistent);
994 #if PHP_CAN_DO_PTS
995 if (dev_ptmx >= 0) {
996 close(dev_ptmx);
997 }
998 if (slave_pty >= 0) {
999 close(slave_pty);
1000 }
1001 #endif
1002 RETURN_FALSE;
1003
1004 }
1005 /* }}} */
1006
1007 #endif /* PHP_CAN_SUPPORT_PROC_OPEN */
1008
1009 /*
1010 * Local variables:
1011 * tab-width: 4
1012 * c-basic-offset: 4
1013 * End:
1014 * vim600: sw=4 ts=4 fdm=marker
1015 * vim<600: sw=4 ts=4
1016 */
1017