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