Implementing Thomas Bushnell's suggestion to work around the signal race without...
[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   ret = fork ();
599   if (ret != 0)
600   {
601     if (ret == -1)
602     {
603       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
604 #if ENABLE_WINDOWS_WORKAROUNDS
605       GNUNET_DISK_npipe_close (control_pipe);
606 #endif
607     }
608     else
609     {
610       gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
611       gnunet_proc->pid = ret;
612 #if ENABLE_WINDOWS_WORKAROUNDS
613       gnunet_proc->control_pipe = control_pipe;
614 #endif
615     }
616     GNUNET_free (argv);
617 #if ENABLE_WINDOWS_WORKAROUNDS
618     GNUNET_free (childpipename);
619 #endif
620     return gnunet_proc;
621   }
622
623 #if ENABLE_WINDOWS_WORKAROUNDS
624   setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
625   GNUNET_free (childpipename);
626 #endif
627
628   if (pipe_stdout != NULL)
629   {
630     GNUNET_break (0 == close (fd_stdout_read));
631     if (-1 == dup2 (fd_stdout_write, 1))
632       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
633     GNUNET_break (0 == close (fd_stdout_write));
634   }
635
636   if (pipe_stdin != NULL)
637   {
638
639     GNUNET_break (0 == close (fd_stdin_write));
640     if (-1 == dup2 (fd_stdin_read, 0))
641       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
642     GNUNET_break (0 == close (fd_stdin_read));
643   }
644   execvp (filename, argv);
645   LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
646   _exit (1);
647 #else
648   char *arg;
649   unsigned int cmdlen;
650   char *cmd, *idx;
651   STARTUPINFO start;
652   PROCESS_INFORMATION proc;
653
654   HANDLE stdin_handle;
655   HANDLE stdout_handle;
656
657   char path[MAX_PATH + 1];
658
659   char *our_env[3] = { NULL, NULL, NULL };
660   char *env_block = NULL;
661   char *pathbuf;
662   DWORD pathbuf_len, alloc_len;
663   char *self_prefix;
664   char *bindir;
665   char *libdir;
666   char *ptr;
667   char *non_const_filename;
668
669   /* Search in prefix dir (hopefully - the directory from which
670    * the current module was loaded), bindir and libdir, then in PATH
671    */
672   self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
673   bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
674   libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
675
676   pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
677
678   alloc_len =
679       pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
680       strlen (libdir);
681
682   pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
683
684   ptr = pathbuf;
685   ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
686   GNUNET_free (self_prefix);
687   GNUNET_free (bindir);
688   GNUNET_free (libdir);
689
690   alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
691   GNUNET_assert (alloc_len == (pathbuf_len - 1));
692
693   cmdlen = strlen (filename);
694   if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
695     GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
696   else
697     GNUNET_asprintf (&non_const_filename, "%s", filename);
698
699   /* Check that this is the full path. If it isn't, search. */
700   if (non_const_filename[1] == ':')
701     snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
702   else if (!SearchPathA
703            (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
704             path, NULL))
705   {
706     SetErrnoFromWinError (GetLastError ());
707     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
708                        non_const_filename);
709     GNUNET_free (non_const_filename);
710     GNUNET_free (pathbuf);
711     return NULL;
712   }
713   GNUNET_free (pathbuf);
714   GNUNET_free (non_const_filename);
715
716   cmdlen = 0;
717   va_copy (ap, va);
718   while (NULL != (arg = va_arg (ap, char *)))
719   {
720     if (cmdlen == 0)
721       cmdlen = cmdlen + strlen (path) + 3;
722     else
723       cmdlen = cmdlen + strlen (arg) + 3;
724   }
725   va_end (ap);
726
727   cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
728   va_copy (ap, va);
729   while (NULL != (arg = va_arg (ap, char *)))
730   {
731     if (idx == cmd)
732       idx += sprintf (idx, "\"%s\" ", path);
733     else
734       idx += sprintf (idx, "\"%s\" ", arg);
735   }
736   va_end (ap);
737
738   memset (&start, 0, sizeof (start));
739   start.cb = sizeof (start);
740
741   if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
742     start.dwFlags |= STARTF_USESTDHANDLES;
743
744   if (pipe_stdin != NULL)
745   {
746     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
747                                        (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
748                                        &stdin_handle, sizeof (HANDLE));
749     start.hStdInput = stdin_handle;
750   }
751
752   if (pipe_stdout != NULL)
753   {
754     GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
755                                        (pipe_stdout,
756                                         GNUNET_DISK_PIPE_END_WRITE),
757                                        &stdout_handle, sizeof (HANDLE));
758     start.hStdOutput = stdout_handle;
759   }
760
761   control_pipe =
762       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
763                                 GNUNET_DISK_PERM_USER_READ |
764                                 GNUNET_DISK_PERM_USER_WRITE);
765   if (control_pipe == NULL)
766   {
767     GNUNET_free (cmd);
768     GNUNET_free (path);
769     return NULL;
770   }
771
772 #if DEBUG_OS
773   LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
774        childpipename);
775 #endif
776
777   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
778   GNUNET_asprintf (&our_env[1], "%s", childpipename);
779   our_env[2] = NULL;
780   env_block = CreateCustomEnvTable (our_env);
781   GNUNET_free (our_env[0]);
782   GNUNET_free (our_env[1]);
783
784   if (!CreateProcessA
785       (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
786        env_block, NULL, &start, &proc))
787   {
788     SetErrnoFromWinError (GetLastError ());
789     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
790     GNUNET_free (env_block);
791     GNUNET_free (cmd);
792     return NULL;
793   }
794
795   GNUNET_free (env_block);
796
797   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
798   gnunet_proc->pid = proc.dwProcessId;
799   gnunet_proc->handle = proc.hProcess;
800   gnunet_proc->control_pipe = control_pipe;
801
802   CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
803
804   ResumeThread (proc.hThread);
805   CloseHandle (proc.hThread);
806
807   GNUNET_free (cmd);
808
809   return gnunet_proc;
810 #endif
811 }
812
813
814 /**
815  * Start a process.
816  *
817  * @param pipe_stdin pipe to use to send input to child process (or NULL)
818  * @param pipe_stdout pipe to use to get output from child process (or NULL)
819  * @param filename name of the binary
820  * @param ... NULL-terminated list of arguments to the process
821  *
822  * @return pointer to process structure of the new process, NULL on error
823  *
824  */
825 struct GNUNET_OS_Process *
826 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
827                          struct GNUNET_DISK_PipeHandle *pipe_stdout,
828                          const char *filename, ...)
829 {
830   struct GNUNET_OS_Process *ret;
831   va_list ap;
832
833   va_start (ap, filename);
834   ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
835   va_end (ap);
836   return ret;
837 }
838
839
840 /**
841  * Start a process.
842  *
843  * @param lsocks array of listen sockets to dup systemd-style (or NULL);
844  *         must be NULL on platforms where dup is not supported
845  * @param filename name of the binary
846  * @param argv NULL-terminated list of arguments to the process
847  * @return process ID of the new process, -1 on error
848  */
849 struct GNUNET_OS_Process *
850 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
851                            char *const argv[])
852 {
853 #if ENABLE_WINDOWS_WORKAROUNDS
854   struct GNUNET_DISK_FileHandle *control_pipe = NULL;
855   char *childpipename = NULL;
856 #endif
857
858 #ifndef MINGW
859   pid_t ret;
860   char lpid[16];
861   char fds[16];
862   struct GNUNET_OS_Process *gnunet_proc = NULL;
863   int i;
864   int j;
865   int k;
866   int tgt;
867   int flags;
868   int *lscp;
869   unsigned int ls;
870
871 #if ENABLE_WINDOWS_WORKAROUNDS
872   control_pipe =
873       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
874                                 GNUNET_DISK_PERM_USER_READ |
875                                 GNUNET_DISK_PERM_USER_WRITE);
876   if (control_pipe == NULL)
877     return NULL;
878 #endif
879
880   lscp = NULL;
881   ls = 0;
882   if (lsocks != NULL)
883   {
884     i = 0;
885     while (-1 != (k = lsocks[i++]))
886       GNUNET_array_append (lscp, ls, k);
887     GNUNET_array_append (lscp, ls, -1);
888   }
889   ret = fork ();
890   if (ret != 0)
891   {
892     if (ret == -1)
893     {
894       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
895 #if ENABLE_WINDOWS_WORKAROUNDS
896       GNUNET_DISK_npipe_close (control_pipe);
897 #endif
898     }
899     else
900     {
901       gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
902       gnunet_proc->pid = ret;
903 #if ENABLE_WINDOWS_WORKAROUNDS
904       gnunet_proc->control_pipe = control_pipe;
905
906 #endif
907     }
908     GNUNET_array_grow (lscp, ls, 0);
909 #if ENABLE_WINDOWS_WORKAROUNDS
910     GNUNET_free (childpipename);
911 #endif
912     return gnunet_proc;
913   }
914
915 #if ENABLE_WINDOWS_WORKAROUNDS
916   setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
917   GNUNET_free (childpipename);
918 #endif
919
920   if (lscp != NULL)
921   {
922     /* read systemd documentation... */
923     GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
924     setenv ("LISTEN_PID", lpid, 1);
925     i = 0;
926     tgt = 3;
927     while (-1 != lscp[i])
928     {
929       j = i + 1;
930       while (-1 != lscp[j])
931       {
932         if (lscp[j] == tgt)
933         {
934           /* dup away */
935           k = dup (lscp[j]);
936           GNUNET_assert (-1 != k);
937           GNUNET_assert (0 == close (lscp[j]));
938           lscp[j] = k;
939           break;
940         }
941         j++;
942       }
943       if (lscp[i] != tgt)
944       {
945         /* Bury any existing FD, no matter what; they should all be closed
946          * on exec anyway and the important onces have been dup'ed away */
947         (void) close (tgt);
948         GNUNET_assert (-1 != dup2 (lscp[i], tgt));
949       }
950       /* unset close-on-exec flag */
951       flags = fcntl (tgt, F_GETFD);
952       GNUNET_assert (flags >= 0);
953       flags &= ~FD_CLOEXEC;
954       fflush (stderr);
955       (void) fcntl (tgt, F_SETFD, flags);
956       tgt++;
957       i++;
958     }
959     GNUNET_snprintf (fds, sizeof (fds), "%u", i);
960     setenv ("LISTEN_FDS", fds, 1);
961   }
962   GNUNET_array_grow (lscp, ls, 0);
963   execvp (filename, argv);
964   LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
965   _exit (1);
966 #else
967   char **arg, **non_const_argv;
968   unsigned int cmdlen;
969   char *cmd, *idx;
970   STARTUPINFO start;
971   PROCESS_INFORMATION proc;
972   int argcount = 0;
973   struct GNUNET_OS_Process *gnunet_proc = NULL;
974
975   char path[MAX_PATH + 1];
976
977   char *our_env[3] = { NULL, NULL, NULL };
978   char *env_block = NULL;
979   char *pathbuf;
980   DWORD pathbuf_len, alloc_len;
981   char *self_prefix;
982   char *bindir;
983   char *libdir;
984   char *ptr;
985   char *non_const_filename;
986
987   GNUNET_assert (lsocks == NULL);
988
989   /* Search in prefix dir (hopefully - the directory from which
990    * the current module was loaded), bindir and libdir, then in PATH
991    */
992   self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
993   bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
994   libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
995
996   pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
997
998   alloc_len =
999       pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1000       strlen (libdir);
1001
1002   pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1003
1004   ptr = pathbuf;
1005   ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1006   GNUNET_free (self_prefix);
1007   GNUNET_free (bindir);
1008   GNUNET_free (libdir);
1009
1010   alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1011   if (alloc_len != pathbuf_len - 1)
1012   {
1013     GNUNET_free (pathbuf);
1014     errno = ENOSYS;             /* PATH changed on the fly. What kind of error is that? */
1015     return NULL;
1016   }
1017
1018   cmdlen = strlen (filename);
1019   if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1020     GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1021   else
1022     GNUNET_asprintf (&non_const_filename, "%s", filename);
1023
1024   /* Check that this is the full path. If it isn't, search. */
1025   if (non_const_filename[1] == ':')
1026     snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1027   else if (!SearchPathA
1028            (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1029             path, NULL))
1030   {
1031     SetErrnoFromWinError (GetLastError ());
1032     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1033                        non_const_filename);
1034     GNUNET_free (non_const_filename);
1035     GNUNET_free (pathbuf);
1036     return NULL;
1037   }
1038   GNUNET_free (pathbuf);
1039   GNUNET_free (non_const_filename);
1040
1041   /* Count the number of arguments */
1042   arg = (char **) argv;
1043   while (*arg)
1044   {
1045     arg++;
1046     argcount++;
1047   }
1048
1049   /* Allocate a copy argv */
1050   non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1051
1052   /* Copy all argv strings */
1053   argcount = 0;
1054   arg = (char **) argv;
1055   while (*arg)
1056   {
1057     if (arg == argv)
1058       non_const_argv[argcount] = GNUNET_strdup (path);
1059     else
1060       non_const_argv[argcount] = GNUNET_strdup (*arg);
1061     arg++;
1062     argcount++;
1063   }
1064   non_const_argv[argcount] = NULL;
1065
1066   /* Count cmd len */
1067   cmdlen = 1;
1068   arg = non_const_argv;
1069   while (*arg)
1070   {
1071     cmdlen = cmdlen + strlen (*arg) + 3;
1072     arg++;
1073   }
1074
1075   /* Allocate and create cmd */
1076   cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1077   arg = non_const_argv;
1078   while (*arg)
1079   {
1080     idx += sprintf (idx, "\"%s\" ", *arg);
1081     arg++;
1082   }
1083
1084   while (argcount > 0)
1085     GNUNET_free (non_const_argv[--argcount]);
1086   GNUNET_free (non_const_argv);
1087
1088   memset (&start, 0, sizeof (start));
1089   start.cb = sizeof (start);
1090
1091   control_pipe =
1092       GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1093                                 GNUNET_DISK_PERM_USER_READ |
1094                                 GNUNET_DISK_PERM_USER_WRITE);
1095   if (control_pipe == NULL)
1096   {
1097     GNUNET_free (cmd);
1098     GNUNET_free (path);
1099     return NULL;
1100   }
1101
1102 #if DEBUG_OS
1103   LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1104        childpipename);
1105 #endif
1106
1107   GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1108   GNUNET_asprintf (&our_env[1], "%s", childpipename);
1109   our_env[2] = NULL;
1110   env_block = CreateCustomEnvTable (our_env);
1111   GNUNET_free (our_env[0]);
1112   GNUNET_free (our_env[1]);
1113
1114   if (!CreateProcess
1115       (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1116        env_block, NULL, &start, &proc))
1117   {
1118     SetErrnoFromWinError (GetLastError ());
1119     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1120     GNUNET_free (env_block);
1121     GNUNET_free (cmd);
1122     return NULL;
1123   }
1124
1125   GNUNET_free (env_block);
1126
1127   gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1128   gnunet_proc->pid = proc.dwProcessId;
1129   gnunet_proc->handle = proc.hProcess;
1130   gnunet_proc->control_pipe = control_pipe;
1131
1132   CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1133
1134   ResumeThread (proc.hThread);
1135   CloseHandle (proc.hThread);
1136   GNUNET_free (cmd);
1137
1138   return gnunet_proc;
1139 #endif
1140 }
1141
1142
1143 /**
1144  * Retrieve the status of a process
1145  * @param proc process ID
1146  * @param type status type
1147  * @param code return code/signal number
1148  * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1149  */
1150 int
1151 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1152                           enum GNUNET_OS_ProcessStatusType *type,
1153                           unsigned long *code)
1154 {
1155 #ifndef MINGW
1156   int status;
1157   int ret;
1158
1159   GNUNET_assert (0 != proc);
1160   ret = waitpid (proc->pid, &status, WNOHANG);
1161   if (ret < 0)
1162   {
1163     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1164     return GNUNET_SYSERR;
1165   }
1166   if (0 == ret)
1167   {
1168     *type = GNUNET_OS_PROCESS_RUNNING;
1169     *code = 0;
1170     return GNUNET_NO;
1171   }
1172   if (proc->pid != ret)
1173   {
1174     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1175     return GNUNET_SYSERR;
1176   }
1177   if (WIFEXITED (status))
1178   {
1179     *type = GNUNET_OS_PROCESS_EXITED;
1180     *code = WEXITSTATUS (status);
1181   }
1182   else if (WIFSIGNALED (status))
1183   {
1184     *type = GNUNET_OS_PROCESS_SIGNALED;
1185     *code = WTERMSIG (status);
1186   }
1187   else if (WIFSTOPPED (status))
1188   {
1189     *type = GNUNET_OS_PROCESS_SIGNALED;
1190     *code = WSTOPSIG (status);
1191   }
1192 #ifdef WIFCONTINUED
1193   else if (WIFCONTINUED (status))
1194   {
1195     *type = GNUNET_OS_PROCESS_RUNNING;
1196     *code = 0;
1197   }
1198 #endif
1199   else
1200   {
1201     *type = GNUNET_OS_PROCESS_UNKNOWN;
1202     *code = 0;
1203   }
1204 #else
1205   HANDLE h;
1206   DWORD c, error_code, ret;
1207
1208   h = proc->handle;
1209   ret = proc->pid;
1210   if (h == NULL || ret == 0)
1211   {
1212     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1213          ret, h);
1214     return GNUNET_SYSERR;
1215   }
1216   if (h == NULL)
1217     h = GetCurrentProcess ();
1218
1219   SetLastError (0);
1220   ret = GetExitCodeProcess (h, &c);
1221   error_code = GetLastError ();
1222   if (ret == 0 || error_code != NO_ERROR)
1223   {
1224     SetErrnoFromWinError (error_code);
1225     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1226     return GNUNET_SYSERR;
1227   }
1228   if (STILL_ACTIVE == c)
1229   {
1230     *type = GNUNET_OS_PROCESS_RUNNING;
1231     *code = 0;
1232     return GNUNET_NO;
1233   }
1234   *type = GNUNET_OS_PROCESS_EXITED;
1235   *code = c;
1236 #endif
1237
1238   return GNUNET_OK;
1239 }
1240
1241
1242 /**
1243  * Wait for a process
1244  * @param proc pointer to process structure
1245  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1246  */
1247 int
1248 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1249 {
1250
1251 #ifndef MINGW
1252   pid_t pid = proc->pid;
1253
1254   if (pid != waitpid (pid, NULL, 0))
1255     return GNUNET_SYSERR;
1256   return GNUNET_OK;
1257 #else
1258   HANDLE h;
1259   int ret;
1260
1261   h = proc->handle;
1262   if (NULL == h)
1263   {
1264     LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1265          proc->pid, h);
1266     return GNUNET_SYSERR;
1267   }
1268   if (h == NULL)
1269     h = GetCurrentProcess ();
1270
1271   if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1272   {
1273     SetErrnoFromWinError (GetLastError ());
1274     ret = GNUNET_SYSERR;
1275   }
1276   else
1277     ret = GNUNET_OK;
1278
1279   return ret;
1280 #endif
1281 }
1282
1283
1284 /**
1285  * Handle to a command.
1286  */
1287 struct GNUNET_OS_CommandHandle
1288 {
1289
1290   /**
1291    * Process handle.
1292    */
1293   struct GNUNET_OS_Process *eip;
1294
1295   /**
1296    * Handle to the output pipe.
1297    */
1298   struct GNUNET_DISK_PipeHandle *opipe;
1299
1300   /**
1301    * Read-end of output pipe.
1302    */
1303   const struct GNUNET_DISK_FileHandle *r;
1304
1305   /**
1306    * Function to call on each line of output.
1307    */
1308   GNUNET_OS_LineProcessor proc;
1309
1310   /**
1311    * Closure for 'proc'.
1312    */
1313   void *proc_cls;
1314
1315   /**
1316    * Buffer for the output.
1317    */
1318   char buf[1024];
1319
1320   /**
1321    * Task reading from pipe.
1322    */
1323   GNUNET_SCHEDULER_TaskIdentifier rtask;
1324
1325   /**
1326    * When to time out.
1327    */
1328   struct GNUNET_TIME_Absolute timeout;
1329
1330   /**
1331    * Current read offset in buf.
1332    */
1333   size_t off;
1334 };
1335
1336
1337 /**
1338  * Stop/kill a command.  Must ONLY be called either from
1339  * the callback after 'NULL' was passed for 'line' *OR*
1340  * from an independent task (not within the line processor).
1341  *
1342  * @param cmd handle to the process
1343  */
1344 void
1345 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1346 {
1347
1348   if (cmd->proc != NULL)
1349   {
1350     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1351     GNUNET_SCHEDULER_cancel (cmd->rtask);
1352   }
1353   (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1354   GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1355   GNUNET_OS_process_close (cmd->eip);
1356   GNUNET_DISK_pipe_close (cmd->opipe);
1357   GNUNET_free (cmd);
1358 }
1359
1360
1361 /**
1362  * Read from the process and call the line processor.
1363  *
1364  * @param cls the 'struct GNUNET_OS_CommandHandle'
1365  * @param tc scheduler context
1366  */
1367 static void
1368 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1369 {
1370   struct GNUNET_OS_CommandHandle *cmd = cls;
1371   GNUNET_OS_LineProcessor proc;
1372   char *end;
1373   ssize_t ret;
1374
1375   cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1376   if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1377   {
1378     /* timeout, shutdown, etc. */
1379     proc = cmd->proc;
1380     cmd->proc = NULL;
1381     proc (cmd->proc_cls, NULL);
1382     return;
1383   }
1384   ret =
1385       GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1386                              sizeof (cmd->buf) - cmd->off);
1387   if (ret <= 0)
1388   {
1389     if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1390     {
1391       cmd->buf[cmd->off] = '\0';
1392       cmd->proc (cmd->proc_cls, cmd->buf);
1393     }
1394     proc = cmd->proc;
1395     cmd->proc = NULL;
1396     proc (cmd->proc_cls, NULL);
1397     return;
1398   }
1399   end = memchr (&cmd->buf[cmd->off], '\n', ret);
1400   cmd->off += ret;
1401   while (end != NULL)
1402   {
1403     *end = '\0';
1404     cmd->proc (cmd->proc_cls, cmd->buf);
1405     memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1406     cmd->off -= (end + 1 - cmd->buf);
1407     end = memchr (cmd->buf, '\n', cmd->off);
1408   }
1409   cmd->rtask =
1410       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1411                                       (cmd->timeout), cmd->r, &cmd_read, cmd);
1412 }
1413
1414
1415 /**
1416  * Run the given command line and call the given function
1417  * for each line of the output.
1418  *
1419  * @param proc function to call for each line of the output
1420  * @param proc_cls closure for proc
1421  * @param timeout when to time out
1422  * @param binary command to run
1423  * @param ... arguments to command
1424  * @return NULL on error
1425  */
1426 struct GNUNET_OS_CommandHandle *
1427 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1428                        struct GNUNET_TIME_Relative timeout, const char *binary,
1429                        ...)
1430 {
1431   struct GNUNET_OS_CommandHandle *cmd;
1432   struct GNUNET_OS_Process *eip;
1433   struct GNUNET_DISK_PipeHandle *opipe;
1434   va_list ap;
1435
1436   opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1437   if (NULL == opipe)
1438     return NULL;
1439   va_start (ap, binary);
1440   eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1441   va_end (ap);
1442   if (NULL == eip)
1443   {
1444     GNUNET_DISK_pipe_close (opipe);
1445     return NULL;
1446   }
1447   GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1448   cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1449   cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1450   cmd->eip = eip;
1451   cmd->opipe = opipe;
1452   cmd->proc = proc;
1453   cmd->proc_cls = proc_cls;
1454   cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1455   cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1456   return cmd;
1457 }
1458
1459
1460
1461
1462 /* end of os_priority.c */