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