2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/os_priority.c
23 * @brief Methods to set process priority
28 #include "gnunet_common.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_scheduler_lib.h"
31 #include "gnunet_strings_lib.h"
32 #include "gnunet_crypto_lib.h"
36 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
38 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
40 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
42 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
45 struct GNUNET_OS_Process
60 * Pipe we use to signal the process.
61 * NULL if unused, or if process was deemed uncontrollable.
63 struct GNUNET_DISK_FileHandle *control_pipe;
68 * Handle for 'this' process.
70 static struct GNUNET_OS_Process current_process;
74 * This handler is called when there are control data to be read on the pipe
76 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
77 * @param tc scheduler context
80 parent_control_handler (void *cls,
81 const struct GNUNET_SCHEDULER_TaskContext *tc)
83 struct GNUNET_DISK_FileHandle *control_pipe = cls;
88 LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
90 if (0 != (tc->reason &
91 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT)))
93 GNUNET_DISK_file_close (control_pipe);
97 ret = GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig));
98 if (sizeof (sig) != ret)
101 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
102 LOG (GNUNET_ERROR_TYPE_DEBUG, "Closing control pipe\n");
103 GNUNET_DISK_file_close (control_pipe);
107 pipe_fd = getenv (GNUNET_OS_CONTROL_PIPE);
108 GNUNET_assert ( (NULL == pipe_fd) || (strlen (pipe_fd) <= 0) );
109 LOG (GNUNET_ERROR_TYPE_DEBUG,
110 "Got control code %d from parent via pipe %s\n", sig, pipe_fd);
111 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
112 control_pipe, &parent_control_handler,
119 * Task that connects this process to its parent via pipe;
120 * essentially, the parent control handler will read signal numbers
121 * from the 'GNUNET_OS_CONTROL_PIPE' (as given in an environment
122 * variable) and raise those signals.
124 * @param cls closure (unused)
125 * @param tc scheduler context (unused)
128 GNUNET_OS_install_parent_control_handler (void *cls,
130 GNUNET_SCHEDULER_TaskContext *tc)
134 struct GNUNET_DISK_FileHandle *control_pipe;
137 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
138 if ( (NULL == env_buf) || (strlen (env_buf) <= 0) )
140 LOG (GNUNET_ERROR_TYPE_DEBUG,
141 "Not installing a handler because $%s is empty\n",
142 GNUNET_OS_CONTROL_PIPE);
143 putenv (GNUNET_OS_CONTROL_PIPE "=");
147 pipe_fd = strtoull (env_buf, &env_buf_end, 16);
148 if ((0 != errno) || (env_buf == env_buf_end))
150 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "strtoull", env_buf);
151 putenv (GNUNET_OS_CONTROL_PIPE "=");
154 #if !defined (WINDOWS)
155 if (pipe_fd >= FD_SETSIZE)
157 if ((FILE_TYPE_UNKNOWN == GetFileType ((HANDLE) (uintptr_t) pipe_fd))
158 && (0 != GetLastError ()))
161 LOG (GNUNET_ERROR_TYPE_ERROR,
162 "GNUNET_OS_CONTROL_PIPE `%s' contains garbage?\n", env_buf);
163 putenv (GNUNET_OS_CONTROL_PIPE "=");
167 control_pipe = GNUNET_DISK_get_handle_from_w32_handle ((HANDLE) (uintptr_t) pipe_fd);
169 control_pipe = GNUNET_DISK_get_handle_from_int_fd ((int) pipe_fd);
171 if (NULL == control_pipe)
173 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
174 putenv (GNUNET_OS_CONTROL_PIPE "=");
177 LOG (GNUNET_ERROR_TYPE_DEBUG,
178 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
179 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
180 &parent_control_handler, control_pipe);
181 putenv (GNUNET_OS_CONTROL_PIPE "=");
186 * Get process structure for current process
188 * The pointer it returns points to static memory location and must not be
191 * @return pointer to the process sturcutre for this process
193 struct GNUNET_OS_Process *
194 GNUNET_OS_process_current ()
197 current_process.pid = GetCurrentProcessId ();
198 current_process.handle = GetCurrentProcess ();
200 current_process.pid = 0;
202 return ¤t_process;
207 * Sends a signal to the process
209 * @param proc pointer to process structure
211 * @return 0 on success, -1 on error
214 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
220 if (NULL != proc->control_pipe)
222 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending signal %d to pid: %u via pipe\n", sig, proc->pid);
223 ret = GNUNET_DISK_file_write (proc->control_pipe, &csig, sizeof (csig));
224 if (sizeof (csig) == ret)
227 /* pipe failed or non-existent, try other methods */
230 #if !defined (WINDOWS)
236 #if defined(WINDOWS) && !defined(__CYGWIN__)
239 int must_kill = GNUNET_YES;
240 if (0 != GetExitCodeProcess (proc->handle, &exitcode))
241 must_kill = (exitcode == STILL_ACTIVE) ? GNUNET_YES : GNUNET_NO;
242 if (GNUNET_YES == must_kill)
243 if (0 == SafeTerminateProcess (proc->handle, 0, 0))
245 DWORD error_code = GetLastError ();
246 if ((error_code != WAIT_TIMEOUT) && (error_code != ERROR_PROCESS_ABORTED))
248 LOG ((error_code == ERROR_ACCESS_DENIED) ?
249 GNUNET_ERROR_TYPE_INFO : GNUNET_ERROR_TYPE_WARNING,
250 "SafeTermiateProcess failed with code %lu\n", error_code);
251 /* The problem here is that a process that is already dying
252 * might cause SafeTerminateProcess to fail with
253 * ERROR_ACCESS_DENIED, but the process WILL die eventually.
254 * If we really had a permissions problem, hanging up (which
255 * is what will happen in process_wait() in that case) is
258 if (ERROR_ACCESS_DENIED == error_code)
264 SetErrnoFromWinError (error_code);
272 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending signal %d to pid: %u via system call\n", sig, proc->pid);
273 return PLIBC_KILL (proc->pid, sig);
276 #if defined (WINDOWS)
280 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending signal %d to pid: %u via system call\n", sig, proc->pid);
281 return PLIBC_KILL (proc->pid, sig);
287 * Get the pid of the process in question
289 * @param proc the process to get the pid of
291 * @return the current process id
294 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
301 * Cleans up process structure contents (OS-dependent) and deallocates it
303 * @param proc pointer to process structure
306 GNUNET_OS_process_destroy (struct GNUNET_OS_Process *proc)
308 if (NULL != proc->control_pipe)
309 GNUNET_DISK_file_close (proc->control_pipe);
310 #if defined (WINDOWS)
311 if (proc->handle != NULL)
312 CloseHandle (proc->handle);
318 #include "gnunet_signal_lib.h"
320 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
323 * Make seaspider happy.
325 #define DWORD_WINAPI DWORD WINAPI
328 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
329 * @param proc pointer to process structure
332 child_wait_thread (void *arg)
334 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
336 WaitForSingleObject (proc->handle, INFINITE);
338 if (w32_sigchld_handler)
339 w32_sigchld_handler ();
348 CreateCustomEnvTable (char **vars)
350 char *win32_env_table;
355 size_t tablesize = 0;
356 size_t items_count = 0;
365 win32_env_table = GetEnvironmentStringsA ();
366 if (NULL == win32_env_table)
368 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
370 index = GNUNET_malloc (sizeof (char *) * n_var);
371 for (c = 0; c < n_var; c++)
373 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
375 size_t len = strlen (ptr);
378 for (var_ptr = vars; *var_ptr; var_ptr++)
382 var_len = strlen (var);
383 if (strncmp (var, ptr, var_len) == 0)
387 tablesize += var_len + strlen (val) + 1;
392 tablesize += len + 1;
395 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
400 n_found += strlen (var) + strlen (val) + 1;
402 result = GNUNET_malloc (tablesize + n_found + 1);
403 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
405 size_t len = strlen (ptr);
408 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
412 var_len = strlen (var);
413 if (strncmp (var, ptr, var_len) == 0)
421 strcpy (result_ptr, ptr);
422 result_ptr += len + 1;
426 strcpy (result_ptr, var);
427 result_ptr += var_len;
428 strcpy (result_ptr, val);
429 result_ptr += strlen (val) + 1;
433 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
437 var_len = strlen (var);
440 strcpy (result_ptr, var);
441 result_ptr += var_len;
442 strcpy (result_ptr, val);
443 result_ptr += strlen (val) + 1;
446 FreeEnvironmentStrings (win32_env_table);
455 * Open '/dev/null' and make the result the given
458 * @param target_fd desired FD to point to /dev/null
459 * @param flags open flags (O_RDONLY, O_WRONLY)
462 open_dev_null (int target_fd,
467 fd = open ("/dev/null", flags);
470 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", "/dev/null");
475 if (-1 == dup2 (fd, target_fd))
477 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
481 GNUNET_break (0 == close (fd));
489 * @param pipe_control should a pipe be used to send signals to the child?
490 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
491 * std handles of the parent are inherited by the child.
492 * pipe_stdin and pipe_stdout take priority over std_inheritance
493 * (when they are non-NULL).
494 * @param pipe_stdin pipe to use to send input to child process (or NULL)
495 * @param pipe_stdout pipe to use to get output from child process (or NULL)
496 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
497 * must be NULL on platforms where dup is not supported
498 * @param filename name of the binary
499 * @param argv NULL-terminated list of arguments to the process
500 * @return process ID of the new process, -1 on error
502 static struct GNUNET_OS_Process *
503 start_process (int pipe_control,
504 enum GNUNET_OS_InheritStdioFlags std_inheritance,
505 struct GNUNET_DISK_PipeHandle *pipe_stdin,
506 struct GNUNET_DISK_PipeHandle *pipe_stdout,
507 const SOCKTYPE *lsocks,
508 const char *filename,
514 struct GNUNET_OS_Process *gnunet_proc;
515 struct GNUNET_DISK_FileHandle *childpipe_read;
516 struct GNUNET_DISK_FileHandle *childpipe_write;
517 int childpipe_read_fd;
530 if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename, GNUNET_NO, NULL))
531 return NULL; /* not executable */
532 if (GNUNET_YES == pipe_control)
534 struct GNUNET_DISK_PipeHandle *childpipe;
535 int dup_childpipe_read_fd = -1;
537 childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
538 if (NULL == childpipe)
540 childpipe_read = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ);
541 childpipe_write = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE);
542 GNUNET_DISK_pipe_close (childpipe);
543 if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
544 (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read,
545 &childpipe_read_fd, sizeof (int))) ||
546 (-1 == (dup_childpipe_read_fd = dup (childpipe_read_fd))))
548 if (NULL != childpipe_read)
549 GNUNET_DISK_file_close (childpipe_read);
550 if (NULL != childpipe_write)
551 GNUNET_DISK_file_close (childpipe_write);
552 if (0 <= dup_childpipe_read_fd)
553 close (dup_childpipe_read_fd);
556 childpipe_read_fd = dup_childpipe_read_fd;
557 GNUNET_DISK_file_close (childpipe_read);
561 childpipe_write = NULL;
562 childpipe_read_fd = -1;
564 if (NULL != pipe_stdout)
566 GNUNET_assert (GNUNET_OK ==
567 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
569 GNUNET_DISK_PIPE_END_WRITE),
570 &fd_stdout_write, sizeof (int)));
571 GNUNET_assert (GNUNET_OK ==
572 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
573 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
574 &fd_stdout_read, sizeof (int)));
576 if (NULL != pipe_stdin)
578 GNUNET_assert (GNUNET_OK ==
579 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
580 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
581 &fd_stdin_read, sizeof (int)));
582 GNUNET_assert (GNUNET_OK ==
583 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
584 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
585 &fd_stdin_write, sizeof (int)));
592 while (-1 != (k = lsocks[i++]))
593 GNUNET_array_append (lscp, ls, k);
594 GNUNET_array_append (lscp, ls, -1);
597 /* see https://gnunet.org/vfork */
605 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
606 GNUNET_array_grow (lscp, ls, 0);
607 if (NULL != childpipe_write)
608 GNUNET_DISK_file_close (childpipe_write);
609 if (0 <= childpipe_read_fd)
610 close (childpipe_read_fd);
616 unsetenv (GNUNET_OS_CONTROL_PIPE);
617 gnunet_proc = GNUNET_new (struct GNUNET_OS_Process);
618 gnunet_proc->pid = ret;
619 gnunet_proc->control_pipe = childpipe_write;
620 if (GNUNET_YES == pipe_control)
622 close (childpipe_read_fd);
624 GNUNET_array_grow (lscp, ls, 0);
627 if (0 <= childpipe_read_fd)
631 /* due to vfork, we must NOT free memory on DARWIN! */
632 GNUNET_DISK_file_close (childpipe_write);
634 snprintf (fdbuf, 100, "%x", childpipe_read_fd);
635 setenv (GNUNET_OS_CONTROL_PIPE, fdbuf, 1);
638 unsetenv (GNUNET_OS_CONTROL_PIPE);
639 if (NULL != pipe_stdin)
641 GNUNET_break (0 == close (fd_stdin_write));
642 if (-1 == dup2 (fd_stdin_read, 0))
643 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
644 GNUNET_break (0 == close (fd_stdin_read));
646 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_IN))
648 GNUNET_break (0 == close (0));
649 open_dev_null (0, O_RDONLY);
651 if (NULL != pipe_stdout)
653 GNUNET_break (0 == close (fd_stdout_read));
654 if (-1 == dup2 (fd_stdout_write, 1))
655 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
656 GNUNET_break (0 == close (fd_stdout_write));
658 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_OUT))
660 GNUNET_break (0 == close (1));
661 open_dev_null (1, O_WRONLY);
663 if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_ERR))
665 GNUNET_break (0 == close (2));
666 open_dev_null (2, O_WRONLY);
670 /* read systemd documentation... */
673 while (-1 != lscp[i])
676 while (-1 != lscp[j])
682 GNUNET_assert (-1 != k);
683 GNUNET_assert (0 == close (lscp[j]));
691 /* Bury any existing FD, no matter what; they should all be closed
692 * on exec anyway and the important onces have been dup'ed away */
694 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
696 /* unset close-on-exec flag */
697 flags = fcntl (tgt, F_GETFD);
698 GNUNET_assert (flags >= 0);
699 flags &= ~FD_CLOEXEC;
701 (void) fcntl (tgt, F_SETFD, flags);
705 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
706 setenv ("LISTEN_FDS", fds, 1);
709 /* due to vfork, we must NOT free memory on DARWIN! */
710 GNUNET_array_grow (lscp, ls, 0);
712 execvp (filename, argv);
713 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
716 struct GNUNET_DISK_FileHandle *childpipe_read;
717 struct GNUNET_DISK_FileHandle *childpipe_write;
718 HANDLE childpipe_read_handle;
720 char **non_const_argv;
725 PROCESS_INFORMATION proc;
727 struct GNUNET_OS_Process *gnunet_proc;
728 char path[MAX_PATH + 1];
729 char *our_env[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };
730 char *env_block = NULL;
738 char *non_const_filename;
739 char win_path[MAX_PATH + 1];
740 struct GNUNET_DISK_PipeHandle *lsocks_pipe;
741 const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
752 HANDLE stdout_handle;
753 HANDLE stdih, stdoh, stdeh;
754 DWORD stdif, stdof, stdef;
758 if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename, GNUNET_NO, NULL))
759 return NULL; /* not executable */
761 /* Search in prefix dir (hopefully - the directory from which
762 * the current module was loaded), bindir and libdir, then in PATH
764 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
765 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
766 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
768 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
771 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
774 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
777 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
778 GNUNET_free (self_prefix);
779 GNUNET_free (bindir);
780 GNUNET_free (libdir);
782 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
783 if (alloc_len != pathbuf_len - 1)
785 GNUNET_free (pathbuf);
786 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
790 cmdlen = strlen (filename);
791 if ( (cmdlen < 5) || (0 != strcmp (&filename[cmdlen - 4], ".exe")) )
792 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
794 GNUNET_asprintf (&non_const_filename, "%s", filename);
796 /* It could be in POSIX form, convert it to a DOS path early on */
797 if (ERROR_SUCCESS != (lRet = plibc_conv_to_win_path (non_const_filename, win_path)))
799 SetErrnoFromWinError (lRet);
800 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "plibc_conv_to_win_path",
802 GNUNET_free (non_const_filename);
803 GNUNET_free (pathbuf);
806 GNUNET_free (non_const_filename);
807 non_const_filename = GNUNET_strdup (win_path);
808 /* Check that this is the full path. If it isn't, search. */
809 /* FIXME: convert it to wchar_t and use SearchPathW?
810 * Remember: arguments to _start_process() are technically in UTF-8...
812 if (non_const_filename[1] == ':')
814 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
815 LOG (GNUNET_ERROR_TYPE_DEBUG,
816 "Using path `%s' as-is. PATH is %s\n", path, ptr);
818 else if (!SearchPathA
819 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
822 SetErrnoFromWinError (GetLastError ());
823 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
825 GNUNET_free (non_const_filename);
826 GNUNET_free (pathbuf);
830 LOG (GNUNET_ERROR_TYPE_DEBUG,
831 "Found `%s' in PATH `%s'\n", path, pathbuf);
832 GNUNET_free (pathbuf);
833 GNUNET_free (non_const_filename);
835 /* Count the number of arguments */
836 arg = (char **) argv;
843 /* Allocate a copy argv */
844 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
846 /* Copy all argv strings */
848 arg = (char **) argv;
852 non_const_argv[argcount] = GNUNET_strdup (path);
854 non_const_argv[argcount] = GNUNET_strdup (*arg);
858 non_const_argv[argcount] = NULL;
862 arg = non_const_argv;
865 cmdlen = cmdlen + strlen (*arg) + 4;
869 /* Allocate and create cmd */
870 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
871 arg = non_const_argv;
874 char arg_last_char = (*arg)[strlen (*arg) - 1];
875 idx += sprintf (idx, "\"%s%s\"%s", *arg,
876 arg_last_char == '\\' ? "\\" : "", *(arg + 1) ? " " : "");
881 GNUNET_free (non_const_argv[--argcount]);
882 GNUNET_free (non_const_argv);
884 memset (&start, 0, sizeof (start));
885 start.cb = sizeof (start);
886 if ((pipe_stdin != NULL) || (pipe_stdout != NULL) || (std_inheritance != 0))
887 start.dwFlags |= STARTF_USESTDHANDLES;
889 stdih = GetStdHandle (STD_INPUT_HANDLE);
890 GetHandleInformation (stdih, &stdif);
891 if (pipe_stdin != NULL)
893 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
894 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
895 &stdin_handle, sizeof (HANDLE));
896 start.hStdInput = stdin_handle;
900 if (std_inheritance & GNUNET_OS_INHERIT_STD_IN)
902 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 1);
903 if (pipe_stdin == NULL)
904 start.hStdInput = stdih;
907 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 0);
911 stdoh = GetStdHandle (STD_OUTPUT_HANDLE);
912 GetHandleInformation (stdoh, &stdof);
913 if (NULL != pipe_stdout)
915 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
917 GNUNET_DISK_PIPE_END_WRITE),
918 &stdout_handle, sizeof (HANDLE));
919 start.hStdOutput = stdout_handle;
923 if (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)
925 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 1);
926 if (pipe_stdout == NULL)
927 start.hStdOutput = stdoh;
930 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 0);
933 stdeh = GetStdHandle (STD_ERROR_HANDLE);
934 GetHandleInformation (stdeh, &stdef);
937 if (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)
939 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 1);
940 start.hStdError = stdeh;
943 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 0);
946 if (GNUNET_YES == pipe_control)
948 struct GNUNET_DISK_PipeHandle *childpipe;
949 childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
950 if (NULL == childpipe)
952 childpipe_read = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ);
953 childpipe_write = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE);
954 GNUNET_DISK_pipe_close (childpipe);
955 if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
956 (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read,
957 &childpipe_read_handle, sizeof (HANDLE))))
960 GNUNET_DISK_file_close (childpipe_read);
962 GNUNET_DISK_file_close (childpipe_write);
966 /* Unlike *nix variant, we don't dup the handle, so can't close
967 * filehandle right now.
969 SetHandleInformation (childpipe_read_handle, HANDLE_FLAG_INHERIT, 1);
973 childpipe_read = NULL;
974 childpipe_write = NULL;
977 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
979 lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
981 if (lsocks_pipe == NULL)
984 GNUNET_DISK_pipe_close (lsocks_pipe);
985 if (GNUNET_YES == pipe_control)
987 GNUNET_DISK_file_close (childpipe_write);
988 GNUNET_DISK_file_close (childpipe_read);
992 lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
993 GNUNET_DISK_PIPE_END_WRITE);
994 GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
995 &lsocks_write, sizeof (HANDLE));
996 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
997 (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
998 &lsocks_read, sizeof (HANDLE));
1004 if (GNUNET_YES == pipe_control)
1006 GNUNET_asprintf (&our_env[env_off++], "%s=", GNUNET_OS_CONTROL_PIPE);
1007 GNUNET_asprintf (&our_env[env_off++], "%p", childpipe_read_handle);
1009 if ( (lsocks != NULL) && (lsocks[0] != INVALID_SOCKET))
1011 /*This will tell the child that we're going to send lsocks over the pipe*/
1012 GNUNET_asprintf (&our_env[env_off++], "%s=", "GNUNET_OS_READ_LSOCKS");
1013 GNUNET_asprintf (&our_env[env_off++], "%lu", lsocks_read);
1015 our_env[env_off++] = NULL;
1016 env_block = CreateCustomEnvTable (our_env);
1018 GNUNET_free_non_null (our_env[--env_off]);
1021 if (NULL == (wpath = u8_to_u16 ((uint8_t *) path, 1 + strlen (path), NULL, &wpath_len)))
1023 LOG (GNUNET_ERROR_TYPE_DEBUG,
1024 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", path, errno);
1025 GNUNET_free (env_block);
1028 GNUNET_DISK_pipe_close (lsocks_pipe);
1029 if (GNUNET_YES == pipe_control)
1031 GNUNET_DISK_file_close (childpipe_write);
1032 GNUNET_DISK_file_close (childpipe_read);
1038 if (NULL == (wcmd = u8_to_u16 ((uint8_t *) cmd, 1 + strlen (cmd), NULL, &wcmd_len)))
1040 LOG (GNUNET_ERROR_TYPE_DEBUG,
1041 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", cmd, errno);
1042 GNUNET_free (env_block);
1046 GNUNET_DISK_pipe_close (lsocks_pipe);
1047 if (GNUNET_YES == pipe_control)
1049 GNUNET_DISK_file_close (childpipe_write);
1050 GNUNET_DISK_file_close (childpipe_read);
1055 bresult = CreateProcessW (wpath, wcmd, NULL, NULL, GNUNET_YES,
1056 CREATE_NO_WINDOW | CREATE_SUSPENDED, env_block, NULL, &start, &proc);
1057 error_code = GetLastError ();
1059 if ((NULL == pipe_stdin) && (stdih))
1060 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, stdif);
1063 if ((NULL == pipe_stdout) && (stdoh))
1064 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, stdof);
1067 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, stdef);
1070 LOG (GNUNET_ERROR_TYPE_ERROR, "CreateProcess(%s, %s) failed: %lu\n", path, cmd, error_code);
1072 GNUNET_free (env_block);
1076 if (GNUNET_YES == pipe_control)
1078 GNUNET_DISK_file_close (childpipe_read);
1083 if (GNUNET_YES == pipe_control)
1085 GNUNET_DISK_file_close (childpipe_write);
1088 GNUNET_DISK_pipe_close (lsocks_pipe);
1089 SetErrnoFromWinError (error_code);
1093 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1094 gnunet_proc->pid = proc.dwProcessId;
1095 gnunet_proc->handle = proc.hProcess;
1096 gnunet_proc->control_pipe = childpipe_write;
1098 CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
1100 ResumeThread (proc.hThread);
1101 CloseHandle (proc.hThread);
1103 if ( (NULL == lsocks) || (INVALID_SOCKET == lsocks[0]) )
1106 GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1108 /* This is a replacement for "goto error" that doesn't use goto */
1117 /* Tell the number of sockets */
1118 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1120 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1121 if (sizeof (count) != wrote)
1123 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1124 "Failed to write %u count bytes to the child: %u\n",
1125 sizeof (count), GetLastError ());
1128 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1130 WSAPROTOCOL_INFOA pi;
1131 /* Get a socket duplication info */
1132 if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1134 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1135 "Failed to duplicate an socket[%llu]: %u\n", i,
1139 /* Synchronous I/O is not nice, but we can't schedule this:
1140 * lsocks will be closed/freed by the caller soon, and until
1141 * the child creates a duplicate, closing a socket here will
1142 * close it for good.
1144 /* Send the size of the structure
1145 * (the child might be built with different headers...)
1148 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1149 if (sizeof (size) != wrote)
1151 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1152 "Failed to write %u size[%llu] bytes to the child: %u\n",
1153 sizeof (size), i, GetLastError ());
1156 /* Finally! Send the data */
1157 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1158 if (sizeof (pi) != wrote)
1160 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1161 "Failed to write %u socket[%llu] bytes to the child: %u\n",
1162 sizeof (pi), i, GetLastError ());
1166 /* This will block us until the child makes a final read or closes
1167 * the pipe (hence no 'wrote' check), since we have to wait for it
1168 * to duplicate the last socket, before we return and start closing
1171 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1176 GNUNET_DISK_file_sync (lsocks_write_fd);
1177 GNUNET_DISK_pipe_close (lsocks_pipe);
1181 /* If we can't pass on the socket(s), the child will block forever,
1182 * better put it out of its misery.
1184 SafeTerminateProcess (gnunet_proc->handle, 0, 0);
1185 CloseHandle (gnunet_proc->handle);
1186 if (NULL != gnunet_proc->control_pipe)
1187 GNUNET_DISK_file_close (gnunet_proc->control_pipe);
1188 GNUNET_free (gnunet_proc);
1201 * @param pipe_control should a pipe be used to send signals to the child?
1202 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1203 * @param pipe_stdin pipe to use to send input to child process (or NULL)
1204 * @param pipe_stdout pipe to use to get output from child process (or NULL)
1205 * @param filename name of the binary
1206 * @param argv NULL-terminated array of arguments to the process
1207 * @return pointer to process structure of the new process, NULL on error
1209 struct GNUNET_OS_Process *
1210 GNUNET_OS_start_process_vap (int pipe_control,
1211 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1212 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1213 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1214 const char *filename,
1217 return start_process (pipe_control,
1230 * @param pipe_control should a pipe be used to send signals to the child?
1231 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1232 * @param pipe_stdin pipe to use to send input to child process (or NULL)
1233 * @param pipe_stdout pipe to use to get output from child process (or NULL)
1234 * @param filename name of the binary
1235 * @param va NULL-terminated list of arguments to the process
1236 * @return pointer to process structure of the new process, NULL on error
1238 struct GNUNET_OS_Process *
1239 GNUNET_OS_start_process_va (int pipe_control,
1240 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1241 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1242 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1243 const char *filename, va_list va)
1245 struct GNUNET_OS_Process *ret;
1252 while (NULL != va_arg (ap, char *))
1255 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
1258 while (NULL != (argv[argc] = va_arg (ap, char *)))
1261 ret = GNUNET_OS_start_process_vap (pipe_control,
1275 * @param pipe_control should a pipe be used to send signals to the child?
1276 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1277 * @param pipe_stdin pipe to use to send input to child process (or NULL)
1278 * @param pipe_stdout pipe to use to get output from child process (or NULL)
1279 * @param filename name of the binary
1280 * @param ... NULL-terminated list of arguments to the process
1281 * @return pointer to process structure of the new process, NULL on error
1283 struct GNUNET_OS_Process *
1284 GNUNET_OS_start_process (int pipe_control,
1285 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1286 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1287 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1288 const char *filename, ...)
1290 struct GNUNET_OS_Process *ret;
1293 va_start (ap, filename);
1294 ret = GNUNET_OS_start_process_va (pipe_control, std_inheritance, pipe_stdin,
1295 pipe_stdout, filename, ap);
1304 * @param pipe_control should a pipe be used to send signals to the child?
1305 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
1306 * std handles of the parent are inherited by the child.
1307 * pipe_stdin and pipe_stdout take priority over std_inheritance
1308 * (when they are non-NULL).
1309 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
1310 * must be NULL on platforms where dup is not supported
1311 * @param filename name of the binary
1312 * @param argv NULL-terminated list of arguments to the process
1313 * @return process ID of the new process, -1 on error
1315 struct GNUNET_OS_Process *
1316 GNUNET_OS_start_process_v (int pipe_control,
1317 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1318 const SOCKTYPE *lsocks,
1319 const char *filename,
1322 return start_process (pipe_control,
1333 * Retrieve the status of a process, waiting on him if dead.
1334 * Nonblocking version.
1336 * @param proc process ID
1337 * @param type status type
1338 * @param code return code/signal number
1339 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1342 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1343 enum GNUNET_OS_ProcessStatusType *type,
1344 unsigned long *code)
1350 GNUNET_assert (0 != proc);
1351 ret = waitpid (proc->pid, &status, WNOHANG);
1354 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1355 return GNUNET_SYSERR;
1359 *type = GNUNET_OS_PROCESS_RUNNING;
1363 if (proc->pid != ret)
1365 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1366 return GNUNET_SYSERR;
1368 if (WIFEXITED (status))
1370 *type = GNUNET_OS_PROCESS_EXITED;
1371 *code = WEXITSTATUS (status);
1373 else if (WIFSIGNALED (status))
1375 *type = GNUNET_OS_PROCESS_SIGNALED;
1376 *code = WTERMSIG (status);
1378 else if (WIFSTOPPED (status))
1380 *type = GNUNET_OS_PROCESS_SIGNALED;
1381 *code = WSTOPSIG (status);
1384 else if (WIFCONTINUED (status))
1386 *type = GNUNET_OS_PROCESS_RUNNING;
1392 *type = GNUNET_OS_PROCESS_UNKNOWN;
1397 DWORD c, error_code, ret;
1401 if (h == NULL || ret == 0)
1403 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1405 return GNUNET_SYSERR;
1408 h = GetCurrentProcess ();
1411 ret = GetExitCodeProcess (h, &c);
1412 error_code = GetLastError ();
1413 if (ret == 0 || error_code != NO_ERROR)
1415 SetErrnoFromWinError (error_code);
1416 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1417 return GNUNET_SYSERR;
1419 if (STILL_ACTIVE == c)
1421 *type = GNUNET_OS_PROCESS_RUNNING;
1425 *type = GNUNET_OS_PROCESS_EXITED;
1434 * Wait for a process
1436 * @param proc pointer to process structure
1437 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1440 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1443 pid_t pid = proc->pid;
1446 while ( (pid != (ret = waitpid (pid, NULL, 0))) &&
1447 (EINTR == errno) ) ;
1450 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1451 return GNUNET_SYSERR;
1460 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1462 return GNUNET_SYSERR;
1465 h = GetCurrentProcess ();
1467 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1469 SetErrnoFromWinError (GetLastError ());
1470 return GNUNET_SYSERR;
1478 * Handle to a command.
1480 struct GNUNET_OS_CommandHandle
1486 struct GNUNET_OS_Process *eip;
1489 * Handle to the output pipe.
1491 struct GNUNET_DISK_PipeHandle *opipe;
1494 * Read-end of output pipe.
1496 const struct GNUNET_DISK_FileHandle *r;
1499 * Function to call on each line of output.
1501 GNUNET_OS_LineProcessor proc;
1504 * Closure for 'proc'.
1509 * Buffer for the output.
1514 * Task reading from pipe.
1516 GNUNET_SCHEDULER_TaskIdentifier rtask;
1521 struct GNUNET_TIME_Absolute timeout;
1524 * Current read offset in buf.
1531 * Stop/kill a command. Must ONLY be called either from
1532 * the callback after 'NULL' was passed for 'line' *OR*
1533 * from an independent task (not within the line processor).
1535 * @param cmd handle to the process
1538 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1540 if (NULL != cmd->proc)
1542 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1543 GNUNET_SCHEDULER_cancel (cmd->rtask);
1545 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1546 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1547 GNUNET_OS_process_destroy (cmd->eip);
1548 GNUNET_DISK_pipe_close (cmd->opipe);
1554 * Read from the process and call the line processor.
1556 * @param cls the 'struct GNUNET_OS_CommandHandle'
1557 * @param tc scheduler context
1560 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1562 struct GNUNET_OS_CommandHandle *cmd = cls;
1563 GNUNET_OS_LineProcessor proc;
1567 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1568 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1570 /* timeout, shutdown, etc. */
1573 proc (cmd->proc_cls, NULL);
1577 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1578 sizeof (cmd->buf) - cmd->off);
1581 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1583 cmd->buf[cmd->off] = '\0';
1584 cmd->proc (cmd->proc_cls, cmd->buf);
1588 proc (cmd->proc_cls, NULL);
1591 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1596 cmd->proc (cmd->proc_cls, cmd->buf);
1597 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1598 cmd->off -= (end + 1 - cmd->buf);
1599 end = memchr (cmd->buf, '\n', cmd->off);
1602 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1603 (cmd->timeout), cmd->r, &cmd_read, cmd);
1608 * Run the given command line and call the given function
1609 * for each line of the output.
1611 * @param proc function to call for each line of the output
1612 * @param proc_cls closure for proc
1613 * @param timeout when to time out
1614 * @param binary command to run
1615 * @param ... arguments to command
1616 * @return NULL on error
1618 struct GNUNET_OS_CommandHandle *
1619 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1620 struct GNUNET_TIME_Relative timeout, const char *binary,
1623 struct GNUNET_OS_CommandHandle *cmd;
1624 struct GNUNET_OS_Process *eip;
1625 struct GNUNET_DISK_PipeHandle *opipe;
1628 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1631 va_start (ap, binary);
1632 /* redirect stdout, don't inherit stderr/stdin */
1633 eip = GNUNET_OS_start_process_va (GNUNET_NO, 0, NULL, opipe, binary, ap);
1637 GNUNET_DISK_pipe_close (opipe);
1640 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1641 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1642 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1646 cmd->proc_cls = proc_cls;
1647 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1648 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1653 /* end of os_priority.c */