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 ChildWaitThread (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 va NULL-terminated list 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_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
542 struct GNUNET_DISK_PipeHandle *pipe_stdout,
543 const char *filename, va_list va)
547 #if ENABLE_WINDOWS_WORKAROUNDS
548 char *childpipename = NULL;
549 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
551 struct GNUNET_OS_Process *gnunet_proc = NULL;
562 #if ENABLE_WINDOWS_WORKAROUNDS
564 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
565 GNUNET_DISK_PERM_USER_READ |
566 GNUNET_DISK_PERM_USER_WRITE);
567 if (control_pipe == NULL)
573 while (NULL != va_arg (ap, char *))
577 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
580 while (NULL != (argv[argc] = va_arg (ap, char *)))
584 if (pipe_stdout != NULL)
586 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
588 GNUNET_DISK_PIPE_END_WRITE),
589 &fd_stdout_write, sizeof (int));
590 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
591 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
592 &fd_stdout_read, sizeof (int));
594 if (pipe_stdin != NULL)
596 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
597 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
598 &fd_stdin_read, sizeof (int));
599 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
600 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
601 &fd_stdin_write, sizeof (int));
609 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
610 #if ENABLE_WINDOWS_WORKAROUNDS
611 GNUNET_DISK_npipe_close (control_pipe);
616 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
617 gnunet_proc->pid = ret;
618 #if ENABLE_WINDOWS_WORKAROUNDS
619 gnunet_proc->control_pipe = control_pipe;
623 #if ENABLE_WINDOWS_WORKAROUNDS
624 GNUNET_free (childpipename);
629 #if ENABLE_WINDOWS_WORKAROUNDS
630 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
631 GNUNET_free (childpipename);
634 if (pipe_stdout != NULL)
636 GNUNET_break (0 == close (fd_stdout_read));
637 if (-1 == dup2 (fd_stdout_write, 1))
638 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
639 GNUNET_break (0 == close (fd_stdout_write));
642 if (pipe_stdin != NULL)
645 GNUNET_break (0 == close (fd_stdin_write));
646 if (-1 == dup2 (fd_stdin_read, 0))
647 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
648 GNUNET_break (0 == close (fd_stdin_read));
650 execvp (filename, argv);
651 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
658 PROCESS_INFORMATION proc;
661 HANDLE stdout_handle;
663 char path[MAX_PATH + 1];
665 char *our_env[3] = { NULL, NULL, NULL };
666 char *env_block = NULL;
668 DWORD pathbuf_len, alloc_len;
673 char *non_const_filename;
674 wchar_t wpath[MAX_PATH + 1], wcmd[32768];
676 /* Search in prefix dir (hopefully - the directory from which
677 * the current module was loaded), bindir and libdir, then in PATH
679 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
680 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
681 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
683 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
686 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
689 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
692 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
693 GNUNET_free (self_prefix);
694 GNUNET_free (bindir);
695 GNUNET_free (libdir);
697 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
698 GNUNET_assert (alloc_len == (pathbuf_len - 1));
700 cmdlen = strlen (filename);
701 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
702 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
704 GNUNET_asprintf (&non_const_filename, "%s", filename);
706 /* Check that this is the full path. If it isn't, search. */
707 if (non_const_filename[1] == ':')
708 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
709 else if (!SearchPathA
710 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
713 SetErrnoFromWinError (GetLastError ());
714 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
716 GNUNET_free (non_const_filename);
717 GNUNET_free (pathbuf);
720 GNUNET_free (pathbuf);
721 GNUNET_free (non_const_filename);
725 while (NULL != (arg = va_arg (ap, char *)))
728 cmdlen = cmdlen + strlen (path) + 3;
730 cmdlen = cmdlen + strlen (arg) + 3;
734 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
736 while (NULL != (arg = va_arg (ap, char *)))
739 idx += sprintf (idx, "\"%s\" ", path);
741 idx += sprintf (idx, "\"%s\" ", arg);
745 memset (&start, 0, sizeof (start));
746 start.cb = sizeof (start);
748 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
749 start.dwFlags |= STARTF_USESTDHANDLES;
751 if (pipe_stdin != NULL)
753 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
754 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
755 &stdin_handle, sizeof (HANDLE));
756 start.hStdInput = stdin_handle;
759 if (pipe_stdout != NULL)
761 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
763 GNUNET_DISK_PIPE_END_WRITE),
764 &stdout_handle, sizeof (HANDLE));
765 start.hStdOutput = stdout_handle;
769 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
770 GNUNET_DISK_PERM_USER_READ |
771 GNUNET_DISK_PERM_USER_WRITE);
772 if (control_pipe == NULL)
780 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
784 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
785 GNUNET_asprintf (&our_env[1], "%s", childpipename);
787 env_block = CreateCustomEnvTable (our_env);
788 GNUNET_free (our_env[0]);
789 GNUNET_free (our_env[1]);
791 if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath)
792 || ERROR_SUCCESS != plibc_conv_to_win_pathwconv(cmd, wcmd)
794 (wpath, wcmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
795 env_block, NULL, &start, &proc))
797 SetErrnoFromWinError (GetLastError ());
798 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
799 GNUNET_free (env_block);
804 GNUNET_free (env_block);
806 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
807 gnunet_proc->pid = proc.dwProcessId;
808 gnunet_proc->handle = proc.hProcess;
809 gnunet_proc->control_pipe = control_pipe;
811 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
813 ResumeThread (proc.hThread);
814 CloseHandle (proc.hThread);
826 * @param pipe_stdin pipe to use to send input to child process (or NULL)
827 * @param pipe_stdout pipe to use to get output from child process (or NULL)
828 * @param filename name of the binary
829 * @param ... NULL-terminated list of arguments to the process
831 * @return pointer to process structure of the new process, NULL on error
834 struct GNUNET_OS_Process *
835 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
836 struct GNUNET_DISK_PipeHandle *pipe_stdout,
837 const char *filename, ...)
839 struct GNUNET_OS_Process *ret;
842 va_start (ap, filename);
843 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
852 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
853 * must be NULL on platforms where dup is not supported
854 * @param filename name of the binary
855 * @param argv NULL-terminated list of arguments to the process
856 * @return process ID of the new process, -1 on error
858 struct GNUNET_OS_Process *
859 GNUNET_OS_start_process_v (const SOCKTYPE *lsocks,
860 const char *filename,
863 #if ENABLE_WINDOWS_WORKAROUNDS
864 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
865 char *childpipename = NULL;
872 struct GNUNET_OS_Process *gnunet_proc = NULL;
881 #if ENABLE_WINDOWS_WORKAROUNDS
883 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
884 GNUNET_DISK_PERM_USER_READ |
885 GNUNET_DISK_PERM_USER_WRITE);
886 if (control_pipe == NULL)
895 while (-1 != (k = lsocks[i++]))
896 GNUNET_array_append (lscp, ls, k);
897 GNUNET_array_append (lscp, ls, -1);
904 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
905 #if ENABLE_WINDOWS_WORKAROUNDS
906 GNUNET_DISK_npipe_close (control_pipe);
911 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
912 gnunet_proc->pid = ret;
913 #if ENABLE_WINDOWS_WORKAROUNDS
914 gnunet_proc->control_pipe = control_pipe;
918 GNUNET_array_grow (lscp, ls, 0);
919 #if ENABLE_WINDOWS_WORKAROUNDS
920 GNUNET_free (childpipename);
925 #if ENABLE_WINDOWS_WORKAROUNDS
926 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
927 GNUNET_free (childpipename);
932 /* read systemd documentation... */
933 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
934 setenv ("LISTEN_PID", lpid, 1);
937 while (-1 != lscp[i])
940 while (-1 != lscp[j])
946 GNUNET_assert (-1 != k);
947 GNUNET_assert (0 == close (lscp[j]));
955 /* Bury any existing FD, no matter what; they should all be closed
956 * on exec anyway and the important onces have been dup'ed away */
958 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
960 /* unset close-on-exec flag */
961 flags = fcntl (tgt, F_GETFD);
962 GNUNET_assert (flags >= 0);
963 flags &= ~FD_CLOEXEC;
965 (void) fcntl (tgt, F_SETFD, flags);
969 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
970 setenv ("LISTEN_FDS", fds, 1);
972 GNUNET_array_grow (lscp, ls, 0);
973 execvp (filename, argv);
974 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
977 char **arg, **non_const_argv;
981 PROCESS_INFORMATION proc;
983 struct GNUNET_OS_Process *gnunet_proc = NULL;
985 char path[MAX_PATH + 1];
987 char *our_env[5] = { NULL, NULL, NULL, NULL, NULL };
988 char *env_block = NULL;
990 DWORD pathbuf_len, alloc_len;
995 char *non_const_filename;
996 struct GNUNET_DISK_PipeHandle *lsocks_pipe;
997 const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
1000 wchar_t wpath[MAX_PATH + 1], wcmd[32768];
1004 /* Search in prefix dir (hopefully - the directory from which
1005 * the current module was loaded), bindir and libdir, then in PATH
1007 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1008 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1009 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1011 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1014 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1017 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1020 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1021 GNUNET_free (self_prefix);
1022 GNUNET_free (bindir);
1023 GNUNET_free (libdir);
1025 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1026 if (alloc_len != pathbuf_len - 1)
1028 GNUNET_free (pathbuf);
1029 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1033 cmdlen = strlen (filename);
1034 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1035 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1037 GNUNET_asprintf (&non_const_filename, "%s", filename);
1039 /* Check that this is the full path. If it isn't, search. */
1040 if (non_const_filename[1] == ':')
1041 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1042 else if (!SearchPathA
1043 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1046 SetErrnoFromWinError (GetLastError ());
1047 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1048 non_const_filename);
1049 GNUNET_free (non_const_filename);
1050 GNUNET_free (pathbuf);
1053 GNUNET_free (pathbuf);
1054 GNUNET_free (non_const_filename);
1056 /* Count the number of arguments */
1057 arg = (char **) argv;
1064 /* Allocate a copy argv */
1065 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1067 /* Copy all argv strings */
1069 arg = (char **) argv;
1073 non_const_argv[argcount] = GNUNET_strdup (path);
1075 non_const_argv[argcount] = GNUNET_strdup (*arg);
1079 non_const_argv[argcount] = NULL;
1083 arg = non_const_argv;
1086 cmdlen = cmdlen + strlen (*arg) + 3;
1090 /* Allocate and create cmd */
1091 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1092 arg = non_const_argv;
1095 idx += sprintf (idx, "\"%s\" ", *arg);
1099 while (argcount > 0)
1100 GNUNET_free (non_const_argv[--argcount]);
1101 GNUNET_free (non_const_argv);
1103 memset (&start, 0, sizeof (start));
1104 start.cb = sizeof (start);
1107 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1108 GNUNET_DISK_PERM_USER_READ |
1109 GNUNET_DISK_PERM_USER_WRITE);
1110 if (control_pipe == NULL)
1116 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1118 lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
1120 if (lsocks_pipe == NULL)
1124 GNUNET_DISK_pipe_close (lsocks_pipe);
1127 lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
1128 GNUNET_DISK_PIPE_END_WRITE);
1129 GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1130 &lsocks_write, sizeof (HANDLE));
1131 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1132 (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1133 &lsocks_read, sizeof (HANDLE));
1137 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1141 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1142 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1143 GNUNET_free (childpipename);
1144 if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1148 /*This will tell the child that we're going to send lsocks over the pipe*/
1149 GNUNET_asprintf (&our_env[2], "%s=", "GNUNET_OS_READ_LSOCKS");
1150 GNUNET_asprintf (&our_env[3], "%lu", lsocks_read);
1153 env_block = CreateCustomEnvTable (our_env);
1154 GNUNET_free_non_null (our_env[0]);
1155 GNUNET_free_non_null (our_env[1]);
1156 GNUNET_free_non_null (our_env[2]);
1157 GNUNET_free_non_null (our_env[3]);
1159 if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath)
1160 || ERROR_SUCCESS != plibc_conv_to_win_pathwconv(cmd, wcmd)
1162 (wpath, wcmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
1163 env_block, NULL, &start, &proc))
1165 SetErrnoFromWinError (GetLastError ());
1166 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1167 GNUNET_DISK_npipe_close (control_pipe);
1169 GNUNET_DISK_pipe_close (lsocks_pipe);
1170 GNUNET_free (env_block);
1175 GNUNET_free (env_block);
1177 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1178 gnunet_proc->pid = proc.dwProcessId;
1179 gnunet_proc->handle = proc.hProcess;
1180 gnunet_proc->control_pipe = control_pipe;
1182 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1184 ResumeThread (proc.hThread);
1185 CloseHandle (proc.hThread);
1188 if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1191 GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1193 /* This is a replacement for "goto error" that doesn't use goto */
1198 uint64_t size, count, i;
1200 /* Tell the number of sockets */
1201 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1203 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1204 if (wrote != sizeof (count))
1206 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u count bytes to the child: %u\n", sizeof (count), GetLastError ());
1209 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1211 WSAPROTOCOL_INFOA pi;
1212 /* Get a socket duplication info */
1213 if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1215 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to duplicate an socket[%llu]: %u\n", i, GetLastError ());
1216 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1219 /* Synchronous I/O is not nice, but we can't schedule this:
1220 * lsocks will be closed/freed by the caller soon, and until
1221 * the child creates a duplicate, closing a socket here will
1222 * close it for good.
1224 /* Send the size of the structure
1225 * (the child might be built with different headers...)
1228 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1229 if (wrote != sizeof (size))
1231 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u size[%llu] bytes to the child: %u\n", sizeof (size), i, GetLastError ());
1234 /* Finally! Send the data */
1235 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1236 if (wrote != sizeof (pi))
1238 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u socket[%llu] bytes to the child: %u\n", sizeof (pi), i, GetLastError ());
1242 /* This will block us until the child makes a final read or closes
1243 * the pipe (hence no 'wrote' check), since we have to wait for it
1244 * to duplicate the last socket, before we return and start closing
1247 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1252 GNUNET_DISK_file_sync (lsocks_write_fd);
1253 GNUNET_DISK_pipe_close (lsocks_pipe);
1257 /* If we can't pass on the socket(s), the child will block forever,
1258 * better put it out of its misery.
1260 TerminateProcess (gnunet_proc->handle, 0);
1261 CloseHandle (gnunet_proc->handle);
1262 GNUNET_DISK_npipe_close (gnunet_proc->control_pipe);
1263 GNUNET_free (gnunet_proc);
1273 * Retrieve the status of a process
1274 * @param proc process ID
1275 * @param type status type
1276 * @param code return code/signal number
1277 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1280 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1281 enum GNUNET_OS_ProcessStatusType *type,
1282 unsigned long *code)
1288 GNUNET_assert (0 != proc);
1289 ret = waitpid (proc->pid, &status, WNOHANG);
1292 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1293 return GNUNET_SYSERR;
1297 *type = GNUNET_OS_PROCESS_RUNNING;
1301 if (proc->pid != ret)
1303 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1304 return GNUNET_SYSERR;
1306 if (WIFEXITED (status))
1308 *type = GNUNET_OS_PROCESS_EXITED;
1309 *code = WEXITSTATUS (status);
1311 else if (WIFSIGNALED (status))
1313 *type = GNUNET_OS_PROCESS_SIGNALED;
1314 *code = WTERMSIG (status);
1316 else if (WIFSTOPPED (status))
1318 *type = GNUNET_OS_PROCESS_SIGNALED;
1319 *code = WSTOPSIG (status);
1322 else if (WIFCONTINUED (status))
1324 *type = GNUNET_OS_PROCESS_RUNNING;
1330 *type = GNUNET_OS_PROCESS_UNKNOWN;
1335 DWORD c, error_code, ret;
1339 if (h == NULL || ret == 0)
1341 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1343 return GNUNET_SYSERR;
1346 h = GetCurrentProcess ();
1349 ret = GetExitCodeProcess (h, &c);
1350 error_code = GetLastError ();
1351 if (ret == 0 || error_code != NO_ERROR)
1353 SetErrnoFromWinError (error_code);
1354 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1355 return GNUNET_SYSERR;
1357 if (STILL_ACTIVE == c)
1359 *type = GNUNET_OS_PROCESS_RUNNING;
1363 *type = GNUNET_OS_PROCESS_EXITED;
1372 * Wait for a process
1373 * @param proc pointer to process structure
1374 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1377 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1381 pid_t pid = proc->pid;
1383 if (pid != waitpid (pid, NULL, 0))
1384 return GNUNET_SYSERR;
1393 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1395 return GNUNET_SYSERR;
1398 h = GetCurrentProcess ();
1400 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1402 SetErrnoFromWinError (GetLastError ());
1403 ret = GNUNET_SYSERR;
1414 * Handle to a command.
1416 struct GNUNET_OS_CommandHandle
1422 struct GNUNET_OS_Process *eip;
1425 * Handle to the output pipe.
1427 struct GNUNET_DISK_PipeHandle *opipe;
1430 * Read-end of output pipe.
1432 const struct GNUNET_DISK_FileHandle *r;
1435 * Function to call on each line of output.
1437 GNUNET_OS_LineProcessor proc;
1440 * Closure for 'proc'.
1445 * Buffer for the output.
1450 * Task reading from pipe.
1452 GNUNET_SCHEDULER_TaskIdentifier rtask;
1457 struct GNUNET_TIME_Absolute timeout;
1460 * Current read offset in buf.
1467 * Stop/kill a command. Must ONLY be called either from
1468 * the callback after 'NULL' was passed for 'line' *OR*
1469 * from an independent task (not within the line processor).
1471 * @param cmd handle to the process
1474 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1477 if (cmd->proc != NULL)
1479 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1480 GNUNET_SCHEDULER_cancel (cmd->rtask);
1482 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1483 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1484 GNUNET_OS_process_close (cmd->eip);
1485 GNUNET_DISK_pipe_close (cmd->opipe);
1491 * Read from the process and call the line processor.
1493 * @param cls the 'struct GNUNET_OS_CommandHandle'
1494 * @param tc scheduler context
1497 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1499 struct GNUNET_OS_CommandHandle *cmd = cls;
1500 GNUNET_OS_LineProcessor proc;
1504 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1505 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1507 /* timeout, shutdown, etc. */
1510 proc (cmd->proc_cls, NULL);
1514 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1515 sizeof (cmd->buf) - cmd->off);
1518 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1520 cmd->buf[cmd->off] = '\0';
1521 cmd->proc (cmd->proc_cls, cmd->buf);
1525 proc (cmd->proc_cls, NULL);
1528 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1533 cmd->proc (cmd->proc_cls, cmd->buf);
1534 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1535 cmd->off -= (end + 1 - cmd->buf);
1536 end = memchr (cmd->buf, '\n', cmd->off);
1539 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1540 (cmd->timeout), cmd->r, &cmd_read, cmd);
1545 * Run the given command line and call the given function
1546 * for each line of the output.
1548 * @param proc function to call for each line of the output
1549 * @param proc_cls closure for proc
1550 * @param timeout when to time out
1551 * @param binary command to run
1552 * @param ... arguments to command
1553 * @return NULL on error
1555 struct GNUNET_OS_CommandHandle *
1556 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1557 struct GNUNET_TIME_Relative timeout, const char *binary,
1560 struct GNUNET_OS_CommandHandle *cmd;
1561 struct GNUNET_OS_Process *eip;
1562 struct GNUNET_DISK_PipeHandle *opipe;
1565 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1568 va_start (ap, binary);
1569 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1573 GNUNET_DISK_pipe_close (opipe);
1576 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1577 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1578 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1582 cmd->proc_cls = proc_cls;
1583 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1584 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1591 /* end of os_priority.c */