-fix
[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, arg_count;
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) + 4;
711     else
712       cmdlen = cmdlen + strlen (arg) + 4;
713   }
714   arg_count = argc;
715
716   cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
717   argc = 0;
718   while (NULL != (arg = argv[argc++]))
719   {
720     /* This is to escape trailing slash */
721     char arg_lastchar = arg[strlen (arg) - 1];
722     if (idx == cmd)
723       idx += sprintf (idx, "\"%s%s\"%s", path,
724           arg_lastchar == '\\' ? "\\" : "", argc + 1 == arg_count ? "" : " ");
725     else
726       idx += sprintf (idx, "\"%s%s\"%s", arg,
727           arg_lastchar == '\\' ? "\\" : "", argc + 1 == arg_count ? "" : " ");
728   }
729
730   memset (&start, 0, sizeof (start));
731   start.cb = sizeof (start);
732
733   if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
734     start.dwFlags |= STARTF_USESTDHANDLES;
735
736   if (pipe_stdin != NULL)
737   {
738     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
739                                        (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
740                                        &stdin_handle, sizeof (HANDLE));
741     start.hStdInput = stdin_handle;
742   }
743
744   if (pipe_stdout != NULL)
745   {
746     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
747                                        (pipe_stdout,
748                                         GNUNET_DISK_PIPE_END_WRITE),
749                                        &stdout_handle, sizeof (HANDLE));
750     start.hStdOutput = stdout_handle;
751   }
752
753   control_pipe =
754       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
755                                 GNUNET_DISK_PERM_USER_READ |
756                                 GNUNET_DISK_PERM_USER_WRITE);
757   if (control_pipe == NULL)
758   {
759     GNUNET_free (cmd);
760     GNUNET_free (path);
761     return NULL;
762   }
763
764 #if DEBUG_OS
765   LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
766        childpipename);
767 #endif
768
769   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
770   GNUNET_asprintf (&our_env[1], "%s", childpipename);
771   our_env[2] = NULL;
772   env_block = CreateCustomEnvTable (our_env);
773   GNUNET_free (our_env[0]);
774   GNUNET_free (our_env[1]);
775
776   if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath)
777       || ERROR_SUCCESS != plibc_conv_to_win_pathwconv(cmd, wcmd)
778       || !CreateProcessW
779       (wpath, wcmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
780        env_block, NULL, &start, &proc))
781   {
782     SetErrnoFromWinError (GetLastError ());
783     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
784     GNUNET_free (env_block);
785     GNUNET_free (cmd);
786     return NULL;
787   }
788
789   GNUNET_free (env_block);
790
791   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
792   gnunet_proc->pid = proc.dwProcessId;
793   gnunet_proc->handle = proc.hProcess;
794   gnunet_proc->control_pipe = control_pipe;
795
796   CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
797
798   ResumeThread (proc.hThread);
799   CloseHandle (proc.hThread);
800
801   GNUNET_free (cmd);
802
803   return gnunet_proc;
804 #endif
805 }
806
807
808 /**
809  * Start a process.
810  *
811  * @param pipe_stdin pipe to use to send input to child process (or NULL)
812  * @param pipe_stdout pipe to use to get output from child process (or NULL)
813  * @param filename name of the binary
814  * @param va NULL-terminated list of arguments to the process
815  * @return pointer to process structure of the new process, NULL on error
816  */
817 struct GNUNET_OS_Process *
818 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
819                             struct GNUNET_DISK_PipeHandle *pipe_stdout,
820                             const char *filename, va_list va)
821 {
822   struct GNUNET_OS_Process *ret;
823   va_list ap;
824   char **argv;
825   int argc;
826
827   argc = 0;
828   va_copy (ap, va);
829   while (NULL != va_arg (ap, char *))
830     argc++;
831   va_end (ap);
832   argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
833   argc = 0;
834   va_copy (ap, va);
835   while (NULL != (argv[argc] = va_arg (ap, char *)))
836     argc++;
837   va_end (ap);
838   ret = GNUNET_OS_start_process_vap (pipe_stdin,
839                                      pipe_stdout,
840                                      filename,
841                                      argv);
842   GNUNET_free (argv);
843   return ret;
844 }
845
846
847
848 /**
849  * Start a process.
850  *
851  * @param pipe_stdin pipe to use to send input to child process (or NULL)
852  * @param pipe_stdout pipe to use to get output from child process (or NULL)
853  * @param filename name of the binary
854  * @param ... NULL-terminated list of arguments to the process
855  *
856  * @return pointer to process structure of the new process, NULL on error
857  *
858  */
859 struct GNUNET_OS_Process *
860 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
861                          struct GNUNET_DISK_PipeHandle *pipe_stdout,
862                          const char *filename, ...)
863 {
864   struct GNUNET_OS_Process *ret;
865   va_list ap;
866
867   va_start (ap, filename);
868   ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
869   va_end (ap);
870   return ret;
871 }
872
873
874 /**
875  * Start a process.
876  *
877  * @param lsocks array of listen sockets to dup systemd-style (or NULL);
878  *         must be NULL on platforms where dup is not supported
879  * @param filename name of the binary
880  * @param argv NULL-terminated list of arguments to the process
881  * @return process ID of the new process, -1 on error
882  */
883 struct GNUNET_OS_Process *
884 GNUNET_OS_start_process_v (const SOCKTYPE *lsocks,
885                            const char *filename,
886                            char *const argv[])
887 {
888 #if ENABLE_WINDOWS_WORKAROUNDS
889   struct GNUNET_DISK_FileHandle *control_pipe = NULL;
890   char *childpipename = NULL;
891 #endif
892
893 #ifndef MINGW
894   pid_t ret;
895   char lpid[16];
896   char fds[16];
897   struct GNUNET_OS_Process *gnunet_proc = NULL;
898   int i;
899   int j;
900   int k;
901   int tgt;
902   int flags;
903   int *lscp;
904   unsigned int ls;
905
906 #if ENABLE_WINDOWS_WORKAROUNDS
907   control_pipe =
908       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
909                                 GNUNET_DISK_PERM_USER_READ |
910                                 GNUNET_DISK_PERM_USER_WRITE);
911   if (control_pipe == NULL)
912     return NULL;
913 #endif
914
915   lscp = NULL;
916   ls = 0;
917   if (lsocks != NULL)
918   {
919     i = 0;
920     while (-1 != (k = lsocks[i++]))
921       GNUNET_array_append (lscp, ls, k);
922     GNUNET_array_append (lscp, ls, -1);
923   }
924   ret = fork ();
925   if (ret != 0)
926   {
927     if (ret == -1)
928     {
929       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
930 #if ENABLE_WINDOWS_WORKAROUNDS
931       GNUNET_DISK_npipe_close (control_pipe);
932 #endif
933     }
934     else
935     {
936       gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
937       gnunet_proc->pid = ret;
938 #if ENABLE_WINDOWS_WORKAROUNDS
939       gnunet_proc->control_pipe = control_pipe;
940
941 #endif
942     }
943     GNUNET_array_grow (lscp, ls, 0);
944 #if ENABLE_WINDOWS_WORKAROUNDS
945     GNUNET_free (childpipename);
946 #endif
947     return gnunet_proc;
948   }
949
950 #if ENABLE_WINDOWS_WORKAROUNDS
951   setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
952   GNUNET_free (childpipename);
953 #endif
954
955   if (lscp != NULL)
956   {
957     /* read systemd documentation... */
958     GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
959     setenv ("LISTEN_PID", lpid, 1);
960     i = 0;
961     tgt = 3;
962     while (-1 != lscp[i])
963     {
964       j = i + 1;
965       while (-1 != lscp[j])
966       {
967         if (lscp[j] == tgt)
968         {
969           /* dup away */
970           k = dup (lscp[j]);
971           GNUNET_assert (-1 != k);
972           GNUNET_assert (0 == close (lscp[j]));
973           lscp[j] = k;
974           break;
975         }
976         j++;
977       }
978       if (lscp[i] != tgt)
979       {
980         /* Bury any existing FD, no matter what; they should all be closed
981          * on exec anyway and the important onces have been dup'ed away */
982         (void) close (tgt);
983         GNUNET_assert (-1 != dup2 (lscp[i], tgt));
984       }
985       /* unset close-on-exec flag */
986       flags = fcntl (tgt, F_GETFD);
987       GNUNET_assert (flags >= 0);
988       flags &= ~FD_CLOEXEC;
989       fflush (stderr);
990       (void) fcntl (tgt, F_SETFD, flags);
991       tgt++;
992       i++;
993     }
994     GNUNET_snprintf (fds, sizeof (fds), "%u", i);
995     setenv ("LISTEN_FDS", fds, 1);
996   }
997   GNUNET_array_grow (lscp, ls, 0);
998   execvp (filename, argv);
999   LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
1000   _exit (1);
1001 #else
1002   char **arg, **non_const_argv;
1003   unsigned int cmdlen;
1004   char *cmd, *idx;
1005   STARTUPINFOW start;
1006   PROCESS_INFORMATION proc;
1007   int argcount = 0;
1008   struct GNUNET_OS_Process *gnunet_proc = NULL;
1009
1010   char path[MAX_PATH + 1];
1011
1012   char *our_env[5] = { NULL, NULL, NULL, NULL, NULL };
1013   char *env_block = NULL;
1014   char *pathbuf;
1015   DWORD pathbuf_len, alloc_len;
1016   char *self_prefix;
1017   char *bindir;
1018   char *libdir;
1019   char *ptr;
1020   char *non_const_filename;
1021   struct GNUNET_DISK_PipeHandle *lsocks_pipe;
1022   const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
1023   HANDLE lsocks_read;
1024   HANDLE lsocks_write;
1025   wchar_t wpath[MAX_PATH + 1], wcmd[32768];
1026
1027   int fail;
1028
1029   /* Search in prefix dir (hopefully - the directory from which
1030    * the current module was loaded), bindir and libdir, then in PATH
1031    */
1032   self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1033   bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1034   libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1035
1036   pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1037
1038   alloc_len =
1039       pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1040       strlen (libdir);
1041
1042   pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1043
1044   ptr = pathbuf;
1045   ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1046   GNUNET_free (self_prefix);
1047   GNUNET_free (bindir);
1048   GNUNET_free (libdir);
1049
1050   alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1051   if (alloc_len != pathbuf_len - 1)
1052   {
1053     GNUNET_free (pathbuf);
1054     errno = ENOSYS;             /* PATH changed on the fly. What kind of error is that? */
1055     return NULL;
1056   }
1057
1058   cmdlen = strlen (filename);
1059   if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1060     GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1061   else
1062     GNUNET_asprintf (&non_const_filename, "%s", filename);
1063
1064   /* Check that this is the full path. If it isn't, search. */
1065   if (non_const_filename[1] == ':')
1066     snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1067   else if (!SearchPathA
1068            (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1069             path, NULL))
1070   {
1071     SetErrnoFromWinError (GetLastError ());
1072     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1073                        non_const_filename);
1074     GNUNET_free (non_const_filename);
1075     GNUNET_free (pathbuf);
1076     return NULL;
1077   }
1078   GNUNET_free (pathbuf);
1079   GNUNET_free (non_const_filename);
1080
1081   /* Count the number of arguments */
1082   arg = (char **) argv;
1083   while (*arg)
1084   {
1085     arg++;
1086     argcount++;
1087   }
1088
1089   /* Allocate a copy argv */
1090   non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1091
1092   /* Copy all argv strings */
1093   argcount = 0;
1094   arg = (char **) argv;
1095   while (*arg)
1096   {
1097     if (arg == argv)
1098       non_const_argv[argcount] = GNUNET_strdup (path);
1099     else
1100       non_const_argv[argcount] = GNUNET_strdup (*arg);
1101     arg++;
1102     argcount++;
1103   }
1104   non_const_argv[argcount] = NULL;
1105
1106   /* Count cmd len */
1107   cmdlen = 1;
1108   arg = non_const_argv;
1109   while (*arg)
1110   {
1111     cmdlen = cmdlen + strlen (*arg) + 4;
1112     arg++;
1113   }
1114
1115   /* Allocate and create cmd */
1116   cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1117   arg = non_const_argv;
1118   while (*arg)
1119   {
1120     char arg_last_char = (*arg)[strlen (*arg) - 1];
1121     idx += sprintf (idx, "\"%s%s\"%s", *arg,
1122         arg_last_char == '\\' ? "\\" : "", *(arg + 1) ? " " : "");
1123     arg++;
1124   }
1125
1126   while (argcount > 0)
1127     GNUNET_free (non_const_argv[--argcount]);
1128   GNUNET_free (non_const_argv);
1129
1130   memset (&start, 0, sizeof (start));
1131   start.cb = sizeof (start);
1132
1133   control_pipe =
1134       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1135                                 GNUNET_DISK_PERM_USER_READ |
1136                                 GNUNET_DISK_PERM_USER_WRITE);
1137   if (control_pipe == NULL)
1138   {
1139     GNUNET_free (cmd);
1140     GNUNET_free (path);
1141     return NULL;
1142   }
1143   if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1144   {
1145     lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
1146
1147     if (lsocks_pipe == NULL)
1148     {
1149       GNUNET_free (cmd);
1150       GNUNET_free (path);
1151       GNUNET_DISK_pipe_close (lsocks_pipe);
1152       return NULL;
1153     }
1154     lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
1155         GNUNET_DISK_PIPE_END_WRITE);
1156     GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1157                                        &lsocks_write, sizeof (HANDLE));
1158     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1159                                        (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1160                                        &lsocks_read, sizeof (HANDLE));
1161   }
1162
1163 #if DEBUG_OS
1164   LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1165        childpipename);
1166 #endif
1167
1168   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1169   GNUNET_asprintf (&our_env[1], "%s", childpipename);
1170   GNUNET_free (childpipename);
1171   if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1172     our_env[2] = NULL;
1173   else
1174   {
1175     /*This will tell the child that we're going to send lsocks over the pipe*/
1176     GNUNET_asprintf (&our_env[2], "%s=", "GNUNET_OS_READ_LSOCKS");
1177     GNUNET_asprintf (&our_env[3], "%lu", lsocks_read);
1178     our_env[4] = NULL;
1179   }
1180   env_block = CreateCustomEnvTable (our_env);
1181   GNUNET_free_non_null (our_env[0]);
1182   GNUNET_free_non_null (our_env[1]);
1183   GNUNET_free_non_null (our_env[2]);
1184   GNUNET_free_non_null (our_env[3]);
1185
1186   if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath)
1187       || ERROR_SUCCESS != plibc_conv_to_win_pathwconv(cmd, wcmd)
1188       || !CreateProcessW
1189       (wpath, wcmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
1190        env_block, NULL, &start, &proc))
1191   {
1192     SetErrnoFromWinError (GetLastError ());
1193     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1194     GNUNET_DISK_npipe_close (control_pipe);
1195     if (lsocks != NULL)
1196       GNUNET_DISK_pipe_close (lsocks_pipe);
1197     GNUNET_free (env_block);
1198     GNUNET_free (cmd);
1199     return NULL;
1200   }
1201
1202   GNUNET_free (env_block);
1203
1204   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1205   gnunet_proc->pid = proc.dwProcessId;
1206   gnunet_proc->handle = proc.hProcess;
1207   gnunet_proc->control_pipe = control_pipe;
1208
1209   CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
1210
1211   ResumeThread (proc.hThread);
1212   CloseHandle (proc.hThread);
1213   GNUNET_free (cmd);
1214
1215   if (lsocks == NULL || lsocks[0] == INVALID_SOCKET)
1216     return gnunet_proc;
1217
1218   GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1219
1220   /* This is a replacement for "goto error" that doesn't use goto */
1221   fail = 1;
1222   do
1223   {
1224     int wrote;
1225     uint64_t size, count, i;
1226
1227     /* Tell the number of sockets */
1228     for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1229
1230     wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1231     if (wrote != sizeof (count))
1232     {
1233       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u count bytes to the child: %u\n", sizeof (count), GetLastError ());
1234       break;
1235     }
1236     for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1237     {
1238       WSAPROTOCOL_INFOA pi;
1239       /* Get a socket duplication info */
1240       if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1241       {
1242         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to duplicate an socket[%llu]: %u\n", i, GetLastError ());
1243         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1244         break;
1245       }
1246       /* Synchronous I/O is not nice, but we can't schedule this:
1247        * lsocks will be closed/freed by the caller soon, and until
1248        * the child creates a duplicate, closing a socket here will
1249        * close it for good.
1250        */
1251       /* Send the size of the structure
1252        * (the child might be built with different headers...)
1253        */
1254       size = sizeof (pi);
1255       wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1256       if (wrote != sizeof (size))
1257       {
1258         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u size[%llu] bytes to the child: %u\n", sizeof (size), i, GetLastError ());
1259         break;
1260       }
1261       /* Finally! Send the data */
1262       wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1263       if (wrote != sizeof (pi))
1264       {
1265         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to write %u socket[%llu] bytes to the child: %u\n", sizeof (pi), i, GetLastError ());
1266         break;
1267       }
1268     }
1269     /* This will block us until the child makes a final read or closes
1270      * the pipe (hence no 'wrote' check), since we have to wait for it
1271      * to duplicate the last socket, before we return and start closing
1272      * our own copies)
1273      */
1274     wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1275     fail = 0;
1276   }
1277   while (fail);
1278
1279   GNUNET_DISK_file_sync (lsocks_write_fd);
1280   GNUNET_DISK_pipe_close (lsocks_pipe);
1281
1282   if (fail)
1283   {
1284     /* If we can't pass on the socket(s), the child will block forever,
1285      * better put it out of its misery.
1286      */
1287     TerminateProcess (gnunet_proc->handle, 0);
1288     CloseHandle (gnunet_proc->handle);
1289     GNUNET_DISK_npipe_close (gnunet_proc->control_pipe);
1290     GNUNET_free (gnunet_proc);
1291     return NULL;
1292   }
1293
1294   return gnunet_proc;
1295 #endif
1296 }
1297
1298
1299 /**
1300  * Retrieve the status of a process
1301  * @param proc process ID
1302  * @param type status type
1303  * @param code return code/signal number
1304  * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1305  */
1306 int
1307 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1308                           enum GNUNET_OS_ProcessStatusType *type,
1309                           unsigned long *code)
1310 {
1311 #ifndef MINGW
1312   int status;
1313   int ret;
1314
1315   GNUNET_assert (0 != proc);
1316   ret = waitpid (proc->pid, &status, WNOHANG);
1317   if (ret < 0)
1318   {
1319     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1320     return GNUNET_SYSERR;
1321   }
1322   if (0 == ret)
1323   {
1324     *type = GNUNET_OS_PROCESS_RUNNING;
1325     *code = 0;
1326     return GNUNET_NO;
1327   }
1328   if (proc->pid != ret)
1329   {
1330     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1331     return GNUNET_SYSERR;
1332   }
1333   if (WIFEXITED (status))
1334   {
1335     *type = GNUNET_OS_PROCESS_EXITED;
1336     *code = WEXITSTATUS (status);
1337   }
1338   else if (WIFSIGNALED (status))
1339   {
1340     *type = GNUNET_OS_PROCESS_SIGNALED;
1341     *code = WTERMSIG (status);
1342   }
1343   else if (WIFSTOPPED (status))
1344   {
1345     *type = GNUNET_OS_PROCESS_SIGNALED;
1346     *code = WSTOPSIG (status);
1347   }
1348 #ifdef WIFCONTINUED
1349   else if (WIFCONTINUED (status))
1350   {
1351     *type = GNUNET_OS_PROCESS_RUNNING;
1352     *code = 0;
1353   }
1354 #endif
1355   else
1356   {
1357     *type = GNUNET_OS_PROCESS_UNKNOWN;
1358     *code = 0;
1359   }
1360 #else
1361   HANDLE h;
1362   DWORD c, error_code, ret;
1363
1364   h = proc->handle;
1365   ret = proc->pid;
1366   if (h == NULL || ret == 0)
1367   {
1368     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1369          ret, h);
1370     return GNUNET_SYSERR;
1371   }
1372   if (h == NULL)
1373     h = GetCurrentProcess ();
1374
1375   SetLastError (0);
1376   ret = GetExitCodeProcess (h, &c);
1377   error_code = GetLastError ();
1378   if (ret == 0 || error_code != NO_ERROR)
1379   {
1380     SetErrnoFromWinError (error_code);
1381     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1382     return GNUNET_SYSERR;
1383   }
1384   if (STILL_ACTIVE == c)
1385   {
1386     *type = GNUNET_OS_PROCESS_RUNNING;
1387     *code = 0;
1388     return GNUNET_NO;
1389   }
1390   *type = GNUNET_OS_PROCESS_EXITED;
1391   *code = c;
1392 #endif
1393
1394   return GNUNET_OK;
1395 }
1396
1397
1398 /**
1399  * Wait for a process
1400  * @param proc pointer to process structure
1401  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1402  */
1403 int
1404 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1405 {
1406
1407 #ifndef MINGW
1408   pid_t pid = proc->pid;
1409   pid_t ret;
1410
1411   while ( (pid != (ret = waitpid (pid, NULL, 0))) &&
1412           (EINTR == errno) ) ;
1413   if (pid != ret) 
1414   {
1415     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1416     return GNUNET_SYSERR;
1417   }
1418   return GNUNET_OK;
1419 #else
1420   HANDLE h;
1421   int ret;
1422
1423   h = proc->handle;
1424   if (NULL == h)
1425   {
1426     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1427          proc->pid, h);
1428     return GNUNET_SYSERR;
1429   }
1430   if (h == NULL)
1431     h = GetCurrentProcess ();
1432
1433   if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1434   {
1435     SetErrnoFromWinError (GetLastError ());
1436     ret = GNUNET_SYSERR;
1437   }
1438   else
1439     ret = GNUNET_OK;
1440
1441   return ret;
1442 #endif
1443 }
1444
1445
1446 /**
1447  * Handle to a command.
1448  */
1449 struct GNUNET_OS_CommandHandle
1450 {
1451
1452   /**
1453    * Process handle.
1454    */
1455   struct GNUNET_OS_Process *eip;
1456
1457   /**
1458    * Handle to the output pipe.
1459    */
1460   struct GNUNET_DISK_PipeHandle *opipe;
1461
1462   /**
1463    * Read-end of output pipe.
1464    */
1465   const struct GNUNET_DISK_FileHandle *r;
1466
1467   /**
1468    * Function to call on each line of output.
1469    */
1470   GNUNET_OS_LineProcessor proc;
1471
1472   /**
1473    * Closure for 'proc'.
1474    */
1475   void *proc_cls;
1476
1477   /**
1478    * Buffer for the output.
1479    */
1480   char buf[1024];
1481
1482   /**
1483    * Task reading from pipe.
1484    */
1485   GNUNET_SCHEDULER_TaskIdentifier rtask;
1486
1487   /**
1488    * When to time out.
1489    */
1490   struct GNUNET_TIME_Absolute timeout;
1491
1492   /**
1493    * Current read offset in buf.
1494    */
1495   size_t off;
1496 };
1497
1498
1499 /**
1500  * Stop/kill a command.  Must ONLY be called either from
1501  * the callback after 'NULL' was passed for 'line' *OR*
1502  * from an independent task (not within the line processor).
1503  *
1504  * @param cmd handle to the process
1505  */
1506 void
1507 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1508 {
1509
1510   if (cmd->proc != NULL)
1511   {
1512     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1513     GNUNET_SCHEDULER_cancel (cmd->rtask);
1514   }
1515   (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1516   GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1517   GNUNET_OS_process_close (cmd->eip);
1518   GNUNET_DISK_pipe_close (cmd->opipe);
1519   GNUNET_free (cmd);
1520 }
1521
1522
1523 /**
1524  * Read from the process and call the line processor.
1525  *
1526  * @param cls the 'struct GNUNET_OS_CommandHandle'
1527  * @param tc scheduler context
1528  */
1529 static void
1530 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1531 {
1532   struct GNUNET_OS_CommandHandle *cmd = cls;
1533   GNUNET_OS_LineProcessor proc;
1534   char *end;
1535   ssize_t ret;
1536
1537   cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1538   if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1539   {
1540     /* timeout, shutdown, etc. */
1541     proc = cmd->proc;
1542     cmd->proc = NULL;
1543     proc (cmd->proc_cls, NULL);
1544     return;
1545   }
1546   ret =
1547       GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1548                              sizeof (cmd->buf) - cmd->off);
1549   if (ret <= 0)
1550   {
1551     if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1552     {
1553       cmd->buf[cmd->off] = '\0';
1554       cmd->proc (cmd->proc_cls, cmd->buf);
1555     }
1556     proc = cmd->proc;
1557     cmd->proc = NULL;
1558     proc (cmd->proc_cls, NULL);
1559     return;
1560   }
1561   end = memchr (&cmd->buf[cmd->off], '\n', ret);
1562   cmd->off += ret;
1563   while (end != NULL)
1564   {
1565     *end = '\0';
1566     cmd->proc (cmd->proc_cls, cmd->buf);
1567     memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1568     cmd->off -= (end + 1 - cmd->buf);
1569     end = memchr (cmd->buf, '\n', cmd->off);
1570   }
1571   cmd->rtask =
1572       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1573                                       (cmd->timeout), cmd->r, &cmd_read, cmd);
1574 }
1575
1576
1577 /**
1578  * Run the given command line and call the given function
1579  * for each line of the output.
1580  *
1581  * @param proc function to call for each line of the output
1582  * @param proc_cls closure for proc
1583  * @param timeout when to time out
1584  * @param binary command to run
1585  * @param ... arguments to command
1586  * @return NULL on error
1587  */
1588 struct GNUNET_OS_CommandHandle *
1589 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1590                        struct GNUNET_TIME_Relative timeout, const char *binary,
1591                        ...)
1592 {
1593   struct GNUNET_OS_CommandHandle *cmd;
1594   struct GNUNET_OS_Process *eip;
1595   struct GNUNET_DISK_PipeHandle *opipe;
1596   va_list ap;
1597
1598   opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1599   if (NULL == opipe)
1600     return NULL;
1601   va_start (ap, binary);
1602   eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1603   va_end (ap);
1604   if (NULL == eip)
1605   {
1606     GNUNET_DISK_pipe_close (opipe);
1607     return NULL;
1608   }
1609   GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1610   cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1611   cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1612   cmd->eip = eip;
1613   cmd->opipe = opipe;
1614   cmd->proc = proc;
1615   cmd->proc_cls = proc_cls;
1616   cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1617   cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1618   return cmd;
1619 }
1620
1621
1622
1623
1624 /* end of os_priority.c */