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