4c78e325212e1a5217ca80cac28c875fbd1bb270
[oweals/gnunet.git] / src / testbed / gnunet-helper-testbed.c
1 /*
2       This file is part of GNUnet
3       (C) 2012 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 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 testbed/gnunet-helper-testbed.c
23  * @brief Helper binary that is started from a remote controller to start
24  *          gnunet-service-testbed. This binary also receives configuration
25  *          from the remove controller which is put in a temporary location
26  *          with ports and paths fixed so that gnunet-service-testbed runs
27  *          without any hurdles.  
28  * 
29  *          This helper monitors for three termination events.  They are: (1)The
30  *          stdin of the helper is closed for reading; (2)the helper received
31  *          SIGTERM/SIGINT; (3)the testbed crashed.  In case of events 1 and 2
32  *          the helper kills the testbed service.
33  *
34  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
35  */
36
37
38 #include "platform.h"
39 #include "gnunet_util_lib.h"
40 #include "gnunet_testing_lib.h"
41 #include "gnunet_testbed_service.h"
42 #include "testbed_helper.h"
43 #include "testbed_api.h"
44 #include <zlib.h>
45
46 /**
47  * Generic logging shortcut
48  */
49 #define LOG(kind, ...)                                   \
50   GNUNET_log (kind, __VA_ARGS__)
51
52 /**
53  * Debug logging shorthand
54  */
55 #define LOG_DEBUG(...)                          \
56   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
57
58
59 /**
60  * We need pipe control only on WINDOWS
61  */
62 #if WINDOWS
63 #define PIPE_CONTROL GNUNET_YES
64 #else
65 #define PIPE_CONTROL GNUNET_NO
66 #endif
67
68
69 /**
70  * Context for a single write on a chunk of memory
71  */
72 struct WriteContext
73 {
74   /**
75    * The data to write
76    */
77   void *data;
78
79   /**
80    * The length of the data
81    */
82   size_t length;
83
84   /**
85    * The current position from where the write operation should begin
86    */
87   size_t pos;
88 };
89
90
91 /**
92  * Handle to the testing system
93  */
94 static struct GNUNET_TESTING_System *test_system;
95
96 /**
97  * Our message stream tokenizer
98  */
99 struct GNUNET_SERVER_MessageStreamTokenizer *tokenizer;
100
101 /**
102  * Disk handle from stdin
103  */
104 static struct GNUNET_DISK_FileHandle *stdin_fd;
105
106 /**
107  * Disk handle for stdout
108  */
109 static struct GNUNET_DISK_FileHandle *stdout_fd;
110
111 /**
112  * The process handle to the testbed service
113  */
114 static struct GNUNET_OS_Process *testbed;
115
116 /**
117  * Pipe used to communicate shutdown via signal.
118  */
119 static struct GNUNET_DISK_PipeHandle *sigpipe;
120
121 /**
122  * Task identifier for the read task
123  */
124 static GNUNET_SCHEDULER_TaskIdentifier read_task_id;
125
126 /**
127  * Task identifier for the write task
128  */
129 static GNUNET_SCHEDULER_TaskIdentifier write_task_id;
130
131 /**
132  * Task to kill the child
133  */
134 static GNUNET_SCHEDULER_TaskIdentifier child_death_task_id;
135
136 /**
137  * shutdown task id
138  */
139 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
140
141 /**
142  * Are we done reading messages from stdin?
143  */
144 static int done_reading;
145
146 /**
147  * Result to return in case we fail
148  */
149 static int status;
150
151
152 /**
153  * Task to shut down cleanly
154  *
155  * @param cls NULL
156  * @param tc the task context
157  */
158 static void
159 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
160 {
161   LOG_DEBUG ("Shutting down\n");  
162   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
163   if (NULL != testbed)
164   {
165     LOG_DEBUG ("Killing testbed\n");
166     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, SIGTERM));
167   }  
168   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
169   {
170     GNUNET_SCHEDULER_cancel (read_task_id);
171     read_task_id = GNUNET_SCHEDULER_NO_TASK;
172   }
173   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
174   {
175     GNUNET_SCHEDULER_cancel (write_task_id);
176     write_task_id = GNUNET_SCHEDULER_NO_TASK;
177   }
178   if (GNUNET_SCHEDULER_NO_TASK != child_death_task_id)
179   {
180     GNUNET_SCHEDULER_cancel (child_death_task_id);
181     child_death_task_id = GNUNET_SCHEDULER_NO_TASK;
182   }
183   if (NULL != stdin_fd)
184     (void) GNUNET_DISK_file_close (stdin_fd);
185   if (NULL != stdout_fd)
186     (void) GNUNET_DISK_file_close (stdout_fd);
187   GNUNET_SERVER_mst_destroy (tokenizer);
188   tokenizer = NULL;
189   if (NULL != testbed)
190   {
191     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (testbed));
192     GNUNET_OS_process_destroy (testbed);
193     testbed = NULL;
194   }  
195   if (NULL != test_system)
196   {
197     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
198     test_system = NULL;
199   }
200 }
201
202
203 /**
204  * Scheduler shutdown task to be run now.
205  */
206 static void
207 shutdown_now (void)
208 {
209   if (GNUNET_SCHEDULER_NO_TASK != shutdown_task_id)
210     GNUNET_SCHEDULER_cancel (shutdown_task_id);
211   shutdown_task_id = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
212 }
213
214
215 /**
216  * Task to write to the standard out
217  *
218  * @param cls the WriteContext
219  * @param tc the TaskContext
220  */
221 static void
222 write_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
223 {
224   struct WriteContext *wc = cls;
225   ssize_t bytes_wrote;
226
227   GNUNET_assert (NULL != wc);
228   write_task_id = GNUNET_SCHEDULER_NO_TASK;
229   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
230   {
231     GNUNET_free (wc->data);
232     GNUNET_free (wc);
233     return;
234   }
235   bytes_wrote =
236       GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
237                               wc->length - wc->pos);
238   if (GNUNET_SYSERR == bytes_wrote)
239   {
240     LOG (GNUNET_ERROR_TYPE_WARNING, "Cannot reply back configuration\n");
241     GNUNET_free (wc->data);
242     GNUNET_free (wc);
243     return;
244   }
245   wc->pos += bytes_wrote;
246   if (wc->pos == wc->length)
247   {
248     GNUNET_free (wc->data);
249     GNUNET_free (wc);
250     return;
251   }
252   write_task_id =
253       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
254                                        &write_task, wc);
255 }
256
257
258 /**
259  * Task triggered whenever we receive a SIGCHLD (child
260  * process died).
261  *
262  * @param cls closure, NULL if we need to self-restart
263  * @param tc context
264  */
265 static void
266 child_death_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
267 {
268   const struct GNUNET_DISK_FileHandle *pr;
269   char c[16];
270   enum GNUNET_OS_ProcessStatusType type;
271   unsigned long code;
272   int ret;
273
274   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
275   child_death_task_id = GNUNET_SCHEDULER_NO_TASK;
276   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
277   {
278     child_death_task_id =
279         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
280                                         pr, &child_death_task, NULL);
281     return;
282   }
283   /* consume the signal */
284   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
285   LOG_DEBUG ("Got SIGCHLD\n");
286   if (NULL == testbed)
287   {
288     GNUNET_break (0);
289     return;
290   }
291   GNUNET_break (GNUNET_SYSERR != 
292                 (ret = GNUNET_OS_process_status (testbed, &type, &code)));
293   if (GNUNET_NO != ret)
294   {
295     GNUNET_OS_process_destroy (testbed);
296     testbed = NULL;
297     shutdown_now ();
298     return;
299   }
300   LOG_DEBUG ("Child hasn't died.  Resuming to monitor its status\n");
301   child_death_task_id =
302       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
303                                       pr, &child_death_task, NULL);
304 }
305
306
307 /**
308  * Functions with this signature are called whenever a
309  * complete message is received by the tokenizer.
310  *
311  * Do not call GNUNET_SERVER_mst_destroy in callback
312  *
313  * @param cls closure
314  * @param client identification of the client
315  * @param message the actual message
316  *
317  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
318  */
319 static int
320 tokenizer_cb (void *cls, void *client,
321               const struct GNUNET_MessageHeader *message)
322 {
323   const struct GNUNET_TESTBED_HelperInit *msg;
324   struct GNUNET_TESTBED_HelperReply *reply;
325   struct GNUNET_CONFIGURATION_Handle *cfg;
326   struct WriteContext *wc;
327   char *binary;
328   char *trusted_ip;
329   char *hostname;
330   char *config;
331   char *xconfig;
332   size_t config_size;
333   uLongf ul_config_size;
334   size_t xconfig_size;
335   uint16_t trusted_ip_size;
336   uint16_t hostname_size;
337   uint16_t msize;
338
339   msize = ntohs (message->size);
340   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
341       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
342   {
343     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
344     goto error;
345   }
346   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
347   trusted_ip_size = ntohs (msg->trusted_ip_size);
348   trusted_ip = (char *) &msg[1];
349   if ('\0' != trusted_ip[trusted_ip_size])
350   {
351     LOG (GNUNET_ERROR_TYPE_WARNING, "Trusted IP cannot be empty -- exiting\n");
352     goto error;
353   }
354   hostname_size = ntohs (msg->hostname_size);
355   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
356        hostname_size) >= msize)
357   {
358     GNUNET_break (0);
359     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
360     goto error;
361   }
362   ul_config_size = (uLongf) ntohs (msg->config_size);
363   config = GNUNET_malloc (ul_config_size);
364   xconfig_size =
365       ntohs (message->size) - (trusted_ip_size + 1 +
366                                sizeof (struct GNUNET_TESTBED_HelperInit));
367   if (Z_OK !=
368       uncompress ((Bytef *) config, &ul_config_size,
369                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 +
370                                    hostname_size), (uLongf) xconfig_size))
371   {
372     LOG (GNUNET_ERROR_TYPE_WARNING,
373          "Error while uncompressing config -- exiting\n");
374     GNUNET_free (config);
375     goto error;
376   }
377   cfg = GNUNET_CONFIGURATION_create ();
378   if (GNUNET_OK !=
379       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
380   {
381     LOG (GNUNET_ERROR_TYPE_WARNING,
382          "Unable to deserialize config -- exiting\n");
383     GNUNET_free (config);
384     goto error;
385   }
386   GNUNET_free (config);
387   hostname = NULL;
388   if (0 != hostname_size)
389   {
390     hostname = GNUNET_malloc (hostname_size + 1);
391     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1,
392                     hostname_size);
393     hostname[hostname_size] = '\0';
394   }
395   test_system =
396       GNUNET_TESTING_system_create ("testbed-helper", trusted_ip, hostname);
397   GNUNET_free_non_null (hostname);
398   hostname = NULL;
399   GNUNET_assert (NULL != test_system);
400   GNUNET_assert (GNUNET_OK ==
401                  GNUNET_TESTING_configuration_create (test_system, cfg));
402   GNUNET_assert (GNUNET_OK ==
403                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
404                                                         "DEFAULTCONFIG",
405                                                         &config));
406   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
407   {
408     LOG (GNUNET_ERROR_TYPE_WARNING,
409          "Unable to write config file: %s -- exiting\n", config);
410     GNUNET_CONFIGURATION_destroy (cfg);
411     GNUNET_free (config);
412     goto error;
413   }
414   LOG_DEBUG ("Staring testbed with config: %s\n", config);
415   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
416   testbed =
417       GNUNET_OS_start_process (PIPE_CONTROL,
418                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ , NULL,
419                                NULL, binary, "gnunet-service-testbed", "-c",
420                                config, NULL);
421   GNUNET_free (binary);
422   GNUNET_free (config);
423   if (NULL == testbed)
424   {
425     LOG (GNUNET_ERROR_TYPE_WARNING,
426          "Error starting gnunet-service-testbed -- exiting\n");
427     GNUNET_CONFIGURATION_destroy (cfg);
428     goto error;
429   }
430   done_reading = GNUNET_YES;
431   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
432   GNUNET_CONFIGURATION_destroy (cfg);
433   cfg = NULL;
434   xconfig_size =
435       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
436   GNUNET_free (config);
437   wc = GNUNET_malloc (sizeof (struct WriteContext));
438   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
439   reply = GNUNET_realloc (xconfig, wc->length);
440   memmove (&reply[1], reply, xconfig_size);
441   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
442   reply->header.size = htons ((uint16_t) wc->length);
443   reply->config_size = htons ((uint16_t) config_size);
444   wc->data = reply;
445   write_task_id =
446       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
447                                        &write_task, wc);  
448   child_death_task_id =
449       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
450                                       GNUNET_DISK_pipe_handle (sigpipe,
451                                                                GNUNET_DISK_PIPE_END_READ),
452                                       &child_death_task, NULL);
453   return GNUNET_OK;
454
455 error:
456   status = GNUNET_SYSERR;
457   shutdown_now ();
458   return GNUNET_SYSERR;
459 }
460
461
462 /**
463  * Task to read from stdin
464  *
465  * @param cls NULL
466  * @param tc the task context
467  */
468 static void
469 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
470 {
471   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
472   ssize_t sread;
473
474   read_task_id = GNUNET_SCHEDULER_NO_TASK;
475   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
476     return;
477   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
478   if ((GNUNET_SYSERR == sread) || (0 == sread))
479   {
480     LOG_DEBUG ("STDIN closed\n");
481     shutdown_now ();
482     return;
483   }
484   if (GNUNET_YES == done_reading)
485   {
486     /* didn't expect any more data! */
487     GNUNET_break_op (0);
488     shutdown_now ();
489     return;
490   }
491   LOG_DEBUG ("Read %u bytes\n", sread);
492   if (GNUNET_OK !=
493       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
494                                  GNUNET_NO))
495   {
496     GNUNET_break (0);
497     shutdown_now ();
498     return;
499   }
500   read_task_id =                /* No timeout while reading */
501       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
502                                       &read_task, NULL);
503 }
504
505
506 /**
507  * Main function that will be run.
508  *
509  * @param cls closure
510  * @param args remaining command-line arguments
511  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
512  * @param cfg configuration
513  */
514 static void
515 run (void *cls, char *const *args, const char *cfgfile,
516      const struct GNUNET_CONFIGURATION_Handle *cfg)
517 {
518   LOG_DEBUG ("Starting testbed helper...\n");
519   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
520   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
521   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
522   read_task_id =
523       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
524                                       &read_task, NULL);
525   shutdown_task_id = 
526       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
527                                     NULL);
528 }
529
530
531 /**
532  * Signal handler called for SIGCHLD.
533  */
534 static void
535 sighandler_child_death ()
536 {
537   static char c;
538   int old_errno;        /* back-up errno */
539
540   old_errno = errno;
541   GNUNET_break (1 ==
542                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
543                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
544                                         &c, sizeof (c)));
545   errno = old_errno;
546 }
547
548
549 /**
550  * Main function
551  *
552  * @param argc the number of command line arguments
553  * @param argv command line arg array
554  * @return return code
555  */
556 int
557 main (int argc, char **argv)
558 {
559   struct GNUNET_SIGNAL_Context *shc_chld;
560
561   struct GNUNET_GETOPT_CommandLineOption options[] = {
562     GNUNET_GETOPT_OPTION_END
563   };
564   int ret;
565
566   status = GNUNET_OK;
567   if (NULL == (sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, 
568                                            GNUNET_NO, GNUNET_NO)))
569   {
570     GNUNET_break (0);
571     ret = GNUNET_SYSERR;
572     return 1;
573   }
574   shc_chld =
575       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
576   ret =
577       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
578                           "Helper for starting gnunet-service-testbed", options,
579                           &run, NULL);
580   GNUNET_SIGNAL_handler_uninstall (shc_chld);
581   shc_chld = NULL;
582   GNUNET_DISK_pipe_close (sigpipe);
583   if (GNUNET_OK != ret)
584     return 1;
585   return (GNUNET_OK == status) ? 0 : 1;
586 }
587
588 /* end of gnunet-helper-testbed.c */