57e5798d8f1f43187f778ba49e30ba698556d48e
[oweals/gnunet.git] / src / util / helper.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011, 2012 Christian Grothoff
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/helper.c
23  * @brief API for dealing with (SUID) helper processes that communicate via
24  *          GNUNET_MessageHeaders on stdin/stdout
25  * @author Philipp Toelke
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30
31
32 /**
33  * Entry in the queue of messages we need to transmit to the helper.
34  */
35 struct GNUNET_HELPER_SendHandle
36 {
37
38   /**
39    * This is an entry in a DLL.
40    */
41   struct GNUNET_HELPER_SendHandle *next;
42
43   /**
44    * This is an entry in a DLL.
45    */
46   struct GNUNET_HELPER_SendHandle *prev;
47
48   /**
49    * Message to transmit (allocated at the end of this struct)
50    */
51   const struct GNUNET_MessageHeader *msg;
52  
53   /**
54    * The handle to a helper process.
55    */
56   struct GNUNET_HELPER_Handle *h;
57  
58   /**
59    * Function to call upon completion.
60    */
61   GNUNET_HELPER_Continuation cont;
62
63   /**
64    * Closure to 'cont'.
65    */
66   void *cont_cls;
67
68   /**
69    * Current write position.
70    */
71   unsigned int wpos;
72
73 };
74
75
76 /**
77  * The handle to a helper process.
78  */
79 struct GNUNET_HELPER_Handle
80 {
81
82   /**
83    * PipeHandle to receive data from the helper
84    */
85   struct GNUNET_DISK_PipeHandle *helper_in;
86   
87   /**
88    * PipeHandle to send data to the helper
89    */
90   struct GNUNET_DISK_PipeHandle *helper_out;
91   
92   /**
93    * FileHandle to receive data from the helper
94    */
95   const struct GNUNET_DISK_FileHandle *fh_from_helper;
96   
97   /**
98    * FileHandle to send data to the helper
99    */
100   const struct GNUNET_DISK_FileHandle *fh_to_helper;
101   
102   /**
103    * The process id of the helper
104    */
105   struct GNUNET_OS_Process *helper_proc;
106
107   /**
108    * The Message-Tokenizer that tokenizes the messages comming from the helper
109    */
110   struct GNUNET_SERVER_MessageStreamTokenizer *mst;
111
112   /**
113    * The exception callback
114    */
115   GNUNET_HELPER_ExceptionCallback exp_cb;
116
117   /**
118    * The closure for callbacks
119    */
120   void *cb_cls;
121
122   /**
123    * First message queued for transmission to helper.
124    */
125   struct GNUNET_HELPER_SendHandle *sh_head;
126
127   /**
128    * Last message queued for transmission to helper.
129    */
130   struct GNUNET_HELPER_SendHandle *sh_tail;
131
132   /**
133    * Binary to run.
134    */
135   char *binary_name;
136
137   /**
138    * NULL-terminated list of command-line arguments.
139    */
140   char **binary_argv;
141                     
142   /**
143    * Task to read from the helper.
144    */
145   GNUNET_SCHEDULER_TaskIdentifier read_task;
146
147   /**
148    * Task to read from the helper.
149    */
150   GNUNET_SCHEDULER_TaskIdentifier write_task;
151
152   /**
153    * Restart task.
154    */
155   GNUNET_SCHEDULER_TaskIdentifier restart_task;
156
157   /**
158    * Does the helper support the use of a control pipe for signalling?
159    */
160   int with_control_pipe;
161
162 };
163
164
165 /**
166  * Sends termination signal to the helper process.  The helper process is not
167  * reaped; call GNUNET_HELPER_wait() for reaping the dead helper process.
168  *
169  * @param h the helper handle
170  * @param soft_kill if GNUNET_YES, signals termination by closing the helper's
171  *          stdin; GNUNET_NO to signal termination by sending SIGTERM to helper
172  * @return GNUNET_OK on success; GNUNET_SYSERR on error
173  */
174 int
175 GNUNET_HELPER_kill (struct GNUNET_HELPER_Handle *h, int soft_kill)
176 {
177   struct GNUNET_HELPER_SendHandle *sh;
178   int ret;
179
180   while (NULL != (sh = h->sh_head))
181   {
182     GNUNET_CONTAINER_DLL_remove (h->sh_head,
183                                  h->sh_tail,
184                                  sh);
185     if (NULL != sh->cont)
186       sh->cont (sh->cont_cls, GNUNET_NO);
187     GNUNET_free (sh);
188   }
189   if (GNUNET_SCHEDULER_NO_TASK != h->restart_task)
190   {
191     GNUNET_SCHEDULER_cancel (h->restart_task);
192     h->restart_task = GNUNET_SCHEDULER_NO_TASK;
193   }
194   if (NULL == h->helper_proc)
195     return GNUNET_SYSERR;
196   if (GNUNET_YES == soft_kill)
197   { 
198     /* soft-kill only possible with pipes */
199     GNUNET_assert (NULL != h->helper_in);
200     ret = GNUNET_DISK_pipe_close (h->helper_in);
201     h->helper_in = NULL;
202     h->fh_to_helper = NULL;
203     return ret;
204   }
205   if (0 != GNUNET_OS_process_kill (h->helper_proc, SIGTERM))
206     return GNUNET_SYSERR;
207   return GNUNET_OK;
208 }
209
210
211 /**
212  * Reap the helper process.  This call is blocking(!).  The helper process
213  * should either be sent a termination signal before or should be dead before
214  * calling this function
215  *
216  * @param h the helper handle
217  * @return GNUNET_OK on success; GNUNET_SYSERR on error
218  */
219 int
220 GNUNET_HELPER_wait (struct GNUNET_HELPER_Handle *h)
221 {
222   struct GNUNET_HELPER_SendHandle *sh;
223   int ret;
224
225   if (NULL != h->helper_proc)
226   {
227     ret = GNUNET_OS_process_wait (h->helper_proc);
228     GNUNET_OS_process_destroy (h->helper_proc);
229     h->helper_proc = NULL;
230   }
231   if (GNUNET_SCHEDULER_NO_TASK != h->read_task)
232   {
233     GNUNET_SCHEDULER_cancel (h->read_task);
234     h->read_task = GNUNET_SCHEDULER_NO_TASK;
235   }
236   if (GNUNET_SCHEDULER_NO_TASK != h->write_task)
237   {
238     GNUNET_SCHEDULER_cancel (h->write_task);
239     h->write_task = GNUNET_SCHEDULER_NO_TASK;
240   }
241   if (NULL != h->helper_in)
242   {
243     GNUNET_DISK_pipe_close (h->helper_in);
244     h->helper_in = NULL;
245     h->fh_to_helper = NULL;
246   }
247   if (NULL != h->helper_out)
248   {
249     GNUNET_DISK_pipe_close (h->helper_out);
250     h->helper_out = NULL;
251     h->fh_from_helper = NULL;
252   }
253   while (NULL != (sh = h->sh_head))
254   {
255     GNUNET_CONTAINER_DLL_remove (h->sh_head,
256                                  h->sh_tail,
257                                  sh);
258     if (NULL != sh->cont)
259       sh->cont (sh->cont_cls, GNUNET_NO);
260     GNUNET_free (sh);
261   }
262   /* purge MST buffer */
263   (void) GNUNET_SERVER_mst_receive (h->mst, NULL, NULL, 0, GNUNET_YES, GNUNET_NO);
264   return ret;
265 }
266
267
268 /**
269  * Stop the helper process, we're closing down or had an error.
270  *
271  * @param h handle to the helper process
272  * @param soft_kill if GNUNET_YES, signals termination by closing the helper's
273  *          stdin; GNUNET_NO to signal termination by sending SIGTERM to helper
274  */
275 static void
276 stop_helper (struct GNUNET_HELPER_Handle *h, int soft_kill)
277 {
278   GNUNET_break (GNUNET_OK == GNUNET_HELPER_kill (h, soft_kill));
279   GNUNET_break (GNUNET_OK == GNUNET_HELPER_wait (h));
280 }
281
282
283 /**
284  * Restart the helper process.
285  *
286  * @param cls handle to the helper process
287  * @param tc scheduler context
288  */
289 static void
290 restart_task (void *cls,
291               const struct GNUNET_SCHEDULER_TaskContext *tc);
292
293
294 /**
295  * Read from the helper-process
296  *
297  * @param cls handle to the helper process
298  * @param tc scheduler context
299  */
300 static void
301 helper_read (void *cls,
302              const struct GNUNET_SCHEDULER_TaskContext *tc)
303 {
304   struct GNUNET_HELPER_Handle *h = cls;
305   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE] GNUNET_ALIGN;
306   ssize_t t;
307
308   h->read_task = GNUNET_SCHEDULER_NO_TASK;
309   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
310   {
311     /* try again */
312     h->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
313                                                    h->fh_from_helper, &helper_read, h);
314     return;
315   }
316   t = GNUNET_DISK_file_read (h->fh_from_helper, &buf, sizeof (buf));
317   if (t < 0)
318   {
319     /* On read-error, restart the helper */
320     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
321                 _("Error reading from `%s': %s\n"),
322                 h->binary_name,
323                 STRERROR (errno));
324     if (NULL != h->exp_cb)
325     {
326       h->exp_cb (h->cb_cls);
327       GNUNET_HELPER_stop (h, GNUNET_NO);
328       return;
329     }
330     stop_helper (h, GNUNET_NO);
331     /* Restart the helper */
332     h->restart_task =
333         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &restart_task, h);
334     return;
335   }
336   if (0 == t)
337   {
338     /* this happens if the helper is shut down via a 
339        signal, so it is not a "hard" error */
340     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
341                 "Got 0 bytes from helper `%s' (EOF)\n",
342                 h->binary_name);
343     if (NULL != h->exp_cb)
344     {
345       h->exp_cb (h->cb_cls);
346       GNUNET_HELPER_stop (h, GNUNET_NO);
347       return;
348     }
349     stop_helper (h, GNUNET_NO);
350     /* Restart the helper */
351     h->restart_task =
352       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
353                                     &restart_task, h);
354     return;
355   }
356   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
357               "Got %u bytes from helper `%s'\n",
358               (unsigned int) t,
359               h->binary_name);
360   h->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
361                                                  h->fh_from_helper, &helper_read, h);
362   if (GNUNET_SYSERR ==
363       GNUNET_SERVER_mst_receive (h->mst, NULL, buf, t, GNUNET_NO, GNUNET_NO))
364   {
365     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
366                 _("Failed to parse inbound message from helper `%s'\n"),
367                 h->binary_name);
368     if (NULL != h->exp_cb)
369     {
370       h->exp_cb (h->cb_cls);
371       GNUNET_HELPER_stop (h, GNUNET_NO);
372       return;
373     }     
374     stop_helper (h, GNUNET_NO);
375     /* Restart the helper */
376     h->restart_task =
377         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
378                                       &restart_task, h);
379     return;
380   }
381 }
382
383
384 /**
385  * Start the helper process.
386  *
387  * @param h handle to the helper process
388  */
389 static void
390 start_helper (struct GNUNET_HELPER_Handle *h)
391 {
392   h->helper_in = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
393   h->helper_out = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
394   if ( (h->helper_in == NULL) || (h->helper_out == NULL))
395   {
396     /* out of file descriptors? try again later... */
397     stop_helper (h, GNUNET_NO);
398     h->restart_task =
399       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
400                                     &restart_task, h);    
401     return;
402   }
403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
404               "Starting HELPER process `%s'\n",
405               h->binary_name);
406   h->fh_from_helper =
407       GNUNET_DISK_pipe_handle (h->helper_out, GNUNET_DISK_PIPE_END_READ);
408   h->fh_to_helper =
409       GNUNET_DISK_pipe_handle (h->helper_in, GNUNET_DISK_PIPE_END_WRITE);
410   h->helper_proc =
411     GNUNET_OS_start_process_vap (h->with_control_pipe, GNUNET_OS_INHERIT_STD_ERR, 
412                                  h->helper_in, h->helper_out,
413                                  h->binary_name,
414                                  h->binary_argv);
415   if (NULL == h->helper_proc)
416   {
417     /* failed to start process? try again later... */
418     stop_helper (h, GNUNET_NO);
419     h->restart_task =
420       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
421                                     &restart_task, h);    
422     return;
423   }
424   GNUNET_DISK_pipe_close_end (h->helper_out, GNUNET_DISK_PIPE_END_WRITE);
425   GNUNET_DISK_pipe_close_end (h->helper_in, GNUNET_DISK_PIPE_END_READ);
426   h->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
427                                                  h->fh_from_helper, 
428                                                  &helper_read, 
429                                                  h);
430 }
431
432
433 /**
434  * Restart the helper process.
435  *
436  * @param cls handle to the helper process
437  * @param tc scheduler context
438  */
439 static void
440 restart_task (void *cls,
441               const struct GNUNET_SCHEDULER_TaskContext *tc)
442 {
443   struct GNUNET_HELPER_Handle*h = cls;
444
445   h->restart_task = GNUNET_SCHEDULER_NO_TASK;
446   start_helper (h);
447 }
448
449
450 /**
451  * Starts a helper and begins reading from it. The helper process is
452  * restarted when it dies except when it is stopped using GNUNET_HELPER_stop()
453  * or when the exp_cb callback is not NULL.
454  *
455  * @param with_control_pipe does the helper support the use of a control pipe for signalling?
456  * @param binary_name name of the binary to run
457  * @param binary_argv NULL-terminated list of arguments to give when starting the binary (this
458  *                    argument must not be modified by the client for
459  *                     the lifetime of the helper handle)
460  * @param cb function to call if we get messages from the helper
461  * @param exp_cb the exception callback to call. Set this to NULL if the helper
462  *          process has to be restarted automatically when it dies/crashes
463  * @param cb_cls closure for the above callback
464  * @return the new Handle, NULL on error
465  */
466 struct GNUNET_HELPER_Handle *
467 GNUNET_HELPER_start (int with_control_pipe,
468                      const char *binary_name,
469                      char *const binary_argv[],
470                      GNUNET_SERVER_MessageTokenizerCallback cb,
471                      GNUNET_HELPER_ExceptionCallback exp_cb,
472                      void *cb_cls)
473 {
474   struct GNUNET_HELPER_Handle *h;
475   unsigned int c;
476
477   h = GNUNET_malloc (sizeof (struct GNUNET_HELPER_Handle));
478   h->with_control_pipe = with_control_pipe;
479   /* Lookup in libexec path only if we are starting gnunet helpers */
480   if (NULL != strstr (binary_name, "gnunet"))
481     h->binary_name = GNUNET_OS_get_libexec_binary_path (binary_name);
482   else
483     h->binary_name = strdup (binary_name);
484   for (c = 0; NULL != binary_argv[c]; c++);
485   h->binary_argv = GNUNET_malloc (sizeof (char *) * (c + 1));
486   for (c = 0; NULL != binary_argv[c]; c++)
487     h->binary_argv[c] = GNUNET_strdup (binary_argv[c]);
488   h->binary_argv[c] = NULL;
489   h->cb_cls = cb_cls;
490   h->mst = GNUNET_SERVER_mst_create (cb, h->cb_cls);
491   h->exp_cb = exp_cb;
492   start_helper (h);
493   return h;
494 }
495
496
497 /**
498  * Free's the resources occupied by the helper handle
499  *
500  * @param h the helper handle to free
501  */
502 void
503 GNUNET_HELPER_destroy (struct GNUNET_HELPER_Handle *h)
504 {
505   unsigned int c;
506
507   GNUNET_SERVER_mst_destroy (h->mst);
508   GNUNET_free (h->binary_name);
509   for (c = 0; h->binary_argv[c] != NULL; c++)
510     GNUNET_free (h->binary_argv[c]);
511   GNUNET_free (h->binary_argv);
512   GNUNET_free (h);
513 }
514
515
516 /**
517  * Kills the helper, closes the pipe and frees the handle
518  *
519  * @param h handle to helper to stop
520  * @param soft_kill if GNUNET_YES, signals termination by closing the helper's
521  *          stdin; GNUNET_NO to signal termination by sending SIGTERM to helper
522  */
523 void
524 GNUNET_HELPER_stop (struct GNUNET_HELPER_Handle *h, int soft_kill)
525 {
526   h->exp_cb = NULL;
527   stop_helper (h, soft_kill);
528   GNUNET_HELPER_destroy (h);
529 }
530
531
532 /**
533  * Write to the helper-process
534  *
535  * @param cls handle to the helper process
536  * @param tc scheduler context
537  */
538 static void
539 helper_write (void *cls,
540              const struct GNUNET_SCHEDULER_TaskContext *tc)
541 {
542   struct GNUNET_HELPER_Handle *h = cls;
543   struct GNUNET_HELPER_SendHandle *sh;
544   const char *buf;
545   ssize_t t;
546
547   h->write_task = GNUNET_SCHEDULER_NO_TASK;
548   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
549   {
550     /* try again */
551     h->write_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
552                                                     h->fh_to_helper, &helper_write, h);
553     return;
554   }  
555   if (NULL == (sh = h->sh_head))
556     return; /* how did this happen? */
557   buf = (const char*) sh->msg;
558   t = GNUNET_DISK_file_write (h->fh_to_helper, &buf[sh->wpos], ntohs (sh->msg->size) - sh->wpos);
559   if (t <= 0)
560   {
561     /* On write-error, restart the helper */
562     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
563                 _("Error writing to `%s': %s\n"),
564                 h->binary_name,
565                 STRERROR (errno));
566     if (NULL != h->exp_cb)
567     {
568       h->exp_cb (h->cb_cls);
569       GNUNET_HELPER_stop (h, GNUNET_NO);
570       return;
571     }
572     stop_helper (h, GNUNET_NO);
573     /* Restart the helper */
574     h->restart_task =
575       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
576                                     &restart_task, h);
577     return;
578   }
579   sh->wpos += t;
580   if (sh->wpos == ntohs (sh->msg->size))
581   {
582     GNUNET_CONTAINER_DLL_remove (h->sh_head,
583                                  h->sh_tail,
584                                  sh);
585     if (NULL != sh->cont)
586       sh->cont (sh->cont_cls, GNUNET_YES);
587     GNUNET_free (sh);
588   }
589   if (NULL != h->sh_head)
590     h->write_task = GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
591                                                      h->fh_to_helper, 
592                                                      &helper_write, 
593                                                      h);
594 }
595
596
597 /**
598  * Send an message to the helper.
599  *
600  * @param h helper to send message to
601  * @param msg message to send
602  * @param can_drop can the message be dropped if there is already one in the queue?
603  * @param cont continuation to run once the message is out (PREREQ_DONE on succees, CANCEL
604  *             if the helper process died, NULL during GNUNET_HELPER_stop).
605  * @param cont_cls closure for 'cont'
606  * @return NULL if the message was dropped, 
607  *         otherwise handle to cancel *cont* (actual transmission may
608  *         not be abortable)
609  */
610 struct GNUNET_HELPER_SendHandle *
611 GNUNET_HELPER_send (struct GNUNET_HELPER_Handle *h, 
612                     const struct GNUNET_MessageHeader *msg,
613                     int can_drop,
614                     GNUNET_HELPER_Continuation cont,
615                     void *cont_cls)
616 {
617   struct GNUNET_HELPER_SendHandle *sh;
618   uint16_t mlen;
619
620   if (NULL == h->fh_to_helper)
621     return NULL;
622   if ( (GNUNET_YES == can_drop) &&
623        (NULL != h->sh_head) )
624     return NULL;
625   mlen = ntohs (msg->size);
626   sh = GNUNET_malloc (sizeof (struct GNUNET_HELPER_SendHandle) + mlen);
627   sh->msg = (const struct GNUNET_MessageHeader*) &sh[1];
628   memcpy (&sh[1], msg, mlen);
629   sh->h = h;
630   sh->cont = cont;
631   sh->cont_cls = cont_cls;
632   GNUNET_CONTAINER_DLL_insert_tail (h->sh_head,
633                                     h->sh_tail,
634                                     sh);
635   if (GNUNET_SCHEDULER_NO_TASK == h->write_task)
636     h->write_task = GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
637                                                      h->fh_to_helper, 
638                                                      &helper_write, 
639                                                      h);
640     
641   return sh;
642 }
643
644 /**
645  * Cancel a 'send' operation.  If possible, transmitting the
646  * message is also aborted, but at least 'cont' won't be
647  * called.
648  *
649  * @param sh operation to cancel
650  */
651 void
652 GNUNET_HELPER_send_cancel (struct GNUNET_HELPER_SendHandle *sh)
653 {
654   struct GNUNET_HELPER_Handle *h = sh->h;
655
656   sh->cont = NULL;
657   sh->cont_cls = NULL;
658   if (0 == sh->wpos)
659   {
660     GNUNET_CONTAINER_DLL_remove (h->sh_head, h->sh_tail, sh);
661     if (NULL == h->sh_head)
662     {
663       GNUNET_SCHEDULER_cancel (h->write_task);
664       h->write_task = GNUNET_SCHEDULER_NO_TASK;
665     }
666     GNUNET_free (sh);
667   }
668 }
669
670
671 /* end of helper.c */