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