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