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