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 2, 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"
33 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
35 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
37 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
39 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
41 #define DEBUG_OS GNUNET_EXTRA_LOGGING
43 struct GNUNET_OS_Process
50 struct GNUNET_DISK_FileHandle *control_pipe;
53 static struct GNUNET_OS_Process current_process;
57 * This handler is called when there are control data to be read on the pipe
59 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
60 * @param tc scheduler context
63 parent_control_handler (void *cls,
64 const struct GNUNET_SCHEDULER_TaskContext *tc)
66 struct GNUNET_DISK_FileHandle *control_pipe =
67 (struct GNUNET_DISK_FileHandle *) cls;
71 LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
75 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT |
76 GNUNET_SCHEDULER_REASON_PREREQ_DONE))
78 GNUNET_DISK_npipe_close (control_pipe);
82 if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) !=
85 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
86 GNUNET_DISK_npipe_close (control_pipe);
91 LOG (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
93 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
94 control_pipe, &parent_control_handler,
103 * Task that connects this process to its parent via pipe
106 GNUNET_OS_install_parent_control_handler (void *cls,
108 GNUNET_SCHEDULER_TaskContext *tc)
111 struct GNUNET_DISK_FileHandle *control_pipe;
113 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
114 if ((env_buf == NULL) || (strlen (env_buf) <= 0))
116 LOG (GNUNET_ERROR_TYPE_INFO, _("Not installing a handler because $%s=%s\n"),
117 GNUNET_OS_CONTROL_PIPE, env_buf);
118 putenv ("GNUNET_OS_CONTROL_PIPE=");
122 GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
123 GNUNET_DISK_PERM_USER_READ |
124 GNUNET_DISK_PERM_USER_WRITE);
125 if (control_pipe == NULL)
127 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
128 putenv ("GNUNET_OS_CONTROL_PIPE=");
132 LOG (GNUNET_ERROR_TYPE_DEBUG,
133 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
135 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
136 &parent_control_handler, control_pipe);
137 putenv ("GNUNET_OS_CONTROL_PIPE=");
142 * Get process structure for current process
144 * The pointer it returns points to static memory location and must not be
147 * @return pointer to the process sturcutre for this process
149 struct GNUNET_OS_Process *
150 GNUNET_OS_process_current ()
153 current_process.pid = GetCurrentProcessId ();
154 current_process.handle = GetCurrentProcess ();
156 current_process.pid = 0;
158 return ¤t_process;
163 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
165 #if ENABLE_WINDOWS_WORKAROUNDS
169 ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
170 if (ret != sizeof (sig))
174 /* Child process is not controllable via pipe */
176 LOG (GNUNET_ERROR_TYPE_DEBUG,
177 "Child process is not controllable, will kill it directly\n");
180 else if (errno == EPIPE)
183 LOG (GNUNET_ERROR_TYPE_DEBUG,
184 "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
188 LOG (GNUNET_ERROR_TYPE_WARNING,
189 "Failed to write into control pipe , errno is %d\n", errno);
190 #if WINDOWS && !defined(__CYGWIN__)
191 TerminateProcess (proc->handle, 0);
193 PLIBC_KILL (proc->pid, sig);
199 LOG (GNUNET_ERROR_TYPE_DEBUG,
200 "Wrote control code into control pipe, now waiting\n");
204 /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
205 if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
206 TerminateProcess (proc->handle, 0);
209 struct GNUNET_NETWORK_FDSet *rfds;
210 struct GNUNET_NETWORK_FDSet *efds;
212 rfds = GNUNET_NETWORK_fdset_create ();
213 efds = GNUNET_NETWORK_fdset_create ();
215 GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
216 GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
218 /* Ndurner thought this up, and i have no idea what it does.
219 * There's have never been any code to answer the shutdown call
220 * (write a single int into the pipe, so that this function can read it).
221 * On *nix select() will probably tell that pipe is ready
222 * for reading, once the other process shuts down,
223 * but the read () call will fail, triggering a kill ()
224 * on the pid that is already dead. This will probably result in non-0
225 * return from kill(), and therefore from this function.
230 GNUNET_NETWORK_socket_select (rfds, NULL, efds,
231 GNUNET_TIME_relative_multiply
232 (GNUNET_TIME_relative_get_unit (),
236 GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
238 /* Just to be sure */
239 PLIBC_KILL (proc->pid, sig);
245 if (GNUNET_DISK_file_read (proc->control_pipe, &ret, sizeof (ret)) !=
247 res = PLIBC_KILL (proc->pid, sig);
249 /* Child signaled shutdown is in progress */
258 return kill (proc->pid, sig);
263 * Get the pid of the process in question
265 * @param proc the process to get the pid of
267 * @return the current process id
270 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
277 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
279 #if ENABLE_WINDOWS_WORKAROUNDS
280 if (proc->control_pipe)
281 GNUNET_DISK_npipe_close (proc->control_pipe);
285 if (proc->handle != NULL)
286 CloseHandle (proc->handle);
293 #include "gnunet_signal_lib.h"
295 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
298 * Make seaspider happy.
300 #define DWORD_WINAPI DWORD WINAPI
303 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
304 * @param proc pointer to process structure
307 ChildWaitThread (void *arg)
309 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
311 WaitForSingleObject (proc->handle, INFINITE);
313 if (w32_sigchld_handler)
314 w32_sigchld_handler ();
321 * Set process priority
323 * @param proc pointer to process structure
324 * @param prio priority value
325 * @return GNUNET_OK on success, GNUNET_SYSERR on error
328 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
329 enum GNUNET_SCHEDULER_Priority prio)
333 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
334 if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
337 /* convert to MINGW/Unix values */
340 case GNUNET_SCHEDULER_PRIORITY_UI:
341 case GNUNET_SCHEDULER_PRIORITY_URGENT:
343 rprio = HIGH_PRIORITY_CLASS;
349 case GNUNET_SCHEDULER_PRIORITY_HIGH:
351 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
357 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
359 rprio = NORMAL_PRIORITY_CLASS;
365 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
367 rprio = BELOW_NORMAL_PRIORITY_CLASS;
373 case GNUNET_SCHEDULER_PRIORITY_IDLE:
375 rprio = IDLE_PRIORITY_CLASS;
382 return GNUNET_SYSERR;
385 /* Set process priority */
388 HANDLE h = proc->handle;
390 GNUNET_assert (h != NULL);
391 SetPriorityClass (h, rprio);
397 if ((0 == pid) || (pid == getpid ()))
400 int delta = rprio - have;
403 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
405 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
406 return GNUNET_SYSERR;
411 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
413 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
415 return GNUNET_SYSERR;
420 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
421 "Priority management not availabe for this platform\n");
429 CreateCustomEnvTable (char **vars)
431 char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
432 size_t tablesize = 0;
433 size_t items_count = 0;
434 size_t n_found = 0, n_var;
441 win32_env_table = GetEnvironmentStringsA ();
442 if (win32_env_table == NULL)
444 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
446 index = GNUNET_malloc (sizeof (char *) * n_var);
447 for (c = 0; c < n_var; c++)
449 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
451 size_t len = strlen (ptr);
454 for (var_ptr = vars; *var_ptr; var_ptr++)
458 var_len = strlen (var);
459 if (strncmp (var, ptr, var_len) == 0)
463 tablesize += var_len + strlen (val) + 1;
468 tablesize += len + 1;
471 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
476 n_found += strlen (var) + strlen (val) + 1;
478 result = GNUNET_malloc (tablesize + n_found + 1);
479 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
481 size_t len = strlen (ptr);
484 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
488 var_len = strlen (var);
489 if (strncmp (var, ptr, var_len) == 0)
497 strcpy (result_ptr, ptr);
498 result_ptr += len + 1;
502 strcpy (result_ptr, var);
503 result_ptr += var_len;
504 strcpy (result_ptr, val);
505 result_ptr += strlen (val) + 1;
509 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
513 var_len = strlen (var);
516 strcpy (result_ptr, var);
517 result_ptr += var_len;
518 strcpy (result_ptr, val);
519 result_ptr += strlen (val) + 1;
522 FreeEnvironmentStrings (win32_env_table);
533 * @param pipe_stdin pipe to use to send input to child process (or NULL)
534 * @param pipe_stdout pipe to use to get output from child process (or NULL)
535 * @param filename name of the binary
536 * @param va NULL-terminated list of arguments to the process
537 * @return pointer to process structure of the new process, NULL on error
539 struct GNUNET_OS_Process *
540 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
541 struct GNUNET_DISK_PipeHandle *pipe_stdout,
542 const char *filename, va_list va)
546 #if ENABLE_WINDOWS_WORKAROUNDS
547 char *childpipename = NULL;
548 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
550 struct GNUNET_OS_Process *gnunet_proc = NULL;
561 #if ENABLE_WINDOWS_WORKAROUNDS
563 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
564 GNUNET_DISK_PERM_USER_READ |
565 GNUNET_DISK_PERM_USER_WRITE);
566 if (control_pipe == NULL)
572 while (NULL != va_arg (ap, char *))
576 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
579 while (NULL != (argv[argc] = va_arg (ap, char *)))
583 if (pipe_stdout != NULL)
585 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
587 GNUNET_DISK_PIPE_END_WRITE),
588 &fd_stdout_write, sizeof (int));
589 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
590 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
591 &fd_stdout_read, sizeof (int));
593 if (pipe_stdin != NULL)
595 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
596 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
597 &fd_stdin_read, sizeof (int));
598 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
599 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
600 &fd_stdin_write, sizeof (int));
608 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
609 #if ENABLE_WINDOWS_WORKAROUNDS
610 GNUNET_DISK_npipe_close (control_pipe);
615 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
616 gnunet_proc->pid = ret;
617 #if ENABLE_WINDOWS_WORKAROUNDS
618 gnunet_proc->control_pipe = control_pipe;
622 #if ENABLE_WINDOWS_WORKAROUNDS
623 GNUNET_free (childpipename);
628 #if ENABLE_WINDOWS_WORKAROUNDS
629 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
630 GNUNET_free (childpipename);
633 if (pipe_stdout != NULL)
635 GNUNET_break (0 == close (fd_stdout_read));
636 if (-1 == dup2 (fd_stdout_write, 1))
637 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
638 GNUNET_break (0 == close (fd_stdout_write));
641 if (pipe_stdin != NULL)
644 GNUNET_break (0 == close (fd_stdin_write));
645 if (-1 == dup2 (fd_stdin_read, 0))
646 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
647 GNUNET_break (0 == close (fd_stdin_read));
649 execvp (filename, argv);
650 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
657 PROCESS_INFORMATION proc;
660 HANDLE stdout_handle;
662 char path[MAX_PATH + 1];
664 char *our_env[3] = { NULL, NULL, NULL };
665 char *env_block = NULL;
667 DWORD pathbuf_len, alloc_len;
672 char *non_const_filename;
674 /* Search in prefix dir (hopefully - the directory from which
675 * the current module was loaded), bindir and libdir, then in PATH
677 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
678 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
679 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
681 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
684 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
687 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
690 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
691 GNUNET_free (self_prefix);
692 GNUNET_free (bindir);
693 GNUNET_free (libdir);
695 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
696 GNUNET_assert (alloc_len == (pathbuf_len - 1));
698 cmdlen = strlen (filename);
699 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
700 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
702 GNUNET_asprintf (&non_const_filename, "%s", filename);
704 /* Check that this is the full path. If it isn't, search. */
705 if (non_const_filename[1] == ':')
706 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
707 else if (!SearchPathA
708 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
711 SetErrnoFromWinError (GetLastError ());
712 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
714 GNUNET_free (non_const_filename);
715 GNUNET_free (pathbuf);
718 GNUNET_free (pathbuf);
719 GNUNET_free (non_const_filename);
723 while (NULL != (arg = va_arg (ap, char *)))
726 cmdlen = cmdlen + strlen (path) + 3;
728 cmdlen = cmdlen + strlen (arg) + 3;
732 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
734 while (NULL != (arg = va_arg (ap, char *)))
737 idx += sprintf (idx, "\"%s\" ", path);
739 idx += sprintf (idx, "\"%s\" ", arg);
743 memset (&start, 0, sizeof (start));
744 start.cb = sizeof (start);
746 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
747 start.dwFlags |= STARTF_USESTDHANDLES;
749 if (pipe_stdin != NULL)
751 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
752 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
753 &stdin_handle, sizeof (HANDLE));
754 start.hStdInput = stdin_handle;
757 if (pipe_stdout != NULL)
759 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
761 GNUNET_DISK_PIPE_END_WRITE),
762 &stdout_handle, sizeof (HANDLE));
763 start.hStdOutput = stdout_handle;
767 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
768 GNUNET_DISK_PERM_USER_READ |
769 GNUNET_DISK_PERM_USER_WRITE);
770 if (control_pipe == NULL)
778 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
782 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
783 GNUNET_asprintf (&our_env[1], "%s", childpipename);
785 env_block = CreateCustomEnvTable (our_env);
786 GNUNET_free (our_env[0]);
787 GNUNET_free (our_env[1]);
790 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
791 env_block, NULL, &start, &proc))
793 SetErrnoFromWinError (GetLastError ());
794 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
795 GNUNET_free (env_block);
800 GNUNET_free (env_block);
802 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
803 gnunet_proc->pid = proc.dwProcessId;
804 gnunet_proc->handle = proc.hProcess;
805 gnunet_proc->control_pipe = control_pipe;
807 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
809 ResumeThread (proc.hThread);
810 CloseHandle (proc.hThread);
822 * @param pipe_stdin pipe to use to send input to child process (or NULL)
823 * @param pipe_stdout pipe to use to get output from child process (or NULL)
824 * @param filename name of the binary
825 * @param ... NULL-terminated list of arguments to the process
827 * @return pointer to process structure of the new process, NULL on error
830 struct GNUNET_OS_Process *
831 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
832 struct GNUNET_DISK_PipeHandle *pipe_stdout,
833 const char *filename, ...)
835 struct GNUNET_OS_Process *ret;
838 va_start (ap, filename);
839 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
848 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
849 * must be NULL on platforms where dup is not supported
850 * @param filename name of the binary
851 * @param argv NULL-terminated list of arguments to the process
852 * @return process ID of the new process, -1 on error
854 struct GNUNET_OS_Process *
855 GNUNET_OS_start_process_v (const SOCKTYPE *lsocks,
856 const char *filename,
859 #if ENABLE_WINDOWS_WORKAROUNDS
860 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
861 char *childpipename = NULL;
868 struct GNUNET_OS_Process *gnunet_proc = NULL;
877 #if ENABLE_WINDOWS_WORKAROUNDS
879 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
880 GNUNET_DISK_PERM_USER_READ |
881 GNUNET_DISK_PERM_USER_WRITE);
882 if (control_pipe == NULL)
891 while (-1 != (k = lsocks[i++]))
892 GNUNET_array_append (lscp, ls, k);
893 GNUNET_array_append (lscp, ls, -1);
900 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
901 #if ENABLE_WINDOWS_WORKAROUNDS
902 GNUNET_DISK_npipe_close (control_pipe);
907 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
908 gnunet_proc->pid = ret;
909 #if ENABLE_WINDOWS_WORKAROUNDS
910 gnunet_proc->control_pipe = control_pipe;
914 GNUNET_array_grow (lscp, ls, 0);
915 #if ENABLE_WINDOWS_WORKAROUNDS
916 GNUNET_free (childpipename);
921 #if ENABLE_WINDOWS_WORKAROUNDS
922 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
923 GNUNET_free (childpipename);
928 /* read systemd documentation... */
929 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
930 setenv ("LISTEN_PID", lpid, 1);
933 while (-1 != lscp[i])
936 while (-1 != lscp[j])
942 GNUNET_assert (-1 != k);
943 GNUNET_assert (0 == close (lscp[j]));
951 /* Bury any existing FD, no matter what; they should all be closed
952 * on exec anyway and the important onces have been dup'ed away */
954 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
956 /* unset close-on-exec flag */
957 flags = fcntl (tgt, F_GETFD);
958 GNUNET_assert (flags >= 0);
959 flags &= ~FD_CLOEXEC;
961 (void) fcntl (tgt, F_SETFD, flags);
965 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
966 setenv ("LISTEN_FDS", fds, 1);
968 GNUNET_array_grow (lscp, ls, 0);
969 execvp (filename, argv);
970 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
973 char **arg, **non_const_argv;
977 PROCESS_INFORMATION proc;
979 struct GNUNET_OS_Process *gnunet_proc = NULL;
981 char path[MAX_PATH + 1];
983 char *our_env[5] = { NULL, NULL, NULL, NULL, NULL };
984 char *env_block = NULL;
986 DWORD pathbuf_len, alloc_len;
991 char *non_const_filename;
992 struct GNUNET_DISK_PipeHandle *lsocks_pipe;
993 const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
999 /* Search in prefix dir (hopefully - the directory from which
1000 * the current module was loaded), bindir and libdir, then in PATH
1002 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1003 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1004 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1006 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1009 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1012 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1015 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1016 GNUNET_free (self_prefix);
1017 GNUNET_free (bindir);
1018 GNUNET_free (libdir);
1020 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1021 if (alloc_len != pathbuf_len - 1)
1023 GNUNET_free (pathbuf);
1024 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1028 cmdlen = strlen (filename);
1029 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1030 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1032 GNUNET_asprintf (&non_const_filename, "%s", filename);
1034 /* Check that this is the full path. If it isn't, search. */
1035 if (non_const_filename[1] == ':')
1036 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1037 else if (!SearchPathA
1038 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1041 SetErrnoFromWinError (GetLastError ());
1042 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1043 non_const_filename);
1044 GNUNET_free (non_const_filename);
1045 GNUNET_free (pathbuf);
1048 GNUNET_free (pathbuf);
1049 GNUNET_free (non_const_filename);
1051 /* Count the number of arguments */
1052 arg = (char **) argv;
1059 /* Allocate a copy argv */
1060 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1062 /* Copy all argv strings */
1064 arg = (char **) argv;
1068 non_const_argv[argcount] = GNUNET_strdup (path);
1070 non_const_argv[argcount] = GNUNET_strdup (*arg);
1074 non_const_argv[argcount] = NULL;
1078 arg = non_const_argv;
1081 cmdlen = cmdlen + strlen (*arg) + 3;
1085 /* Allocate and create cmd */
1086 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1087 arg = non_const_argv;
1090 idx += sprintf (idx, "\"%s\" ", *arg);
1094 while (argcount > 0)
1095 GNUNET_free (non_const_argv[--argcount]);
1096 GNUNET_free (non_const_argv);
1098 memset (&start, 0, sizeof (start));
1099 start.cb = sizeof (start);
1102 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1103 GNUNET_DISK_PERM_USER_READ |
1104 GNUNET_DISK_PERM_USER_WRITE);
1105 if (control_pipe == NULL)
1111 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1113 lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
1115 if (lsocks_pipe == NULL)
1119 GNUNET_DISK_pipe_close (lsocks_pipe);
1122 lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
1123 GNUNET_DISK_PIPE_END_WRITE);
1124 GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1125 &lsocks_write, sizeof (HANDLE));
1126 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1127 (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1128 &lsocks_read, sizeof (HANDLE));
1132 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1136 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1137 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1138 GNUNET_free (childpipename);
1139 if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1143 /*This will tell the child that we're going to send lsocks over the pipe*/
1144 GNUNET_asprintf (&our_env[2], "%s=", "GNUNET_OS_READ_LSOCKS");
1145 GNUNET_asprintf (&our_env[3], "%lu", lsocks_read);
1148 env_block = CreateCustomEnvTable (our_env);
1149 GNUNET_free_non_null (our_env[0]);
1150 GNUNET_free_non_null (our_env[1]);
1151 GNUNET_free_non_null (our_env[2]);
1152 GNUNET_free_non_null (our_env[3]);
1155 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
1156 env_block, NULL, &start, &proc))
1158 SetErrnoFromWinError (GetLastError ());
1159 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1160 GNUNET_DISK_npipe_close (control_pipe);
1162 GNUNET_DISK_pipe_close (lsocks_pipe);
1163 GNUNET_free (env_block);
1168 GNUNET_free (env_block);
1170 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1171 gnunet_proc->pid = proc.dwProcessId;
1172 gnunet_proc->handle = proc.hProcess;
1173 gnunet_proc->control_pipe = control_pipe;
1175 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1177 ResumeThread (proc.hThread);
1178 CloseHandle (proc.hThread);
1181 if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1184 GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1186 /* This is a replacement for "goto error" that doesn't use goto */
1191 uint64_t size, count, i;
1193 /* Tell the number of sockets */
1194 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1196 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1197 if (wrote != sizeof (count))
1199 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u count bytes to the child: %u\n", sizeof (count), GetLastError ());
1202 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1204 WSAPROTOCOL_INFOA pi;
1205 /* Get a socket duplication info */
1206 if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1208 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to duplicate an socket[%llu]: %u\n", i, GetLastError ());
1209 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1212 /* Synchronous I/O is not nice, but we can't schedule this:
1213 * lsocks will be closed/freed by the caller soon, and until
1214 * the child creates a duplicate, closing a socket here will
1215 * close it for good.
1217 /* Send the size of the structure
1218 * (the child might be built with different headers...)
1221 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1222 if (wrote != sizeof (size))
1224 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u size[%llu] bytes to the child: %u\n", sizeof (size), i, GetLastError ());
1227 /* Finally! Send the data */
1228 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1229 if (wrote != sizeof (pi))
1231 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u socket[%llu] bytes to the child: %u\n", sizeof (pi), i, GetLastError ());
1235 /* This will block us until the child makes a final read or closes
1236 * the pipe (hence no 'wrote' check), since we have to wait for it
1237 * to duplicate the last socket, before we return and start closing
1240 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1245 GNUNET_DISK_file_sync (lsocks_write_fd);
1246 GNUNET_DISK_pipe_close (lsocks_pipe);
1250 /* If we can't pass on the socket(s), the child will block forever,
1251 * better put it out of its misery.
1253 TerminateProcess (gnunet_proc->handle, 0);
1254 CloseHandle (gnunet_proc->handle);
1255 GNUNET_DISK_npipe_close (gnunet_proc->control_pipe);
1256 GNUNET_free (gnunet_proc);
1266 * Retrieve the status of a process
1267 * @param proc process ID
1268 * @param type status type
1269 * @param code return code/signal number
1270 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1273 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1274 enum GNUNET_OS_ProcessStatusType *type,
1275 unsigned long *code)
1281 GNUNET_assert (0 != proc);
1282 ret = waitpid (proc->pid, &status, WNOHANG);
1285 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1286 return GNUNET_SYSERR;
1290 *type = GNUNET_OS_PROCESS_RUNNING;
1294 if (proc->pid != ret)
1296 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1297 return GNUNET_SYSERR;
1299 if (WIFEXITED (status))
1301 *type = GNUNET_OS_PROCESS_EXITED;
1302 *code = WEXITSTATUS (status);
1304 else if (WIFSIGNALED (status))
1306 *type = GNUNET_OS_PROCESS_SIGNALED;
1307 *code = WTERMSIG (status);
1309 else if (WIFSTOPPED (status))
1311 *type = GNUNET_OS_PROCESS_SIGNALED;
1312 *code = WSTOPSIG (status);
1315 else if (WIFCONTINUED (status))
1317 *type = GNUNET_OS_PROCESS_RUNNING;
1323 *type = GNUNET_OS_PROCESS_UNKNOWN;
1328 DWORD c, error_code, ret;
1332 if (h == NULL || ret == 0)
1334 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1336 return GNUNET_SYSERR;
1339 h = GetCurrentProcess ();
1342 ret = GetExitCodeProcess (h, &c);
1343 error_code = GetLastError ();
1344 if (ret == 0 || error_code != NO_ERROR)
1346 SetErrnoFromWinError (error_code);
1347 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1348 return GNUNET_SYSERR;
1350 if (STILL_ACTIVE == c)
1352 *type = GNUNET_OS_PROCESS_RUNNING;
1356 *type = GNUNET_OS_PROCESS_EXITED;
1365 * Wait for a process
1366 * @param proc pointer to process structure
1367 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1370 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1374 pid_t pid = proc->pid;
1376 if (pid != waitpid (pid, NULL, 0))
1377 return GNUNET_SYSERR;
1386 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1388 return GNUNET_SYSERR;
1391 h = GetCurrentProcess ();
1393 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1395 SetErrnoFromWinError (GetLastError ());
1396 ret = GNUNET_SYSERR;
1407 * Handle to a command.
1409 struct GNUNET_OS_CommandHandle
1415 struct GNUNET_OS_Process *eip;
1418 * Handle to the output pipe.
1420 struct GNUNET_DISK_PipeHandle *opipe;
1423 * Read-end of output pipe.
1425 const struct GNUNET_DISK_FileHandle *r;
1428 * Function to call on each line of output.
1430 GNUNET_OS_LineProcessor proc;
1433 * Closure for 'proc'.
1438 * Buffer for the output.
1443 * Task reading from pipe.
1445 GNUNET_SCHEDULER_TaskIdentifier rtask;
1450 struct GNUNET_TIME_Absolute timeout;
1453 * Current read offset in buf.
1460 * Stop/kill a command. Must ONLY be called either from
1461 * the callback after 'NULL' was passed for 'line' *OR*
1462 * from an independent task (not within the line processor).
1464 * @param cmd handle to the process
1467 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1470 if (cmd->proc != NULL)
1472 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1473 GNUNET_SCHEDULER_cancel (cmd->rtask);
1475 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1476 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1477 GNUNET_OS_process_close (cmd->eip);
1478 GNUNET_DISK_pipe_close (cmd->opipe);
1484 * Read from the process and call the line processor.
1486 * @param cls the 'struct GNUNET_OS_CommandHandle'
1487 * @param tc scheduler context
1490 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1492 struct GNUNET_OS_CommandHandle *cmd = cls;
1493 GNUNET_OS_LineProcessor proc;
1497 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1498 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1500 /* timeout, shutdown, etc. */
1503 proc (cmd->proc_cls, NULL);
1507 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1508 sizeof (cmd->buf) - cmd->off);
1511 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1513 cmd->buf[cmd->off] = '\0';
1514 cmd->proc (cmd->proc_cls, cmd->buf);
1518 proc (cmd->proc_cls, NULL);
1521 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1526 cmd->proc (cmd->proc_cls, cmd->buf);
1527 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1528 cmd->off -= (end + 1 - cmd->buf);
1529 end = memchr (cmd->buf, '\n', cmd->off);
1532 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1533 (cmd->timeout), cmd->r, &cmd_read, cmd);
1538 * Run the given command line and call the given function
1539 * for each line of the output.
1541 * @param proc function to call for each line of the output
1542 * @param proc_cls closure for proc
1543 * @param timeout when to time out
1544 * @param binary command to run
1545 * @param ... arguments to command
1546 * @return NULL on error
1548 struct GNUNET_OS_CommandHandle *
1549 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1550 struct GNUNET_TIME_Relative timeout, const char *binary,
1553 struct GNUNET_OS_CommandHandle *cmd;
1554 struct GNUNET_OS_Process *eip;
1555 struct GNUNET_DISK_PipeHandle *opipe;
1558 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1561 va_start (ap, binary);
1562 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1566 GNUNET_DISK_pipe_close (opipe);
1569 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1570 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1571 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1575 cmd->proc_cls = proc_cls;
1576 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1577 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1584 /* end of os_priority.c */