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