-add identity service to standard build
[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_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 lpid[16];
514   char fds[16];
515   struct GNUNET_OS_Process *gnunet_proc;
516   struct GNUNET_DISK_FileHandle *childpipe_read;
517   struct GNUNET_DISK_FileHandle *childpipe_write;
518   int childpipe_read_fd;
519   int i;
520   int j;
521   int k;
522   int tgt;
523   int flags;
524   int *lscp;
525   unsigned int ls;
526   int fd_stdout_write;
527   int fd_stdout_read;
528   int fd_stdin_read;
529   int fd_stdin_write;
530
531   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename, GNUNET_NO, NULL))
532     return NULL; /* not executable */
533   if (GNUNET_YES == pipe_control)
534   {
535     struct GNUNET_DISK_PipeHandle *childpipe;
536     int dup_childpipe_read_fd = -1;
537
538     childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
539     if (NULL == childpipe)
540       return NULL;
541     childpipe_read = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ);
542     childpipe_write = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE);
543     GNUNET_DISK_pipe_close (childpipe);
544     if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
545         (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read,
546         &childpipe_read_fd, sizeof (int))) ||
547         (-1 == (dup_childpipe_read_fd = dup (childpipe_read_fd))))
548     {
549       if (NULL != childpipe_read)
550         GNUNET_DISK_file_close (childpipe_read);
551       if (NULL != childpipe_write)
552         GNUNET_DISK_file_close (childpipe_write);
553       if (0 <= dup_childpipe_read_fd)
554         close (dup_childpipe_read_fd);
555       return NULL;
556     }
557     childpipe_read_fd = dup_childpipe_read_fd;
558     GNUNET_DISK_file_close (childpipe_read);
559   }
560   else
561   {
562     childpipe_write = NULL;
563     childpipe_read_fd = -1;
564   }
565   if (NULL != pipe_stdout)
566   {
567     GNUNET_assert (GNUNET_OK ==
568                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
569                                                       (pipe_stdout,
570                                                        GNUNET_DISK_PIPE_END_WRITE),
571                                                       &fd_stdout_write, sizeof (int)));
572     GNUNET_assert (GNUNET_OK ==
573                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
574                                                       (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
575                                                       &fd_stdout_read, sizeof (int)));
576   }
577   if (NULL != pipe_stdin)
578   {
579     GNUNET_assert (GNUNET_OK ==
580                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
581                                                       (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
582                                                       &fd_stdin_read, sizeof (int)));
583     GNUNET_assert (GNUNET_OK ==
584                    GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
585                                                       (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
586                                                       &fd_stdin_write, sizeof (int)));
587   }
588   lscp = NULL;
589   ls = 0;
590   if (NULL != lsocks)
591   {
592     i = 0;
593     while (-1 != (k = lsocks[i++]))
594       GNUNET_array_append (lscp, ls, k);
595     GNUNET_array_append (lscp, ls, -1);
596   }
597 #if DARWIN
598   /* see https://gnunet.org/vfork */
599   ret = vfork ();
600 #else
601   ret = fork ();
602 #endif
603   if (-1 == ret)
604   {
605     int eno = errno;
606     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
607     GNUNET_array_grow (lscp, ls, 0);
608     if (NULL != childpipe_write)
609       GNUNET_DISK_file_close (childpipe_write);
610     if (0 <= childpipe_read_fd)
611       close (childpipe_read_fd);
612     errno = eno;
613     return NULL;
614   }
615   if (0 != ret)
616   {
617     unsetenv (GNUNET_OS_CONTROL_PIPE);
618     gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
619     gnunet_proc->pid = ret;
620     gnunet_proc->control_pipe = childpipe_write;
621     if (GNUNET_YES == pipe_control)
622     {
623       close (childpipe_read_fd);
624     }
625     GNUNET_array_grow (lscp, ls, 0);
626     return gnunet_proc;
627   }
628   if (0 <= childpipe_read_fd)
629   {
630     char fdbuf[100];
631 #ifndef DARWIN
632     /* due to vfork, we must NOT free memory on DARWIN! */
633     GNUNET_DISK_file_close (childpipe_write);
634 #endif
635     snprintf (fdbuf, 100, "%x", childpipe_read_fd);
636     setenv (GNUNET_OS_CONTROL_PIPE, fdbuf, 1);
637   }
638   else
639     unsetenv (GNUNET_OS_CONTROL_PIPE);
640   if (NULL != pipe_stdin)
641   {
642     GNUNET_break (0 == close (fd_stdin_write));
643     if (-1 == dup2 (fd_stdin_read, 0))
644       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
645     GNUNET_break (0 == close (fd_stdin_read));
646   }
647   else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_IN))
648   {
649     GNUNET_break (0 == close (0));
650     open_dev_null (0, O_RDONLY);
651   }
652   if (NULL != pipe_stdout)
653   {
654     GNUNET_break (0 == close (fd_stdout_read));
655     if (-1 == dup2 (fd_stdout_write, 1))
656       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
657     GNUNET_break (0 == close (fd_stdout_write));
658   }
659   else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_OUT))
660   {
661     GNUNET_break (0 == close (1));
662     open_dev_null (1, O_WRONLY);
663   }
664   if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_ERR))
665   {
666     GNUNET_break (0 == close (2));
667     open_dev_null (2, O_WRONLY);
668   }
669   if (NULL != lscp)
670   {
671     /* read systemd documentation... */
672     GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
673     setenv ("LISTEN_PID", lpid, 1);
674     i = 0;
675     tgt = 3;
676     while (-1 != lscp[i])
677     {
678       j = i + 1;
679       while (-1 != lscp[j])
680       {
681         if (lscp[j] == tgt)
682         {
683           /* dup away */
684           k = dup (lscp[j]);
685           GNUNET_assert (-1 != k);
686           GNUNET_assert (0 == close (lscp[j]));
687           lscp[j] = k;
688           break;
689         }
690         j++;
691       }
692       if (lscp[i] != tgt)
693       {
694         /* Bury any existing FD, no matter what; they should all be closed
695          * on exec anyway and the important onces have been dup'ed away */
696         (void) close (tgt);
697         GNUNET_assert (-1 != dup2 (lscp[i], tgt));
698       }
699       /* unset close-on-exec flag */
700       flags = fcntl (tgt, F_GETFD);
701       GNUNET_assert (flags >= 0);
702       flags &= ~FD_CLOEXEC;
703       fflush (stderr);
704       (void) fcntl (tgt, F_SETFD, flags);
705       tgt++;
706       i++;
707     }
708     GNUNET_snprintf (fds, sizeof (fds), "%u", i);
709     setenv ("LISTEN_FDS", fds, 1);
710   }
711 #ifndef DARWIN
712   /* due to vfork, we must NOT free memory on DARWIN! */
713   GNUNET_array_grow (lscp, ls, 0);
714 #endif
715   execvp (filename, argv);
716   LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
717   _exit (1);
718 #else
719   struct GNUNET_DISK_FileHandle *childpipe_read;
720   struct GNUNET_DISK_FileHandle *childpipe_write;
721   HANDLE childpipe_read_handle;
722   char **arg;
723   char **non_const_argv;
724   unsigned int cmdlen;
725   char *cmd;
726   char *idx;
727   STARTUPINFOW start;
728   PROCESS_INFORMATION proc;
729   int argcount = 0;
730   struct GNUNET_OS_Process *gnunet_proc;
731   char path[MAX_PATH + 1];
732   char *our_env[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };
733   char *env_block = NULL;
734   char *pathbuf;
735   DWORD pathbuf_len;
736   DWORD alloc_len;
737   char *self_prefix;
738   char *bindir;
739   char *libdir;
740   char *ptr;
741   char *non_const_filename;
742   char win_path[MAX_PATH + 1];
743   struct GNUNET_DISK_PipeHandle *lsocks_pipe;
744   const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
745   HANDLE lsocks_read;
746   HANDLE lsocks_write;
747   wchar_t *wpath;
748   wchar_t *wcmd;
749   size_t wpath_len;
750   size_t wcmd_len;
751   int env_off;
752   int fail;
753   long lRet;
754   HANDLE stdin_handle;
755   HANDLE stdout_handle;
756   HANDLE stdih, stdoh, stdeh;
757   DWORD stdif, stdof, stdef;
758   BOOL bresult;
759   DWORD error_code;
760
761   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename, GNUNET_NO, NULL))
762     return NULL; /* not executable */
763  
764   /* Search in prefix dir (hopefully - the directory from which
765    * the current module was loaded), bindir and libdir, then in PATH
766    */
767   self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
768   bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
769   libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
770
771   pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
772
773   alloc_len =
774       pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
775       strlen (libdir);
776
777   pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
778
779   ptr = pathbuf;
780   ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
781   GNUNET_free (self_prefix);
782   GNUNET_free (bindir);
783   GNUNET_free (libdir);
784
785   alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
786   if (alloc_len != pathbuf_len - 1)
787   {
788     GNUNET_free (pathbuf);
789     errno = ENOSYS;             /* PATH changed on the fly. What kind of error is that? */
790     return NULL;
791   }
792
793   cmdlen = strlen (filename);
794   if ( (cmdlen < 5) || (0 != strcmp (&filename[cmdlen - 4], ".exe")) )
795     GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
796   else
797     GNUNET_asprintf (&non_const_filename, "%s", filename);
798
799   /* It could be in POSIX form, convert it to a DOS path early on */
800   if (ERROR_SUCCESS != (lRet = plibc_conv_to_win_path (non_const_filename, win_path)))
801   {
802     SetErrnoFromWinError (lRet);
803     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "plibc_conv_to_win_path",
804                        non_const_filename);
805     GNUNET_free (non_const_filename);
806     GNUNET_free (pathbuf);
807     return NULL;
808   }
809   GNUNET_free (non_const_filename);
810   non_const_filename = GNUNET_strdup (win_path);
811    /* Check that this is the full path. If it isn't, search. */
812   /* FIXME: convert it to wchar_t and use SearchPathW?
813    * Remember: arguments to _start_process() are technically in UTF-8...
814    */
815   if (non_const_filename[1] == ':')
816   {
817     snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
818     LOG (GNUNET_ERROR_TYPE_DEBUG,
819         "Using path `%s' as-is. PATH is %s\n", path, ptr);
820   }
821   else if (!SearchPathA
822            (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
823             path, NULL))
824   {
825     SetErrnoFromWinError (GetLastError ());
826     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
827                        non_const_filename);
828     GNUNET_free (non_const_filename);
829     GNUNET_free (pathbuf);
830     return NULL;
831   }
832   else
833     LOG (GNUNET_ERROR_TYPE_DEBUG,
834         "Found `%s' in PATH `%s'\n", path, pathbuf);
835   GNUNET_free (pathbuf);
836   GNUNET_free (non_const_filename);
837
838   /* Count the number of arguments */
839   arg = (char **) argv;
840   while (*arg)
841   {
842     arg++;
843     argcount++;
844   }
845
846   /* Allocate a copy argv */
847   non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
848
849   /* Copy all argv strings */
850   argcount = 0;
851   arg = (char **) argv;
852   while (*arg)
853   {
854     if (arg == argv)
855       non_const_argv[argcount] = GNUNET_strdup (path);
856     else
857       non_const_argv[argcount] = GNUNET_strdup (*arg);
858     arg++;
859     argcount++;
860   }
861   non_const_argv[argcount] = NULL;
862
863   /* Count cmd len */
864   cmdlen = 1;
865   arg = non_const_argv;
866   while (*arg)
867   {
868     cmdlen = cmdlen + strlen (*arg) + 4;
869     arg++;
870   }
871
872   /* Allocate and create cmd */
873   cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
874   arg = non_const_argv;
875   while (*arg)
876   {
877     char arg_last_char = (*arg)[strlen (*arg) - 1];
878     idx += sprintf (idx, "\"%s%s\"%s", *arg,
879         arg_last_char == '\\' ? "\\" : "", *(arg + 1) ? " " : "");
880     arg++;
881   }
882
883   while (argcount > 0)
884     GNUNET_free (non_const_argv[--argcount]);
885   GNUNET_free (non_const_argv);
886
887   memset (&start, 0, sizeof (start));
888   start.cb = sizeof (start);
889   if ((pipe_stdin != NULL) || (pipe_stdout != NULL) || (std_inheritance != 0))
890     start.dwFlags |= STARTF_USESTDHANDLES;
891
892   stdih = GetStdHandle (STD_INPUT_HANDLE);
893   GetHandleInformation (stdih, &stdif);
894   if (pipe_stdin != NULL)
895   {
896     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
897                                        (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
898                                        &stdin_handle, sizeof (HANDLE));
899     start.hStdInput = stdin_handle;
900   }
901   else if (stdih)
902   {
903     if (std_inheritance & GNUNET_OS_INHERIT_STD_IN)
904     {
905       SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 1);
906       if (pipe_stdin == NULL)
907         start.hStdInput = stdih;
908     }
909     else
910       SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 0);
911   }
912     
913
914   stdoh = GetStdHandle (STD_OUTPUT_HANDLE);
915   GetHandleInformation (stdoh, &stdof);
916   if (NULL != pipe_stdout)
917   {
918     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
919                                        (pipe_stdout,
920                                         GNUNET_DISK_PIPE_END_WRITE),
921                                        &stdout_handle, sizeof (HANDLE));
922     start.hStdOutput = stdout_handle;
923   }
924   else if (stdoh)
925   {
926     if (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)
927     {
928       SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 1);
929       if (pipe_stdout == NULL)
930         start.hStdOutput = stdoh;
931     }
932     else
933       SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 0);
934   }
935
936   stdeh = GetStdHandle (STD_ERROR_HANDLE);
937   GetHandleInformation (stdeh, &stdef);
938   if (stdeh)
939   {
940     if (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)
941     {
942       SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 1);
943       start.hStdError = stdeh;
944     }
945     else
946       SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 0);
947   }
948
949   if (GNUNET_YES == pipe_control)
950   {
951     struct GNUNET_DISK_PipeHandle *childpipe;
952     childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
953     if (NULL == childpipe)
954       return NULL;
955     childpipe_read = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ);
956     childpipe_write = GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE);
957     GNUNET_DISK_pipe_close (childpipe);
958     if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
959         (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read,
960         &childpipe_read_handle, sizeof (HANDLE))))
961     {
962       if (childpipe_read)
963         GNUNET_DISK_file_close (childpipe_read);
964       if (childpipe_write)
965         GNUNET_DISK_file_close (childpipe_write);
966       GNUNET_free (cmd);
967       return NULL;
968     }
969     /* Unlike *nix variant, we don't dup the handle, so can't close
970      * filehandle right now.
971      */
972     SetHandleInformation (childpipe_read_handle, HANDLE_FLAG_INHERIT, 1);
973   }
974   else
975   {
976     childpipe_read = NULL;
977     childpipe_write = NULL;
978   }
979
980   if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
981   {
982     lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
983
984     if (lsocks_pipe == NULL)
985     {
986       GNUNET_free (cmd);
987       GNUNET_DISK_pipe_close (lsocks_pipe);
988       if (GNUNET_YES == pipe_control)
989       {
990         GNUNET_DISK_file_close (childpipe_write);
991         GNUNET_DISK_file_close (childpipe_read);
992       }
993       return NULL;
994     }
995     lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
996         GNUNET_DISK_PIPE_END_WRITE);
997     GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
998                                        &lsocks_write, sizeof (HANDLE));
999     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1000                                        (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1001                                        &lsocks_read, sizeof (HANDLE));
1002   }
1003   else
1004     lsocks_pipe = NULL;
1005
1006   env_off = 0;
1007   if (GNUNET_YES == pipe_control)
1008   {
1009     GNUNET_asprintf (&our_env[env_off++], "%s=", GNUNET_OS_CONTROL_PIPE);
1010     GNUNET_asprintf (&our_env[env_off++], "%p", childpipe_read_handle);
1011   }
1012   if ( (lsocks != NULL) && (lsocks[0] != INVALID_SOCKET))
1013   {
1014     /*This will tell the child that we're going to send lsocks over the pipe*/
1015     GNUNET_asprintf (&our_env[env_off++], "%s=", "GNUNET_OS_READ_LSOCKS");
1016     GNUNET_asprintf (&our_env[env_off++], "%lu", lsocks_read);
1017   }
1018   our_env[env_off++] = NULL;
1019   env_block = CreateCustomEnvTable (our_env);
1020   while (0 > env_off)
1021     GNUNET_free_non_null (our_env[--env_off]);
1022
1023   wpath_len = 0;
1024   if (NULL == (wpath = u8_to_u16 ((uint8_t *) path, 1 + strlen (path), NULL, &wpath_len)))
1025   {
1026     LOG (GNUNET_ERROR_TYPE_DEBUG,
1027         "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", path, errno);
1028     GNUNET_free (env_block);
1029     GNUNET_free (cmd);
1030     if (lsocks_pipe)
1031       GNUNET_DISK_pipe_close (lsocks_pipe);
1032     if (GNUNET_YES == pipe_control)
1033     {
1034       GNUNET_DISK_file_close (childpipe_write);
1035       GNUNET_DISK_file_close (childpipe_read);
1036     }
1037     return NULL;
1038   }
1039
1040   wcmd_len = 0;
1041   if (NULL == (wcmd = u8_to_u16 ((uint8_t *) cmd, 1 + strlen (cmd), NULL, &wcmd_len)))
1042   {
1043     LOG (GNUNET_ERROR_TYPE_DEBUG,
1044         "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", cmd, errno);
1045     GNUNET_free (env_block);
1046     GNUNET_free (cmd);
1047     free (wpath);
1048     if (lsocks_pipe)
1049       GNUNET_DISK_pipe_close (lsocks_pipe);
1050     if (GNUNET_YES == pipe_control)
1051     {
1052       GNUNET_DISK_file_close (childpipe_write);
1053       GNUNET_DISK_file_close (childpipe_read);
1054     }
1055     return NULL;
1056   }
1057
1058   bresult = CreateProcessW (wpath, wcmd, NULL, NULL, GNUNET_YES,
1059        DETACHED_PROCESS | CREATE_SUSPENDED, env_block, NULL, &start, &proc);
1060   error_code = GetLastError ();
1061
1062   if ((NULL == pipe_stdin) && (stdih))
1063     SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, stdif);
1064     
1065
1066   if ((NULL == pipe_stdout) && (stdoh))
1067     SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, stdof);
1068
1069   if (stdeh)
1070     SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, stdef);
1071
1072   if (!bresult)
1073     LOG (GNUNET_ERROR_TYPE_ERROR, "CreateProcess(%s, %s) failed: %lu\n", path, cmd, error_code);
1074
1075   GNUNET_free (env_block);
1076   GNUNET_free (cmd);
1077   free (wpath);
1078   free (wcmd);
1079   if (GNUNET_YES == pipe_control)
1080   {
1081     GNUNET_DISK_file_close (childpipe_read);
1082   }
1083
1084   if (!bresult)
1085   {
1086     if (GNUNET_YES == pipe_control)
1087     {
1088       GNUNET_DISK_file_close (childpipe_write);
1089     }
1090     if (NULL != lsocks)
1091       GNUNET_DISK_pipe_close (lsocks_pipe);
1092     SetErrnoFromWinError (error_code);
1093     return NULL;
1094   }
1095
1096   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1097   gnunet_proc->pid = proc.dwProcessId;
1098   gnunet_proc->handle = proc.hProcess;
1099   gnunet_proc->control_pipe = childpipe_write;
1100
1101   CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
1102
1103   ResumeThread (proc.hThread);
1104   CloseHandle (proc.hThread);
1105
1106   if ( (NULL == lsocks) || (INVALID_SOCKET == lsocks[0]) )
1107     return gnunet_proc;
1108
1109   GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1110
1111   /* This is a replacement for "goto error" that doesn't use goto */
1112   fail = 1;
1113   do
1114   {
1115     ssize_t wrote;
1116     uint64_t size;
1117     uint64_t count;
1118     unsigned int i;
1119
1120     /* Tell the number of sockets */
1121     for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1122
1123     wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1124     if (sizeof (count) != wrote)
1125     {
1126       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1127                   "Failed to write %u count bytes to the child: %u\n",
1128                   sizeof (count), GetLastError ());
1129       break;
1130     }
1131     for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1132     {
1133       WSAPROTOCOL_INFOA pi;
1134       /* Get a socket duplication info */
1135       if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1136       {
1137         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1138                     "Failed to duplicate an socket[%llu]: %u\n", i, 
1139                     GetLastError ());
1140         break;
1141       }
1142       /* Synchronous I/O is not nice, but we can't schedule this:
1143        * lsocks will be closed/freed by the caller soon, and until
1144        * the child creates a duplicate, closing a socket here will
1145        * close it for good.
1146        */
1147       /* Send the size of the structure
1148        * (the child might be built with different headers...)
1149        */
1150       size = sizeof (pi);
1151       wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1152       if (sizeof (size) != wrote)
1153       {
1154         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1155                     "Failed to write %u size[%llu] bytes to the child: %u\n", 
1156                     sizeof (size), i, GetLastError ());
1157         break;
1158       }
1159       /* Finally! Send the data */
1160       wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1161       if (sizeof (pi) != wrote)
1162       {
1163         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1164                     "Failed to write %u socket[%llu] bytes to the child: %u\n", 
1165                     sizeof (pi), i, GetLastError ());
1166         break;
1167       }
1168     }
1169     /* This will block us until the child makes a final read or closes
1170      * the pipe (hence no 'wrote' check), since we have to wait for it
1171      * to duplicate the last socket, before we return and start closing
1172      * our own copies)
1173      */
1174     wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1175     fail = 0;
1176   }
1177   while (fail);
1178
1179   GNUNET_DISK_file_sync (lsocks_write_fd);
1180   GNUNET_DISK_pipe_close (lsocks_pipe);
1181
1182   if (fail)
1183   {
1184     /* If we can't pass on the socket(s), the child will block forever,
1185      * better put it out of its misery.
1186      */
1187     SafeTerminateProcess (gnunet_proc->handle, 0, 0);
1188     CloseHandle (gnunet_proc->handle);
1189     if (NULL != gnunet_proc->control_pipe)
1190       GNUNET_DISK_file_close (gnunet_proc->control_pipe);
1191     GNUNET_free (gnunet_proc);
1192     return NULL;
1193   }
1194   return gnunet_proc;
1195 #endif
1196 }
1197
1198
1199
1200
1201 /**
1202  * Start a process.
1203  *
1204  * @param pipe_control should a pipe be used to send signals to the child?
1205  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1206  * @param pipe_stdin pipe to use to send input to child process (or NULL)
1207  * @param pipe_stdout pipe to use to get output from child process (or NULL)
1208  * @param filename name of the binary
1209  * @param argv NULL-terminated array of arguments to the process
1210  * @return pointer to process structure of the new process, NULL on error
1211  */
1212 struct GNUNET_OS_Process *
1213 GNUNET_OS_start_process_vap (int pipe_control,
1214                              enum GNUNET_OS_InheritStdioFlags std_inheritance,
1215                              struct GNUNET_DISK_PipeHandle *pipe_stdin,
1216                              struct GNUNET_DISK_PipeHandle *pipe_stdout,
1217                              const char *filename, 
1218                              char *const argv[])
1219 {
1220   return start_process (pipe_control,
1221                         std_inheritance,
1222                         pipe_stdin,
1223                         pipe_stdout,
1224                         NULL,
1225                         filename,
1226                         argv);
1227 }
1228
1229
1230 /**
1231  * Start a process.
1232  *
1233  * @param pipe_control should a pipe be used to send signals to the child?
1234  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1235  * @param pipe_stdin pipe to use to send input to child process (or NULL)
1236  * @param pipe_stdout pipe to use to get output from child process (or NULL)
1237  * @param filename name of the binary
1238  * @param va NULL-terminated list of arguments to the process
1239  * @return pointer to process structure of the new process, NULL on error
1240  */
1241 struct GNUNET_OS_Process *
1242 GNUNET_OS_start_process_va (int pipe_control,
1243                             enum GNUNET_OS_InheritStdioFlags std_inheritance,
1244                             struct GNUNET_DISK_PipeHandle *pipe_stdin,
1245                             struct GNUNET_DISK_PipeHandle *pipe_stdout,
1246                             const char *filename, va_list va)
1247 {
1248   struct GNUNET_OS_Process *ret;
1249   va_list ap;
1250   char **argv;
1251   int argc;
1252
1253   argc = 0;
1254   va_copy (ap, va);
1255   while (NULL != va_arg (ap, char *))
1256     argc++;
1257   va_end (ap);
1258   argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
1259   argc = 0;
1260   va_copy (ap, va);
1261   while (NULL != (argv[argc] = va_arg (ap, char *)))
1262     argc++;
1263   va_end (ap);
1264   ret = GNUNET_OS_start_process_vap (pipe_control,
1265                                      std_inheritance,
1266                                      pipe_stdin,
1267                                      pipe_stdout,
1268                                      filename,
1269                                      argv);
1270   GNUNET_free (argv);
1271   return ret;
1272 }
1273
1274
1275 /**
1276  * Start a process.
1277  *
1278  * @param pipe_control should a pipe be used to send signals to the child?
1279  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1280  * @param pipe_stdin pipe to use to send input to child process (or NULL)
1281  * @param pipe_stdout pipe to use to get output from child process (or NULL)
1282  * @param filename name of the binary
1283  * @param ... NULL-terminated list of arguments to the process
1284  * @return pointer to process structure of the new process, NULL on error
1285  */
1286 struct GNUNET_OS_Process *
1287 GNUNET_OS_start_process (int pipe_control,
1288                          enum GNUNET_OS_InheritStdioFlags std_inheritance,
1289                          struct GNUNET_DISK_PipeHandle *pipe_stdin,
1290                          struct GNUNET_DISK_PipeHandle *pipe_stdout,
1291                          const char *filename, ...)
1292 {
1293   struct GNUNET_OS_Process *ret;
1294   va_list ap;
1295
1296   va_start (ap, filename);
1297   ret = GNUNET_OS_start_process_va (pipe_control, std_inheritance, pipe_stdin,
1298                                     pipe_stdout, filename, ap);
1299   va_end (ap);
1300   return ret;
1301 }
1302
1303
1304 /**
1305  * Start a process.
1306  *
1307  * @param pipe_control should a pipe be used to send signals to the child?
1308  * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
1309  *        std handles of the parent are inherited by the child.
1310  *        pipe_stdin and pipe_stdout take priority over std_inheritance
1311  *        (when they are non-NULL).
1312  * @param lsocks array of listen sockets to dup systemd-style (or NULL);
1313  *         must be NULL on platforms where dup is not supported
1314  * @param filename name of the binary
1315  * @param argv NULL-terminated list of arguments to the process
1316  * @return process ID of the new process, -1 on error
1317  */
1318 struct GNUNET_OS_Process *
1319 GNUNET_OS_start_process_v (int pipe_control,
1320                            enum GNUNET_OS_InheritStdioFlags std_inheritance,
1321                            const SOCKTYPE *lsocks,
1322                            const char *filename,
1323                            char *const argv[])
1324 {
1325   return start_process (pipe_control,
1326                         std_inheritance,
1327                         NULL,
1328                         NULL,
1329                         lsocks,
1330                         filename,
1331                         argv);
1332 }
1333
1334
1335 /**
1336  * Retrieve the status of a process, waiting on him if dead.
1337  * Nonblocking version.
1338  * 
1339  * @param proc process ID
1340  * @param type status type
1341  * @param code return code/signal number
1342  * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1343  */
1344 int
1345 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1346                           enum GNUNET_OS_ProcessStatusType *type,
1347                           unsigned long *code)
1348 {
1349 #ifndef MINGW
1350   int status;
1351   int ret;
1352
1353   GNUNET_assert (0 != proc);
1354   ret = waitpid (proc->pid, &status, WNOHANG);
1355   if (ret < 0)
1356   {
1357     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1358     return GNUNET_SYSERR;
1359   }
1360   if (0 == ret)
1361   {
1362     *type = GNUNET_OS_PROCESS_RUNNING;
1363     *code = 0;
1364     return GNUNET_NO;
1365   }
1366   if (proc->pid != ret)
1367   {
1368     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1369     return GNUNET_SYSERR;
1370   }
1371   if (WIFEXITED (status))
1372   {
1373     *type = GNUNET_OS_PROCESS_EXITED;
1374     *code = WEXITSTATUS (status);
1375   }
1376   else if (WIFSIGNALED (status))
1377   {
1378     *type = GNUNET_OS_PROCESS_SIGNALED;
1379     *code = WTERMSIG (status);
1380   }
1381   else if (WIFSTOPPED (status))
1382   {
1383     *type = GNUNET_OS_PROCESS_SIGNALED;
1384     *code = WSTOPSIG (status);
1385   }
1386 #ifdef WIFCONTINUED
1387   else if (WIFCONTINUED (status))
1388   {
1389     *type = GNUNET_OS_PROCESS_RUNNING;
1390     *code = 0;
1391   }
1392 #endif
1393   else
1394   {
1395     *type = GNUNET_OS_PROCESS_UNKNOWN;
1396     *code = 0;
1397   }
1398 #else
1399   HANDLE h;
1400   DWORD c, error_code, ret;
1401
1402   h = proc->handle;
1403   ret = proc->pid;
1404   if (h == NULL || ret == 0)
1405   {
1406     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1407          ret, h);
1408     return GNUNET_SYSERR;
1409   }
1410   if (h == NULL)
1411     h = GetCurrentProcess ();
1412
1413   SetLastError (0);
1414   ret = GetExitCodeProcess (h, &c);
1415   error_code = GetLastError ();
1416   if (ret == 0 || error_code != NO_ERROR)
1417   {
1418     SetErrnoFromWinError (error_code);
1419     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1420     return GNUNET_SYSERR;
1421   }
1422   if (STILL_ACTIVE == c)
1423   {
1424     *type = GNUNET_OS_PROCESS_RUNNING;
1425     *code = 0;
1426     return GNUNET_NO;
1427   }
1428   *type = GNUNET_OS_PROCESS_EXITED;
1429   *code = c;
1430 #endif
1431
1432   return GNUNET_OK;
1433 }
1434
1435
1436 /**
1437  * Wait for a process
1438  *
1439  * @param proc pointer to process structure
1440  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1441  */
1442 int
1443 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1444 {
1445 #ifndef MINGW
1446   pid_t pid = proc->pid;
1447   pid_t ret;
1448
1449   while ( (pid != (ret = waitpid (pid, NULL, 0))) &&
1450           (EINTR == errno) ) ;
1451   if (pid != ret) 
1452   {
1453     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1454     return GNUNET_SYSERR;
1455   }
1456   return GNUNET_OK;
1457 #else
1458   HANDLE h;
1459
1460   h = proc->handle;
1461   if (NULL == h)
1462   {
1463     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1464          proc->pid, h);
1465     return GNUNET_SYSERR;
1466   }
1467   if (NULL == h)
1468     h = GetCurrentProcess ();
1469
1470   if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1471   {
1472     SetErrnoFromWinError (GetLastError ());
1473     return GNUNET_SYSERR;
1474   }
1475   return GNUNET_OK;
1476 #endif
1477 }
1478
1479
1480 /**
1481  * Handle to a command.
1482  */
1483 struct GNUNET_OS_CommandHandle
1484 {
1485
1486   /**
1487    * Process handle.
1488    */
1489   struct GNUNET_OS_Process *eip;
1490
1491   /**
1492    * Handle to the output pipe.
1493    */
1494   struct GNUNET_DISK_PipeHandle *opipe;
1495
1496   /**
1497    * Read-end of output pipe.
1498    */
1499   const struct GNUNET_DISK_FileHandle *r;
1500
1501   /**
1502    * Function to call on each line of output.
1503    */
1504   GNUNET_OS_LineProcessor proc;
1505
1506   /**
1507    * Closure for 'proc'.
1508    */
1509   void *proc_cls;
1510
1511   /**
1512    * Buffer for the output.
1513    */
1514   char buf[1024];
1515
1516   /**
1517    * Task reading from pipe.
1518    */
1519   GNUNET_SCHEDULER_TaskIdentifier rtask;
1520
1521   /**
1522    * When to time out.
1523    */
1524   struct GNUNET_TIME_Absolute timeout;
1525
1526   /**
1527    * Current read offset in buf.
1528    */
1529   size_t off;
1530 };
1531
1532
1533 /**
1534  * Stop/kill a command.  Must ONLY be called either from
1535  * the callback after 'NULL' was passed for 'line' *OR*
1536  * from an independent task (not within the line processor).
1537  *
1538  * @param cmd handle to the process
1539  */
1540 void
1541 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1542 {
1543   if (NULL != cmd->proc)
1544   {
1545     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1546     GNUNET_SCHEDULER_cancel (cmd->rtask);
1547   }
1548   (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1549   GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1550   GNUNET_OS_process_destroy (cmd->eip);
1551   GNUNET_DISK_pipe_close (cmd->opipe);
1552   GNUNET_free (cmd);
1553 }
1554
1555
1556 /**
1557  * Read from the process and call the line processor.
1558  *
1559  * @param cls the 'struct GNUNET_OS_CommandHandle'
1560  * @param tc scheduler context
1561  */
1562 static void
1563 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1564 {
1565   struct GNUNET_OS_CommandHandle *cmd = cls;
1566   GNUNET_OS_LineProcessor proc;
1567   char *end;
1568   ssize_t ret;
1569
1570   cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1571   if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1572   {
1573     /* timeout, shutdown, etc. */
1574     proc = cmd->proc;
1575     cmd->proc = NULL;
1576     proc (cmd->proc_cls, NULL);
1577     return;
1578   }
1579   ret =
1580       GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1581                              sizeof (cmd->buf) - cmd->off);
1582   if (ret <= 0)
1583   {
1584     if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1585     {
1586       cmd->buf[cmd->off] = '\0';
1587       cmd->proc (cmd->proc_cls, cmd->buf);
1588     }
1589     proc = cmd->proc;
1590     cmd->proc = NULL;
1591     proc (cmd->proc_cls, NULL);
1592     return;
1593   }
1594   end = memchr (&cmd->buf[cmd->off], '\n', ret);
1595   cmd->off += ret;
1596   while (NULL != end)
1597   {
1598     *end = '\0';
1599     cmd->proc (cmd->proc_cls, cmd->buf);
1600     memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1601     cmd->off -= (end + 1 - cmd->buf);
1602     end = memchr (cmd->buf, '\n', cmd->off);
1603   }
1604   cmd->rtask =
1605       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1606                                       (cmd->timeout), cmd->r, &cmd_read, cmd);
1607 }
1608
1609
1610 /**
1611  * Run the given command line and call the given function
1612  * for each line of the output.
1613  *
1614  * @param proc function to call for each line of the output
1615  * @param proc_cls closure for proc
1616  * @param timeout when to time out
1617  * @param binary command to run
1618  * @param ... arguments to command
1619  * @return NULL on error
1620  */
1621 struct GNUNET_OS_CommandHandle *
1622 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1623                        struct GNUNET_TIME_Relative timeout, const char *binary,
1624                        ...)
1625 {
1626   struct GNUNET_OS_CommandHandle *cmd;
1627   struct GNUNET_OS_Process *eip;
1628   struct GNUNET_DISK_PipeHandle *opipe;
1629   va_list ap;
1630
1631   opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1632   if (NULL == opipe)
1633     return NULL;
1634   va_start (ap, binary);
1635   /* redirect stdout, don't inherit stderr/stdin */
1636   eip = GNUNET_OS_start_process_va (GNUNET_NO, 0, NULL, opipe, binary, ap);
1637   va_end (ap);
1638   if (NULL == eip)
1639   {
1640     GNUNET_DISK_pipe_close (opipe);
1641     return NULL;
1642   }
1643   GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1644   cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1645   cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1646   cmd->eip = eip;
1647   cmd->opipe = opipe;
1648   cmd->proc = proc;
1649   cmd->proc_cls = proc_cls;
1650   cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1651   cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1652   return cmd;
1653 }
1654
1655
1656 /* end of os_priority.c */