fix related to #4909/12605: force desirability of path if path is in use
[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
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., 51 Franklin Street, Fifth Floor,
18       Boston, MA 02110-1301, 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_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 struct GNUNET_SCHEDULER_Task *read_task_id;
128
129 /**
130  * Task identifier for the write task
131  */
132 static struct GNUNET_SCHEDULER_Task *write_task_id;
133
134 /**
135  * Task to kill the child
136  */
137 static struct GNUNET_SCHEDULER_Task *child_death_task_id;
138
139 /**
140  * Are we done reading messages from stdin?
141  */
142 static int done_reading;
143
144 /**
145  * Result to return in case we fail
146  */
147 static int status;
148
149
150 /**
151  * Task to shut down cleanly
152  *
153  * @param cls NULL
154  */
155 static void
156 shutdown_task (void *cls)
157 {
158   LOG_DEBUG ("Shutting down\n");
159   if (NULL != testbed)
160   {
161     LOG_DEBUG ("Killing testbed\n");
162     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, GNUNET_TERM_SIG));
163   }
164   if (NULL != read_task_id)
165   {
166     GNUNET_SCHEDULER_cancel (read_task_id);
167     read_task_id = NULL;
168   }
169   if (NULL != write_task_id)
170   {
171     struct WriteContext *wc;
172
173     wc = GNUNET_SCHEDULER_cancel (write_task_id);
174     write_task_id = NULL;
175     GNUNET_free (wc->data);
176     GNUNET_free (wc);
177   }
178   if (NULL != child_death_task_id)
179   {
180     GNUNET_SCHEDULER_cancel (child_death_task_id);
181     child_death_task_id = NULL;
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_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  * Task to write to the standard out
205  *
206  * @param cls the WriteContext
207  */
208 static void
209 write_task (void *cls)
210 {
211   struct WriteContext *wc = cls;
212   ssize_t bytes_wrote;
213
214   GNUNET_assert (NULL != wc);
215   write_task_id = NULL;
216   bytes_wrote =
217       GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
218                               wc->length - wc->pos);
219   if (GNUNET_SYSERR == bytes_wrote)
220   {
221     LOG (GNUNET_ERROR_TYPE_WARNING,
222          "Cannot reply back configuration\n");
223     GNUNET_free (wc->data);
224     GNUNET_free (wc);
225     return;
226   }
227   wc->pos += bytes_wrote;
228   if (wc->pos == wc->length)
229   {
230     GNUNET_free (wc->data);
231     GNUNET_free (wc);
232     return;
233   }
234   write_task_id =
235       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
236                                        stdout_fd,
237                                        &write_task, wc);
238 }
239
240
241 /**
242  * Task triggered whenever we receive a SIGCHLD (child
243  * process died).
244  *
245  * @param cls closure, NULL if we need to self-restart
246  */
247 static void
248 child_death_task (void *cls)
249 {
250   const struct GNUNET_DISK_FileHandle *pr;
251   char c[16];
252   enum GNUNET_OS_ProcessStatusType type;
253   unsigned long code;
254   int ret;
255
256   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
257   child_death_task_id = NULL;
258   /* consume the signal */
259   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
260   LOG_DEBUG ("Got SIGCHLD\n");
261   if (NULL == testbed)
262   {
263     GNUNET_break (0);
264     return;
265   }
266   GNUNET_break (GNUNET_SYSERR !=
267                 (ret = GNUNET_OS_process_status (testbed, &type, &code)));
268   if (GNUNET_NO != ret)
269   {
270     GNUNET_OS_process_destroy (testbed);
271     testbed = NULL;
272     /* Send SIGTERM to our process group */
273     if (0 != PLIBC_KILL (0, GNUNET_TERM_SIG))
274     {
275       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "signal");
276       GNUNET_SCHEDULER_shutdown ();   /* Couldn't send the signal, we shutdown frowning */
277     }
278     return;
279   }
280   LOG_DEBUG ("Child hasn't died.  Resuming to monitor its status\n");
281   child_death_task_id =
282       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
283                                       pr, &child_death_task, NULL);
284 }
285
286
287 /**
288  * Functions with this signature are called whenever a
289  * complete message is received by the tokenizer.
290  *
291  * Do not call #GNUNET_mst_destroy() in this callback
292  *
293  * @param cls identification of the client
294  * @param message the actual message
295  *
296  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
297  */
298 static int
299 tokenizer_cb (void *cls,
300               const struct GNUNET_MessageHeader *message)
301 {
302   const struct GNUNET_TESTBED_HelperInit *msg;
303   struct GNUNET_TESTBED_HelperReply *reply;
304   struct GNUNET_CONFIGURATION_Handle *cfg;
305   struct WriteContext *wc;
306   char *binary;
307   char *trusted_ip;
308   char *hostname;
309   char *config;
310   char *xconfig;
311   char *evstr;
312   //char *str;
313   size_t config_size;
314   uLongf ul_config_size;
315   size_t xconfig_size;
316   uint16_t trusted_ip_size;
317   uint16_t hostname_size;
318   uint16_t msize;
319
320   msize = ntohs (message->size);
321   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
322       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
323   {
324     LOG (GNUNET_ERROR_TYPE_WARNING,
325          "Received unexpected message -- exiting\n");
326     goto error;
327   }
328   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
329   trusted_ip_size = ntohs (msg->trusted_ip_size);
330   trusted_ip = (char *) &msg[1];
331   if ('\0' != trusted_ip[trusted_ip_size])
332   {
333     LOG (GNUNET_ERROR_TYPE_WARNING, "Trusted IP cannot be empty -- exiting\n");
334     goto error;
335   }
336   hostname_size = ntohs (msg->hostname_size);
337   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
338        hostname_size) >= msize)
339   {
340     GNUNET_break (0);
341     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
342     goto error;
343   }
344   ul_config_size = (uLongf) ntohs (msg->config_size);
345   config = GNUNET_malloc (ul_config_size);
346   xconfig_size =
347       ntohs (message->size) - (trusted_ip_size + 1 +
348                                sizeof (struct GNUNET_TESTBED_HelperInit));
349   if (Z_OK !=
350       uncompress ((Bytef *) config, &ul_config_size,
351                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 +
352                                    hostname_size), (uLongf) xconfig_size))
353   {
354     LOG (GNUNET_ERROR_TYPE_WARNING,
355          "Error while uncompressing config -- exiting\n");
356     GNUNET_free (config);
357     goto error;
358   }
359   cfg = GNUNET_CONFIGURATION_create ();
360   if (GNUNET_OK !=
361       GNUNET_CONFIGURATION_deserialize (cfg,
362                                         config, 
363                                         ul_config_size,
364                                         NULL))
365   {
366     LOG (GNUNET_ERROR_TYPE_WARNING,
367          "Unable to deserialize config -- exiting\n");
368     GNUNET_free (config);
369     goto error;
370   }
371   GNUNET_free (config);
372   hostname = NULL;
373   if (0 != hostname_size)
374   {
375     hostname = GNUNET_malloc (hostname_size + 1);
376     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1,
377                     hostname_size);
378     hostname[hostname_size] = '\0';
379   }
380   /* unset GNUNET_TESTING_PREFIX if present as it is more relevant for testbed */
381   evstr = getenv (GNUNET_TESTING_PREFIX);
382   if (NULL != evstr)
383   {
384     /* unsetting the variable will invalidate the pointer! */
385     evstr = GNUNET_strdup (evstr);
386 #ifdef WINDOWS
387     GNUNET_break (0 != SetEnvironmentVariable (GNUNET_TESTING_PREFIX, NULL));
388 #else
389     GNUNET_break (0 == unsetenv (GNUNET_TESTING_PREFIX));
390 #endif
391   }
392   test_system =
393       GNUNET_TESTING_system_create ("testbed-helper", trusted_ip, hostname,
394                                     NULL);
395   if (NULL != evstr)
396   {
397 #ifdef WINDOWS
398     GNUNET_assert (0 != SetEnvironmentVariable (GNUNET_TESTING_PREFIX,
399                                                 evstr));
400 #else
401     char *evar;
402
403     GNUNET_asprintf (&evar,
404                      GNUNET_TESTING_PREFIX "=%s",
405                      evstr);
406     GNUNET_assert (0 == putenv (evar)); /* consumes 'evar',
407                                            see putenv(): becomes part of envrionment! */
408 #endif
409     GNUNET_free (evstr);
410     evstr = NULL;
411   }
412   GNUNET_free_non_null (hostname);
413   hostname = NULL;
414   GNUNET_assert (NULL != test_system);
415   GNUNET_assert (GNUNET_OK ==
416                  GNUNET_TESTING_configuration_create (test_system, cfg));
417   GNUNET_assert (GNUNET_OK ==
418                  GNUNET_CONFIGURATION_get_value_filename (cfg, "PATHS",
419                                                         "DEFAULTCONFIG",
420                                                         &config));
421   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
422   {
423     LOG (GNUNET_ERROR_TYPE_WARNING,
424          "Unable to write config file: %s -- exiting\n", config);
425     GNUNET_CONFIGURATION_destroy (cfg);
426     GNUNET_free (config);
427     goto error;
428   }
429   LOG_DEBUG ("Staring testbed with config: %s\n", config);
430   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
431   {
432     char *evar;
433
434     /* expose testbed configuration through env variable */
435     GNUNET_asprintf (&evar,
436                      "%s=%s",
437                      ENV_TESTBED_CONFIG,
438                      config);
439     GNUNET_assert (0 == putenv (evar));  /* consumes 'evar',
440                                             see putenv(): becomes part of envrionment! */
441     evstr = NULL;
442   }
443   testbed =
444       GNUNET_OS_start_process (PIPE_CONTROL,
445                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ ,
446                                NULL, NULL, NULL,
447                                binary,
448                                "gnunet-service-testbed",
449                                "-c", config,
450                                NULL);
451   GNUNET_free (binary);
452   GNUNET_free (config);
453   if (NULL == testbed)
454   {
455     LOG (GNUNET_ERROR_TYPE_WARNING,
456          "Error starting gnunet-service-testbed -- exiting\n");
457     GNUNET_CONFIGURATION_destroy (cfg);
458     goto error;
459   }
460   done_reading = GNUNET_YES;
461   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
462   GNUNET_CONFIGURATION_destroy (cfg);
463   cfg = NULL;
464   xconfig_size =
465       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
466   GNUNET_free (config);
467   wc = GNUNET_new (struct WriteContext);
468   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
469   reply = GNUNET_realloc (xconfig, wc->length);
470   memmove (&reply[1], reply, xconfig_size);
471   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
472   reply->header.size = htons ((uint16_t) wc->length);
473   reply->config_size = htons ((uint16_t) config_size);
474   wc->data = reply;
475   write_task_id =
476       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
477                                        stdout_fd,
478                                        &write_task, wc);
479   child_death_task_id =
480       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
481                                       GNUNET_DISK_pipe_handle (sigpipe,
482                                                                GNUNET_DISK_PIPE_END_READ),
483                                       &child_death_task, NULL);
484   return GNUNET_OK;
485
486 error:
487   status = GNUNET_SYSERR;
488   GNUNET_SCHEDULER_shutdown ();
489   return GNUNET_SYSERR;
490 }
491
492
493 /**
494  * Task to read from stdin
495  *
496  * @param cls NULL
497  */
498 static void
499 read_task (void *cls)
500 {
501   char buf[GNUNET_MAX_MESSAGE_SIZE];
502   ssize_t sread;
503
504   read_task_id = NULL;
505   sread = GNUNET_DISK_file_read (stdin_fd,
506                                  buf,
507                                  sizeof (buf));
508   if ( (GNUNET_SYSERR == sread) ||
509        (0 == sread) )
510   {
511     LOG_DEBUG ("STDIN closed\n");
512     GNUNET_SCHEDULER_shutdown ();
513     return;
514   }
515   if (GNUNET_YES == done_reading)
516   {
517     /* didn't expect any more data! */
518     GNUNET_break_op (0);
519     GNUNET_SCHEDULER_shutdown ();
520     return;
521   }
522   LOG_DEBUG ("Read %u bytes\n",
523              (unsigned int) sread);
524   /* FIXME: could introduce a GNUNET_MST_read2 to read
525      directly from 'stdin_fd' and save a memcpy() here */
526   if (GNUNET_OK !=
527       GNUNET_MST_from_buffer (tokenizer,
528                               buf,
529                               sread,
530                               GNUNET_NO,
531                               GNUNET_NO))
532   {
533     GNUNET_break (0);
534     GNUNET_SCHEDULER_shutdown ();
535     return;
536   }
537   read_task_id                 /* No timeout while reading */
538     = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
539                                       stdin_fd,
540                                       &read_task,
541                                       NULL);
542 }
543
544
545 /**
546  * Main function that will be run.
547  *
548  * @param cls closure
549  * @param args remaining command-line arguments
550  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
551  * @param cfg configuration
552  */
553 static void
554 run (void *cls,
555      char *const *args,
556      const char *cfgfile,
557      const struct GNUNET_CONFIGURATION_Handle *cfg)
558 {
559   LOG_DEBUG ("Starting testbed helper...\n");
560   tokenizer = GNUNET_MST_create (&tokenizer_cb, NULL);
561   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
562   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
563   read_task_id =
564       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
565                                       stdin_fd,
566                                       &read_task, NULL);
567   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
568                                  NULL);
569 }
570
571
572 /**
573  * Signal handler called for SIGCHLD.
574  */
575 static void
576 sighandler_child_death ()
577 {
578   static char c;
579   int old_errno;        /* back-up errno */
580
581   old_errno = errno;
582   GNUNET_break (1 ==
583                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
584                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
585                                         &c, sizeof (c)));
586   errno = old_errno;
587 }
588
589
590 /**
591  * Main function
592  *
593  * @param argc the number of command line arguments
594  * @param argv command line arg array
595  * @return return code
596  */
597 int
598 main (int argc,
599       char **argv)
600 {
601   struct GNUNET_SIGNAL_Context *shc_chld;
602   struct GNUNET_GETOPT_CommandLineOption options[] = {
603     GNUNET_GETOPT_OPTION_END
604   };
605   int ret;
606
607   status = GNUNET_OK;
608   if (NULL == (sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO,
609                                            GNUNET_NO, GNUNET_NO)))
610   {
611     GNUNET_break (0);
612     return 1;
613   }
614   shc_chld = GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD,
615                                             &sighandler_child_death);
616   ret = GNUNET_PROGRAM_run (argc, argv,
617                             "gnunet-helper-testbed",
618                             "Helper for starting gnunet-service-testbed",
619                             options,
620                             &run,
621                             NULL);
622   GNUNET_SIGNAL_handler_uninstall (shc_chld);
623   shc_chld = NULL;
624   GNUNET_DISK_pipe_close (sigpipe);
625   if (GNUNET_OK != ret)
626     return 1;
627   return (GNUNET_OK == status) ? 0 : 1;
628 }
629
630 /* end of gnunet-helper-testbed.c */