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