add units to time, use configuration time api where appropriate, fixing Mantis #1875
[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 "disk.h"
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34
35 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36
37 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
38
39 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
40
41 struct GNUNET_OS_Process
42 {
43   pid_t pid;
44 #if WINDOWS
45   HANDLE handle;
46 #endif
47   int sig;
48   struct GNUNET_DISK_FileHandle *control_pipe;
49 };
50
51 static struct GNUNET_OS_Process current_process;
52
53
54 /**
55  * This handler is called when there are control data to be read on the pipe
56  *
57  * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
58  * @param tc scheduler context
59  */
60 static void
61 parent_control_handler (void *cls,
62                         const struct GNUNET_SCHEDULER_TaskContext *tc)
63 {
64   struct GNUNET_DISK_FileHandle *control_pipe =
65       (struct GNUNET_DISK_FileHandle *) cls;
66   int sig;
67
68 #if DEBUG_OS
69   LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
70        tc->reason);
71 #endif
72   if (tc->reason &
73       (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT |
74        GNUNET_SCHEDULER_REASON_PREREQ_DONE))
75   {
76     GNUNET_DISK_npipe_close (control_pipe);
77   }
78   else
79   {
80     if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) !=
81         sizeof (sig))
82     {
83       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
84       GNUNET_DISK_npipe_close (control_pipe);
85     }
86     else
87     {
88 #if DEBUG_OS
89       LOG (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
90 #endif
91       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
92                                       control_pipe, &parent_control_handler,
93                                       control_pipe);
94       raise (sig);
95     }
96   }
97 }
98
99
100 /**
101  * Task that connects this process to its parent via pipe
102  */
103 void
104 GNUNET_OS_install_parent_control_handler (void *cls,
105                                           const struct
106                                           GNUNET_SCHEDULER_TaskContext *tc)
107 {
108   const char *env_buf;
109   struct GNUNET_DISK_FileHandle *control_pipe;
110
111   env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
112   if ((env_buf == NULL) || (strlen (env_buf) <= 0))
113   {
114     LOG (GNUNET_ERROR_TYPE_INFO, _("Not installing a handler because $%s=%s\n"),
115          GNUNET_OS_CONTROL_PIPE, env_buf);
116     return;
117   }
118   control_pipe =
119       GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
120                               GNUNET_DISK_PERM_USER_READ |
121                               GNUNET_DISK_PERM_USER_WRITE);
122   if (control_pipe == NULL)
123   {
124     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
125     return;
126   }
127 #if DEBUG_OS
128   LOG (GNUNET_ERROR_TYPE_DEBUG,
129        "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
130 #endif
131   GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
132                                   &parent_control_handler, control_pipe);
133 }
134
135
136 /**
137  * Get process structure for current process
138  *
139  * The pointer it returns points to static memory location and must not be
140  * deallocated/closed
141  *
142  * @return pointer to the process sturcutre for this process
143  */
144 struct GNUNET_OS_Process *
145 GNUNET_OS_process_current ()
146 {
147 #if WINDOWS
148   current_process.pid = GetCurrentProcessId ();
149   current_process.handle = GetCurrentProcess ();
150 #else
151   current_process.pid = 0;
152 #endif
153   return &current_process;
154 }
155
156
157 int
158 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
159 {
160 #if ENABLE_WINDOWS_WORKAROUNDS
161   int res = 0;
162   int ret = 0;
163
164   ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
165   if (ret != sizeof (sig))
166   {
167     if (errno == ECOMM)
168     {
169       /* Child process is not controllable via pipe */
170 #if DEBUG_OS
171       LOG (GNUNET_ERROR_TYPE_DEBUG,
172            "Child process is not controllable, will kill it directly\n");
173 #endif
174     }
175     else if (errno == EPIPE)
176     {
177 #if DEBUG_OS
178       LOG (GNUNET_ERROR_TYPE_DEBUG,
179            "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
180 #endif
181     }
182     else
183       LOG (GNUNET_ERROR_TYPE_WARNING,
184            "Failed to write into control pipe , errno is %d\n", errno);
185 #if WINDOWS && !defined(__CYGWIN__)
186     TerminateProcess (proc->handle, 0);
187 #else
188     PLIBC_KILL (proc->pid, sig);
189 #endif
190   }
191   else
192   {
193 #if DEBUG_OS
194     LOG (GNUNET_ERROR_TYPE_DEBUG,
195          "Wrote control code into control pipe, now waiting\n");
196 #endif
197
198 #if WINDOWS
199     /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
200     if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
201       TerminateProcess (proc->handle, 0);
202     res = 0;
203 #else
204     struct GNUNET_NETWORK_FDSet *rfds;
205     struct GNUNET_NETWORK_FDSet *efds;
206
207     rfds = GNUNET_NETWORK_fdset_create ();
208     efds = GNUNET_NETWORK_fdset_create ();
209
210     GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
211     GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
212
213     /* Ndurner thought this up, and i have no idea what it does.
214      * There's have never been any code to answer the shutdown call
215      * (write a single int into the pipe, so that this function can read it).
216      * On *nix select() will probably tell that pipe is ready
217      * for reading, once the other process shuts down,
218      * but the read () call will fail, triggering a kill ()
219      * on the pid that is already dead. This will probably result in non-0
220      * return from kill(), and therefore from this function.
221      */
222     while (1)
223     {
224       ret =
225           GNUNET_NETWORK_socket_select (rfds, NULL, efds,
226                                         GNUNET_TIME_relative_multiply
227                                         (GNUNET_TIME_relative_get_unit (),
228                                          5000));
229
230       if (ret < 1 ||
231           GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
232       {
233         /* Just to be sure */
234         PLIBC_KILL (proc->pid, sig);
235         res = 0;
236         break;
237       }
238       else
239       {
240         if (GNUNET_DISK_file_read (proc->control_pipe, &ret, sizeof (ret)) !=
241             GNUNET_OK)
242           res = PLIBC_KILL (proc->pid, sig);
243
244         /* Child signaled shutdown is in progress */
245         continue;
246       }
247     }
248 #endif
249   }
250
251   return res;
252 #else
253   return kill (proc->pid, sig);
254 #endif
255 }
256
257 /**
258  * Get the pid of the process in question
259  *
260  * @param proc the process to get the pid of
261  *
262  * @return the current process id
263  */
264 pid_t
265 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
266 {
267   return proc->pid;
268 }
269
270
271 void
272 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
273 {
274 #if ENABLE_WINDOWS_WORKAROUNDS
275   if (proc->control_pipe)
276     GNUNET_DISK_npipe_close (proc->control_pipe);
277 #endif
278 // FIXME NILS
279 #ifdef WINDOWS
280   if (proc->handle != NULL)
281     CloseHandle (proc->handle);
282 #endif
283   GNUNET_free (proc);
284 }
285
286 // FIXME NILS
287 #if WINDOWS
288 #include "gnunet_signal_lib.h"
289
290 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
291
292 /**
293  * Make seaspider happy.
294  */
295 #define DWORD_WINAPI DWORD WINAPI
296
297 /**
298  * @brief Waits for a process to terminate and invokes the SIGCHLD handler
299  * @param proc pointer to process structure
300  */
301 static DWORD_WINAPI
302 ChildWaitThread (void *arg)
303 {
304   struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
305
306   WaitForSingleObject (proc->handle, INFINITE);
307
308   if (w32_sigchld_handler)
309     w32_sigchld_handler ();
310
311   return 0;
312 }
313 #endif
314
315 /**
316  * Set process priority
317  *
318  * @param proc pointer to process structure
319  * @param prio priority value
320  * @return GNUNET_OK on success, GNUNET_SYSERR on error
321  */
322 int
323 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
324                                 enum GNUNET_SCHEDULER_Priority prio)
325 {
326   int rprio;
327
328   GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
329   if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
330     return GNUNET_OK;
331
332   /* convert to MINGW/Unix values */
333   switch (prio)
334   {
335   case GNUNET_SCHEDULER_PRIORITY_UI:
336   case GNUNET_SCHEDULER_PRIORITY_URGENT:
337 #ifdef MINGW
338     rprio = HIGH_PRIORITY_CLASS;
339 #else
340     rprio = 0;
341 #endif
342     break;
343
344   case GNUNET_SCHEDULER_PRIORITY_HIGH:
345 #ifdef MINGW
346     rprio = ABOVE_NORMAL_PRIORITY_CLASS;
347 #else
348     rprio = 5;
349 #endif
350     break;
351
352   case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
353 #ifdef MINGW
354     rprio = NORMAL_PRIORITY_CLASS;
355 #else
356     rprio = 7;
357 #endif
358     break;
359
360   case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
361 #ifdef MINGW
362     rprio = BELOW_NORMAL_PRIORITY_CLASS;
363 #else
364     rprio = 10;
365 #endif
366     break;
367
368   case GNUNET_SCHEDULER_PRIORITY_IDLE:
369 #ifdef MINGW
370     rprio = IDLE_PRIORITY_CLASS;
371 #else
372     rprio = 19;
373 #endif
374     break;
375   default:
376     GNUNET_assert (0);
377     return GNUNET_SYSERR;
378   }
379
380   /* Set process priority */
381 #ifdef MINGW
382   {
383     HANDLE h = proc->handle;
384
385     GNUNET_assert (h != NULL);
386     SetPriorityClass (h, rprio);
387   }
388 #elif LINUX
389   pid_t pid;
390
391   pid = proc->pid;
392   if ((0 == pid) || (pid == getpid ()))
393   {
394     int have = nice (0);
395     int delta = rprio - have;
396
397     errno = 0;
398     if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
399     {
400       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
401       return GNUNET_SYSERR;
402     }
403   }
404   else
405   {
406     if (0 != setpriority (PRIO_PROCESS, pid, rprio))
407     {
408       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
409                     "setpriority");
410       return GNUNET_SYSERR;
411     }
412   }
413 #else
414 #if DEBUG_OS
415   LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
416        "Priority management not availabe for this platform\n");
417 #endif
418 #endif
419   return GNUNET_OK;
420 }
421
422 #if MINGW
423 static char *
424 CreateCustomEnvTable (char **vars)
425 {
426   char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
427   size_t tablesize = 0;
428   size_t items_count = 0;
429   size_t n_found = 0, n_var;
430   char *index = NULL;
431   size_t c;
432   size_t var_len;
433   char *var;
434   char *val;
435
436   win32_env_table = GetEnvironmentStringsA ();
437   if (win32_env_table == NULL)
438     return NULL;
439   for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
440   n_var = c;
441   index = GNUNET_malloc (sizeof (char *) * n_var);
442   for (c = 0; c < n_var; c++)
443     index[c] = 0;
444   for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
445   {
446     size_t len = strlen (ptr);
447     int found = 0;
448
449     for (var_ptr = vars; *var_ptr; var_ptr++)
450     {
451       var = *var_ptr++;
452       val = *var_ptr;
453       var_len = strlen (var);
454       if (strncmp (var, ptr, var_len) == 0)
455       {
456         found = 1;
457         index[c] = 1;
458         tablesize += var_len + strlen (val) + 1;
459         break;
460       }
461     }
462     if (!found)
463       tablesize += len + 1;
464     ptr += len + 1;
465   }
466   for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
467   {
468     var = *var_ptr++;
469     val = *var_ptr;
470     if (index[c] != 1)
471       n_found += strlen (var) + strlen (val) + 1;
472   }
473   result = GNUNET_malloc (tablesize + n_found + 1);
474   for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
475   {
476     size_t len = strlen (ptr);
477     int found = 0;
478
479     for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
480     {
481       var = *var_ptr++;
482       val = *var_ptr;
483       var_len = strlen (var);
484       if (strncmp (var, ptr, var_len) == 0)
485       {
486         found = 1;
487         break;
488       }
489     }
490     if (!found)
491     {
492       strcpy (result_ptr, ptr);
493       result_ptr += len + 1;
494     }
495     else
496     {
497       strcpy (result_ptr, var);
498       result_ptr += var_len;
499       strcpy (result_ptr, val);
500       result_ptr += strlen (val) + 1;
501     }
502     ptr += len + 1;
503   }
504   for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
505   {
506     var = *var_ptr++;
507     val = *var_ptr;
508     var_len = strlen (var);
509     if (index[c] != 1)
510     {
511       strcpy (result_ptr, var);
512       result_ptr += var_len;
513       strcpy (result_ptr, val);
514       result_ptr += strlen (val) + 1;
515     }
516   }
517   FreeEnvironmentStrings (win32_env_table);
518   GNUNET_free (index);
519   *result_ptr = 0;
520   return result;
521 }
522 #endif
523
524
525 /**
526  * Start a process.
527  *
528  * @param pipe_stdin pipe to use to send input to child process (or NULL)
529  * @param pipe_stdout pipe to use to get output from child process (or NULL)
530  * @param filename name of the binary
531  * @param va NULL-terminated list of arguments to the process
532  * @return pointer to process structure of the new process, NULL on error
533  */
534 struct GNUNET_OS_Process *
535 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
536                             struct GNUNET_DISK_PipeHandle *pipe_stdout,
537                             const char *filename, va_list va)
538 {
539   va_list ap;
540
541 #if ENABLE_WINDOWS_WORKAROUNDS
542   char *childpipename = NULL;
543   struct GNUNET_DISK_FileHandle *control_pipe = NULL;
544 #endif
545   struct GNUNET_OS_Process *gnunet_proc = NULL;
546
547 #ifndef MINGW
548   pid_t ret;
549   char **argv;
550   int argc;
551   int fd_stdout_write;
552   int fd_stdout_read;
553   int fd_stdin_read;
554   int fd_stdin_write;
555
556 #if ENABLE_WINDOWS_WORKAROUNDS
557   control_pipe =
558       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
559                                 GNUNET_DISK_PERM_USER_READ |
560                                 GNUNET_DISK_PERM_USER_WRITE);
561   if (control_pipe == NULL)
562     return NULL;
563 #endif
564
565   argc = 0;
566   va_copy (ap, va);
567   while (NULL != va_arg (ap, char *))
568          argc++;
569
570   va_end (ap);
571   argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
572   argc = 0;
573   va_copy (ap, va);
574   while (NULL != (argv[argc] = va_arg (ap, char *)))
575          argc++;
576
577   va_end (ap);
578   if (pipe_stdout != NULL)
579   {
580     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
581                                        (pipe_stdout,
582                                         GNUNET_DISK_PIPE_END_WRITE),
583                                        &fd_stdout_write, sizeof (int));
584     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
585                                        (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
586                                        &fd_stdout_read, sizeof (int));
587   }
588   if (pipe_stdin != NULL)
589   {
590     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
591                                        (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
592                                        &fd_stdin_read, sizeof (int));
593     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
594                                        (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
595                                        &fd_stdin_write, sizeof (int));
596   }
597
598 #if HAVE_WORKING_VFORK
599   ret = vfork ();
600 #else
601   ret = fork ();
602 #endif
603   if (ret != 0)
604   {
605     if (ret == -1)
606     {
607       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
608 #if ENABLE_WINDOWS_WORKAROUNDS
609       GNUNET_DISK_npipe_close (control_pipe);
610 #endif
611     }
612     else
613     {
614
615 #if HAVE_WORKING_VFORK
616       /* let's hope vfork actually works; for some extreme cases (including
617        * a testcase) we need 'execvp' to have run before we return, since
618        * we may send a signal to the process next and we don't want it
619        * to be caught by OUR signal handler (but either by the default
620        * handler or the actual handler as installed by the process itself). */
621 #else
622       /* let's give the child process a chance to run execvp, 1s should
623        * be plenty in practice */
624       if (pipe_stdout != NULL)
625         GNUNET_DISK_pipe_close_end (pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
626       if (pipe_stdin != NULL)
627         GNUNET_DISK_pipe_close_end (pipe_stdin, GNUNET_DISK_PIPE_END_READ);
628       sleep (1);
629 #endif
630       gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
631       gnunet_proc->pid = ret;
632 #if ENABLE_WINDOWS_WORKAROUNDS
633       gnunet_proc->control_pipe = control_pipe;
634 #endif
635     }
636     GNUNET_free (argv);
637 #if ENABLE_WINDOWS_WORKAROUNDS
638     GNUNET_free (childpipename);
639 #endif
640     return gnunet_proc;
641   }
642
643 #if ENABLE_WINDOWS_WORKAROUNDS
644   setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
645   GNUNET_free (childpipename);
646 #endif
647
648   if (pipe_stdout != NULL)
649   {
650     GNUNET_break (0 == close (fd_stdout_read));
651     if (-1 == dup2 (fd_stdout_write, 1))
652       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
653     GNUNET_break (0 == close (fd_stdout_write));
654   }
655
656   if (pipe_stdin != NULL)
657   {
658
659     GNUNET_break (0 == close (fd_stdin_write));
660     if (-1 == dup2 (fd_stdin_read, 0))
661       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
662     GNUNET_break (0 == close (fd_stdin_read));
663   }
664   execvp (filename, argv);
665   LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
666   _exit (1);
667 #else
668   char *arg;
669   unsigned int cmdlen;
670   char *cmd, *idx;
671   STARTUPINFO start;
672   PROCESS_INFORMATION proc;
673
674   HANDLE stdin_handle;
675   HANDLE stdout_handle;
676
677   char path[MAX_PATH + 1];
678
679   char *our_env[3] = { NULL, NULL, NULL };
680   char *env_block = NULL;
681   char *pathbuf;
682   DWORD pathbuf_len, alloc_len;
683   char *self_prefix;
684   char *bindir;
685   char *libdir;
686   char *ptr;
687   char *non_const_filename;
688
689   /* Search in prefix dir (hopefully - the directory from which
690    * the current module was loaded), bindir and libdir, then in PATH
691    */
692   self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
693   bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
694   libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
695
696   pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
697
698   alloc_len =
699       pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
700       strlen (libdir);
701
702   pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
703
704   ptr = pathbuf;
705   ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
706   GNUNET_free (self_prefix);
707   GNUNET_free (bindir);
708   GNUNET_free (libdir);
709
710   alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
711   GNUNET_assert (alloc_len == (pathbuf_len - 1));
712
713   cmdlen = strlen (filename);
714   if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
715     GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
716   else
717     GNUNET_asprintf (&non_const_filename, "%s", filename);
718
719   /* Check that this is the full path. If it isn't, search. */
720   if (non_const_filename[1] == ':')
721     snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
722   else if (!SearchPathA
723            (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
724             path, NULL))
725   {
726     SetErrnoFromWinError (GetLastError ());
727     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
728                        non_const_filename);
729     GNUNET_free (non_const_filename);
730     GNUNET_free (pathbuf);
731     return NULL;
732   }
733   GNUNET_free (pathbuf);
734   GNUNET_free (non_const_filename);
735
736   cmdlen = 0;
737   va_copy (ap, va);
738   while (NULL != (arg = va_arg (ap, char *)))
739   {
740     if (cmdlen == 0)
741       cmdlen = cmdlen + strlen (path) + 3;
742     else
743       cmdlen = cmdlen + strlen (arg) + 3;
744   }
745   va_end (ap);
746
747   cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
748   va_copy (ap, va);
749   while (NULL != (arg = va_arg (ap, char *)))
750   {
751     if (idx == cmd)
752       idx += sprintf (idx, "\"%s\" ", path);
753     else
754       idx += sprintf (idx, "\"%s\" ", arg);
755   }
756   va_end (ap);
757
758   memset (&start, 0, sizeof (start));
759   start.cb = sizeof (start);
760
761   if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
762     start.dwFlags |= STARTF_USESTDHANDLES;
763
764   if (pipe_stdin != NULL)
765   {
766     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
767                                        (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
768                                        &stdin_handle, sizeof (HANDLE));
769     start.hStdInput = stdin_handle;
770   }
771
772   if (pipe_stdout != NULL)
773   {
774     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
775                                        (pipe_stdout,
776                                         GNUNET_DISK_PIPE_END_WRITE),
777                                        &stdout_handle, sizeof (HANDLE));
778     start.hStdOutput = stdout_handle;
779   }
780
781   control_pipe =
782       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
783                                 GNUNET_DISK_PERM_USER_READ |
784                                 GNUNET_DISK_PERM_USER_WRITE);
785   if (control_pipe == NULL)
786   {
787     GNUNET_free (cmd);
788     GNUNET_free (path);
789     return NULL;
790   }
791
792 #if DEBUG_OS
793   LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
794        childpipename);
795 #endif
796
797   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
798   GNUNET_asprintf (&our_env[1], "%s", childpipename);
799   our_env[2] = NULL;
800   env_block = CreateCustomEnvTable (our_env);
801   GNUNET_free (our_env[0]);
802   GNUNET_free (our_env[1]);
803
804   if (!CreateProcessA
805       (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
806        env_block, NULL, &start, &proc))
807   {
808     SetErrnoFromWinError (GetLastError ());
809     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
810     GNUNET_free (env_block);
811     GNUNET_free (cmd);
812     return NULL;
813   }
814
815   GNUNET_free (env_block);
816
817   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
818   gnunet_proc->pid = proc.dwProcessId;
819   gnunet_proc->handle = proc.hProcess;
820   gnunet_proc->control_pipe = control_pipe;
821
822   CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
823
824   ResumeThread (proc.hThread);
825   CloseHandle (proc.hThread);
826
827   GNUNET_free (cmd);
828
829   return gnunet_proc;
830 #endif
831 }
832
833
834 /**
835  * Start a process.
836  *
837  * @param pipe_stdin pipe to use to send input to child process (or NULL)
838  * @param pipe_stdout pipe to use to get output from child process (or NULL)
839  * @param filename name of the binary
840  * @param ... NULL-terminated list of arguments to the process
841  *
842  * @return pointer to process structure of the new process, NULL on error
843  *
844  */
845 struct GNUNET_OS_Process *
846 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
847                          struct GNUNET_DISK_PipeHandle *pipe_stdout,
848                          const char *filename, ...)
849 {
850   struct GNUNET_OS_Process *ret;
851   va_list ap;
852
853   va_start (ap, filename);
854   ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
855   va_end (ap);
856   return ret;
857 }
858
859
860 /**
861  * Start a process.
862  *
863  * @param lsocks array of listen sockets to dup systemd-style (or NULL);
864  *         must be NULL on platforms where dup is not supported
865  * @param filename name of the binary
866  * @param argv NULL-terminated list of arguments to the process
867  * @return process ID of the new process, -1 on error
868  */
869 struct GNUNET_OS_Process *
870 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
871                            char *const argv[])
872 {
873 #if ENABLE_WINDOWS_WORKAROUNDS
874   struct GNUNET_DISK_FileHandle *control_pipe = NULL;
875   char *childpipename = NULL;
876 #endif
877
878 #ifndef MINGW
879   pid_t ret;
880   char lpid[16];
881   char fds[16];
882   struct GNUNET_OS_Process *gnunet_proc = NULL;
883   int i;
884   int j;
885   int k;
886   int tgt;
887   int flags;
888   int *lscp;
889   unsigned int ls;
890
891 #if ENABLE_WINDOWS_WORKAROUNDS
892   control_pipe =
893       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
894                                 GNUNET_DISK_PERM_USER_READ |
895                                 GNUNET_DISK_PERM_USER_WRITE);
896   if (control_pipe == NULL)
897     return NULL;
898 #endif
899
900   lscp = NULL;
901   ls = 0;
902   if (lsocks != NULL)
903   {
904     i = 0;
905     while (-1 != (k = lsocks[i++]))
906       GNUNET_array_append (lscp, ls, k);
907     GNUNET_array_append (lscp, ls, -1);
908   }
909 #if HAVE_WORKING_VFORK
910   ret = vfork ();
911 #else
912   ret = fork ();
913 #endif
914   if (ret != 0)
915   {
916     if (ret == -1)
917     {
918       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
919 #if ENABLE_WINDOWS_WORKAROUNDS
920       GNUNET_DISK_npipe_close (control_pipe);
921 #endif
922     }
923     else
924     {
925 #if HAVE_WORKING_VFORK
926       /* let's hope vfork actually works; for some extreme cases (including
927        * a testcase) we need 'execvp' to have run before we return, since
928        * we may send a signal to the process next and we don't want it
929        * to be caught by OUR signal handler (but either by the default
930        * handler or the actual handler as installed by the process itself). */
931 #else
932       /* let's give the child process a chance to run execvp, 1s should
933        * be plenty in practice */
934       sleep (1);
935 #endif
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   STARTUPINFO 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[3] = { 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
1022   GNUNET_assert (lsocks == NULL);
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
1137 #if DEBUG_OS
1138   LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1139        childpipename);
1140 #endif
1141
1142   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1143   GNUNET_asprintf (&our_env[1], "%s", childpipename);
1144   our_env[2] = NULL;
1145   env_block = CreateCustomEnvTable (our_env);
1146   GNUNET_free (our_env[0]);
1147   GNUNET_free (our_env[1]);
1148
1149   if (!CreateProcess
1150       (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1151        env_block, NULL, &start, &proc))
1152   {
1153     SetErrnoFromWinError (GetLastError ());
1154     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1155     GNUNET_free (env_block);
1156     GNUNET_free (cmd);
1157     return NULL;
1158   }
1159
1160   GNUNET_free (env_block);
1161
1162   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1163   gnunet_proc->pid = proc.dwProcessId;
1164   gnunet_proc->handle = proc.hProcess;
1165   gnunet_proc->control_pipe = control_pipe;
1166
1167   CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1168
1169   ResumeThread (proc.hThread);
1170   CloseHandle (proc.hThread);
1171   GNUNET_free (cmd);
1172
1173   return gnunet_proc;
1174 #endif
1175 }
1176
1177
1178 /**
1179  * Retrieve the status of a process
1180  * @param proc process ID
1181  * @param type status type
1182  * @param code return code/signal number
1183  * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1184  */
1185 int
1186 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1187                           enum GNUNET_OS_ProcessStatusType *type,
1188                           unsigned long *code)
1189 {
1190 #ifndef MINGW
1191   int status;
1192   int ret;
1193
1194   GNUNET_assert (0 != proc);
1195   ret = waitpid (proc->pid, &status, WNOHANG);
1196   if (ret < 0)
1197   {
1198     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1199     return GNUNET_SYSERR;
1200   }
1201   if (0 == ret)
1202   {
1203     *type = GNUNET_OS_PROCESS_RUNNING;
1204     *code = 0;
1205     return GNUNET_NO;
1206   }
1207   if (proc->pid != ret)
1208   {
1209     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1210     return GNUNET_SYSERR;
1211   }
1212   if (WIFEXITED (status))
1213   {
1214     *type = GNUNET_OS_PROCESS_EXITED;
1215     *code = WEXITSTATUS (status);
1216   }
1217   else if (WIFSIGNALED (status))
1218   {
1219     *type = GNUNET_OS_PROCESS_SIGNALED;
1220     *code = WTERMSIG (status);
1221   }
1222   else if (WIFSTOPPED (status))
1223   {
1224     *type = GNUNET_OS_PROCESS_SIGNALED;
1225     *code = WSTOPSIG (status);
1226   }
1227 #ifdef WIFCONTINUED
1228   else if (WIFCONTINUED (status))
1229   {
1230     *type = GNUNET_OS_PROCESS_RUNNING;
1231     *code = 0;
1232   }
1233 #endif
1234   else
1235   {
1236     *type = GNUNET_OS_PROCESS_UNKNOWN;
1237     *code = 0;
1238   }
1239 #else
1240   HANDLE h;
1241   DWORD c, error_code, ret;
1242
1243   h = proc->handle;
1244   ret = proc->pid;
1245   if (h == NULL || ret == 0)
1246   {
1247     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1248          ret, h);
1249     return GNUNET_SYSERR;
1250   }
1251   if (h == NULL)
1252     h = GetCurrentProcess ();
1253
1254   SetLastError (0);
1255   ret = GetExitCodeProcess (h, &c);
1256   error_code = GetLastError ();
1257   if (ret == 0 || error_code != NO_ERROR)
1258   {
1259     SetErrnoFromWinError (error_code);
1260     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1261     return GNUNET_SYSERR;
1262   }
1263   if (STILL_ACTIVE == c)
1264   {
1265     *type = GNUNET_OS_PROCESS_RUNNING;
1266     *code = 0;
1267     return GNUNET_NO;
1268   }
1269   *type = GNUNET_OS_PROCESS_EXITED;
1270   *code = c;
1271 #endif
1272
1273   return GNUNET_OK;
1274 }
1275
1276
1277 /**
1278  * Wait for a process
1279  * @param proc pointer to process structure
1280  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1281  */
1282 int
1283 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1284 {
1285
1286 #ifndef MINGW
1287   pid_t pid = proc->pid;
1288
1289   if (pid != waitpid (pid, NULL, 0))
1290     return GNUNET_SYSERR;
1291   return GNUNET_OK;
1292 #else
1293   HANDLE h;
1294   int ret;
1295
1296   h = proc->handle;
1297   if (NULL == h)
1298   {
1299     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1300          proc->pid, h);
1301     return GNUNET_SYSERR;
1302   }
1303   if (h == NULL)
1304     h = GetCurrentProcess ();
1305
1306   if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1307   {
1308     SetErrnoFromWinError (GetLastError ());
1309     ret = GNUNET_SYSERR;
1310   }
1311   else
1312     ret = GNUNET_OK;
1313
1314   return ret;
1315 #endif
1316 }
1317
1318
1319 /**
1320  * Handle to a command.
1321  */
1322 struct GNUNET_OS_CommandHandle
1323 {
1324
1325   /**
1326    * Process handle.
1327    */
1328   struct GNUNET_OS_Process *eip;
1329
1330   /**
1331    * Handle to the output pipe.
1332    */
1333   struct GNUNET_DISK_PipeHandle *opipe;
1334
1335   /**
1336    * Read-end of output pipe.
1337    */
1338   const struct GNUNET_DISK_FileHandle *r;
1339
1340   /**
1341    * Function to call on each line of output.
1342    */
1343   GNUNET_OS_LineProcessor proc;
1344
1345   /**
1346    * Closure for 'proc'.
1347    */
1348   void *proc_cls;
1349
1350   /**
1351    * Buffer for the output.
1352    */
1353   char buf[1024];
1354
1355   /**
1356    * Task reading from pipe.
1357    */
1358   GNUNET_SCHEDULER_TaskIdentifier rtask;
1359
1360   /**
1361    * When to time out.
1362    */
1363   struct GNUNET_TIME_Absolute timeout;
1364
1365   /**
1366    * Current read offset in buf.
1367    */
1368   size_t off;
1369 };
1370
1371
1372 /**
1373  * Stop/kill a command.  Must ONLY be called either from
1374  * the callback after 'NULL' was passed for 'line' *OR*
1375  * from an independent task (not within the line processor).
1376  *
1377  * @param cmd handle to the process
1378  */
1379 void
1380 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1381 {
1382
1383   if (cmd->proc != NULL)
1384   {
1385     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1386     GNUNET_SCHEDULER_cancel (cmd->rtask);
1387   }
1388   (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1389   GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1390   GNUNET_OS_process_close (cmd->eip);
1391   GNUNET_DISK_pipe_close (cmd->opipe);
1392   GNUNET_free (cmd);
1393 }
1394
1395
1396 /**
1397  * Read from the process and call the line processor.
1398  *
1399  * @param cls the 'struct GNUNET_OS_CommandHandle'
1400  * @param tc scheduler context
1401  */
1402 static void
1403 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1404 {
1405   struct GNUNET_OS_CommandHandle *cmd = cls;
1406   GNUNET_OS_LineProcessor proc;
1407   char *end;
1408   ssize_t ret;
1409
1410   cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1411   if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1412   {
1413     /* timeout, shutdown, etc. */
1414     proc = cmd->proc;
1415     cmd->proc = NULL;
1416     proc (cmd->proc_cls, NULL);
1417     return;
1418   }
1419   ret =
1420       GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1421                              sizeof (cmd->buf) - cmd->off);
1422   if (ret <= 0)
1423   {
1424     if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1425     {
1426       cmd->buf[cmd->off] = '\0';
1427       cmd->proc (cmd->proc_cls, cmd->buf);
1428     }
1429     proc = cmd->proc;
1430     cmd->proc = NULL;
1431     proc (cmd->proc_cls, NULL);
1432     return;
1433   }
1434   end = memchr (&cmd->buf[cmd->off], '\n', ret);
1435   cmd->off += ret;
1436   while (end != NULL)
1437   {
1438     *end = '\0';
1439     cmd->proc (cmd->proc_cls, cmd->buf);
1440     memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1441     cmd->off -= (end + 1 - cmd->buf);
1442     end = memchr (cmd->buf, '\n', cmd->off);
1443   }
1444   cmd->rtask =
1445       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1446                                       (cmd->timeout), cmd->r, &cmd_read, cmd);
1447 }
1448
1449
1450 /**
1451  * Run the given command line and call the given function
1452  * for each line of the output.
1453  *
1454  * @param proc function to call for each line of the output
1455  * @param proc_cls closure for proc
1456  * @param timeout when to time out
1457  * @param binary command to run
1458  * @param ... arguments to command
1459  * @return NULL on error
1460  */
1461 struct GNUNET_OS_CommandHandle *
1462 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1463                        struct GNUNET_TIME_Relative timeout, const char *binary,
1464                        ...)
1465 {
1466   struct GNUNET_OS_CommandHandle *cmd;
1467   struct GNUNET_OS_Process *eip;
1468   struct GNUNET_DISK_PipeHandle *opipe;
1469   va_list ap;
1470
1471   opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1472   if (NULL == opipe)
1473     return NULL;
1474   va_start (ap, binary);
1475   eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1476   va_end (ap);
1477   if (NULL == eip)
1478   {
1479     GNUNET_DISK_pipe_close (opipe);
1480     return NULL;
1481   }
1482   GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1483   cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1484   cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1485   cmd->eip = eip;
1486   cmd->opipe = opipe;
1487   cmd->proc = proc;
1488   cmd->proc_cls = proc_cls;
1489   cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1490   cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1491   return cmd;
1492 }
1493
1494
1495
1496
1497 /* end of os_priority.c */