Back to index

php5  5.3.10
proc_open.c
Go to the documentation of this file.
00001 /*
00002    +----------------------------------------------------------------------+
00003    | PHP Version 5                                                        |
00004    +----------------------------------------------------------------------+
00005    | Copyright (c) 1997-2012 The PHP Group                                |
00006    +----------------------------------------------------------------------+
00007    | This source file is subject to version 3.01 of the PHP license,      |
00008    | that is bundled with this package in the file LICENSE, and is        |
00009    | available through the world-wide-web at the following url:           |
00010    | http://www.php.net/license/3_01.txt                                  |
00011    | If you did not receive a copy of the PHP license and are unable to   |
00012    | obtain it through the world-wide-web, please send a note to          |
00013    | license@php.net so we can mail you a copy immediately.               |
00014    +----------------------------------------------------------------------+
00015    | Author: Wez Furlong <wez@thebrainroom.com>                           |
00016    +----------------------------------------------------------------------+
00017  */
00018 /* $Id: proc_open.c 321634 2012-01-01 13:15:04Z felipe $ */
00019 
00020 #if 0 && (defined(__linux__) || defined(sun) || defined(__IRIX__))
00021 # define _BSD_SOURCE               /* linux wants this when XOPEN mode is on */
00022 # define _BSD_COMPAT        /* irix: uint */
00023 # define _XOPEN_SOURCE 500  /* turn on Unix98 */
00024 # define __EXTENSIONS__     1      /* Solaris: uint */
00025 #endif
00026 
00027 #include "php.h"
00028 #include <stdio.h>
00029 #include <ctype.h>
00030 #include "php_string.h"
00031 #include "safe_mode.h"
00032 #include "ext/standard/head.h"
00033 #include "ext/standard/basic_functions.h"
00034 #include "ext/standard/file.h"
00035 #include "exec.h"
00036 #include "php_globals.h"
00037 #include "SAPI.h"
00038 
00039 #ifdef NETWARE
00040 #include <proc.h>
00041 #include <library.h>
00042 #endif
00043 
00044 #if HAVE_SYS_WAIT_H
00045 #include <sys/wait.h>
00046 #endif
00047 #if HAVE_SIGNAL_H
00048 #include <signal.h>
00049 #endif
00050 
00051 #if HAVE_SYS_STAT_H
00052 #include <sys/stat.h>
00053 #endif
00054 #if HAVE_FCNTL_H
00055 #include <fcntl.h>
00056 #endif
00057 
00058 /* This symbol is defined in ext/standard/config.m4.
00059  * Essentially, it is set if you HAVE_FORK || PHP_WIN32
00060  * Otherplatforms may modify that configure check and add suitable #ifdefs
00061  * around the alternate code.
00062  * */
00063 #ifdef PHP_CAN_SUPPORT_PROC_OPEN
00064 
00065 #if 0 && HAVE_PTSNAME && HAVE_GRANTPT && HAVE_UNLOCKPT && HAVE_SYS_IOCTL_H && HAVE_TERMIOS_H
00066 # include <sys/ioctl.h>
00067 # include <termios.h>
00068 # define PHP_CAN_DO_PTS     1
00069 #endif
00070 
00071 #include "proc_open.h"
00072 
00073 static int le_proc_open;
00074 
00075 /* {{{ _php_array_to_envp */
00076 static php_process_env_t _php_array_to_envp(zval *environment, int is_persistent TSRMLS_DC)
00077 {
00078        zval **element;
00079        php_process_env_t env;
00080        char *string_key, *data;
00081 #ifndef PHP_WIN32
00082        char **ep;
00083 #endif
00084        char *p;
00085        uint string_length, cnt, l, sizeenv=0, el_len;
00086        ulong num_key;
00087        HashTable *target_hash;
00088        HashPosition pos;
00089 
00090        memset(&env, 0, sizeof(env));
00091 
00092        if (!environment) {
00093               return env;
00094        }
00095 
00096        cnt = zend_hash_num_elements(Z_ARRVAL_P(environment));
00097 
00098        if (cnt < 1) {
00099 #ifndef PHP_WIN32
00100               env.envarray = (char **) pecalloc(1, sizeof(char *), is_persistent);
00101 #endif
00102               env.envp = (char *) pecalloc(4, 1, is_persistent);
00103               return env;
00104        }
00105 
00106        target_hash = HASH_OF(environment);
00107        if (!target_hash) {
00108               return env;
00109        }
00110 
00111        /* first, we have to get the size of all the elements in the hash */
00112        for (zend_hash_internal_pointer_reset_ex(target_hash, &pos);
00113                      zend_hash_get_current_data_ex(target_hash, (void **) &element, &pos) == SUCCESS;
00114                      zend_hash_move_forward_ex(target_hash, &pos)) {
00115 
00116               convert_to_string_ex(element);
00117               el_len = Z_STRLEN_PP(element);
00118               if (el_len == 0) {
00119                      continue;
00120               }
00121 
00122               sizeenv += el_len+1;
00123 
00124               switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_length, &num_key, 0, &pos)) {
00125                      case HASH_KEY_IS_STRING:
00126                             if (string_length == 0) {
00127                                    continue;
00128                             }
00129                             sizeenv += string_length+1;
00130                             break;
00131               }
00132        }
00133 
00134 #ifndef PHP_WIN32
00135        ep = env.envarray = (char **) pecalloc(cnt + 1, sizeof(char *), is_persistent);
00136 #endif
00137        p = env.envp = (char *) pecalloc(sizeenv + 4, 1, is_persistent);
00138 
00139        for (zend_hash_internal_pointer_reset_ex(target_hash, &pos);
00140                      zend_hash_get_current_data_ex(target_hash, (void **) &element, &pos) == SUCCESS;
00141                      zend_hash_move_forward_ex(target_hash, &pos)) {
00142 
00143               convert_to_string_ex(element);
00144               el_len = Z_STRLEN_PP(element);
00145 
00146               if (el_len == 0) {
00147                      continue;
00148               }
00149 
00150               data = Z_STRVAL_PP(element);
00151               switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_length, &num_key, 0, &pos)) {
00152                      case HASH_KEY_IS_STRING:
00153                             if (string_length == 0) {
00154                                    continue;
00155                             }
00156                             if (PG(safe_mode)) {
00157                                    /* Check the protected list */
00158                                    if (zend_hash_exists(&BG(sm_protected_env_vars), string_key, string_length - 1)) {
00159                                           php_error_docref(NULL TSRMLS_CC, E_WARNING, "Safe Mode warning: Cannot override protected environment variable '%s'", string_key);
00160                                           return env;
00161                                    }
00162                                    /* Check the allowed list */
00163                                    if (BG(sm_allowed_env_vars) && *BG(sm_allowed_env_vars)) {
00164                                           char *allowed_env_vars = estrdup(BG(sm_allowed_env_vars));
00165                                           char *strtok_buf = NULL;
00166                                           char *allowed_prefix = php_strtok_r(allowed_env_vars, ", ", &strtok_buf);
00167                                           zend_bool allowed = 0;
00168 
00169                                           while (allowed_prefix) {
00170                                                  if (!strncmp(allowed_prefix, string_key, strlen(allowed_prefix))) {
00171                                                         allowed = 1;
00172                                                         break;
00173                                                  }
00174                                                  allowed_prefix = php_strtok_r(NULL, ", ", &strtok_buf);
00175                                           }
00176                                           efree(allowed_env_vars);
00177                                           if (!allowed) {
00178                                                  php_error_docref(NULL TSRMLS_CC, E_WARNING, "Safe Mode warning: Cannot set environment variable '%s' - it's not in the allowed list", string_key);
00179                                                  return env;
00180                                           }
00181                                    }
00182                             }
00183 
00184                             l = string_length + el_len + 1;
00185                             memcpy(p, string_key, string_length);
00186                             strncat(p, "=", 1);
00187                             strncat(p, data, el_len);
00188 
00189 #ifndef PHP_WIN32
00190                             *ep = p;
00191                             ++ep;
00192 #endif
00193                             p += l;
00194                             break;
00195                      case HASH_KEY_IS_LONG:
00196                             memcpy(p,data,el_len);
00197 #ifndef PHP_WIN32
00198                             *ep = p;
00199                             ++ep;
00200 #endif
00201                             p += el_len + 1;
00202                             break;
00203                      case HASH_KEY_NON_EXISTANT:
00204                             break;
00205               }
00206        }
00207 
00208        assert((uint)(p - env.envp) <= sizeenv);
00209 
00210        zend_hash_internal_pointer_reset_ex(target_hash, &pos);
00211 
00212        return env;
00213 }
00214 /* }}} */
00215 
00216 /* {{{ _php_free_envp */
00217 static void _php_free_envp(php_process_env_t env, int is_persistent)
00218 {
00219 #ifndef PHP_WIN32
00220        if (env.envarray) {
00221               pefree(env.envarray, is_persistent);
00222        }
00223 #endif
00224        if (env.envp) {
00225               pefree(env.envp, is_persistent);
00226        }
00227 }
00228 /* }}} */
00229 
00230 /* {{{ proc_open_rsrc_dtor */
00231 static void proc_open_rsrc_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
00232 {
00233        struct php_process_handle *proc = (struct php_process_handle*)rsrc->ptr;
00234        int i;
00235 #ifdef PHP_WIN32
00236        DWORD wstatus;
00237 #elif HAVE_SYS_WAIT_H
00238        int wstatus;
00239        pid_t wait_pid;
00240 #endif
00241 
00242        /* Close all handles to avoid a deadlock */
00243        for (i = 0; i < proc->npipes; i++) {
00244               if (proc->pipes[i] != 0) {
00245                      zend_list_delete(proc->pipes[i]);
00246                      proc->pipes[i] = 0;
00247               }
00248        }
00249 
00250 #ifdef PHP_WIN32
00251        WaitForSingleObject(proc->childHandle, INFINITE);
00252        GetExitCodeProcess(proc->childHandle, &wstatus);
00253        FG(pclose_ret) = wstatus;
00254        CloseHandle(proc->childHandle);
00255 
00256 #elif HAVE_SYS_WAIT_H
00257 
00258        do {
00259               wait_pid = waitpid(proc->child, &wstatus, 0);
00260        } while (wait_pid == -1 && errno == EINTR);
00261 
00262        if (wait_pid == -1) {
00263               FG(pclose_ret) = -1;
00264        } else {
00265               if (WIFEXITED(wstatus))
00266                      wstatus = WEXITSTATUS(wstatus);
00267               FG(pclose_ret) = wstatus;
00268        }
00269 
00270 #else
00271        FG(pclose_ret) = -1;
00272 #endif
00273        _php_free_envp(proc->env, proc->is_persistent);
00274        pefree(proc->command, proc->is_persistent);
00275        pefree(proc, proc->is_persistent);
00276 }
00277 /* }}} */
00278 
00279 /* {{{ php_make_safe_mode_command */
00280 static int php_make_safe_mode_command(char *cmd, char **safecmd, int is_persistent TSRMLS_DC)
00281 {
00282        int lcmd, larg0;
00283        char *space, *sep, *arg0;
00284 
00285        if (!PG(safe_mode)) {
00286               *safecmd = pestrdup(cmd, is_persistent);
00287               return SUCCESS;
00288        }
00289 
00290        lcmd = strlen(cmd);
00291 
00292        arg0 = estrndup(cmd, lcmd);
00293 
00294        space = memchr(arg0, ' ', lcmd);
00295        if (space) {
00296               *space = '\0';
00297               larg0 = space - arg0;
00298        } else {
00299               larg0 = lcmd;
00300        }
00301 
00302        if (php_memnstr(arg0, "..", sizeof("..")-1, arg0 + larg0)) {
00303               php_error_docref(NULL TSRMLS_CC, E_WARNING, "No '..' components allowed in path");
00304               efree(arg0);
00305               return FAILURE;
00306        }
00307 
00308        sep = zend_memrchr(arg0, PHP_DIR_SEPARATOR, larg0);
00309 
00310        spprintf(safecmd, 0, "%s%s%s%s", PG(safe_mode_exec_dir), (sep ? sep : "/"), (sep ? "" : arg0), (space ? cmd + larg0 : ""));
00311 
00312        efree(arg0);
00313        arg0 = php_escape_shell_cmd(*safecmd);
00314        efree(*safecmd);
00315        if (is_persistent) {
00316               *safecmd = pestrdup(arg0, 1);
00317               efree(arg0);
00318        } else {
00319               *safecmd = arg0;
00320        }
00321 
00322        return SUCCESS;
00323 }
00324 /* }}} */
00325 
00326 /* {{{ PHP_MINIT_FUNCTION(proc_open) */
00327 PHP_MINIT_FUNCTION(proc_open)
00328 {
00329        le_proc_open = zend_register_list_destructors_ex(proc_open_rsrc_dtor, NULL, "process", module_number);
00330        return SUCCESS;
00331 }
00332 /* }}} */
00333 
00334 /* {{{ proto bool proc_terminate(resource process [, long signal])
00335    kill a process opened by proc_open */
00336 PHP_FUNCTION(proc_terminate)
00337 {
00338        zval *zproc;
00339        struct php_process_handle *proc;
00340        long sig_no = SIGTERM;
00341 
00342        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &zproc, &sig_no) == FAILURE) {
00343               RETURN_FALSE;
00344        }
00345 
00346        ZEND_FETCH_RESOURCE(proc, struct php_process_handle *, &zproc, -1, "process", le_proc_open);
00347 
00348 #ifdef PHP_WIN32
00349        if (TerminateProcess(proc->childHandle, 255)) {
00350               RETURN_TRUE;
00351        } else {
00352               RETURN_FALSE;
00353        }
00354 #else
00355        if (kill(proc->child, sig_no) == 0) {
00356               RETURN_TRUE;
00357        } else {
00358               RETURN_FALSE;
00359        }
00360 #endif
00361 }
00362 /* }}} */
00363 
00364 /* {{{ proto int proc_close(resource process)
00365    close a process opened by proc_open */
00366 PHP_FUNCTION(proc_close)
00367 {
00368        zval *zproc;
00369        struct php_process_handle *proc;
00370 
00371        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zproc) == FAILURE) {
00372               RETURN_FALSE;
00373        }
00374 
00375        ZEND_FETCH_RESOURCE(proc, struct php_process_handle *, &zproc, -1, "process", le_proc_open);
00376 
00377        zend_list_delete(Z_LVAL_P(zproc));
00378        RETURN_LONG(FG(pclose_ret));
00379 }
00380 /* }}} */
00381 
00382 /* {{{ proto array proc_get_status(resource process)
00383    get information about a process opened by proc_open */
00384 PHP_FUNCTION(proc_get_status)
00385 {
00386        zval *zproc;
00387        struct php_process_handle *proc;
00388 #ifdef PHP_WIN32
00389        DWORD wstatus;
00390 #elif HAVE_SYS_WAIT_H
00391        int wstatus;
00392        pid_t wait_pid;
00393 #endif
00394        int running = 1, signaled = 0, stopped = 0;
00395        int exitcode = -1, termsig = 0, stopsig = 0;
00396 
00397        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zproc) == FAILURE) {
00398               RETURN_FALSE;
00399        }
00400 
00401        ZEND_FETCH_RESOURCE(proc, struct php_process_handle *, &zproc, -1, "process", le_proc_open);
00402 
00403        array_init(return_value);
00404 
00405        add_assoc_string(return_value, "command", proc->command, 1);
00406        add_assoc_long(return_value, "pid", (long) proc->child);
00407 
00408 #ifdef PHP_WIN32
00409 
00410        GetExitCodeProcess(proc->childHandle, &wstatus);
00411 
00412        running = wstatus == STILL_ACTIVE;
00413        exitcode = running ? -1 : wstatus;
00414 
00415 #elif HAVE_SYS_WAIT_H
00416 
00417        errno = 0;
00418        wait_pid = waitpid(proc->child, &wstatus, WNOHANG|WUNTRACED);
00419 
00420        if (wait_pid == proc->child) {
00421               if (WIFEXITED(wstatus)) {
00422                      running = 0;
00423                      exitcode = WEXITSTATUS(wstatus);
00424               }
00425               if (WIFSIGNALED(wstatus)) {
00426                      running = 0;
00427                      signaled = 1;
00428 #ifdef NETWARE
00429                      termsig = WIFTERMSIG(wstatus);
00430 #else
00431                      termsig = WTERMSIG(wstatus);
00432 #endif
00433               }
00434               if (WIFSTOPPED(wstatus)) {
00435                      stopped = 1;
00436                      stopsig = WSTOPSIG(wstatus);
00437               }
00438        } else if (wait_pid == -1) {
00439               running = 0;
00440        }
00441 #endif
00442 
00443        add_assoc_bool(return_value, "running", running);
00444        add_assoc_bool(return_value, "signaled", signaled);
00445        add_assoc_bool(return_value, "stopped", stopped);
00446        add_assoc_long(return_value, "exitcode", exitcode);
00447        add_assoc_long(return_value, "termsig", termsig);
00448        add_assoc_long(return_value, "stopsig", stopsig);
00449 }
00450 /* }}} */
00451 
00452 /* {{{ handy definitions for portability/readability */
00453 #ifdef PHP_WIN32
00454 # define pipe(pair)         (CreatePipe(&pair[0], &pair[1], &security, 0) ? 0 : -1)
00455 
00456 # define COMSPEC_NT  "cmd.exe"
00457 
00458 static inline HANDLE dup_handle(HANDLE src, BOOL inherit, BOOL closeorig)
00459 {
00460        HANDLE copy, self = GetCurrentProcess();
00461 
00462        if (!DuplicateHandle(self, src, self, &copy, 0, inherit, DUPLICATE_SAME_ACCESS |
00463                             (closeorig ? DUPLICATE_CLOSE_SOURCE : 0)))
00464               return NULL;
00465        return copy;
00466 }
00467 
00468 static inline HANDLE dup_fd_as_handle(int fd)
00469 {
00470        return dup_handle((HANDLE)_get_osfhandle(fd), TRUE, FALSE);
00471 }
00472 
00473 # define close_descriptor(fd)      CloseHandle(fd)
00474 #else
00475 # define close_descriptor(fd)      close(fd)
00476 #endif
00477 
00478 #define DESC_PIPE           1
00479 #define DESC_FILE           2
00480 #define DESC_PARENT_MODE_WRITE     8
00481 
00482 struct php_proc_open_descriptor_item {
00483        int index;                                              /* desired fd number in child process */
00484        php_file_descriptor_t parentend, childend;       /* fds for pipes in parent/child */
00485        int mode;                                               /* mode for proc_open code */
00486        int mode_flags;                                         /* mode flags for opening fds */
00487 };
00488 /* }}} */
00489 
00490 /* {{{ proto resource proc_open(string command, array descriptorspec, array &pipes [, string cwd [, array env [, array other_options]]])
00491    Run a process with more control over it's file descriptors */
00492 PHP_FUNCTION(proc_open)
00493 {
00494        char *command, *cwd=NULL;
00495        int command_len, cwd_len = 0;
00496        zval *descriptorspec;
00497        zval *pipes;
00498        zval *environment = NULL;
00499        zval *other_options = NULL;
00500        php_process_env_t env;
00501        int ndesc = 0;
00502        int i;
00503        zval **descitem = NULL;
00504        HashPosition pos;
00505        struct php_proc_open_descriptor_item descriptors[PHP_PROC_OPEN_MAX_DESCRIPTORS];
00506 #ifdef PHP_WIN32
00507        PROCESS_INFORMATION pi;
00508        HANDLE childHandle;
00509        STARTUPINFO si;
00510        BOOL newprocok;
00511        SECURITY_ATTRIBUTES security;
00512        DWORD dwCreateFlags = 0;
00513        char *command_with_cmd;
00514        UINT old_error_mode;
00515 #endif
00516 #ifdef NETWARE
00517        char** child_argv = NULL;
00518        char* command_dup = NULL;
00519        char* orig_cwd = NULL;
00520        int command_num_args = 0;
00521        wiring_t channel;
00522 #endif
00523        php_process_id_t child;
00524        struct php_process_handle *proc;
00525        int is_persistent = 0; /* TODO: ensure that persistent procs will work */
00526 #ifdef PHP_WIN32
00527        int suppress_errors = 0;
00528        int bypass_shell = 0;
00529 #endif
00530 #if PHP_CAN_DO_PTS
00531        php_file_descriptor_t dev_ptmx = -1;      /* master */
00532        php_file_descriptor_t slave_pty = -1;
00533 #endif
00534 
00535        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "saz|s!a!a!", &command,
00536                             &command_len, &descriptorspec, &pipes, &cwd, &cwd_len, &environment,
00537                             &other_options) == FAILURE) {
00538               RETURN_FALSE;
00539        }
00540 
00541        if (FAILURE == php_make_safe_mode_command(command, &command, is_persistent TSRMLS_CC)) {
00542               RETURN_FALSE;
00543        }
00544 
00545 #ifdef PHP_WIN32
00546        if (other_options) {
00547               zval **item;
00548               if (SUCCESS == zend_hash_find(Z_ARRVAL_P(other_options), "suppress_errors", sizeof("suppress_errors"), (void**)&item)) {
00549                      if ((Z_TYPE_PP(item) == IS_BOOL || Z_TYPE_PP(item) == IS_LONG) &&
00550                          Z_LVAL_PP(item)) {
00551                             suppress_errors = 1;
00552                      }
00553               }
00554               if (SUCCESS == zend_hash_find(Z_ARRVAL_P(other_options), "bypass_shell", sizeof("bypass_shell"), (void**)&item)) {
00555                      if ((Z_TYPE_PP(item) == IS_BOOL || Z_TYPE_PP(item) == IS_LONG) &&
00556                          Z_LVAL_PP(item)) {
00557                             bypass_shell = 1;
00558                      }
00559               }
00560        }
00561 #endif
00562 
00563        command_len = strlen(command);
00564 
00565        if (environment) {
00566               env = _php_array_to_envp(environment, is_persistent TSRMLS_CC);
00567        } else {
00568               memset(&env, 0, sizeof(env));
00569        }
00570 
00571        memset(descriptors, 0, sizeof(descriptors));
00572 
00573 #ifdef PHP_WIN32
00574        /* we use this to allow the child to inherit handles */
00575        memset(&security, 0, sizeof(security));
00576        security.nLength = sizeof(security);
00577        security.bInheritHandle = TRUE;
00578        security.lpSecurityDescriptor = NULL;
00579 #endif
00580 
00581        /* walk the descriptor spec and set up files/pipes */
00582        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(descriptorspec), &pos);
00583        while (zend_hash_get_current_data_ex(Z_ARRVAL_P(descriptorspec), (void **)&descitem, &pos) == SUCCESS) {
00584               char *str_index;
00585               ulong nindex;
00586               zval **ztype;
00587 
00588               str_index = NULL;
00589               zend_hash_get_current_key_ex(Z_ARRVAL_P(descriptorspec), &str_index, NULL, &nindex, 0, &pos);
00590 
00591               if (str_index) {
00592                      php_error_docref(NULL TSRMLS_CC, E_WARNING, "descriptor spec must be an integer indexed array");
00593                      goto exit_fail;
00594               }
00595 
00596               descriptors[ndesc].index = nindex;
00597 
00598               if (Z_TYPE_PP(descitem) == IS_RESOURCE) {
00599                      /* should be a stream - try and dup the descriptor */
00600                      php_stream *stream;
00601                      int fd;
00602 
00603                      php_stream_from_zval(stream, descitem);
00604 
00605                      if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, REPORT_ERRORS)) {
00606                             goto exit_fail;
00607                      }
00608 
00609 #ifdef PHP_WIN32
00610                      descriptors[ndesc].childend = dup_fd_as_handle(fd);
00611                      if (descriptors[ndesc].childend == NULL) {
00612                             php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to dup File-Handle for descriptor %d", nindex);
00613                             goto exit_fail;
00614                      }
00615 #else
00616                      descriptors[ndesc].childend = dup(fd);
00617                      if (descriptors[ndesc].childend < 0) {
00618                             php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to dup File-Handle for descriptor %ld - %s", nindex, strerror(errno));
00619                             goto exit_fail;
00620                      }
00621 #endif
00622                      descriptors[ndesc].mode = DESC_FILE;
00623 
00624               } else if (Z_TYPE_PP(descitem) != IS_ARRAY) {
00625                      php_error_docref(NULL TSRMLS_CC, E_WARNING, "Descriptor item must be either an array or a File-Handle");
00626                      goto exit_fail;
00627               } else {
00628 
00629                      if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 0, (void **)&ztype) == SUCCESS) {
00630                             convert_to_string_ex(ztype);
00631                      } else {
00632                             php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing handle qualifier in array");
00633                             goto exit_fail;
00634                      }
00635 
00636                      if (strcmp(Z_STRVAL_PP(ztype), "pipe") == 0) {
00637                             php_file_descriptor_t newpipe[2];
00638                             zval **zmode;
00639 
00640                             if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 1, (void **)&zmode) == SUCCESS) {
00641                                    convert_to_string_ex(zmode);
00642                             } else {
00643                                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing mode parameter for 'pipe'");
00644                                    goto exit_fail;
00645                             }
00646 
00647                             descriptors[ndesc].mode = DESC_PIPE;
00648 
00649                             if (0 != pipe(newpipe)) {
00650                                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to create pipe %s", strerror(errno));
00651                                    goto exit_fail;
00652                             }
00653 
00654                             if (strncmp(Z_STRVAL_PP(zmode), "w", 1) != 0) {
00655                                    descriptors[ndesc].parentend = newpipe[1];
00656                                    descriptors[ndesc].childend = newpipe[0];
00657                                    descriptors[ndesc].mode |= DESC_PARENT_MODE_WRITE;
00658                             } else {
00659                                    descriptors[ndesc].parentend = newpipe[0];
00660                                    descriptors[ndesc].childend = newpipe[1];
00661                             }
00662 #ifdef PHP_WIN32
00663                             /* don't let the child inherit the parent side of the pipe */
00664                             descriptors[ndesc].parentend = dup_handle(descriptors[ndesc].parentend, FALSE, TRUE);
00665 #endif
00666                             descriptors[ndesc].mode_flags = descriptors[ndesc].mode & DESC_PARENT_MODE_WRITE ? O_WRONLY : O_RDONLY;
00667 #ifdef PHP_WIN32
00668                             if (Z_STRLEN_PP(zmode) >= 2 && Z_STRVAL_PP(zmode)[1] == 'b')
00669                                    descriptors[ndesc].mode_flags |= O_BINARY;
00670 #endif
00671 
00672                      } else if (strcmp(Z_STRVAL_PP(ztype), "file") == 0) {
00673                             zval **zfile, **zmode;
00674                             int fd;
00675                             php_stream *stream;
00676 
00677                             descriptors[ndesc].mode = DESC_FILE;
00678 
00679                             if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 1, (void **)&zfile) == SUCCESS) {
00680                                    convert_to_string_ex(zfile);
00681                             } else {
00682                                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing file name parameter for 'file'");
00683                                    goto exit_fail;
00684                             }
00685 
00686                             if (zend_hash_index_find(Z_ARRVAL_PP(descitem), 2, (void **)&zmode) == SUCCESS) {
00687                                    convert_to_string_ex(zmode);
00688                             } else {
00689                                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing mode parameter for 'file'");
00690                                    goto exit_fail;
00691                             }
00692 
00693                             /* try a wrapper */
00694                             stream = php_stream_open_wrapper(Z_STRVAL_PP(zfile), Z_STRVAL_PP(zmode),
00695                                           ENFORCE_SAFE_MODE|REPORT_ERRORS|STREAM_WILL_CAST, NULL);
00696 
00697                             /* force into an fd */
00698                             if (stream == NULL || FAILURE == php_stream_cast(stream,
00699                                                  PHP_STREAM_CAST_RELEASE|PHP_STREAM_AS_FD,
00700                                                  (void **)&fd, REPORT_ERRORS)) {
00701                                    goto exit_fail;
00702                             }
00703 
00704 #ifdef PHP_WIN32
00705                             descriptors[ndesc].childend = dup_fd_as_handle(fd);
00706                             _close(fd);
00707 
00708                             /* simulate the append mode by fseeking to the end of the file
00709                             this introduces a potential race-condition, but it is the best we can do, though */
00710                             if (strchr(Z_STRVAL_PP(zmode), 'a')) {
00711                                    SetFilePointer(descriptors[ndesc].childend, 0, NULL, FILE_END);
00712                             }
00713 #else
00714                             descriptors[ndesc].childend = fd;
00715 #endif
00716                      } else if (strcmp(Z_STRVAL_PP(ztype), "pty") == 0) {
00717 #if PHP_CAN_DO_PTS
00718                             if (dev_ptmx == -1) {
00719                                    /* open things up */
00720                                    dev_ptmx = open("/dev/ptmx", O_RDWR);
00721                                    if (dev_ptmx == -1) {
00722                                           php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to open /dev/ptmx, errno %d", errno);
00723                                           goto exit_fail;
00724                                    }
00725                                    grantpt(dev_ptmx);
00726                                    unlockpt(dev_ptmx);
00727                                    slave_pty = open(ptsname(dev_ptmx), O_RDWR);
00728 
00729                                    if (slave_pty == -1) {
00730                                           php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to open slave pty, errno %d", errno);
00731                                           goto exit_fail;
00732                                    }
00733                             }
00734                             descriptors[ndesc].mode = DESC_PIPE;
00735                             descriptors[ndesc].childend = dup(slave_pty);
00736                             descriptors[ndesc].parentend = dup(dev_ptmx);
00737                             descriptors[ndesc].mode_flags = O_RDWR;
00738 #else
00739                             php_error_docref(NULL TSRMLS_CC, E_WARNING, "pty pseudo terminal not supported on this system");
00740                             goto exit_fail;
00741 #endif
00742                      } else {
00743                             php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s is not a valid descriptor spec/mode", Z_STRVAL_PP(ztype));
00744                             goto exit_fail;
00745                      }
00746               }
00747 
00748               zend_hash_move_forward_ex(Z_ARRVAL_P(descriptorspec), &pos);
00749               if (++ndesc == PHP_PROC_OPEN_MAX_DESCRIPTORS)
00750                      break;
00751        }
00752 
00753 #ifdef PHP_WIN32
00754        if (cwd == NULL) {
00755               char cur_cwd[MAXPATHLEN];
00756               char *getcwd_result;
00757               getcwd_result = VCWD_GETCWD(cur_cwd, MAXPATHLEN);
00758               if (!getcwd_result) {
00759                      php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot get current directory");
00760                      goto exit_fail;
00761               }
00762        }
00763 
00764        memset(&si, 0, sizeof(si));
00765        si.cb = sizeof(si);
00766        si.dwFlags = STARTF_USESTDHANDLES;
00767 
00768        si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
00769        si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
00770        si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
00771 
00772        /* redirect stdin/stdout/stderr if requested */
00773        for (i = 0; i < ndesc; i++) {
00774               switch(descriptors[i].index) {
00775                      case 0:
00776                             si.hStdInput = descriptors[i].childend;
00777                             break;
00778                      case 1:
00779                             si.hStdOutput = descriptors[i].childend;
00780                             break;
00781                      case 2:
00782                             si.hStdError = descriptors[i].childend;
00783                             break;
00784               }
00785        }
00786 
00787 
00788        memset(&pi, 0, sizeof(pi));
00789 
00790        if (suppress_errors) {
00791               old_error_mode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
00792        }
00793 
00794        dwCreateFlags = NORMAL_PRIORITY_CLASS;
00795        if(strcmp(sapi_module.name, "cli") != 0) {
00796               dwCreateFlags |= CREATE_NO_WINDOW;
00797        }
00798 
00799        if (bypass_shell) {
00800               newprocok = CreateProcess(NULL, command, &security, &security, TRUE, dwCreateFlags, env.envp, cwd, &si, &pi);
00801        } else {
00802               spprintf(&command_with_cmd, 0, "%s /c %s", COMSPEC_NT, command);
00803 
00804               newprocok = CreateProcess(NULL, command_with_cmd, &security, &security, TRUE, dwCreateFlags, env.envp, cwd, &si, &pi);
00805 
00806               efree(command_with_cmd);
00807        }
00808 
00809        if (suppress_errors) {
00810               SetErrorMode(old_error_mode);
00811        }
00812 
00813        if (FALSE == newprocok) {
00814               DWORD dw = GetLastError();
00815 
00816               /* clean up all the descriptors */
00817               for (i = 0; i < ndesc; i++) {
00818                      CloseHandle(descriptors[i].childend);
00819                      if (descriptors[i].parentend) {
00820                             CloseHandle(descriptors[i].parentend);
00821                      }
00822               }
00823               php_error_docref(NULL TSRMLS_CC, E_WARNING, "CreateProcess failed, error code - %u", dw);
00824               goto exit_fail;
00825        }
00826 
00827        childHandle = pi.hProcess;
00828        child       = pi.dwProcessId;
00829        CloseHandle(pi.hThread);
00830 
00831 #elif defined(NETWARE)
00832        if (cwd) {
00833               orig_cwd = getcwd(NULL, PATH_MAX);
00834               chdir2(cwd);
00835        }
00836        channel.infd = descriptors[0].childend;
00837        channel.outfd = descriptors[1].childend;
00838        channel.errfd = -1;
00839        /* Duplicate the command as processing downwards will modify it*/
00840        command_dup = strdup(command);
00841        if (!command_dup) {
00842               goto exit_fail;
00843        }
00844        /* get a number of args */
00845        construct_argc_argv(command_dup, NULL, &command_num_args, NULL);
00846        child_argv = (char**) malloc((command_num_args + 1) * sizeof(char*));
00847        if(!child_argv) {
00848               free(command_dup);
00849               if (cwd && orig_cwd) {
00850                      chdir2(orig_cwd);
00851                      free(orig_cwd);
00852               }
00853        }
00854        /* fill the child arg vector */
00855        construct_argc_argv(command_dup, NULL, &command_num_args, child_argv);
00856        child_argv[command_num_args] = NULL;
00857        child = procve(child_argv[0], PROC_DETACHED|PROC_INHERIT_CWD, NULL, &channel, NULL, NULL, 0, NULL, (const char**)child_argv);
00858        free(child_argv);
00859        free(command_dup);
00860        if (cwd && orig_cwd) {
00861               chdir2(orig_cwd);
00862               free(orig_cwd);
00863        }
00864        if (child < 0) {
00865               /* failed to fork() */
00866               /* clean up all the descriptors */
00867               for (i = 0; i < ndesc; i++) {
00868                      close(descriptors[i].childend);
00869                      if (descriptors[i].parentend)
00870                             close(descriptors[i].parentend);
00871               }
00872               php_error_docref(NULL TSRMLS_CC, E_WARNING, "procve failed - %s", strerror(errno));
00873               goto exit_fail;
00874        }
00875 #elif HAVE_FORK
00876        /* the unix way */
00877        child = fork();
00878 
00879        if (child == 0) {
00880               /* this is the child process */
00881 
00882 #if PHP_CAN_DO_PTS
00883               if (dev_ptmx >= 0) {
00884                      int my_pid = getpid();
00885 
00886 #ifdef TIOCNOTTY
00887                      /* detach from original tty. Might only need this if isatty(0) is true */
00888                      ioctl(0,TIOCNOTTY,NULL);
00889 #else
00890                      setsid();
00891 #endif
00892                      /* become process group leader */
00893                      setpgid(my_pid, my_pid);
00894                      tcsetpgrp(0, my_pid);
00895               }
00896 #endif
00897 
00898               /* close those descriptors that we just opened for the parent stuff,
00899                * dup new descriptors into required descriptors and close the original
00900                * cruft */
00901               for (i = 0; i < ndesc; i++) {
00902                      switch (descriptors[i].mode & ~DESC_PARENT_MODE_WRITE) {
00903                             case DESC_PIPE:
00904                                    close(descriptors[i].parentend);
00905                                    break;
00906                      }
00907                      if (dup2(descriptors[i].childend, descriptors[i].index) < 0)
00908                             perror("dup2");
00909                      if (descriptors[i].childend != descriptors[i].index)
00910                             close(descriptors[i].childend);
00911               }
00912 
00913 #if PHP_CAN_DO_PTS
00914               if (dev_ptmx >= 0) {
00915                      close(dev_ptmx);
00916                      close(slave_pty);
00917               }
00918 #endif
00919 
00920               if (cwd) {
00921                      chdir(cwd);
00922               }
00923 
00924               if (env.envarray) {
00925                      execle("/bin/sh", "sh", "-c", command, NULL, env.envarray);
00926               } else {
00927                      execl("/bin/sh", "sh", "-c", command, NULL);
00928               }
00929               _exit(127);
00930 
00931        } else if (child < 0) {
00932               /* failed to fork() */
00933 
00934               /* clean up all the descriptors */
00935               for (i = 0; i < ndesc; i++) {
00936                      close(descriptors[i].childend);
00937                      if (descriptors[i].parentend)
00938                             close(descriptors[i].parentend);
00939               }
00940 
00941               php_error_docref(NULL TSRMLS_CC, E_WARNING, "fork failed - %s", strerror(errno));
00942 
00943               goto exit_fail;
00944 
00945        }
00946 #else
00947 # error You lose (configure should not have let you get here)
00948 #endif
00949        /* we forked/spawned and this is the parent */
00950 
00951        proc = (struct php_process_handle*)pemalloc(sizeof(struct php_process_handle), is_persistent);
00952        proc->is_persistent = is_persistent;
00953        proc->command = command;
00954        proc->npipes = ndesc;
00955        proc->child = child;
00956 #ifdef PHP_WIN32
00957        proc->childHandle = childHandle;
00958 #endif
00959        proc->env = env;
00960 
00961        if (pipes != NULL) {
00962               zval_dtor(pipes);
00963        }
00964        array_init(pipes);
00965 
00966 #if PHP_CAN_DO_PTS
00967        if (dev_ptmx >= 0) {
00968               close(dev_ptmx);
00969               close(slave_pty);
00970        }
00971 #endif
00972 
00973        /* clean up all the child ends and then open streams on the parent
00974         * ends, where appropriate */
00975        for (i = 0; i < ndesc; i++) {
00976               char *mode_string=NULL;
00977               php_stream *stream = NULL;
00978 
00979               close_descriptor(descriptors[i].childend);
00980 
00981               switch (descriptors[i].mode & ~DESC_PARENT_MODE_WRITE) {
00982                      case DESC_PIPE:
00983                             switch(descriptors[i].mode_flags) {
00984 #ifdef PHP_WIN32
00985                                    case O_WRONLY|O_BINARY:
00986                                           mode_string = "wb";
00987                                           break;
00988                                    case O_RDONLY|O_BINARY:
00989                                           mode_string = "rb";
00990                                           break;
00991 #endif
00992                                    case O_WRONLY:
00993                                           mode_string = "w";
00994                                           break;
00995                                    case O_RDONLY:
00996                                           mode_string = "r";
00997                                           break;
00998                                    case O_RDWR:
00999                                           mode_string = "r+";
01000                                           break;
01001                             }
01002 #ifdef PHP_WIN32
01003                             stream = php_stream_fopen_from_fd(_open_osfhandle((zend_intptr_t)descriptors[i].parentend,
01004                                                  descriptors[i].mode_flags), mode_string, NULL);
01005 #else
01006                             stream = php_stream_fopen_from_fd(descriptors[i].parentend, mode_string, NULL);
01007 # if defined(F_SETFD) && defined(FD_CLOEXEC)
01008                             /* mark the descriptor close-on-exec, so that it won't be inherited by potential other children */
01009                             fcntl(descriptors[i].parentend, F_SETFD, FD_CLOEXEC);
01010 # endif
01011 #endif
01012                             if (stream) {
01013                                    zval *retfp;
01014 
01015                                    /* nasty hack; don't copy it */
01016                                    stream->flags |= PHP_STREAM_FLAG_NO_SEEK;
01017 
01018                                    MAKE_STD_ZVAL(retfp);
01019                                    php_stream_to_zval(stream, retfp);
01020                                    add_index_zval(pipes, descriptors[i].index, retfp);
01021 
01022                                    proc->pipes[i] = Z_LVAL_P(retfp);
01023                             }
01024                             break;
01025                      default:
01026                             proc->pipes[i] = 0;
01027               }
01028        }
01029 
01030        ZEND_REGISTER_RESOURCE(return_value, proc, le_proc_open);
01031        return;
01032 
01033 exit_fail:
01034        _php_free_envp(env, is_persistent);
01035        pefree(command, is_persistent);
01036 #if PHP_CAN_DO_PTS
01037        if (dev_ptmx >= 0) {
01038               close(dev_ptmx);
01039        }
01040        if (slave_pty >= 0) {
01041               close(slave_pty);
01042        }
01043 #endif
01044        RETURN_FALSE;
01045 
01046 }
01047 /* }}} */
01048 
01049 #endif /* PHP_CAN_SUPPORT_PROC_OPEN */
01050 
01051 /*
01052  * Local variables:
01053  * tab-width: 4
01054  * c-basic-offset: 4
01055  * End:
01056  * vim600: sw=4 ts=4 fdm=marker
01057  * vim<600: sw=4 ts=4
01058  */