+/*
+ * safe_fork - Create a child process. The child closes all the
+ * file descriptors that we don't want to leak to a script.
+ * The parent waits for the child to do this before returning.
+ * This also arranges for the specified fds to be dup'd to
+ * fds 0, 1, 2 in the child.
+ */
+pid_t
+safe_fork(int infd, int outfd, int errfd)
+{
+ pid_t pid;
+ int fd, pipefd[2];
+ char buf[1];
+
+ /* make sure fds 0, 1, 2 are occupied (probably not necessary) */
+ while ((fd = dup(fd_devnull)) >= 0) {
+ if (fd > 2) {
+ close(fd);
+ break;
+ }
+ }
+
+ if (pipe(pipefd) == -1)
+ pipefd[0] = pipefd[1] = -1;
+ pid = fork();
+ if (pid < 0) {
+ error("fork failed: %m");
+ return -1;
+ }
+ if (pid > 0) {
+ /* parent */
+ close(pipefd[1]);
+ /* this read() blocks until the close(pipefd[1]) below */
+ complete_read(pipefd[0], buf, 1);
+ close(pipefd[0]);
+ return pid;
+ }
+
+ /* Executing in the child */
+ sys_close();
+#ifdef USE_TDB
+ tdb_close(pppdb);
+#endif
+
+ /* make sure infd, outfd and errfd won't get tromped on below */
+ if (infd == 1 || infd == 2)
+ infd = dup(infd);
+ if (outfd == 0 || outfd == 2)
+ outfd = dup(outfd);
+ if (errfd == 0 || errfd == 1)
+ errfd = dup(errfd);
+
+ closelog();
+
+ /* dup the in, out, err fds to 0, 1, 2 */
+ if (infd != 0)
+ dup2(infd, 0);
+ if (outfd != 1)
+ dup2(outfd, 1);
+ if (errfd != 2)
+ dup2(errfd, 2);
+
+ if (log_to_fd > 2)
+ close(log_to_fd);
+ if (the_channel->close)
+ (*the_channel->close)();
+ else
+ close(devfd); /* some plugins don't have a close function */
+ close(fd_ppp);
+ close(fd_devnull);
+ if (infd != 0)
+ close(infd);
+ if (outfd != 1)
+ close(outfd);
+ if (errfd != 2)
+ close(errfd);
+
+ notify(fork_notifier, 0);
+ close(pipefd[0]);
+ /* this close unblocks the read() call above in the parent */
+ close(pipefd[1]);
+
+ return 0;
+}
+
+static bool
+add_script_env(pos, newstring)
+ int pos;
+ char *newstring;
+{
+ if (pos + 1 >= s_env_nalloc) {
+ int new_n = pos + 17;
+ char **newenv = realloc(script_env, new_n * sizeof(char *));
+ if (newenv == NULL) {
+ free(newstring - 1);
+ return 0;
+ }
+ script_env = newenv;
+ s_env_nalloc = new_n;
+ }
+ script_env[pos] = newstring;
+ script_env[pos + 1] = NULL;
+ return 1;
+}
+
+static void
+remove_script_env(pos)
+ int pos;
+{
+ free(script_env[pos] - 1);
+ while ((script_env[pos] = script_env[pos + 1]) != NULL)
+ pos++;
+}
+
+/*
+ * update_system_environment - process the list of set/unset options
+ * and update the system environment.
+ */
+static void
+update_system_environment()
+{
+ struct userenv *uep;
+
+ for (uep = userenv_list; uep != NULL; uep = uep->ue_next) {
+ if (uep->ue_isset)
+ setenv(uep->ue_name, uep->ue_value, 1);
+ else
+ unsetenv(uep->ue_name);
+ }
+}