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