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