/** kill every subprocess */ void child_destruct(void) { if( !CLIST ) return; int len = m_len(CLIST); while( len-- ) child_close(len); m_free(CLIST); CLIST = 0; }
static void child_input_cb( XtPointer p, int *n, XtInputId *id ) { int hc = (int) p; struct child_stat *child = mls(CLIST, hc); TRACE(trace_child,""); if( child_read2(hc) ) { child_close(hc); return; } while( mrb_get_line(child->qin,child->line)==1) { if( child->cb ) child->cb(hc); m_clear(child->line); }; }
static int fakens_search(const uschar *domain, int type, uschar *answerptr, int size) { int len = Ustrlen(domain); int asize = size; /* Locally modified */ uschar *endname; uschar name[256]; uschar utilname[256]; uschar *aptr = answerptr; /* Locally modified */ struct stat statbuf; /* Remove terminating dot. */ if (domain[len - 1] == '.') len--; Ustrncpy(name, domain, len); name[len] = 0; endname = name + len; /* Look for the fakens utility, and if it exists, call it. */ (void)string_format(utilname, sizeof(utilname), "%s/bin/fakens", config_main_directory); if (stat(CS utilname, &statbuf) >= 0) { pid_t pid; int infd, outfd, rc; uschar *argv[5]; DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) using fakens\n", name, dns_text_type(type)); argv[0] = utilname; argv[1] = config_main_directory; argv[2] = name; argv[3] = dns_text_type(type); argv[4] = NULL; pid = child_open(argv, NULL, 0000, &infd, &outfd, FALSE); if (pid < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to run fakens: %s", strerror(errno)); len = 0; rc = -1; while (asize > 0 && (rc = read(outfd, aptr, asize)) > 0) { len += rc; aptr += rc; /* Don't modify the actual arguments, because they */ asize -= rc; /* may need to be passed on to res_search(). */ } /* If we ran out of output buffer before exhasting the return, carry on reading and counting it. */ if (asize == 0) while ((rc = read(outfd, name, sizeof(name))) > 0) len += rc; if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "read from fakens failed: %s", strerror(errno)); switch(child_close(pid, 0)) { case 0: return len; case 1: h_errno = HOST_NOT_FOUND; return -1; case 2: h_errno = TRY_AGAIN; return -1; default: case 3: h_errno = NO_RECOVERY; return -1; case 4: h_errno = NO_DATA; return -1; case 5: /* Pass on to res_search() */ DEBUG(D_dns) debug_printf("fakens returned PASS_ON\n"); } } else { DEBUG(D_dns) debug_printf("fakens (%s) not found\n", utilname); } /* fakens utility not found, or it returned "pass on" */ DEBUG(D_dns) debug_printf("passing %s on to res_search()\n", domain); return res_search(CS domain, C_IN, type, answerptr, size); }
static int fakens_search(const uschar *domain, int type, uschar *answerptr, int size) { int len = Ustrlen(domain); int asize = size; /* Locally modified */ uschar *endname; uschar name[256]; uschar utilname[256]; uschar *aptr = answerptr; /* Locally modified */ struct stat statbuf; /* Remove terminating dot. */ if (domain[len - 1] == '.') len--; Ustrncpy(name, domain, len); name[len] = 0; endname = name + len; /* This code, for forcing TRY_AGAIN and NO_RECOVERY, is here so that it works for the old test suite that uses a real nameserver. When the old test suite is eventually abandoned, this code could be moved into the fakens utility. */ if (len >= 14 && Ustrcmp(endname - 14, "test.again.dns") == 0) { int delay = Uatoi(name); /* digits at the start of the name */ DEBUG(D_dns) debug_printf("Return from DNS lookup of %s (%s) faked for testing\n", name, dns_text_type(type)); if (delay > 0) { DEBUG(D_dns) debug_printf("delaying %d seconds\n", delay); sleep(delay); } h_errno = TRY_AGAIN; return -1; } if (len >= 13 && Ustrcmp(endname - 13, "test.fail.dns") == 0) { DEBUG(D_dns) debug_printf("Return from DNS lookup of %s (%s) faked for testing\n", name, dns_text_type(type)); h_errno = NO_RECOVERY; return -1; } /* Look for the fakens utility, and if it exists, call it. */ (void)string_format(utilname, sizeof(utilname), "%s/../bin/fakens", spool_directory); if (stat(CS utilname, &statbuf) >= 0) { pid_t pid; int infd, outfd, rc; uschar *argv[5]; DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) using fakens\n", name, dns_text_type(type)); argv[0] = utilname; argv[1] = spool_directory; argv[2] = name; argv[3] = dns_text_type(type); argv[4] = NULL; pid = child_open(argv, NULL, 0000, &infd, &outfd, FALSE); if (pid < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to run fakens: %s", strerror(errno)); len = 0; rc = -1; while (asize > 0 && (rc = read(outfd, aptr, asize)) > 0) { len += rc; aptr += rc; /* Don't modify the actual arguments, because they */ asize -= rc; /* may need to be passed on to res_search(). */ } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "read from fakens failed: %s", strerror(errno)); switch(child_close(pid, 0)) { case 0: return len; case 1: h_errno = HOST_NOT_FOUND; return -1; case 2: h_errno = TRY_AGAIN; return -1; default: case 3: h_errno = NO_RECOVERY; return -1; case 4: h_errno = NO_DATA; return -1; case 5: /* Pass on to res_search() */ DEBUG(D_dns) debug_printf("fakens returned PASS_ON\n"); } } /* fakens utility not found, or it returned "pass on" */ DEBUG(D_dns) debug_printf("passing %s on to res_search()\n", domain); return res_search(CS domain, C_IN, type, answerptr, size); }
BOOL pipe_transport_entry( transport_instance *tblock, /* data for this instantiation */ address_item *addr) /* address(es) we are working on */ { pid_t pid, outpid; int fd_in, fd_out, rc; int envcount = 0; int envsep = 0; int expand_fail; pipe_transport_options_block *ob = (pipe_transport_options_block *)(tblock->options_block); int timeout = ob->timeout; BOOL written_ok = FALSE; BOOL expand_arguments; const uschar **argv; uschar *envp[50]; const uschar *envlist = ob->environment; uschar *cmd, *ss; uschar *eol = (ob->use_crlf)? US"\r\n" : US"\n"; DEBUG(D_transport) debug_printf("%s transport entered\n", tblock->name); /* Set up for the good case */ addr->transport_return = OK; addr->basic_errno = 0; /* Pipes are not accepted as general addresses, but they can be generated from .forward files or alias files. In those cases, the pfr flag is set, and the command to be obeyed is pointed to by addr->local_part; it starts with the pipe symbol. In other cases, the command is supplied as one of the pipe transport's options. */ if (testflag(addr, af_pfr) && addr->local_part[0] == '|') { if (ob->force_command) { /* Enables expansion of $address_pipe into seperate arguments */ setflag(addr, af_force_command); cmd = ob->cmd; expand_arguments = TRUE; expand_fail = PANIC; } else { cmd = addr->local_part + 1; while (isspace(*cmd)) cmd++; expand_arguments = testflag(addr, af_expand_pipe); expand_fail = FAIL; } } else { cmd = ob->cmd; expand_arguments = TRUE; expand_fail = PANIC; } /* If no command has been supplied, we are in trouble. * We also check for an empty string since it may be * coming from addr->local_part[0] == '|' */ if (cmd == NULL || *cmd == '\0') { addr->transport_return = DEFER; addr->message = string_sprintf("no command specified for %s transport", tblock->name); return FALSE; } /* When a pipe is set up by a filter file, there may be values for $thisaddress and numerical the variables in existence. These are passed in addr->pipe_expandn for use here. */ if (expand_arguments && addr->pipe_expandn != NULL) { uschar **ss = addr->pipe_expandn; expand_nmax = -1; if (*ss != NULL) filter_thisaddress = *ss++; while (*ss != NULL) { expand_nstring[++expand_nmax] = *ss; expand_nlength[expand_nmax] = Ustrlen(*ss++); } } /* The default way of processing the command is to split it up into arguments here, and run it directly. This offers some security advantages. However, there are installations that want by default to run commands under /bin/sh always, so there is an option to do that. */ if (ob->use_shell) { if (!set_up_shell_command(&argv, cmd, expand_arguments, expand_fail, addr, tblock->name)) return FALSE; } else if (!set_up_direct_command(&argv, cmd, expand_arguments, expand_fail, addr, tblock->name, ob)) return FALSE; expand_nmax = -1; /* Reset */ filter_thisaddress = NULL; /* Set up the environment for the command. */ envp[envcount++] = string_sprintf("LOCAL_PART=%s", deliver_localpart); envp[envcount++] = string_sprintf("LOGNAME=%s", deliver_localpart); envp[envcount++] = string_sprintf("USER=%s", deliver_localpart); envp[envcount++] = string_sprintf("LOCAL_PART_PREFIX=%#s", deliver_localpart_prefix); envp[envcount++] = string_sprintf("LOCAL_PART_SUFFIX=%#s", deliver_localpart_suffix); envp[envcount++] = string_sprintf("DOMAIN=%s", deliver_domain); envp[envcount++] = string_sprintf("HOME=%#s", deliver_home); envp[envcount++] = string_sprintf("MESSAGE_ID=%s", message_id); envp[envcount++] = string_sprintf("PATH=%s", ob->path); envp[envcount++] = string_sprintf("RECIPIENT=%#s%#s%#s@%#s", deliver_localpart_prefix, deliver_localpart, deliver_localpart_suffix, deliver_domain); envp[envcount++] = string_sprintf("QUALIFY_DOMAIN=%s", qualify_domain_sender); envp[envcount++] = string_sprintf("SENDER=%s", sender_address); envp[envcount++] = US"SHELL=/bin/sh"; if (addr->host_list != NULL) envp[envcount++] = string_sprintf("HOST=%s", addr->host_list->name); if (timestamps_utc) envp[envcount++] = US"TZ=UTC"; else if (timezone_string != NULL && timezone_string[0] != 0) envp[envcount++] = string_sprintf("TZ=%s", timezone_string); /* Add any requested items */ if (envlist) { envlist = expand_cstring(envlist); if (envlist == NULL) { addr->transport_return = DEFER; addr->message = string_sprintf("failed to expand string \"%s\" " "for %s transport: %s", ob->environment, tblock->name, expand_string_message); return FALSE; } } while ((ss = string_nextinlist(&envlist, &envsep, big_buffer, big_buffer_size)) != NULL) { if (envcount > sizeof(envp)/sizeof(uschar *) - 2) { addr->transport_return = DEFER; addr->message = string_sprintf("too many environment settings for " "%s transport", tblock->name); return FALSE; } envp[envcount++] = string_copy(ss); } envp[envcount] = NULL; /* If the -N option is set, can't do any more. */ if (dont_deliver) { DEBUG(D_transport) debug_printf("*** delivery by %s transport bypassed by -N option", tblock->name); return FALSE; } /* Handling the output from the pipe is tricky. If a file for catching this output is provided, we could in theory just hand that fd over to the process, but this isn't very safe because it might loop and carry on writing for ever (which is exactly what happened in early versions of Exim). Therefore we use the standard child_open() function, which creates pipes. We can then read our end of the output pipe and count the number of bytes that come through, chopping the sub-process if it exceeds some limit. However, this means we want to run a sub-process with both its input and output attached to pipes. We can't handle that easily from a single parent process using straightforward code such as the transport_write_message() function because the subprocess might not be reading its input because it is trying to write to a full output pipe. The complication of redesigning the world to handle this is too great - simpler just to run another process to do the reading of the output pipe. */ /* As this is a local transport, we are already running with the required uid/gid and current directory. Request that the new process be a process group leader, so we can kill it and all its children on a timeout. */ if ((pid = child_open(USS argv, envp, ob->umask, &fd_in, &fd_out, TRUE)) < 0) { addr->transport_return = DEFER; addr->message = string_sprintf( "Failed to create child process for %s transport: %s", tblock->name, strerror(errno)); return FALSE; } /* Now fork a process to handle the output that comes down the pipe. */ if ((outpid = fork()) < 0) { addr->basic_errno = errno; addr->transport_return = DEFER; addr->message = string_sprintf( "Failed to create process for handling output in %s transport", tblock->name); (void)close(fd_in); (void)close(fd_out); return FALSE; } /* This is the code for the output-handling subprocess. Read from the pipe in chunks, and write to the return file if one is provided. Keep track of the number of bytes handled. If the limit is exceeded, try to kill the subprocess group, and in any case close the pipe and exit, which should cause the subprocess to fail. */ if (outpid == 0) { int count = 0; (void)close(fd_in); set_process_info("reading output from |%s", cmd); while ((rc = read(fd_out, big_buffer, big_buffer_size)) > 0) { if (addr->return_file >= 0) if(write(addr->return_file, big_buffer, rc) != rc) DEBUG(D_transport) debug_printf("Problem writing to return_file\n"); count += rc; if (count > ob->max_output) { DEBUG(D_transport) debug_printf("Too much output from pipe - killed\n"); if (addr->return_file >= 0) { uschar *message = US"\n\n*** Too much output - remainder discarded ***\n"; rc = Ustrlen(message); if(write(addr->return_file, message, rc) != rc) DEBUG(D_transport) debug_printf("Problem writing to return_file\n"); } killpg(pid, SIGKILL); break; } } (void)close(fd_out); _exit(0); } (void)close(fd_out); /* Not used in this process */ /* Carrying on now with the main parent process. Attempt to write the message to it down the pipe. It is a fallacy to think that you can detect write errors when the sub-process fails to read the pipe. The parent process may complete writing and close the pipe before the sub-process completes. We could sleep a bit here to let the sub-process get going, but it may still not complete. So we ignore all writing errors. (When in the test harness, we do do a short sleep so any debugging output is likely to be in the same order.) */ if (running_in_test_harness) millisleep(500); DEBUG(D_transport) debug_printf("Writing message to pipe\n"); /* Arrange to time out writes if there is a timeout set. */ if (timeout > 0) { sigalrm_seen = FALSE; transport_write_timeout = timeout; } /* Reset the counter of bytes written */ transport_count = 0; /* First write any configured prefix information */ if (ob->message_prefix != NULL) { uschar *prefix = expand_string(ob->message_prefix); if (prefix == NULL) { addr->transport_return = search_find_defer? DEFER : PANIC; addr->message = string_sprintf("Expansion of \"%s\" (prefix for %s " "transport) failed: %s", ob->message_prefix, tblock->name, expand_string_message); return FALSE; } if (!transport_write_block(fd_in, prefix, Ustrlen(prefix))) goto END_WRITE; } /* If the use_bsmtp option is set, we need to write SMTP prefix information. The various different values for batching are handled outside; if there is more than one address available here, all must be included. Force SMTP dot-handling. */ if (ob->use_bsmtp) { address_item *a; if (!transport_write_string(fd_in, "MAIL FROM:<%s>%s", return_path, eol)) goto END_WRITE; for (a = addr; a != NULL; a = a->next) { if (!transport_write_string(fd_in, "RCPT TO:<%s>%s", transport_rcpt_address(a, tblock->rcpt_include_affixes), eol)) goto END_WRITE; } if (!transport_write_string(fd_in, "DATA%s", eol)) goto END_WRITE; } /* Now the actual message - the options were set at initialization time */ if (!transport_write_message(addr, fd_in, ob->options, 0, tblock->add_headers, tblock->remove_headers, ob->check_string, ob->escape_string, tblock->rewrite_rules, tblock->rewrite_existflags)) goto END_WRITE; /* Now any configured suffix */ if (ob->message_suffix != NULL) { uschar *suffix = expand_string(ob->message_suffix); if (suffix == NULL) { addr->transport_return = search_find_defer? DEFER : PANIC; addr->message = string_sprintf("Expansion of \"%s\" (suffix for %s " "transport) failed: %s", ob->message_suffix, tblock->name, expand_string_message); return FALSE; } if (!transport_write_block(fd_in, suffix, Ustrlen(suffix))) goto END_WRITE; } /* If local_smtp, write the terminating dot. */ if (ob->use_bsmtp && !transport_write_string(fd_in, ".%s", eol)) goto END_WRITE; /* Flag all writing completed successfully. */ written_ok = TRUE; /* Come here if there are errors during writing. */ END_WRITE: /* OK, the writing is now all done. Close the pipe. */ (void) close(fd_in); /* Handle errors during writing. For timeouts, set the timeout for waiting for the child process to 1 second. If the process at the far end of the pipe died without reading all of it, we expect an EPIPE error, which should be ignored. We used also to ignore WRITEINCOMPLETE but the writing function is now cleverer at handling OS where the death of a pipe doesn't give EPIPE immediately. See comments therein. */ if (!written_ok) { if (errno == ETIMEDOUT) { addr->message = string_sprintf("%stimeout while writing to pipe", transport_filter_timed_out? "transport filter " : ""); addr->transport_return = ob->timeout_defer? DEFER : FAIL; timeout = 1; } else if (errno == EPIPE) { debug_printf("transport error EPIPE ignored\n"); } else { addr->transport_return = PANIC; addr->basic_errno = errno; if (errno == ERRNO_CHHEADER_FAIL) addr->message = string_sprintf("Failed to expand headers_add or headers_remove: %s", expand_string_message); else if (errno == ERRNO_FILTER_FAIL) addr->message = string_sprintf("Transport filter process failed (%d)%s", addr->more_errno, (addr->more_errno == EX_EXECFAILED)? ": unable to execute command" : ""); else if (errno == ERRNO_WRITEINCOMPLETE) addr->message = string_sprintf("Failed repeatedly to write data"); else addr->message = string_sprintf("Error %d", errno); return FALSE; } } /* Wait for the child process to complete and take action if the returned status is nonzero. The timeout will be just 1 second if any of the writes above timed out. */ if ((rc = child_close(pid, timeout)) != 0) { uschar *tmsg = (addr->message == NULL)? US"" : string_sprintf(" (preceded by %s)", addr->message); /* The process did not complete in time; kill its process group and fail the delivery. It appears to be necessary to kill the output process too, as otherwise it hangs on for some time if the actual pipe process is sleeping. (At least, that's what I observed on Solaris 2.5.1.) Since we are failing the delivery, that shouldn't cause any problem. */ if (rc == -256) { killpg(pid, SIGKILL); kill(outpid, SIGKILL); addr->transport_return = ob->timeout_defer? DEFER : FAIL; addr->message = string_sprintf("pipe delivery process timed out%s", tmsg); } /* Wait() failed. */ else if (rc == -257) { addr->transport_return = PANIC; addr->message = string_sprintf("Wait() failed for child process of %s " "transport: %s%s", tblock->name, strerror(errno), tmsg); } /* Since the transport_filter timed out we assume it has sent the child process a malformed or incomplete data stream. Kill off the child process and prevent checking its exit status as it will has probably exited in error. This prevents the transport_filter timeout message from getting overwritten by the exit error which is not the cause of the problem. */ else if (transport_filter_timed_out) { killpg(pid, SIGKILL); kill(outpid, SIGKILL); } /* Either the process completed, but yielded a non-zero (necessarily positive) status, or the process was terminated by a signal (rc will contain the negation of the signal number). Treat killing by signal as failure unless status is being ignored. By default, the message is bounced back, unless freeze_signal is set, in which case it is frozen instead. */ else if (rc < 0) { if (ob->freeze_signal) { addr->transport_return = DEFER; addr->special_action = SPECIAL_FREEZE; addr->message = string_sprintf("Child process of %s transport (running " "command \"%s\") was terminated by signal %d (%s)%s", tblock->name, cmd, -rc, os_strsignal(-rc), tmsg); } else if (!ob->ignore_status) { addr->transport_return = FAIL; addr->message = string_sprintf("Child process of %s transport (running " "command \"%s\") was terminated by signal %d (%s)%s", tblock->name, cmd, -rc, os_strsignal(-rc), tmsg); } } /* For positive values (process terminated with non-zero status), we need a status code to request deferral. A number of systems contain the following line in sysexits.h: #define EX_TEMPFAIL 75 with the description EX_TEMPFAIL -- temporary failure, indicating something that is not really an error. In sendmail, this means that a mailer (e.g.) could not create a connection, and the request should be reattempted later. Based on this, we use exit code EX_TEMPFAIL as a default to mean "defer" when not ignoring the returned status. However, there is now an option that contains a list of temporary codes, with TEMPFAIL and CANTCREAT as defaults. Another case that needs special treatment is if execve() failed (typically the command that was given is a non-existent path). By default this is treated as just another failure, but if freeze_exec_fail is set, the reaction is to freeze the message rather than bounce the address. Exim used to signal this failure with EX_UNAVAILABLE, which is definined in many systems as #define EX_UNAVAILABLE 69 with the description EX_UNAVAILABLE -- A service is unavailable. This can occur if a support program or file does not exist. This can also be used as a catchall message when something you wanted to do doesn't work, but you don't know why. However, this can be confused with a command that actually returns 69 because something *it* wanted is unavailable. At release 4.21, Exim was changed to use return code 127 instead, because this is what the shell returns when it is unable to exec a command. We define it as EX_EXECFAILED, and use it in child.c to signal execve() failure and other unexpected failures such as setuid() not working - though that won't be the case here because we aren't changing uid. */ else { /* Always handle execve() failure specially if requested to */ if (ob->freeze_exec_fail && (rc == EX_EXECFAILED)) { addr->transport_return = DEFER; addr->special_action = SPECIAL_FREEZE; addr->message = string_sprintf("pipe process failed to exec \"%s\"%s", cmd, tmsg); } /* Otherwise take action only if not ignoring status */ else if (!ob->ignore_status) { uschar *ss; int size, ptr, i; /* If temp_errors is "*" all codes are temporary. Initializion checks that it's either "*" or a list of numbers. If not "*", scan the list of temporary failure codes; if any match, the result is DEFER. */ if (ob->temp_errors[0] == '*') addr->transport_return = DEFER; else { const uschar *s = ob->temp_errors; uschar *p; uschar buffer[64]; int sep = 0; addr->transport_return = FAIL; while ((p = string_nextinlist(&s,&sep,buffer,sizeof(buffer)))) if (rc == Uatoi(p)) { addr->transport_return = DEFER; break; } } /* Ensure the message contains the expanded command and arguments. This doesn't have to be brilliantly efficient - it is an error situation. */ addr->message = string_sprintf("Child process of %s transport returned " "%d", tblock->name, rc); ptr = Ustrlen(addr->message); size = ptr + 1; /* If the return code is > 128, it often means that a shell command was terminated by a signal. */ ss = (rc > 128)? string_sprintf("(could mean shell command ended by signal %d (%s))", rc-128, os_strsignal(rc-128)) : US os_strexit(rc); if (*ss != 0) { addr->message = string_cat(addr->message, &size, &ptr, US" ", 1); addr->message = string_cat(addr->message, &size, &ptr, ss, Ustrlen(ss)); } /* Now add the command and arguments */ addr->message = string_cat(addr->message, &size, &ptr, US" from command:", 14); for (i = 0; i < sizeof(argv)/sizeof(int *) && argv[i] != NULL; i++) { BOOL quote = FALSE; addr->message = string_cat(addr->message, &size, &ptr, US" ", 1); if (Ustrpbrk(argv[i], " \t") != NULL) { quote = TRUE; addr->message = string_cat(addr->message, &size, &ptr, US"\"", 1); } addr->message = string_cat(addr->message, &size, &ptr, argv[i], Ustrlen(argv[i])); if (quote) addr->message = string_cat(addr->message, &size, &ptr, US"\"", 1); } /* Add previous filter timeout message, if present. */ if (*tmsg != 0) addr->message = string_cat(addr->message, &size, &ptr, tmsg, Ustrlen(tmsg)); addr->message[ptr] = 0; /* Ensure concatenated string terminated */ } } } /* Ensure all subprocesses (in particular, the output handling process) are complete before we pass this point. */ while (wait(&rc) >= 0); DEBUG(D_transport) debug_printf("%s transport yielded %d\n", tblock->name, addr->transport_return); /* If there has been a problem, the message in addr->message contains details of the pipe command. We don't want to expose these to the world, so we set up something bland to return to the sender. */ if (addr->transport_return != OK) addr->user_message = US"local delivery failed"; return FALSE; }
int start_command(struct child_process *cmd) { int need_in, need_out, need_err; int fdin[2], fdout[2], fderr[2]; int failed_errno; char *str; if (!cmd->argv) cmd->argv = cmd->args.argv; if (!cmd->env) cmd->env = cmd->env_array.argv; /* * In case of errors we must keep the promise to close FDs * that have been passed in via ->in and ->out. */ need_in = !cmd->no_stdin && cmd->in < 0; if (need_in) { if (pipe(fdin) < 0) { failed_errno = errno; if (cmd->out > 0) close(cmd->out); str = "standard input"; goto fail_pipe; } cmd->in = fdin[1]; } need_out = !cmd->no_stdout && !cmd->stdout_to_stderr && cmd->out < 0; if (need_out) { if (pipe(fdout) < 0) { failed_errno = errno; if (need_in) close_pair(fdin); else if (cmd->in) close(cmd->in); str = "standard output"; goto fail_pipe; } cmd->out = fdout[0]; } need_err = !cmd->no_stderr && cmd->err < 0; if (need_err) { if (pipe(fderr) < 0) { failed_errno = errno; if (need_in) close_pair(fdin); else if (cmd->in) close(cmd->in); if (need_out) close_pair(fdout); else if (cmd->out) close(cmd->out); str = "standard error"; fail_pipe: error("cannot create %s pipe for %s: %s", str, cmd->argv[0], strerror(failed_errno)); child_process_clear(cmd); errno = failed_errno; return -1; } cmd->err = fderr[0]; } trace_argv_printf(cmd->argv, "trace: run_command:"); fflush(NULL); #ifndef GIT_WINDOWS_NATIVE { int notify_pipe[2]; int null_fd = -1; char **childenv; struct argv_array argv = ARGV_ARRAY_INIT; struct child_err cerr; struct atfork_state as; if (pipe(notify_pipe)) notify_pipe[0] = notify_pipe[1] = -1; if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) { null_fd = open("/dev/null", O_RDWR | O_CLOEXEC); if (null_fd < 0) die_errno(_("open /dev/null failed")); set_cloexec(null_fd); } prepare_cmd(&argv, cmd); childenv = prep_childenv(cmd->env); atfork_prepare(&as); /* * NOTE: In order to prevent deadlocking when using threads special * care should be taken with the function calls made in between the * fork() and exec() calls. No calls should be made to functions which * require acquiring a lock (e.g. malloc) as the lock could have been * held by another thread at the time of forking, causing the lock to * never be released in the child process. This means only * Async-Signal-Safe functions are permitted in the child. */ cmd->pid = fork(); failed_errno = errno; if (!cmd->pid) { int sig; /* * Ensure the default die/error/warn routines do not get * called, they can take stdio locks and malloc. */ set_die_routine(child_die_fn); set_error_routine(child_error_fn); set_warn_routine(child_warn_fn); close(notify_pipe[0]); set_cloexec(notify_pipe[1]); child_notifier = notify_pipe[1]; if (cmd->no_stdin) child_dup2(null_fd, 0); else if (need_in) { child_dup2(fdin[0], 0); child_close_pair(fdin); } else if (cmd->in) { child_dup2(cmd->in, 0); child_close(cmd->in); } if (cmd->no_stderr) child_dup2(null_fd, 2); else if (need_err) { child_dup2(fderr[1], 2); child_close_pair(fderr); } else if (cmd->err > 1) { child_dup2(cmd->err, 2); child_close(cmd->err); } if (cmd->no_stdout) child_dup2(null_fd, 1); else if (cmd->stdout_to_stderr) child_dup2(2, 1); else if (need_out) { child_dup2(fdout[1], 1); child_close_pair(fdout); } else if (cmd->out > 1) { child_dup2(cmd->out, 1); child_close(cmd->out); } if (cmd->dir && chdir(cmd->dir)) child_die(CHILD_ERR_CHDIR); /* * restore default signal handlers here, in case * we catch a signal right before execve below */ for (sig = 1; sig < NSIG; sig++) { /* ignored signals get reset to SIG_DFL on execve */ if (signal(sig, SIG_DFL) == SIG_IGN) signal(sig, SIG_IGN); } if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0) child_die(CHILD_ERR_SIGPROCMASK); /* * Attempt to exec using the command and arguments starting at * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will * be used in the event exec failed with ENOEXEC at which point * we will try to interpret the command using 'sh'. */ execve(argv.argv[1], (char *const *) argv.argv + 1, (char *const *) childenv); if (errno == ENOEXEC) execve(argv.argv[0], (char *const *) argv.argv, (char *const *) childenv); if (errno == ENOENT) { if (cmd->silent_exec_failure) child_die(CHILD_ERR_SILENT); child_die(CHILD_ERR_ENOENT); } else { child_die(CHILD_ERR_ERRNO); } } atfork_parent(&as); if (cmd->pid < 0) error_errno("cannot fork() for %s", cmd->argv[0]); else if (cmd->clean_on_exit) mark_child_for_cleanup(cmd->pid, cmd); /* * Wait for child's exec. If the exec succeeds (or if fork() * failed), EOF is seen immediately by the parent. Otherwise, the * child process sends a child_err struct. * Note that use of this infrastructure is completely advisory, * therefore, we keep error checks minimal. */ close(notify_pipe[1]); if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) { /* * At this point we know that fork() succeeded, but exec() * failed. Errors have been reported to our stderr. */ wait_or_whine(cmd->pid, cmd->argv[0], 0); child_err_spew(cmd, &cerr); failed_errno = errno; cmd->pid = -1; } close(notify_pipe[0]); if (null_fd >= 0) close(null_fd); argv_array_clear(&argv); free(childenv); } #else { int fhin = 0, fhout = 1, fherr = 2; const char **sargv = cmd->argv; struct argv_array nargv = ARGV_ARRAY_INIT; if (cmd->no_stdin) fhin = open("/dev/null", O_RDWR); else if (need_in) fhin = dup(fdin[0]); else if (cmd->in) fhin = dup(cmd->in); if (cmd->no_stderr) fherr = open("/dev/null", O_RDWR); else if (need_err) fherr = dup(fderr[1]); else if (cmd->err > 2) fherr = dup(cmd->err); if (cmd->no_stdout) fhout = open("/dev/null", O_RDWR); else if (cmd->stdout_to_stderr) fhout = dup(fherr); else if (need_out) fhout = dup(fdout[1]); else if (cmd->out > 1) fhout = dup(cmd->out); if (cmd->git_cmd) cmd->argv = prepare_git_cmd(&nargv, cmd->argv); else if (cmd->use_shell) cmd->argv = prepare_shell_cmd(&nargv, cmd->argv); cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env, cmd->dir, fhin, fhout, fherr); failed_errno = errno; if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT)) error_errno("cannot spawn %s", cmd->argv[0]); if (cmd->clean_on_exit && cmd->pid >= 0) mark_child_for_cleanup(cmd->pid, cmd); argv_array_clear(&nargv); cmd->argv = sargv; if (fhin != 0) close(fhin); if (fhout != 1) close(fhout); if (fherr != 2) close(fherr); } #endif if (cmd->pid < 0) { if (need_in) close_pair(fdin); else if (cmd->in) close(cmd->in); if (need_out) close_pair(fdout); else if (cmd->out) close(cmd->out); if (need_err) close_pair(fderr); else if (cmd->err) close(cmd->err); child_process_clear(cmd); errno = failed_errno; return -1; } if (need_in) close(fdin[0]); else if (cmd->in) close(cmd->in); if (need_out) close(fdout[1]); else if (cmd->out) close(cmd->out); if (need_err) close(fderr[1]); else if (cmd->err) close(cmd->err); return 0; }
static void child_close_pair(int fd[2]) { child_close(fd[0]); child_close(fd[1]); }