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