6df42c609d498e32f68ff175c151f2d33cf93f35
[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
271   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
272   child_death_task_id = GNUNET_SCHEDULER_NO_TASK;
273   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
274   {
275     child_death_task_id =
276         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
277                                         pr, &child_death_task, NULL);
278     return;
279   }
280   /* consume the signal */
281   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
282   LOG_DEBUG ("Child died\n");
283   if (NULL != testbed)
284   {
285     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (testbed));
286     GNUNET_OS_process_destroy (testbed);
287     testbed = NULL;
288   }
289   shutdown_now ();
290 }
291
292
293 /**
294  * Functions with this signature are called whenever a
295  * complete message is received by the tokenizer.
296  *
297  * Do not call GNUNET_SERVER_mst_destroy in callback
298  *
299  * @param cls closure
300  * @param client identification of the client
301  * @param message the actual message
302  *
303  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
304  */
305 static int
306 tokenizer_cb (void *cls, void *client,
307               const struct GNUNET_MessageHeader *message)
308 {
309   const struct GNUNET_TESTBED_HelperInit *msg;
310   struct GNUNET_TESTBED_HelperReply *reply;
311   struct GNUNET_CONFIGURATION_Handle *cfg;
312   struct WriteContext *wc;
313   char *binary;
314   char *trusted_ip;
315   char *hostname;
316   char *config;
317   char *xconfig;
318   size_t config_size;
319   uLongf ul_config_size;
320   size_t xconfig_size;
321   uint16_t trusted_ip_size;
322   uint16_t hostname_size;
323   uint16_t msize;
324
325   msize = ntohs (message->size);
326   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
327       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
328   {
329     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
330     goto error;
331   }
332   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
333   trusted_ip_size = ntohs (msg->trusted_ip_size);
334   trusted_ip = (char *) &msg[1];
335   if ('\0' != trusted_ip[trusted_ip_size])
336   {
337     LOG (GNUNET_ERROR_TYPE_WARNING, "Trusted IP cannot be empty -- exiting\n");
338     goto error;
339   }
340   hostname_size = ntohs (msg->hostname_size);
341   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
342        hostname_size) >= msize)
343   {
344     GNUNET_break (0);
345     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
346     goto error;
347   }
348   ul_config_size = (uLongf) ntohs (msg->config_size);
349   config = GNUNET_malloc (ul_config_size);
350   xconfig_size =
351       ntohs (message->size) - (trusted_ip_size + 1 +
352                                sizeof (struct GNUNET_TESTBED_HelperInit));
353   if (Z_OK !=
354       uncompress ((Bytef *) config, &ul_config_size,
355                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 +
356                                    hostname_size), (uLongf) xconfig_size))
357   {
358     LOG (GNUNET_ERROR_TYPE_WARNING,
359          "Error while uncompressing config -- exiting\n");
360     GNUNET_free (config);
361     goto error;
362   }
363   cfg = GNUNET_CONFIGURATION_create ();
364   if (GNUNET_OK !=
365       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
366   {
367     LOG (GNUNET_ERROR_TYPE_WARNING,
368          "Unable to deserialize config -- exiting\n");
369     GNUNET_free (config);
370     goto error;
371   }
372   GNUNET_free (config);
373   hostname = NULL;
374   if (0 != hostname_size)
375   {
376     hostname = GNUNET_malloc (hostname_size + 1);
377     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1,
378                     hostname_size);
379     hostname[hostname_size] = '\0';
380   }
381   test_system =
382       GNUNET_TESTING_system_create ("testbed-helper", trusted_ip, hostname);
383   GNUNET_free_non_null (hostname);
384   hostname = NULL;
385   GNUNET_assert (NULL != test_system);
386   GNUNET_assert (GNUNET_OK ==
387                  GNUNET_TESTING_configuration_create (test_system, cfg));
388   GNUNET_assert (GNUNET_OK ==
389                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
390                                                         "DEFAULTCONFIG",
391                                                         &config));
392   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
393   {
394     LOG (GNUNET_ERROR_TYPE_WARNING,
395          "Unable to write config file: %s -- exiting\n", config);
396     GNUNET_CONFIGURATION_destroy (cfg);
397     GNUNET_free (config);
398     goto error;
399   }
400   LOG_DEBUG ("Staring testbed with config: %s\n", config);
401   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
402   testbed =
403       GNUNET_OS_start_process (PIPE_CONTROL,
404                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ , NULL,
405                                NULL, binary, "gnunet-service-testbed", "-c",
406                                config, NULL);
407   GNUNET_free (binary);
408   GNUNET_free (config);
409   if (NULL == testbed)
410   {
411     LOG (GNUNET_ERROR_TYPE_WARNING,
412          "Error starting gnunet-service-testbed -- exiting\n");
413     GNUNET_CONFIGURATION_destroy (cfg);
414     goto error;
415   }
416   done_reading = GNUNET_YES;
417   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
418   GNUNET_CONFIGURATION_destroy (cfg);
419   cfg = NULL;
420   xconfig_size =
421       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
422   GNUNET_free (config);
423   wc = GNUNET_malloc (sizeof (struct WriteContext));
424   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
425   reply = GNUNET_realloc (xconfig, wc->length);
426   memmove (&reply[1], reply, xconfig_size);
427   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
428   reply->header.size = htons ((uint16_t) wc->length);
429   reply->config_size = htons ((uint16_t) config_size);
430   wc->data = reply;
431   write_task_id =
432       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
433                                        &write_task, wc);  
434   child_death_task_id =
435       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
436                                       GNUNET_DISK_pipe_handle (sigpipe,
437                                                                GNUNET_DISK_PIPE_END_READ),
438                                       &child_death_task, NULL);
439   return GNUNET_OK;
440
441 error:
442   status = GNUNET_SYSERR;
443   shutdown_now ();
444   return GNUNET_SYSERR;
445 }
446
447
448 /**
449  * Task to read from stdin
450  *
451  * @param cls NULL
452  * @param tc the task context
453  */
454 static void
455 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
456 {
457   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
458   ssize_t sread;
459
460   read_task_id = GNUNET_SCHEDULER_NO_TASK;
461   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
462     return;
463   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
464   if ((GNUNET_SYSERR == sread) || (0 == sread))
465   {
466     LOG_DEBUG ("STDIN closed\n");
467     shutdown_now ();
468     return;
469   }
470   if (GNUNET_YES == done_reading)
471   {
472     /* didn't expect any more data! */
473     GNUNET_break_op (0);
474     shutdown_now ();
475     return;
476   }
477   LOG_DEBUG ("Read %u bytes\n", sread);
478   if (GNUNET_OK !=
479       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
480                                  GNUNET_NO))
481   {
482     GNUNET_break (0);
483     shutdown_now ();
484     return;
485   }
486   read_task_id =                /* No timeout while reading */
487       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
488                                       &read_task, NULL);
489 }
490
491
492 /**
493  * Main function that will be run.
494  *
495  * @param cls closure
496  * @param args remaining command-line arguments
497  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
498  * @param cfg configuration
499  */
500 static void
501 run (void *cls, char *const *args, const char *cfgfile,
502      const struct GNUNET_CONFIGURATION_Handle *cfg)
503 {
504   LOG_DEBUG ("Starting testbed helper...\n");
505   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
506   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
507   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
508   read_task_id =
509       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
510                                       &read_task, NULL);
511   shutdown_task_id = 
512       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
513                                     NULL);
514 }
515
516
517 /**
518  * Signal handler called for SIGCHLD.
519  */
520 static void
521 sighandler_child_death ()
522 {
523   static char c;
524   int old_errno;        /* back-up errno */
525
526   old_errno = errno;
527   GNUNET_break (1 ==
528                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
529                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
530                                         &c, sizeof (c)));
531   errno = old_errno;
532 }
533
534
535 /**
536  * Main function
537  *
538  * @param argc the number of command line arguments
539  * @param argv command line arg array
540  * @return return code
541  */
542 int
543 main (int argc, char **argv)
544 {
545   struct GNUNET_SIGNAL_Context *shc_chld;
546
547   struct GNUNET_GETOPT_CommandLineOption options[] = {
548     GNUNET_GETOPT_OPTION_END
549   };
550   int ret;
551
552   status = GNUNET_OK;
553   if (NULL == (sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, 
554                                            GNUNET_NO, GNUNET_NO)))
555   {
556     GNUNET_break (0);
557     ret = GNUNET_SYSERR;
558     return 1;
559   }
560   shc_chld =
561       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
562   ret =
563       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
564                           "Helper for starting gnunet-service-testbed", options,
565                           &run, NULL);
566   GNUNET_SIGNAL_handler_uninstall (shc_chld);
567   shc_chld = NULL;
568   GNUNET_DISK_pipe_close (sigpipe);
569   if (GNUNET_OK != ret)
570     return 1;
571   return (GNUNET_OK == status) ? 0 : 1;
572 }
573
574 /* end of gnunet-helper-testbed.c */