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"
31 #include "gnunet_strings_lib.h"
34 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
36 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
38 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
42 #define DEBUG_OS GNUNET_EXTRA_LOGGING
44 struct GNUNET_OS_Process
51 struct GNUNET_DISK_FileHandle *control_pipe;
54 static struct GNUNET_OS_Process current_process;
58 * This handler is called when there are control data to be read on the pipe
60 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
61 * @param tc scheduler context
64 parent_control_handler (void *cls,
65 const struct GNUNET_SCHEDULER_TaskContext *tc)
67 struct GNUNET_DISK_FileHandle *control_pipe =
68 (struct GNUNET_DISK_FileHandle *) cls;
72 LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
76 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT |
77 GNUNET_SCHEDULER_REASON_PREREQ_DONE))
79 GNUNET_DISK_npipe_close (control_pipe);
83 if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) !=
86 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
87 GNUNET_DISK_npipe_close (control_pipe);
92 LOG (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
94 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
95 control_pipe, &parent_control_handler,
104 * Task that connects this process to its parent via pipe
107 GNUNET_OS_install_parent_control_handler (void *cls,
109 GNUNET_SCHEDULER_TaskContext *tc)
112 struct GNUNET_DISK_FileHandle *control_pipe;
114 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
115 if ((env_buf == NULL) || (strlen (env_buf) <= 0))
117 LOG (GNUNET_ERROR_TYPE_INFO, _("Not installing a handler because $%s=%s\n"),
118 GNUNET_OS_CONTROL_PIPE, env_buf);
119 putenv ("GNUNET_OS_CONTROL_PIPE=");
123 GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
124 GNUNET_DISK_PERM_USER_READ |
125 GNUNET_DISK_PERM_USER_WRITE);
126 if (control_pipe == NULL)
128 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
129 putenv ("GNUNET_OS_CONTROL_PIPE=");
133 LOG (GNUNET_ERROR_TYPE_DEBUG,
134 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
136 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
137 &parent_control_handler, control_pipe);
138 putenv ("GNUNET_OS_CONTROL_PIPE=");
143 * Get process structure for current process
145 * The pointer it returns points to static memory location and must not be
148 * @return pointer to the process sturcutre for this process
150 struct GNUNET_OS_Process *
151 GNUNET_OS_process_current ()
154 current_process.pid = GetCurrentProcessId ();
155 current_process.handle = GetCurrentProcess ();
157 current_process.pid = 0;
159 return ¤t_process;
164 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
166 #if ENABLE_WINDOWS_WORKAROUNDS
170 ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
171 if (ret != sizeof (sig))
175 /* Child process is not controllable via pipe */
177 LOG (GNUNET_ERROR_TYPE_DEBUG,
178 "Child process is not controllable, will kill it directly\n");
181 else if (errno == EPIPE)
184 LOG (GNUNET_ERROR_TYPE_DEBUG,
185 "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
189 LOG (GNUNET_ERROR_TYPE_WARNING,
190 "Failed to write into control pipe , errno is %d\n", errno);
191 #if WINDOWS && !defined(__CYGWIN__)
192 TerminateProcess (proc->handle, 0);
194 PLIBC_KILL (proc->pid, sig);
200 LOG (GNUNET_ERROR_TYPE_DEBUG,
201 "Wrote control code into control pipe, now waiting\n");
205 /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
206 if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
207 TerminateProcess (proc->handle, 0);
210 struct GNUNET_NETWORK_FDSet *rfds;
211 struct GNUNET_NETWORK_FDSet *efds;
213 rfds = GNUNET_NETWORK_fdset_create ();
214 efds = GNUNET_NETWORK_fdset_create ();
216 GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
217 GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
219 /* Ndurner thought this up, and i have no idea what it does.
220 * There's have never been any code to answer the shutdown call
221 * (write a single int into the pipe, so that this function can read it).
222 * On *nix select() will probably tell that pipe is ready
223 * for reading, once the other process shuts down,
224 * but the read () call will fail, triggering a kill ()
225 * on the pid that is already dead. This will probably result in non-0
226 * return from kill(), and therefore from this function.
231 GNUNET_NETWORK_socket_select (rfds, NULL, efds,
232 GNUNET_TIME_relative_multiply
233 (GNUNET_TIME_relative_get_unit (),
237 GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
239 /* Just to be sure */
240 PLIBC_KILL (proc->pid, sig);
246 if (GNUNET_DISK_file_read (proc->control_pipe, &ret, sizeof (ret)) !=
248 res = PLIBC_KILL (proc->pid, sig);
250 /* Child signaled shutdown is in progress */
259 return kill (proc->pid, sig);
264 * Get the pid of the process in question
266 * @param proc the process to get the pid of
268 * @return the current process id
271 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
278 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
280 #if ENABLE_WINDOWS_WORKAROUNDS
281 if (proc->control_pipe)
282 GNUNET_DISK_npipe_close (proc->control_pipe);
286 if (proc->handle != NULL)
287 CloseHandle (proc->handle);
294 #include "gnunet_signal_lib.h"
296 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
299 * Make seaspider happy.
301 #define DWORD_WINAPI DWORD WINAPI
304 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
305 * @param proc pointer to process structure
308 child_wait_thread (void *arg)
310 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
312 WaitForSingleObject (proc->handle, INFINITE);
314 if (w32_sigchld_handler)
315 w32_sigchld_handler ();
322 * Set process priority
324 * @param proc pointer to process structure
325 * @param prio priority value
326 * @return GNUNET_OK on success, GNUNET_SYSERR on error
329 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
330 enum GNUNET_SCHEDULER_Priority prio)
334 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
335 if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
338 /* convert to MINGW/Unix values */
341 case GNUNET_SCHEDULER_PRIORITY_UI:
342 case GNUNET_SCHEDULER_PRIORITY_URGENT:
344 rprio = HIGH_PRIORITY_CLASS;
350 case GNUNET_SCHEDULER_PRIORITY_HIGH:
352 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
358 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
360 rprio = NORMAL_PRIORITY_CLASS;
366 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
368 rprio = BELOW_NORMAL_PRIORITY_CLASS;
374 case GNUNET_SCHEDULER_PRIORITY_IDLE:
376 rprio = IDLE_PRIORITY_CLASS;
383 return GNUNET_SYSERR;
386 /* Set process priority */
389 HANDLE h = proc->handle;
391 GNUNET_assert (h != NULL);
392 SetPriorityClass (h, rprio);
398 if ((0 == pid) || (pid == getpid ()))
401 int delta = rprio - have;
404 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
406 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
407 return GNUNET_SYSERR;
412 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
414 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
416 return GNUNET_SYSERR;
421 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
422 "Priority management not availabe for this platform\n");
430 CreateCustomEnvTable (char **vars)
432 char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
433 size_t tablesize = 0;
434 size_t items_count = 0;
435 size_t n_found = 0, n_var;
442 win32_env_table = GetEnvironmentStringsA ();
443 if (win32_env_table == NULL)
445 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
447 index = GNUNET_malloc (sizeof (char *) * n_var);
448 for (c = 0; c < n_var; c++)
450 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
452 size_t len = strlen (ptr);
455 for (var_ptr = vars; *var_ptr; var_ptr++)
459 var_len = strlen (var);
460 if (strncmp (var, ptr, var_len) == 0)
464 tablesize += var_len + strlen (val) + 1;
469 tablesize += len + 1;
472 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
477 n_found += strlen (var) + strlen (val) + 1;
479 result = GNUNET_malloc (tablesize + n_found + 1);
480 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
482 size_t len = strlen (ptr);
485 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
489 var_len = strlen (var);
490 if (strncmp (var, ptr, var_len) == 0)
498 strcpy (result_ptr, ptr);
499 result_ptr += len + 1;
503 strcpy (result_ptr, var);
504 result_ptr += var_len;
505 strcpy (result_ptr, val);
506 result_ptr += strlen (val) + 1;
510 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
514 var_len = strlen (var);
517 strcpy (result_ptr, var);
518 result_ptr += var_len;
519 strcpy (result_ptr, val);
520 result_ptr += strlen (val) + 1;
523 FreeEnvironmentStrings (win32_env_table);
534 * @param pipe_stdin pipe to use to send input to child process (or NULL)
535 * @param pipe_stdout pipe to use to get output from child process (or NULL)
536 * @param filename name of the binary
537 * @param argv NULL-terminated array of arguments to the process
538 * @return pointer to process structure of the new process, NULL on error
540 struct GNUNET_OS_Process *
541 GNUNET_OS_start_process_vap (struct GNUNET_DISK_PipeHandle *pipe_stdin,
542 struct GNUNET_DISK_PipeHandle *pipe_stdout,
543 const char *filename,
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;
559 #if ENABLE_WINDOWS_WORKAROUNDS
561 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
562 GNUNET_DISK_PERM_USER_READ |
563 GNUNET_DISK_PERM_USER_WRITE);
564 if (control_pipe == NULL)
567 if (pipe_stdout != NULL)
569 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
571 GNUNET_DISK_PIPE_END_WRITE),
572 &fd_stdout_write, sizeof (int));
573 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
574 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
575 &fd_stdout_read, sizeof (int));
577 if (pipe_stdin != NULL)
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_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
583 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
584 &fd_stdin_write, sizeof (int));
592 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
593 #if ENABLE_WINDOWS_WORKAROUNDS
594 GNUNET_DISK_npipe_close (control_pipe);
599 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
600 gnunet_proc->pid = ret;
601 #if ENABLE_WINDOWS_WORKAROUNDS
602 gnunet_proc->control_pipe = control_pipe;
605 #if ENABLE_WINDOWS_WORKAROUNDS
606 GNUNET_free (childpipename);
611 #if ENABLE_WINDOWS_WORKAROUNDS
612 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
613 GNUNET_free (childpipename);
616 if (pipe_stdout != NULL)
618 GNUNET_break (0 == close (fd_stdout_read));
619 if (-1 == dup2 (fd_stdout_write, 1))
620 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
621 GNUNET_break (0 == close (fd_stdout_write));
624 if (pipe_stdin != NULL)
627 GNUNET_break (0 == close (fd_stdin_write));
628 if (-1 == dup2 (fd_stdin_read, 0))
629 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
630 GNUNET_break (0 == close (fd_stdin_read));
632 execvp (filename, argv);
633 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
640 PROCESS_INFORMATION proc;
643 HANDLE stdout_handle;
645 char path[MAX_PATH + 1];
647 char *our_env[3] = { NULL, NULL, NULL };
648 char *env_block = NULL;
650 DWORD pathbuf_len, alloc_len;
655 char *non_const_filename;
656 wchar_t wpath[MAX_PATH + 1], wcmd[32768];
658 /* Search in prefix dir (hopefully - the directory from which
659 * the current module was loaded), bindir and libdir, then in PATH
661 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
662 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
663 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
665 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
668 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
671 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
674 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
675 GNUNET_free (self_prefix);
676 GNUNET_free (bindir);
677 GNUNET_free (libdir);
679 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
680 GNUNET_assert (alloc_len == (pathbuf_len - 1));
682 cmdlen = strlen (filename);
683 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
684 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
686 GNUNET_asprintf (&non_const_filename, "%s", filename);
688 /* Check that this is the full path. If it isn't, search. */
689 if (non_const_filename[1] == ':')
690 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
691 else if (!SearchPathA
692 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
695 SetErrnoFromWinError (GetLastError ());
696 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
698 GNUNET_free (non_const_filename);
699 GNUNET_free (pathbuf);
702 GNUNET_free (pathbuf);
703 GNUNET_free (non_const_filename);
707 while (NULL != (arg = argv[argc++]))
710 cmdlen = cmdlen + strlen (path) + 3;
712 cmdlen = cmdlen + strlen (arg) + 3;
715 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
717 while (NULL != (arg = argv[argc++]))
720 idx += sprintf (idx, "\"%s\" ", path);
722 idx += sprintf (idx, "\"%s\" ", arg);
725 memset (&start, 0, sizeof (start));
726 start.cb = sizeof (start);
728 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
729 start.dwFlags |= STARTF_USESTDHANDLES;
731 if (pipe_stdin != NULL)
733 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
734 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
735 &stdin_handle, sizeof (HANDLE));
736 start.hStdInput = stdin_handle;
739 if (pipe_stdout != NULL)
741 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
743 GNUNET_DISK_PIPE_END_WRITE),
744 &stdout_handle, sizeof (HANDLE));
745 start.hStdOutput = stdout_handle;
749 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
750 GNUNET_DISK_PERM_USER_READ |
751 GNUNET_DISK_PERM_USER_WRITE);
752 if (control_pipe == NULL)
760 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
764 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
765 GNUNET_asprintf (&our_env[1], "%s", childpipename);
767 env_block = CreateCustomEnvTable (our_env);
768 GNUNET_free (our_env[0]);
769 GNUNET_free (our_env[1]);
771 if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath)
772 || ERROR_SUCCESS != plibc_conv_to_win_pathwconv(cmd, wcmd)
774 (wpath, wcmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
775 env_block, NULL, &start, &proc))
777 SetErrnoFromWinError (GetLastError ());
778 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
779 GNUNET_free (env_block);
784 GNUNET_free (env_block);
786 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
787 gnunet_proc->pid = proc.dwProcessId;
788 gnunet_proc->handle = proc.hProcess;
789 gnunet_proc->control_pipe = control_pipe;
791 CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
793 ResumeThread (proc.hThread);
794 CloseHandle (proc.hThread);
806 * @param pipe_stdin pipe to use to send input to child process (or NULL)
807 * @param pipe_stdout pipe to use to get output from child process (or NULL)
808 * @param filename name of the binary
809 * @param va NULL-terminated list of arguments to the process
810 * @return pointer to process structure of the new process, NULL on error
812 struct GNUNET_OS_Process *
813 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
814 struct GNUNET_DISK_PipeHandle *pipe_stdout,
815 const char *filename, va_list va)
817 struct GNUNET_OS_Process *ret;
824 while (NULL != va_arg (ap, char *))
827 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
830 while (NULL != (argv[argc] = va_arg (ap, char *)))
833 ret = GNUNET_OS_start_process_vap (pipe_stdin,
846 * @param pipe_stdin pipe to use to send input to child process (or NULL)
847 * @param pipe_stdout pipe to use to get output from child process (or NULL)
848 * @param filename name of the binary
849 * @param ... NULL-terminated list of arguments to the process
851 * @return pointer to process structure of the new process, NULL on error
854 struct GNUNET_OS_Process *
855 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
856 struct GNUNET_DISK_PipeHandle *pipe_stdout,
857 const char *filename, ...)
859 struct GNUNET_OS_Process *ret;
862 va_start (ap, filename);
863 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
872 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
873 * must be NULL on platforms where dup is not supported
874 * @param filename name of the binary
875 * @param argv NULL-terminated list of arguments to the process
876 * @return process ID of the new process, -1 on error
878 struct GNUNET_OS_Process *
879 GNUNET_OS_start_process_v (const SOCKTYPE *lsocks,
880 const char *filename,
883 #if ENABLE_WINDOWS_WORKAROUNDS
884 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
885 char *childpipename = NULL;
892 struct GNUNET_OS_Process *gnunet_proc = NULL;
901 #if ENABLE_WINDOWS_WORKAROUNDS
903 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
904 GNUNET_DISK_PERM_USER_READ |
905 GNUNET_DISK_PERM_USER_WRITE);
906 if (control_pipe == NULL)
915 while (-1 != (k = lsocks[i++]))
916 GNUNET_array_append (lscp, ls, k);
917 GNUNET_array_append (lscp, ls, -1);
924 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
925 #if ENABLE_WINDOWS_WORKAROUNDS
926 GNUNET_DISK_npipe_close (control_pipe);
931 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
932 gnunet_proc->pid = ret;
933 #if ENABLE_WINDOWS_WORKAROUNDS
934 gnunet_proc->control_pipe = control_pipe;
938 GNUNET_array_grow (lscp, ls, 0);
939 #if ENABLE_WINDOWS_WORKAROUNDS
940 GNUNET_free (childpipename);
945 #if ENABLE_WINDOWS_WORKAROUNDS
946 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
947 GNUNET_free (childpipename);
952 /* read systemd documentation... */
953 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
954 setenv ("LISTEN_PID", lpid, 1);
957 while (-1 != lscp[i])
960 while (-1 != lscp[j])
966 GNUNET_assert (-1 != k);
967 GNUNET_assert (0 == close (lscp[j]));
975 /* Bury any existing FD, no matter what; they should all be closed
976 * on exec anyway and the important onces have been dup'ed away */
978 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
980 /* unset close-on-exec flag */
981 flags = fcntl (tgt, F_GETFD);
982 GNUNET_assert (flags >= 0);
983 flags &= ~FD_CLOEXEC;
985 (void) fcntl (tgt, F_SETFD, flags);
989 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
990 setenv ("LISTEN_FDS", fds, 1);
992 GNUNET_array_grow (lscp, ls, 0);
993 execvp (filename, argv);
994 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
997 char **arg, **non_const_argv;
1001 PROCESS_INFORMATION proc;
1003 struct GNUNET_OS_Process *gnunet_proc = NULL;
1005 char path[MAX_PATH + 1];
1007 char *our_env[5] = { NULL, NULL, NULL, NULL, NULL };
1008 char *env_block = NULL;
1010 DWORD pathbuf_len, alloc_len;
1015 char *non_const_filename;
1016 struct GNUNET_DISK_PipeHandle *lsocks_pipe;
1017 const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
1019 HANDLE lsocks_write;
1020 wchar_t wpath[MAX_PATH + 1], wcmd[32768];
1024 /* Search in prefix dir (hopefully - the directory from which
1025 * the current module was loaded), bindir and libdir, then in PATH
1027 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1028 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1029 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1031 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1034 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1037 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1040 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1041 GNUNET_free (self_prefix);
1042 GNUNET_free (bindir);
1043 GNUNET_free (libdir);
1045 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1046 if (alloc_len != pathbuf_len - 1)
1048 GNUNET_free (pathbuf);
1049 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1053 cmdlen = strlen (filename);
1054 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1055 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1057 GNUNET_asprintf (&non_const_filename, "%s", filename);
1059 /* Check that this is the full path. If it isn't, search. */
1060 if (non_const_filename[1] == ':')
1061 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1062 else if (!SearchPathA
1063 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1066 SetErrnoFromWinError (GetLastError ());
1067 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1068 non_const_filename);
1069 GNUNET_free (non_const_filename);
1070 GNUNET_free (pathbuf);
1073 GNUNET_free (pathbuf);
1074 GNUNET_free (non_const_filename);
1076 /* Count the number of arguments */
1077 arg = (char **) argv;
1084 /* Allocate a copy argv */
1085 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1087 /* Copy all argv strings */
1089 arg = (char **) argv;
1093 non_const_argv[argcount] = GNUNET_strdup (path);
1095 non_const_argv[argcount] = GNUNET_strdup (*arg);
1099 non_const_argv[argcount] = NULL;
1103 arg = non_const_argv;
1106 cmdlen = cmdlen + strlen (*arg) + 3;
1110 /* Allocate and create cmd */
1111 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1112 arg = non_const_argv;
1115 idx += sprintf (idx, "\"%s\" ", *arg);
1119 while (argcount > 0)
1120 GNUNET_free (non_const_argv[--argcount]);
1121 GNUNET_free (non_const_argv);
1123 memset (&start, 0, sizeof (start));
1124 start.cb = sizeof (start);
1127 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1128 GNUNET_DISK_PERM_USER_READ |
1129 GNUNET_DISK_PERM_USER_WRITE);
1130 if (control_pipe == NULL)
1136 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1138 lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
1140 if (lsocks_pipe == NULL)
1144 GNUNET_DISK_pipe_close (lsocks_pipe);
1147 lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
1148 GNUNET_DISK_PIPE_END_WRITE);
1149 GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1150 &lsocks_write, sizeof (HANDLE));
1151 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1152 (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1153 &lsocks_read, sizeof (HANDLE));
1157 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1161 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1162 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1163 GNUNET_free (childpipename);
1164 if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1168 /*This will tell the child that we're going to send lsocks over the pipe*/
1169 GNUNET_asprintf (&our_env[2], "%s=", "GNUNET_OS_READ_LSOCKS");
1170 GNUNET_asprintf (&our_env[3], "%lu", lsocks_read);
1173 env_block = CreateCustomEnvTable (our_env);
1174 GNUNET_free_non_null (our_env[0]);
1175 GNUNET_free_non_null (our_env[1]);
1176 GNUNET_free_non_null (our_env[2]);
1177 GNUNET_free_non_null (our_env[3]);
1179 if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath)
1180 || ERROR_SUCCESS != plibc_conv_to_win_pathwconv(cmd, wcmd)
1182 (wpath, wcmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
1183 env_block, NULL, &start, &proc))
1185 SetErrnoFromWinError (GetLastError ());
1186 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1187 GNUNET_DISK_npipe_close (control_pipe);
1189 GNUNET_DISK_pipe_close (lsocks_pipe);
1190 GNUNET_free (env_block);
1195 GNUNET_free (env_block);
1197 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1198 gnunet_proc->pid = proc.dwProcessId;
1199 gnunet_proc->handle = proc.hProcess;
1200 gnunet_proc->control_pipe = control_pipe;
1202 CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
1204 ResumeThread (proc.hThread);
1205 CloseHandle (proc.hThread);
1208 if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1211 GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1213 /* This is a replacement for "goto error" that doesn't use goto */
1218 uint64_t size, count, i;
1220 /* Tell the number of sockets */
1221 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1223 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1224 if (wrote != sizeof (count))
1226 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u count bytes to the child: %u\n", sizeof (count), GetLastError ());
1229 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1231 WSAPROTOCOL_INFOA pi;
1232 /* Get a socket duplication info */
1233 if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1235 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to duplicate an socket[%llu]: %u\n", i, GetLastError ());
1236 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1239 /* Synchronous I/O is not nice, but we can't schedule this:
1240 * lsocks will be closed/freed by the caller soon, and until
1241 * the child creates a duplicate, closing a socket here will
1242 * close it for good.
1244 /* Send the size of the structure
1245 * (the child might be built with different headers...)
1248 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1249 if (wrote != sizeof (size))
1251 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u size[%llu] bytes to the child: %u\n", sizeof (size), i, GetLastError ());
1254 /* Finally! Send the data */
1255 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1256 if (wrote != sizeof (pi))
1258 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u socket[%llu] bytes to the child: %u\n", sizeof (pi), i, GetLastError ());
1262 /* This will block us until the child makes a final read or closes
1263 * the pipe (hence no 'wrote' check), since we have to wait for it
1264 * to duplicate the last socket, before we return and start closing
1267 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1272 GNUNET_DISK_file_sync (lsocks_write_fd);
1273 GNUNET_DISK_pipe_close (lsocks_pipe);
1277 /* If we can't pass on the socket(s), the child will block forever,
1278 * better put it out of its misery.
1280 TerminateProcess (gnunet_proc->handle, 0);
1281 CloseHandle (gnunet_proc->handle);
1282 GNUNET_DISK_npipe_close (gnunet_proc->control_pipe);
1283 GNUNET_free (gnunet_proc);
1293 * Retrieve the status of a process
1294 * @param proc process ID
1295 * @param type status type
1296 * @param code return code/signal number
1297 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1300 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1301 enum GNUNET_OS_ProcessStatusType *type,
1302 unsigned long *code)
1308 GNUNET_assert (0 != proc);
1309 ret = waitpid (proc->pid, &status, WNOHANG);
1312 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1313 return GNUNET_SYSERR;
1317 *type = GNUNET_OS_PROCESS_RUNNING;
1321 if (proc->pid != ret)
1323 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1324 return GNUNET_SYSERR;
1326 if (WIFEXITED (status))
1328 *type = GNUNET_OS_PROCESS_EXITED;
1329 *code = WEXITSTATUS (status);
1331 else if (WIFSIGNALED (status))
1333 *type = GNUNET_OS_PROCESS_SIGNALED;
1334 *code = WTERMSIG (status);
1336 else if (WIFSTOPPED (status))
1338 *type = GNUNET_OS_PROCESS_SIGNALED;
1339 *code = WSTOPSIG (status);
1342 else if (WIFCONTINUED (status))
1344 *type = GNUNET_OS_PROCESS_RUNNING;
1350 *type = GNUNET_OS_PROCESS_UNKNOWN;
1355 DWORD c, error_code, ret;
1359 if (h == NULL || ret == 0)
1361 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1363 return GNUNET_SYSERR;
1366 h = GetCurrentProcess ();
1369 ret = GetExitCodeProcess (h, &c);
1370 error_code = GetLastError ();
1371 if (ret == 0 || error_code != NO_ERROR)
1373 SetErrnoFromWinError (error_code);
1374 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1375 return GNUNET_SYSERR;
1377 if (STILL_ACTIVE == c)
1379 *type = GNUNET_OS_PROCESS_RUNNING;
1383 *type = GNUNET_OS_PROCESS_EXITED;
1392 * Wait for a process
1393 * @param proc pointer to process structure
1394 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1397 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1401 pid_t pid = proc->pid;
1404 while ( (pid != (ret = waitpid (pid, NULL, 0))) &&
1405 (EINTR == errno) ) ;
1408 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1409 return GNUNET_SYSERR;
1419 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1421 return GNUNET_SYSERR;
1424 h = GetCurrentProcess ();
1426 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1428 SetErrnoFromWinError (GetLastError ());
1429 ret = GNUNET_SYSERR;
1440 * Handle to a command.
1442 struct GNUNET_OS_CommandHandle
1448 struct GNUNET_OS_Process *eip;
1451 * Handle to the output pipe.
1453 struct GNUNET_DISK_PipeHandle *opipe;
1456 * Read-end of output pipe.
1458 const struct GNUNET_DISK_FileHandle *r;
1461 * Function to call on each line of output.
1463 GNUNET_OS_LineProcessor proc;
1466 * Closure for 'proc'.
1471 * Buffer for the output.
1476 * Task reading from pipe.
1478 GNUNET_SCHEDULER_TaskIdentifier rtask;
1483 struct GNUNET_TIME_Absolute timeout;
1486 * Current read offset in buf.
1493 * Stop/kill a command. Must ONLY be called either from
1494 * the callback after 'NULL' was passed for 'line' *OR*
1495 * from an independent task (not within the line processor).
1497 * @param cmd handle to the process
1500 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1503 if (cmd->proc != NULL)
1505 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1506 GNUNET_SCHEDULER_cancel (cmd->rtask);
1508 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1509 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1510 GNUNET_OS_process_close (cmd->eip);
1511 GNUNET_DISK_pipe_close (cmd->opipe);
1517 * Read from the process and call the line processor.
1519 * @param cls the 'struct GNUNET_OS_CommandHandle'
1520 * @param tc scheduler context
1523 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1525 struct GNUNET_OS_CommandHandle *cmd = cls;
1526 GNUNET_OS_LineProcessor proc;
1530 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1531 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1533 /* timeout, shutdown, etc. */
1536 proc (cmd->proc_cls, NULL);
1540 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1541 sizeof (cmd->buf) - cmd->off);
1544 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1546 cmd->buf[cmd->off] = '\0';
1547 cmd->proc (cmd->proc_cls, cmd->buf);
1551 proc (cmd->proc_cls, NULL);
1554 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1559 cmd->proc (cmd->proc_cls, cmd->buf);
1560 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1561 cmd->off -= (end + 1 - cmd->buf);
1562 end = memchr (cmd->buf, '\n', cmd->off);
1565 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1566 (cmd->timeout), cmd->r, &cmd_read, cmd);
1571 * Run the given command line and call the given function
1572 * for each line of the output.
1574 * @param proc function to call for each line of the output
1575 * @param proc_cls closure for proc
1576 * @param timeout when to time out
1577 * @param binary command to run
1578 * @param ... arguments to command
1579 * @return NULL on error
1581 struct GNUNET_OS_CommandHandle *
1582 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1583 struct GNUNET_TIME_Relative timeout, const char *binary,
1586 struct GNUNET_OS_CommandHandle *cmd;
1587 struct GNUNET_OS_Process *eip;
1588 struct GNUNET_DISK_PipeHandle *opipe;
1591 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1594 va_start (ap, binary);
1595 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1599 GNUNET_DISK_pipe_close (opipe);
1602 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1603 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1604 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1608 cmd->proc_cls = proc_cls;
1609 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1610 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1617 /* end of os_priority.c */