e24d9fb7362930ba287e1b39b8de755e098aa632
[oweals/gnunet.git] / src / util / os_priority.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2011 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19 */
20
21 /**
22  * @file util/os_priority.c
23  * @brief Methods to set process priority
24  * @author Nils Durner
25  */
26
27 #include "platform.h"
28 #include "gnunet_common.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_scheduler_lib.h"
31 #include "gnunet_strings_lib.h"
32 #include "gnunet_crypto_lib.h"
33 #include "disk.h"
34 #include <unistr.h>
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
37
38 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
39
40 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
41
42 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
43
44
45 struct GNUNET_OS_Process
46 {
47   /**
48    * PID of the process.
49    */
50   pid_t pid;
51
52 #if WINDOWS
53   /**
54    * Process handle.
55    */
56   HANDLE handle;
57 #endif
58
59   /**
60    * Pipe we use to signal the process.
61    * NULL if unused, or if process was deemed uncontrollable.
62    */
63   struct GNUNET_DISK_FileHandle *control_pipe;
64 };
65
66
67 /**
68  * Handle for 'this' process.
69  */
70 static struct GNUNET_OS_Process current_process;
71
72
73 /**
74  * This handler is called when there are control data to be read on the pipe
75  *
76  * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
77  * @param tc scheduler context
78  */
79 static void
80 parent_control_handler (void *cls,
81                         const struct GNUNET_SCHEDULER_TaskContext *tc)
82 {
83   struct GNUNET_DISK_FileHandle *control_pipe = cls;
84   char sig;
85   char *pipe_fd;
86   ssize_t ret;
87   
88   LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
89        tc->reason);
90   if (0 != (tc->reason &
91             (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT)))
92   {
93     GNUNET_DISK_file_close (control_pipe);
94     control_pipe = NULL;
95     return;
96   }
97   ret = GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig));
98   if (sizeof (sig) != ret)
99   {
100     if (-1 == ret)
101       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
102     LOG (GNUNET_ERROR_TYPE_WARNING, "Closing control pipe\n");
103     GNUNET_DISK_file_close (control_pipe);
104     control_pipe = NULL;
105     return;
106   }
107   pipe_fd = getenv (GNUNET_OS_CONTROL_PIPE);
108   GNUNET_assert ( (NULL == pipe_fd) || (strlen (pipe_fd) <= 0) );
109   LOG (GNUNET_ERROR_TYPE_DEBUG,
110        "Got control code %d from parent via pipe %s\n", sig, pipe_fd);
111   GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
112                                   control_pipe, &parent_control_handler,
113                                   control_pipe);
114   raise ((int) sig);
115 }
116
117
118 /**
119  * Task that connects this process to its parent via pipe;
120  * essentially, the parent control handler will read signal numbers
121  * from the 'GNUNET_OS_CONTROL_PIPE' (as given in an environment
122  * variable) and raise those signals.
123  *
124  * @param cls closure (unused)
125  * @param tc scheduler context (unused)
126  */
127 void
128 GNUNET_OS_install_parent_control_handler (void *cls,
129                                           const struct
130                                           GNUNET_SCHEDULER_TaskContext *tc)
131 {
132   const char *env_buf;
133   char *env_buf_end;
134   struct GNUNET_DISK_FileHandle *control_pipe;
135   uint64_t pipe_fd;
136
137   env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
138   if ( (NULL == env_buf) || (strlen (env_buf) <= 0) )
139   {
140     LOG (GNUNET_ERROR_TYPE_DEBUG,
141          "Not installing a handler because $%s is empty\n",
142          GNUNET_OS_CONTROL_PIPE);
143     putenv (GNUNET_OS_CONTROL_PIPE "=");
144     return;
145   }
146   errno = 0;
147   pipe_fd = strtoull (env_buf, &env_buf_end, 16);
148   if ((0 != errno) || (env_buf == env_buf_end))
149   {
150     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "strtoull", env_buf);
151     putenv (GNUNET_OS_CONTROL_PIPE "=");
152     return;
153   }
154 #if !defined (WINDOWS)
155   if (pipe_fd >= FD_SETSIZE)
156 #else
157   if ((FILE_TYPE_UNKNOWN == GetFileType ((HANDLE) pipe_fd))
158       && (0 != GetLastError ()))
159 #endif
160   {
161     LOG (GNUNET_ERROR_TYPE_ERROR,
162          "GNUNET_OS_CONTROL_PIPE `%s' contains garbage?\n", env_buf);
163     putenv (GNUNET_OS_CONTROL_PIPE "=");
164     return;
165   }
166   /* Gcc will issue a warning here. What to do with it? */
167 #if WINDOWS
168   control_pipe = GNUNET_DISK_get_handle_from_w32_handle ((HANDLE) pipe_fd);
169 #else
170   control_pipe = GNUNET_DISK_get_handle_from_int_fd ((int) pipe_fd);
171 #endif
172   if (NULL == control_pipe)
173   {
174     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
175     putenv (GNUNET_OS_CONTROL_PIPE "=");
176     return;
177   }
178   LOG (GNUNET_ERROR_TYPE_DEBUG,
179        "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
180   GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
181                                   &parent_control_handler, control_pipe);
182   putenv (GNUNET_OS_CONTROL_PIPE "=");
183 }
184
185
186 /**
187  * Get process structure for current process
188  *
189  * The pointer it returns points to static memory location and must not be
190  * deallocated/closed
191  *
192  * @return pointer to the process sturcutre for this process
193  */
194 struct GNUNET_OS_Process *
195 GNUNET_OS_process_current ()
196 {
197 #if WINDOWS
198   current_process.pid = GetCurrentProcessId ();
199   current_process.handle = GetCurrentProcess ();
200 #else
201   current_process.pid = 0;
202 #endif
203   return &current_process;
204 }
205
206
207 /**
208  * Sends a signal to the process
209  *
210  * @param proc pointer to process structure
211  * @param sig signal
212  * @return 0 on success, -1 on error
213  */
214 int
215 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
216 {
217   int ret;
218   char csig;
219
220   csig = (char) sig;
221   if (NULL != proc->control_pipe)
222   {
223     LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending signal %d to pid: %u via pipe\n", sig, proc->pid);
224     ret = GNUNET_DISK_file_write (proc->control_pipe, &csig, sizeof (csig));
225     if (sizeof (csig) == ret)
226       return 0;
227   }
228   /* pipe failed or non-existent, try other methods */
229   switch (sig)
230   {
231 #if !defined (WINDOWS)
232   case SIGHUP:
233 #endif
234   case SIGINT:
235   case SIGKILL:
236   case SIGTERM:
237 #if defined(WINDOWS) && !defined(__CYGWIN__)
238     {
239       DWORD exitcode;
240       int must_kill = GNUNET_YES;
241       if (0 != GetExitCodeProcess (proc->handle, &exitcode))
242         must_kill = (exitcode == STILL_ACTIVE) ? GNUNET_YES : GNUNET_NO;
243       if (GNUNET_YES == must_kill)
244         if (0 == SafeTerminateProcess (proc->handle, 0, 0))
245         {
246           DWORD error_code = GetLastError ();
247           if ((error_code != WAIT_TIMEOUT) && (error_code != ERROR_PROCESS_ABORTED))
248           {
249             LOG ((error_code == ERROR_ACCESS_DENIED) ?
250                 GNUNET_ERROR_TYPE_INFO : GNUNET_ERROR_TYPE_WARNING,
251                 "SafeTermiateProcess failed with code %lu\n", error_code);
252             /* The problem here is that a process that is already dying
253              * might cause SafeTerminateProcess to fail with
254              * ERROR_ACCESS_DENIED, but the process WILL die eventually.
255              * If we really had a permissions problem, hanging up (which
256              * is what will happen in process_wait() in that case) is
257              * a valid option.
258              */
259             if (ERROR_ACCESS_DENIED == error_code)
260             {
261               errno = 0;
262             }
263             else
264             {
265               SetErrnoFromWinError (error_code);
266               return -1;
267             }
268           }
269         }
270     }
271     return 0;
272 #else
273     LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending signal %d to pid: %u via system call\n", sig, proc->pid);
274     return PLIBC_KILL (proc->pid, sig);
275 #endif
276   default:
277 #if defined (WINDOWS)
278     errno = EINVAL;
279     return -1;
280 #else
281     LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending signal %d to pid: %u via system call\n", sig, proc->pid);
282     return PLIBC_KILL (proc->pid, sig);
283 #endif    
284   }
285 }
286
287 /**
288  * Get the pid of the process in question
289  *
290  * @param proc the process to get the pid of
291  *
292  * @return the current process id
293  */
294 pid_t
295 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
296 {
297   return proc->pid;
298 }
299
300
301 /**
302  * Cleans up process structure contents (OS-dependent) and deallocates it
303  *
304  * @param proc pointer to process structure
305  */
306 void
307 GNUNET_OS_process_destroy (struct GNUNET_OS_Process *proc)
308 {
309   if (NULL != proc->control_pipe)
310     GNUNET_DISK_file_close (proc->control_pipe);
311 #if defined (WINDOWS)
312   if (proc->handle != NULL)
313     CloseHandle (proc->handle);
314 #endif
315   GNUNET_free (proc);
316 }
317
318 #if WINDOWS
319 #include "gnunet_signal_lib.h"
320
321 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
322
323 /**
324  * Make seaspider happy.
325  */
326 #define DWORD_WINAPI DWORD WINAPI
327
328 /**
329  * @brief Waits for a process to terminate and invokes the SIGCHLD handler
330  * @param proc pointer to process structure
331  */
332 static DWORD_WINAPI
333 child_wait_thread (void *arg)
334 {
335   struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
336
337   WaitForSingleObject (proc->handle, INFINITE);
338
339   if (w32_sigchld_handler)
340     w32_sigchld_handler ();
341
342   return 0;
343 }
344 #endif
345
346
347 /**
348  * Set process priority
349  *
350  * @param proc pointer to process structure
351  * @param prio priority value
352  * @return GNUNET_OK on success, GNUNET_SYSERR on error
353  */
354 int
355 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
356                                 enum GNUNET_SCHEDULER_Priority prio)
357 {
358   int rprio;
359
360   GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
361   if (GNUNET_SCHEDULER_PRIORITY_KEEP == prio)
362     return GNUNET_OK;
363
364   /* convert to MINGW/Unix values */
365   switch (prio)
366   {
367   case GNUNET_SCHEDULER_PRIORITY_UI:
368   case GNUNET_SCHEDULER_PRIORITY_URGENT:
369 #ifdef MINGW
370     rprio = HIGH_PRIORITY_CLASS;
371 #else
372     rprio = 0;
373 #endif
374     break;
375
376   case GNUNET_SCHEDULER_PRIORITY_HIGH:
377 #ifdef MINGW
378     rprio = ABOVE_NORMAL_PRIORITY_CLASS;
379 #else
380     rprio = 5;
381 #endif
382     break;
383
384   case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
385 #ifdef MINGW
386     rprio = NORMAL_PRIORITY_CLASS;
387 #else
388     rprio = 7;
389 #endif
390     break;
391
392   case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
393 #ifdef MINGW
394     rprio = BELOW_NORMAL_PRIORITY_CLASS;
395 #else
396     rprio = 10;
397 #endif
398     break;
399
400   case GNUNET_SCHEDULER_PRIORITY_IDLE:
401 #ifdef MINGW
402     rprio = IDLE_PRIORITY_CLASS;
403 #else
404     rprio = 19;
405 #endif
406     break;
407   default:
408     GNUNET_assert (0);
409     return GNUNET_SYSERR;
410   }
411
412   /* Set process priority */
413 #ifdef MINGW
414   {
415     HANDLE h = proc->handle;
416
417     GNUNET_assert (h != NULL);
418     SetPriorityClass (h, rprio);
419   }
420 #elif LINUX
421   pid_t pid;
422
423   pid = proc->pid;
424   if ((0 == pid) || (pid == getpid ()))
425   {
426     int have = nice (0);
427     int delta = rprio - have;
428
429     errno = 0;
430     if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
431     {
432       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
433       return GNUNET_SYSERR;
434     }
435   }
436   else
437   {
438     if (0 != setpriority (PRIO_PROCESS, pid, rprio))
439     {
440       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
441                     "setpriority");
442       return GNUNET_SYSERR;
443     }
444   }
445 #else
446   LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
447        "Priority management not availabe for this platform\n");
448 #endif
449   return GNUNET_OK;
450 }
451
452
453 #if MINGW
454 static char *
455 CreateCustomEnvTable (char **vars)
456 {
457   char *win32_env_table;
458   char *ptr;
459   char **var_ptr;
460   char *result;
461   char *result_ptr;
462   size_t tablesize = 0;
463   size_t items_count = 0;
464   size_t n_found = 0;
465   size_t n_var;
466   char *index = NULL;
467   size_t c;
468   size_t var_len;
469   char *var;
470   char *val;
471
472   win32_env_table = GetEnvironmentStringsA ();
473   if (NULL == win32_env_table)
474     return NULL;
475   for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
476   n_var = c;
477   index = GNUNET_malloc (sizeof (char *) * n_var);
478   for (c = 0; c < n_var; c++)
479     index[c] = 0;
480   for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
481   {
482     size_t len = strlen (ptr);
483     int found = 0;
484
485     for (var_ptr = vars; *var_ptr; var_ptr++)
486     {
487       var = *var_ptr++;
488       val = *var_ptr;
489       var_len = strlen (var);
490       if (strncmp (var, ptr, var_len) == 0)
491       {
492         found = 1;
493         index[c] = 1;
494         tablesize += var_len + strlen (val) + 1;
495         break;
496       }
497     }
498     if (!found)
499       tablesize += len + 1;
500     ptr += len + 1;
501   }
502   for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
503   {
504     var = *var_ptr++;
505     val = *var_ptr;
506     if (index[c] != 1)
507       n_found += strlen (var) + strlen (val) + 1;
508   }
509   result = GNUNET_malloc (tablesize + n_found + 1);
510   for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
511   {
512     size_t len = strlen (ptr);
513     int found = 0;
514
515     for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
516     {
517       var = *var_ptr++;
518       val = *var_ptr;
519       var_len = strlen (var);
520       if (strncmp (var, ptr, var_len) == 0)
521       {
522         found = 1;
523         break;
524       }
525     }
526     if (!found)
527     {
528       strcpy (result_ptr, ptr);
529       result_ptr += len + 1;
530     }
531     else
532     {
533       strcpy (result_ptr, var);
534       result_ptr += var_len;
535       strcpy (result_ptr, val);
536       result_ptr += strlen (val) + 1;
537     }
538     ptr += len + 1;
539   }
540   for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
541   {
542     var = *var_ptr++;
543     val = *var_ptr;
544     var_len = strlen (var);
545     if (index[c] != 1)
546     {
547       strcpy (result_ptr, var);
548       result_ptr += var_len;
549       strcpy (result_ptr, val);
550       result_ptr += strlen (val) + 1;
551     }
552   }
553   FreeEnvironmentStrings (win32_env_table);
554   GNUNET_free (index);
555   *result_ptr = 0;
556   return result;
557 }
558
559 #else
560
561 /**
562  * Open '/dev/null' and make the result the given
563  * file descriptor.
564  *
565  * @param target_fd desired FD to point to /dev/null
566  * @param flags open flags (O_RDONLY, O_WRONLY)
567  */
568 static void
569 open_dev_null (int target_fd,
570                int flags)
571 {
572   int fd;
573
574   fd = open ("/dev/null", flags);
575   if (-1 == fd)
576   {
577     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", "/dev/null");
578     return;
579   }
580   if (fd == target_fd)
581     return;
582   if (-1 == dup2 (fd, target_fd))
583   {
584     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
585     (void) close (fd);
586     return;
587   }
588   GNUNET_break (0 == close (fd));
589 }
590 #endif
591
592
593 /**
594  * Start a process.
595  *
596  * @param pipe_control should a pipe be used to send signals to the child?
597  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
598  *        std handles of the parent are inherited by the child.
599  *        pipe_stdin and pipe_stdout take priority over std_inheritance
600  *        (when they are non-NULL).
601  * @param pipe_stdin pipe to use to send input to child process (or NULL)
602  * @param pipe_stdout pipe to use to get output from child process (or NULL)
603  * @param lsocks array of listen sockets to dup systemd-style (or NULL);
604  *         must be NULL on platforms where dup is not supported
605  * @param filename name of the binary
606  * @param argv NULL-terminated list of arguments to the process
607  * @return process ID of the new process, -1 on error
608  */
609 static struct GNUNET_OS_Process *
610 start_process (int pipe_control,
611                enum GNUNET_OS_InheritStdioFlags std_inheritance,
612                struct GNUNET_DISK_PipeHandle *pipe_stdin,
613                struct GNUNET_DISK_PipeHandle *pipe_stdout,
614                const SOCKTYPE *lsocks,
615                const char *filename,
616                char *const argv[])
617 {
618 #ifndef MINGW
619   pid_t ret;
620   char lpid[16];
621   char fds[16];
622   struct GNUNET_OS_Process *gnunet_proc;
623   struct GNUNET_DISK_FileHandle *childpipe_read;
624   struct GNUNET_DISK_FileHandle *childpipe_write;
625   int childpipe_read_fd;
626   int i;
627   int j;
628   int k;
629   int tgt;
630   int flags;
631   int *lscp;
632   unsigned int ls;
633   int fd_stdout_write;
634   int fd_stdout_read;
635   int fd_stdin_read;
636   int fd_stdin_write;
637
638   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename))
639     return NULL; /* not executable */
640   if (GNUNET_YES == pipe_control)
641   {
642     struct GNUNET_DISK_PipeHandle *childpipe;
643     int dup_childpipe_read_fd = -1;
644     childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
645     if (NULL == childpipe)
646       return NULL;
647     childpipe_read = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ);
648     childpipe_write = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE);
649     GNUNET_DISK_pipe_close (childpipe);
650     if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
651         (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read,
652         &childpipe_read_fd, sizeof (int))) ||
653         (-1 == (dup_childpipe_read_fd = dup (childpipe_read_fd))))
654     {
655       if (childpipe_read)
656         GNUNET_DISK_file_close (childpipe_read);
657       if (childpipe_write)
658         GNUNET_DISK_file_close (childpipe_write);
659       if (0 <= dup_childpipe_read_fd)
660         close (dup_childpipe_read_fd);
661       return NULL;
662     }
663     childpipe_read_fd = dup_childpipe_read_fd;
664     GNUNET_DISK_file_close (childpipe_read);
665   }
666   else
667   {
668     childpipe_read = NULL;
669     childpipe_write = NULL;
670     childpipe_read_fd = -1;
671   }
672   if (NULL != pipe_stdout)
673   {
674     GNUNET_assert (GNUNET_OK ==
675                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
676                                                       (pipe_stdout,
677                                                        GNUNET_DISK_PIPE_END_WRITE),
678                                                       &fd_stdout_write, sizeof (int)));
679     GNUNET_assert (GNUNET_OK ==
680                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
681                                                       (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
682                                                       &fd_stdout_read, sizeof (int)));
683   }
684   if (NULL != pipe_stdin)
685   {
686     GNUNET_assert (GNUNET_OK ==
687                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
688                                                       (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
689                                                       &fd_stdin_read, sizeof (int)));
690     GNUNET_assert (GNUNET_OK ==
691                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
692                                                       (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
693                                                       &fd_stdin_write, sizeof (int)));
694   }
695   lscp = NULL;
696   ls = 0;
697   if (NULL != lsocks)
698   {
699     i = 0;
700     while (-1 != (k = lsocks[i++]))
701       GNUNET_array_append (lscp, ls, k);
702     GNUNET_array_append (lscp, ls, -1);
703   }
704 #if DARWIN
705   /* see https://gnunet.org/vfork */
706   ret = vfork ();
707 #else
708   ret = fork ();
709 #endif
710   if (-1 == ret)
711   {
712     int eno = errno;
713     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
714     GNUNET_array_grow (lscp, ls, 0);
715     if (childpipe_read)
716       GNUNET_DISK_file_close (childpipe_read);
717     if (childpipe_write)
718       GNUNET_DISK_file_close (childpipe_write);
719     if (0 <= childpipe_read_fd)
720       close (childpipe_read_fd);
721     errno = eno;
722     return NULL;
723   }
724   if (0 != ret)
725   {
726     gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
727     gnunet_proc->pid = ret;
728     gnunet_proc->control_pipe = childpipe_write;
729     if (GNUNET_YES == pipe_control)
730     {
731       close (childpipe_read_fd);
732     }
733     GNUNET_array_grow (lscp, ls, 0);
734     return gnunet_proc;
735   }
736   if (0 <= childpipe_read_fd)
737   {
738     char fdbuf[100];
739 #ifndef DARWIN
740     /* due to vfork, we must NOT free memory on DARWIN! */
741     GNUNET_DISK_file_close (childpipe_write);
742 #endif
743     snprintf (fdbuf, 100, "%x", childpipe_read_fd);
744     setenv (GNUNET_OS_CONTROL_PIPE, fdbuf, 1);
745   }
746   else
747     unsetenv (GNUNET_OS_CONTROL_PIPE);
748   if (NULL != pipe_stdin)
749   {
750     GNUNET_break (0 == close (fd_stdin_write));
751     if (-1 == dup2 (fd_stdin_read, 0))
752       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
753     GNUNET_break (0 == close (fd_stdin_read));
754   }
755   else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_IN))
756   {
757     GNUNET_break (0 == close (0));
758     open_dev_null (0, O_RDONLY);
759   }
760   if (NULL != pipe_stdout)
761   {
762     GNUNET_break (0 == close (fd_stdout_read));
763     if (-1 == dup2 (fd_stdout_write, 1))
764       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
765     GNUNET_break (0 == close (fd_stdout_write));
766   }
767   else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_OUT))
768   {
769     GNUNET_break (0 == close (1));
770     open_dev_null (1, O_WRONLY);
771   }
772   if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_ERR))
773   {
774     GNUNET_break (0 == close (2));
775     open_dev_null (2, O_WRONLY);
776   }
777   if (NULL != lscp)
778   {
779     /* read systemd documentation... */
780     GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
781     setenv ("LISTEN_PID", lpid, 1);
782     i = 0;
783     tgt = 3;
784     while (-1 != lscp[i])
785     {
786       j = i + 1;
787       while (-1 != lscp[j])
788       {
789         if (lscp[j] == tgt)
790         {
791           /* dup away */
792           k = dup (lscp[j]);
793           GNUNET_assert (-1 != k);
794           GNUNET_assert (0 == close (lscp[j]));
795           lscp[j] = k;
796           break;
797         }
798         j++;
799       }
800       if (lscp[i] != tgt)
801       {
802         /* Bury any existing FD, no matter what; they should all be closed
803          * on exec anyway and the important onces have been dup'ed away */
804         (void) close (tgt);
805         GNUNET_assert (-1 != dup2 (lscp[i], tgt));
806       }
807       /* unset close-on-exec flag */
808       flags = fcntl (tgt, F_GETFD);
809       GNUNET_assert (flags >= 0);
810       flags &= ~FD_CLOEXEC;
811       fflush (stderr);
812       (void) fcntl (tgt, F_SETFD, flags);
813       tgt++;
814       i++;
815     }
816     GNUNET_snprintf (fds, sizeof (fds), "%u", i);
817     setenv ("LISTEN_FDS", fds, 1);
818   }
819 #ifndef DARWIN
820   /* due to vfork, we must NOT free memory on DARWIN! */
821   GNUNET_array_grow (lscp, ls, 0);
822 #endif
823   execvp (filename, argv);
824   LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
825   _exit (1);
826 #else
827   struct GNUNET_DISK_FileHandle *childpipe_read;
828   struct GNUNET_DISK_FileHandle *childpipe_write;
829   HANDLE childpipe_read_handle;
830   char **arg;
831   char **non_const_argv;
832   unsigned int cmdlen;
833   char *cmd;
834   char *idx;
835   STARTUPINFOW start;
836   PROCESS_INFORMATION proc;
837   int argcount = 0;
838   struct GNUNET_OS_Process *gnunet_proc;
839   char path[MAX_PATH + 1];
840   char *our_env[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };
841   char *env_block = NULL;
842   char *pathbuf;
843   DWORD pathbuf_len;
844   DWORD alloc_len;
845   char *self_prefix;
846   char *bindir;
847   char *libdir;
848   char *ptr;
849   char *non_const_filename;
850   char win_path[MAX_PATH + 1];
851   struct GNUNET_DISK_PipeHandle *lsocks_pipe;
852   const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
853   HANDLE lsocks_read;
854   HANDLE lsocks_write;
855   wchar_t *wpath;
856   wchar_t *wcmd;
857   size_t wpath_len;
858   size_t wcmd_len;
859   int env_off;
860   int fail;
861   long lRet;
862   HANDLE stdin_handle;
863   HANDLE stdout_handle;
864   HANDLE stdih, stdoh, stdeh;
865   DWORD stdif, stdof, stdef;
866   BOOL bresult;
867   DWORD error_code;
868
869   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename))
870     return NULL; /* not executable */
871  
872   /* Search in prefix dir (hopefully - the directory from which
873    * the current module was loaded), bindir and libdir, then in PATH
874    */
875   self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
876   bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
877   libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
878
879   pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
880
881   alloc_len =
882       pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
883       strlen (libdir);
884
885   pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
886
887   ptr = pathbuf;
888   ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
889   GNUNET_free (self_prefix);
890   GNUNET_free (bindir);
891   GNUNET_free (libdir);
892
893   alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
894   if (alloc_len != pathbuf_len - 1)
895   {
896     GNUNET_free (pathbuf);
897     errno = ENOSYS;             /* PATH changed on the fly. What kind of error is that? */
898     return NULL;
899   }
900
901   cmdlen = strlen (filename);
902   if ( (cmdlen < 5) || (0 != strcmp (&filename[cmdlen - 4], ".exe")) )
903     GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
904   else
905     GNUNET_asprintf (&non_const_filename, "%s", filename);
906
907   /* It could be in POSIX form, convert it to a DOS path early on */
908   if (ERROR_SUCCESS != (lRet = plibc_conv_to_win_path (non_const_filename, win_path)))
909   {
910     SetErrnoFromWinError (lRet);
911     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "plibc_conv_to_win_path",
912                        non_const_filename);
913     GNUNET_free (non_const_filename);
914     GNUNET_free (pathbuf);
915     return NULL;
916   }
917   GNUNET_free (non_const_filename);
918   non_const_filename = GNUNET_strdup (win_path);
919    /* Check that this is the full path. If it isn't, search. */
920   /* FIXME: convert it to wchar_t and use SearchPathW?
921    * Remember: arguments to _start_process() are technically in UTF-8...
922    */
923   if (non_const_filename[1] == ':')
924   {
925     snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
926     LOG (GNUNET_ERROR_TYPE_DEBUG,
927         "Using path `%s' as-is. PATH is %s\n", path, ptr);
928   }
929   else if (!SearchPathA
930            (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
931             path, NULL))
932   {
933     SetErrnoFromWinError (GetLastError ());
934     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
935                        non_const_filename);
936     GNUNET_free (non_const_filename);
937     GNUNET_free (pathbuf);
938     return NULL;
939   }
940   else
941     LOG (GNUNET_ERROR_TYPE_DEBUG,
942         "Found `%s' in PATH `%s'\n", path, pathbuf);
943   GNUNET_free (pathbuf);
944   GNUNET_free (non_const_filename);
945
946   /* Count the number of arguments */
947   arg = (char **) argv;
948   while (*arg)
949   {
950     arg++;
951     argcount++;
952   }
953
954   /* Allocate a copy argv */
955   non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
956
957   /* Copy all argv strings */
958   argcount = 0;
959   arg = (char **) argv;
960   while (*arg)
961   {
962     if (arg == argv)
963       non_const_argv[argcount] = GNUNET_strdup (path);
964     else
965       non_const_argv[argcount] = GNUNET_strdup (*arg);
966     arg++;
967     argcount++;
968   }
969   non_const_argv[argcount] = NULL;
970
971   /* Count cmd len */
972   cmdlen = 1;
973   arg = non_const_argv;
974   while (*arg)
975   {
976     cmdlen = cmdlen + strlen (*arg) + 4;
977     arg++;
978   }
979
980   /* Allocate and create cmd */
981   cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
982   arg = non_const_argv;
983   while (*arg)
984   {
985     char arg_last_char = (*arg)[strlen (*arg) - 1];
986     idx += sprintf (idx, "\"%s%s\"%s", *arg,
987         arg_last_char == '\\' ? "\\" : "", *(arg + 1) ? " " : "");
988     arg++;
989   }
990
991   while (argcount > 0)
992     GNUNET_free (non_const_argv[--argcount]);
993   GNUNET_free (non_const_argv);
994
995   memset (&start, 0, sizeof (start));
996   start.cb = sizeof (start);
997   if ((pipe_stdin != NULL) || (pipe_stdout != NULL) || (std_inheritance != 0))
998     start.dwFlags |= STARTF_USESTDHANDLES;
999
1000   stdih = GetStdHandle (STD_INPUT_HANDLE);
1001   GetHandleInformation (stdih, &stdif);
1002   if (pipe_stdin != NULL)
1003   {
1004     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1005                                        (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
1006                                        &stdin_handle, sizeof (HANDLE));
1007     start.hStdInput = stdin_handle;
1008   }
1009   else if (stdih)
1010   {
1011     if (std_inheritance & GNUNET_OS_INHERIT_STD_IN)
1012     {
1013       SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 1);
1014       if (pipe_stdin == NULL)
1015         start.hStdInput = stdih;
1016     }
1017     else
1018       SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 0);
1019   }
1020     
1021
1022   stdoh = GetStdHandle (STD_OUTPUT_HANDLE);
1023   GetHandleInformation (stdoh, &stdof);
1024   if (NULL != pipe_stdout)
1025   {
1026     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1027                                        (pipe_stdout,
1028                                         GNUNET_DISK_PIPE_END_WRITE),
1029                                        &stdout_handle, sizeof (HANDLE));
1030     start.hStdOutput = stdout_handle;
1031   }
1032   else if (stdoh)
1033   {
1034     if (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)
1035     {
1036       SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 1);
1037       if (pipe_stdout == NULL)
1038         start.hStdOutput = stdoh;
1039     }
1040     else
1041       SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 0);
1042   }
1043
1044   stdeh = GetStdHandle (STD_ERROR_HANDLE);
1045   GetHandleInformation (stdeh, &stdef);
1046   if (stdeh)
1047   {
1048     if (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)
1049     {
1050       SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 1);
1051       start.hStdError = stdeh;
1052     }
1053     else
1054       SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 0);
1055   }
1056
1057   if (GNUNET_YES == pipe_control)
1058   {
1059     struct GNUNET_DISK_PipeHandle *childpipe;
1060     childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
1061     if (NULL == childpipe)
1062       return NULL;
1063     childpipe_read = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ);
1064     childpipe_write = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE);
1065     GNUNET_DISK_pipe_close (childpipe);
1066     if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
1067         (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read,
1068         &childpipe_read_handle, sizeof (HANDLE))))
1069     {
1070       if (childpipe_read)
1071         GNUNET_DISK_file_close (childpipe_read);
1072       if (childpipe_write)
1073         GNUNET_DISK_file_close (childpipe_write);
1074       GNUNET_free (cmd);
1075       return NULL;
1076     }
1077     /* Unlike *nix variant, we don't dup the handle, so can't close
1078      * filehandle right now.
1079      */
1080     SetHandleInformation (childpipe_read_handle, HANDLE_FLAG_INHERIT, 1);
1081   }
1082   else
1083   {
1084     childpipe_read = NULL;
1085     childpipe_write = NULL;
1086   }
1087
1088   if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1089   {
1090     lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
1091
1092     if (lsocks_pipe == NULL)
1093     {
1094       GNUNET_free (cmd);
1095       GNUNET_DISK_pipe_close (lsocks_pipe);
1096       if (GNUNET_YES == pipe_control)
1097       {
1098         GNUNET_DISK_file_close (childpipe_write);
1099         GNUNET_DISK_file_close (childpipe_read);
1100       }
1101       return NULL;
1102     }
1103     lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
1104         GNUNET_DISK_PIPE_END_WRITE);
1105     GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1106                                        &lsocks_write, sizeof (HANDLE));
1107     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1108                                        (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1109                                        &lsocks_read, sizeof (HANDLE));
1110   }
1111   else
1112     lsocks_pipe = NULL;
1113
1114   env_off = 0;
1115   if (GNUNET_YES == pipe_control)
1116   {
1117     GNUNET_asprintf (&our_env[env_off++], "%s=", GNUNET_OS_CONTROL_PIPE);
1118     GNUNET_asprintf (&our_env[env_off++], "%p", childpipe_read_handle);
1119   }
1120   if ( (lsocks != NULL) && (lsocks[0] != INVALID_SOCKET))
1121   {
1122     /*This will tell the child that we're going to send lsocks over the pipe*/
1123     GNUNET_asprintf (&our_env[env_off++], "%s=", "GNUNET_OS_READ_LSOCKS");
1124     GNUNET_asprintf (&our_env[env_off++], "%lu", lsocks_read);
1125   }
1126   our_env[env_off++] = NULL;
1127   env_block = CreateCustomEnvTable (our_env);
1128   while (0 > env_off)
1129     GNUNET_free_non_null (our_env[--env_off]);
1130
1131   wpath_len = 0;
1132   if (NULL == (wpath = u8_to_u16 ((uint8_t *) path, 1 + strlen (path), NULL, &wpath_len)))
1133   {
1134     LOG (GNUNET_ERROR_TYPE_DEBUG,
1135         "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", path, errno);
1136     GNUNET_free (env_block);
1137     GNUNET_free (cmd);
1138     if (lsocks_pipe)
1139       GNUNET_DISK_pipe_close (lsocks_pipe);
1140     if (GNUNET_YES == pipe_control)
1141     {
1142       GNUNET_DISK_file_close (childpipe_write);
1143       GNUNET_DISK_file_close (childpipe_read);
1144     }
1145     return NULL;
1146   }
1147
1148   wcmd_len = 0;
1149   if (NULL == (wcmd = u8_to_u16 ((uint8_t *) cmd, 1 + strlen (cmd), NULL, &wcmd_len)))
1150   {
1151     LOG (GNUNET_ERROR_TYPE_DEBUG,
1152         "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", cmd, errno);
1153     GNUNET_free (env_block);
1154     GNUNET_free (cmd);
1155     free (wpath);
1156     if (lsocks_pipe)
1157       GNUNET_DISK_pipe_close (lsocks_pipe);
1158     if (GNUNET_YES == pipe_control)
1159     {
1160       GNUNET_DISK_file_close (childpipe_write);
1161       GNUNET_DISK_file_close (childpipe_read);
1162     }
1163     return NULL;
1164   }
1165
1166   bresult = CreateProcessW (wpath, wcmd, NULL, NULL, TRUE,
1167        DETACHED_PROCESS | CREATE_SUSPENDED, env_block, NULL, &start, &proc);
1168   error_code = GetLastError ();
1169
1170   if ((NULL == pipe_stdin) && (stdih))
1171     SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, stdif);
1172     
1173
1174   if ((NULL == pipe_stdout) && (stdoh))
1175     SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, stdof);
1176
1177   if (stdeh)
1178     SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, stdef);
1179
1180   if (!bresult)
1181     LOG (GNUNET_ERROR_TYPE_ERROR, "CreateProcess(%s, %s) failed: %lu\n", path, cmd, error_code);
1182
1183   GNUNET_free (env_block);
1184   GNUNET_free (cmd);
1185   free (wpath);
1186   free (wcmd);
1187   if (GNUNET_YES == pipe_control)
1188   {
1189     GNUNET_DISK_file_close (childpipe_read);
1190   }
1191
1192   if (!bresult)
1193   {
1194     if (GNUNET_YES == pipe_control)
1195     {
1196       GNUNET_DISK_file_close (childpipe_write);
1197     }
1198     if (NULL != lsocks)
1199       GNUNET_DISK_pipe_close (lsocks_pipe);
1200     SetErrnoFromWinError (error_code);
1201     return NULL;
1202   }
1203
1204   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1205   gnunet_proc->pid = proc.dwProcessId;
1206   gnunet_proc->handle = proc.hProcess;
1207   gnunet_proc->control_pipe = childpipe_write;
1208
1209   CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
1210
1211   ResumeThread (proc.hThread);
1212   CloseHandle (proc.hThread);
1213
1214   if ( (NULL == lsocks) || (INVALID_SOCKET == lsocks[0]) )
1215     return gnunet_proc;
1216
1217   GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1218
1219   /* This is a replacement for "goto error" that doesn't use goto */
1220   fail = 1;
1221   do
1222   {
1223     ssize_t wrote;
1224     uint64_t size;
1225     uint64_t count;
1226     unsigned int i;
1227
1228     /* Tell the number of sockets */
1229     for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1230
1231     wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1232     if (sizeof (count) != wrote)
1233     {
1234       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1235                   "Failed to write %u count bytes to the child: %u\n",
1236                   sizeof (count), GetLastError ());
1237       break;
1238     }
1239     for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1240     {
1241       WSAPROTOCOL_INFOA pi;
1242       /* Get a socket duplication info */
1243       if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1244       {
1245         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1246                     "Failed to duplicate an socket[%llu]: %u\n", i, 
1247                     GetLastError ());
1248         break;
1249       }
1250       /* Synchronous I/O is not nice, but we can't schedule this:
1251        * lsocks will be closed/freed by the caller soon, and until
1252        * the child creates a duplicate, closing a socket here will
1253        * close it for good.
1254        */
1255       /* Send the size of the structure
1256        * (the child might be built with different headers...)
1257        */
1258       size = sizeof (pi);
1259       wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1260       if (sizeof (size) != wrote)
1261       {
1262         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1263                     "Failed to write %u size[%llu] bytes to the child: %u\n", 
1264                     sizeof (size), i, GetLastError ());
1265         break;
1266       }
1267       /* Finally! Send the data */
1268       wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1269       if (sizeof (pi) != wrote)
1270       {
1271         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1272                     "Failed to write %u socket[%llu] bytes to the child: %u\n", 
1273                     sizeof (pi), i, GetLastError ());
1274         break;
1275       }
1276     }
1277     /* This will block us until the child makes a final read or closes
1278      * the pipe (hence no 'wrote' check), since we have to wait for it
1279      * to duplicate the last socket, before we return and start closing
1280      * our own copies)
1281      */
1282     wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1283     fail = 0;
1284   }
1285   while (fail);
1286
1287   GNUNET_DISK_file_sync (lsocks_write_fd);
1288   GNUNET_DISK_pipe_close (lsocks_pipe);
1289
1290   if (fail)
1291   {
1292     /* If we can't pass on the socket(s), the child will block forever,
1293      * better put it out of its misery.
1294      */
1295     SafeTerminateProcess (gnunet_proc->handle, 0, 0);
1296     CloseHandle (gnunet_proc->handle);
1297     if (NULL != gnunet_proc->control_pipe)
1298       GNUNET_DISK_file_close (gnunet_proc->control_pipe);
1299     GNUNET_free (gnunet_proc);
1300     return NULL;
1301   }
1302   return gnunet_proc;
1303 #endif
1304 }
1305
1306
1307
1308
1309 /**
1310  * Start a process.
1311  *
1312  * @param pipe_control should a pipe be used to send signals to the child?
1313  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1314  * @param pipe_stdin pipe to use to send input to child process (or NULL)
1315  * @param pipe_stdout pipe to use to get output from child process (or NULL)
1316  * @param filename name of the binary
1317  * @param argv NULL-terminated array of arguments to the process
1318  * @return pointer to process structure of the new process, NULL on error
1319  */
1320 struct GNUNET_OS_Process *
1321 GNUNET_OS_start_process_vap (int pipe_control,
1322                              enum GNUNET_OS_InheritStdioFlags std_inheritance,
1323                              struct GNUNET_DISK_PipeHandle *pipe_stdin,
1324                              struct GNUNET_DISK_PipeHandle *pipe_stdout,
1325                              const char *filename, 
1326                              char *const argv[])
1327 {
1328   return start_process (pipe_control,
1329                         std_inheritance,
1330                         pipe_stdin,
1331                         pipe_stdout,
1332                         NULL,
1333                         filename,
1334                         argv);
1335 }
1336
1337
1338 /**
1339  * Start a process.
1340  *
1341  * @param pipe_control should a pipe be used to send signals to the child?
1342  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1343  * @param pipe_stdin pipe to use to send input to child process (or NULL)
1344  * @param pipe_stdout pipe to use to get output from child process (or NULL)
1345  * @param filename name of the binary
1346  * @param va NULL-terminated list of arguments to the process
1347  * @return pointer to process structure of the new process, NULL on error
1348  */
1349 struct GNUNET_OS_Process *
1350 GNUNET_OS_start_process_va (int pipe_control,
1351                             enum GNUNET_OS_InheritStdioFlags std_inheritance,
1352                             struct GNUNET_DISK_PipeHandle *pipe_stdin,
1353                             struct GNUNET_DISK_PipeHandle *pipe_stdout,
1354                             const char *filename, va_list va)
1355 {
1356   struct GNUNET_OS_Process *ret;
1357   va_list ap;
1358   char **argv;
1359   int argc;
1360
1361   argc = 0;
1362   va_copy (ap, va);
1363   while (NULL != va_arg (ap, char *))
1364     argc++;
1365   va_end (ap);
1366   argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
1367   argc = 0;
1368   va_copy (ap, va);
1369   while (NULL != (argv[argc] = va_arg (ap, char *)))
1370     argc++;
1371   va_end (ap);
1372   ret = GNUNET_OS_start_process_vap (pipe_control,
1373                                      std_inheritance,
1374                                      pipe_stdin,
1375                                      pipe_stdout,
1376                                      filename,
1377                                      argv);
1378   GNUNET_free (argv);
1379   return ret;
1380 }
1381
1382
1383 /**
1384  * Start a process.
1385  *
1386  * @param pipe_control should a pipe be used to send signals to the child?
1387  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1388  * @param pipe_stdin pipe to use to send input to child process (or NULL)
1389  * @param pipe_stdout pipe to use to get output from child process (or NULL)
1390  * @param filename name of the binary
1391  * @param ... NULL-terminated list of arguments to the process
1392  * @return pointer to process structure of the new process, NULL on error
1393  */
1394 struct GNUNET_OS_Process *
1395 GNUNET_OS_start_process (int pipe_control,
1396                          enum GNUNET_OS_InheritStdioFlags std_inheritance,
1397                          struct GNUNET_DISK_PipeHandle *pipe_stdin,
1398                          struct GNUNET_DISK_PipeHandle *pipe_stdout,
1399                          const char *filename, ...)
1400 {
1401   struct GNUNET_OS_Process *ret;
1402   va_list ap;
1403
1404   va_start (ap, filename);
1405   ret = GNUNET_OS_start_process_va (pipe_control, std_inheritance, pipe_stdin,
1406                                     pipe_stdout, filename, ap);
1407   va_end (ap);
1408   return ret;
1409 }
1410
1411
1412 /**
1413  * Start a process.
1414  *
1415  * @param pipe_control should a pipe be used to send signals to the child?
1416  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
1417  *        std handles of the parent are inherited by the child.
1418  *        pipe_stdin and pipe_stdout take priority over std_inheritance
1419  *        (when they are non-NULL).
1420  * @param lsocks array of listen sockets to dup systemd-style (or NULL);
1421  *         must be NULL on platforms where dup is not supported
1422  * @param filename name of the binary
1423  * @param argv NULL-terminated list of arguments to the process
1424  * @return process ID of the new process, -1 on error
1425  */
1426 struct GNUNET_OS_Process *
1427 GNUNET_OS_start_process_v (int pipe_control,
1428                            enum GNUNET_OS_InheritStdioFlags std_inheritance,
1429                            const SOCKTYPE *lsocks,
1430                            const char *filename,
1431                            char *const argv[])
1432 {
1433   return start_process (pipe_control,
1434                         std_inheritance,
1435                         NULL,
1436                         NULL,
1437                         lsocks,
1438                         filename,
1439                         argv);
1440 }
1441
1442
1443 /**
1444  * Retrieve the status of a process, waiting on him if dead.
1445  * Nonblocking version.
1446  * 
1447  * @param proc process ID
1448  * @param type status type
1449  * @param code return code/signal number
1450  * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1451  */
1452 int
1453 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1454                           enum GNUNET_OS_ProcessStatusType *type,
1455                           unsigned long *code)
1456 {
1457 #ifndef MINGW
1458   int status;
1459   int ret;
1460
1461   GNUNET_assert (0 != proc);
1462   ret = waitpid (proc->pid, &status, WNOHANG);
1463   if (ret < 0)
1464   {
1465     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1466     return GNUNET_SYSERR;
1467   }
1468   if (0 == ret)
1469   {
1470     *type = GNUNET_OS_PROCESS_RUNNING;
1471     *code = 0;
1472     return GNUNET_NO;
1473   }
1474   if (proc->pid != ret)
1475   {
1476     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1477     return GNUNET_SYSERR;
1478   }
1479   if (WIFEXITED (status))
1480   {
1481     *type = GNUNET_OS_PROCESS_EXITED;
1482     *code = WEXITSTATUS (status);
1483   }
1484   else if (WIFSIGNALED (status))
1485   {
1486     *type = GNUNET_OS_PROCESS_SIGNALED;
1487     *code = WTERMSIG (status);
1488   }
1489   else if (WIFSTOPPED (status))
1490   {
1491     *type = GNUNET_OS_PROCESS_SIGNALED;
1492     *code = WSTOPSIG (status);
1493   }
1494 #ifdef WIFCONTINUED
1495   else if (WIFCONTINUED (status))
1496   {
1497     *type = GNUNET_OS_PROCESS_RUNNING;
1498     *code = 0;
1499   }
1500 #endif
1501   else
1502   {
1503     *type = GNUNET_OS_PROCESS_UNKNOWN;
1504     *code = 0;
1505   }
1506 #else
1507   HANDLE h;
1508   DWORD c, error_code, ret;
1509
1510   h = proc->handle;
1511   ret = proc->pid;
1512   if (h == NULL || ret == 0)
1513   {
1514     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1515          ret, h);
1516     return GNUNET_SYSERR;
1517   }
1518   if (h == NULL)
1519     h = GetCurrentProcess ();
1520
1521   SetLastError (0);
1522   ret = GetExitCodeProcess (h, &c);
1523   error_code = GetLastError ();
1524   if (ret == 0 || error_code != NO_ERROR)
1525   {
1526     SetErrnoFromWinError (error_code);
1527     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1528     return GNUNET_SYSERR;
1529   }
1530   if (STILL_ACTIVE == c)
1531   {
1532     *type = GNUNET_OS_PROCESS_RUNNING;
1533     *code = 0;
1534     return GNUNET_NO;
1535   }
1536   *type = GNUNET_OS_PROCESS_EXITED;
1537   *code = c;
1538 #endif
1539
1540   return GNUNET_OK;
1541 }
1542
1543
1544 /**
1545  * Wait for a process
1546  *
1547  * @param proc pointer to process structure
1548  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1549  */
1550 int
1551 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1552 {
1553 #ifndef MINGW
1554   pid_t pid = proc->pid;
1555   pid_t ret;
1556
1557   while ( (pid != (ret = waitpid (pid, NULL, 0))) &&
1558           (EINTR == errno) ) ;
1559   if (pid != ret) 
1560   {
1561     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1562     return GNUNET_SYSERR;
1563   }
1564   return GNUNET_OK;
1565 #else
1566   HANDLE h;
1567
1568   h = proc->handle;
1569   if (NULL == h)
1570   {
1571     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1572          proc->pid, h);
1573     return GNUNET_SYSERR;
1574   }
1575   if (NULL == h)
1576     h = GetCurrentProcess ();
1577
1578   if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1579   {
1580     SetErrnoFromWinError (GetLastError ());
1581     return GNUNET_SYSERR;
1582   }
1583   return GNUNET_OK;
1584 #endif
1585 }
1586
1587
1588 /**
1589  * Handle to a command.
1590  */
1591 struct GNUNET_OS_CommandHandle
1592 {
1593
1594   /**
1595    * Process handle.
1596    */
1597   struct GNUNET_OS_Process *eip;
1598
1599   /**
1600    * Handle to the output pipe.
1601    */
1602   struct GNUNET_DISK_PipeHandle *opipe;
1603
1604   /**
1605    * Read-end of output pipe.
1606    */
1607   const struct GNUNET_DISK_FileHandle *r;
1608
1609   /**
1610    * Function to call on each line of output.
1611    */
1612   GNUNET_OS_LineProcessor proc;
1613
1614   /**
1615    * Closure for 'proc'.
1616    */
1617   void *proc_cls;
1618
1619   /**
1620    * Buffer for the output.
1621    */
1622   char buf[1024];
1623
1624   /**
1625    * Task reading from pipe.
1626    */
1627   GNUNET_SCHEDULER_TaskIdentifier rtask;
1628
1629   /**
1630    * When to time out.
1631    */
1632   struct GNUNET_TIME_Absolute timeout;
1633
1634   /**
1635    * Current read offset in buf.
1636    */
1637   size_t off;
1638 };
1639
1640
1641 /**
1642  * Stop/kill a command.  Must ONLY be called either from
1643  * the callback after 'NULL' was passed for 'line' *OR*
1644  * from an independent task (not within the line processor).
1645  *
1646  * @param cmd handle to the process
1647  */
1648 void
1649 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1650 {
1651   if (NULL != cmd->proc)
1652   {
1653     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1654     GNUNET_SCHEDULER_cancel (cmd->rtask);
1655   }
1656   (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1657   GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1658   GNUNET_OS_process_destroy (cmd->eip);
1659   GNUNET_DISK_pipe_close (cmd->opipe);
1660   GNUNET_free (cmd);
1661 }
1662
1663
1664 /**
1665  * Read from the process and call the line processor.
1666  *
1667  * @param cls the 'struct GNUNET_OS_CommandHandle'
1668  * @param tc scheduler context
1669  */
1670 static void
1671 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1672 {
1673   struct GNUNET_OS_CommandHandle *cmd = cls;
1674   GNUNET_OS_LineProcessor proc;
1675   char *end;
1676   ssize_t ret;
1677
1678   cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1679   if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1680   {
1681     /* timeout, shutdown, etc. */
1682     proc = cmd->proc;
1683     cmd->proc = NULL;
1684     proc (cmd->proc_cls, NULL);
1685     return;
1686   }
1687   ret =
1688       GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1689                              sizeof (cmd->buf) - cmd->off);
1690   if (ret <= 0)
1691   {
1692     if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1693     {
1694       cmd->buf[cmd->off] = '\0';
1695       cmd->proc (cmd->proc_cls, cmd->buf);
1696     }
1697     proc = cmd->proc;
1698     cmd->proc = NULL;
1699     proc (cmd->proc_cls, NULL);
1700     return;
1701   }
1702   end = memchr (&cmd->buf[cmd->off], '\n', ret);
1703   cmd->off += ret;
1704   while (NULL != end)
1705   {
1706     *end = '\0';
1707     cmd->proc (cmd->proc_cls, cmd->buf);
1708     memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1709     cmd->off -= (end + 1 - cmd->buf);
1710     end = memchr (cmd->buf, '\n', cmd->off);
1711   }
1712   cmd->rtask =
1713       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1714                                       (cmd->timeout), cmd->r, &cmd_read, cmd);
1715 }
1716
1717
1718 /**
1719  * Run the given command line and call the given function
1720  * for each line of the output.
1721  *
1722  * @param proc function to call for each line of the output
1723  * @param proc_cls closure for proc
1724  * @param timeout when to time out
1725  * @param binary command to run
1726  * @param ... arguments to command
1727  * @return NULL on error
1728  */
1729 struct GNUNET_OS_CommandHandle *
1730 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1731                        struct GNUNET_TIME_Relative timeout, const char *binary,
1732                        ...)
1733 {
1734   struct GNUNET_OS_CommandHandle *cmd;
1735   struct GNUNET_OS_Process *eip;
1736   struct GNUNET_DISK_PipeHandle *opipe;
1737   va_list ap;
1738
1739   opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1740   if (NULL == opipe)
1741     return NULL;
1742   va_start (ap, binary);
1743   /* redirect stdout, don't inherit stderr/stdin */
1744   eip = GNUNET_OS_start_process_va (GNUNET_NO, 0, NULL, opipe, binary, ap);
1745   va_end (ap);
1746   if (NULL == eip)
1747   {
1748     GNUNET_DISK_pipe_close (opipe);
1749     return NULL;
1750   }
1751   GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1752   cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1753   cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1754   cmd->eip = eip;
1755   cmd->opipe = opipe;
1756   cmd->proc = proc;
1757   cmd->proc_cls = proc_cls;
1758   cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1759   cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1760   return cmd;
1761 }
1762
1763
1764 /* end of os_priority.c */