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