- remove unused code
[oweals/gnunet.git] / src / testbed / gnunet-helper-testbed.c
1 /*
2       This file is part of GNUnet
3       (C) 2012 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, 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. This binary also kills the testbed service
28  *          should the connection from the remote controller is dropped
29  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
30  */
31
32
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_testing_lib.h"
36 #include "gnunet_testbed_service.h"
37 #include "testbed_helper.h"
38 #include "testbed_api.h"
39 #include <zlib.h>
40
41 /**
42  * Generic logging shortcut
43  */
44 #define LOG(kind, ...)                                   \
45   GNUNET_log (kind, __VA_ARGS__)
46
47 /**
48  * Debug logging shorthand
49  */
50 #define LOG_DEBUG(...)                          \
51   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
52
53
54 /**
55  * We need pipe control only on WINDOWS
56  */
57 #if WINDOWS
58 #define PIPE_CONTROL GNUNET_YES
59 #else
60 #define PIPE_CONTROL GNUNET_NO
61 #endif
62
63
64 /**
65  * Context for a single write on a chunk of memory
66  */
67 struct WriteContext
68 {
69   /**
70    * The data to write
71    */
72   void *data;
73
74   /**
75    * The length of the data
76    */
77   size_t length;
78
79   /**
80    * The current position from where the write operation should begin
81    */
82   size_t pos;
83 };
84
85
86 /**
87  * Handle to the testing system
88  */
89 static struct GNUNET_TESTING_System *test_system;
90
91 /**
92  * Our message stream tokenizer
93  */
94 struct GNUNET_SERVER_MessageStreamTokenizer *tokenizer;
95
96 /**
97  * Disk handle from stdin
98  */
99 static struct GNUNET_DISK_FileHandle *stdin_fd;
100
101 /**
102  * Disk handle for stdout
103  */
104 static struct GNUNET_DISK_FileHandle *stdout_fd;
105
106 /**
107  * The process handle to the testbed service
108  */
109 static struct GNUNET_OS_Process *testbed;
110
111 /**
112  * Pipe used to communicate shutdown via signal.
113  */
114 static struct GNUNET_DISK_PipeHandle *sigpipe;
115
116 /**
117  * Task identifier for the read task
118  */
119 static GNUNET_SCHEDULER_TaskIdentifier read_task_id;
120
121 /**
122  * Task identifier for the write task
123  */
124 static GNUNET_SCHEDULER_TaskIdentifier write_task_id;
125
126 /**
127  * Task to kill the child
128  */
129 static GNUNET_SCHEDULER_TaskIdentifier child_death_task_id;
130
131 /**
132  * Are we done reading messages from stdin?
133  */
134 static int done_reading;
135
136 /**
137  * Result to return in case we fail
138  */
139 static int status;
140
141
142 /**
143  * Are we shutting down
144  */
145 static int in_shutdown;
146
147
148 /**
149  * Task to shutting down nicely
150  *
151  * @param cls NULL
152  * @param tc the task context
153  */
154 static void
155 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
156 {
157   LOG_DEBUG ("Shutting down\n");
158   in_shutdown = GNUNET_YES;
159   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
160   {
161     GNUNET_SCHEDULER_cancel (read_task_id);
162     read_task_id = GNUNET_SCHEDULER_NO_TASK;
163   }
164   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
165   {
166     GNUNET_SCHEDULER_cancel (write_task_id);
167     write_task_id = GNUNET_SCHEDULER_NO_TASK;
168   }
169   if (NULL != stdin_fd)
170     (void) GNUNET_DISK_file_close (stdin_fd);
171   if (NULL != stdout_fd)
172     (void) GNUNET_DISK_file_close (stdout_fd);
173   GNUNET_SERVER_mst_destroy (tokenizer);
174   tokenizer = NULL;
175   if (NULL != testbed)
176   {
177     LOG_DEBUG ("Killing testbed\n");
178     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, SIGTERM));
179   }
180 }
181
182
183 /**
184  * Task to write to the standard out
185  *
186  * @param cls the WriteContext
187  * @param tc the TaskContext
188  */
189 static void
190 write_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
191 {
192   struct WriteContext *wc = cls;
193   ssize_t bytes_wrote;
194
195   GNUNET_assert (NULL != wc);
196   write_task_id = GNUNET_SCHEDULER_NO_TASK;
197   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
198   {
199     GNUNET_free (wc->data);
200     GNUNET_free (wc);
201     return;
202   }
203   bytes_wrote =
204       GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
205                               wc->length - wc->pos);
206   if (GNUNET_SYSERR == bytes_wrote)
207   {
208     LOG (GNUNET_ERROR_TYPE_WARNING, "Cannot reply back configuration\n");
209     GNUNET_free (wc->data);
210     GNUNET_free (wc);
211     return;
212   }
213   wc->pos += bytes_wrote;
214   if (wc->pos == wc->length)
215   {
216     GNUNET_free (wc->data);
217     GNUNET_free (wc);
218     return;
219   }
220   write_task_id =
221       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
222                                        &write_task, wc);
223 }
224
225
226 /**
227  * Functions with this signature are called whenever a
228  * complete message is received by the tokenizer.
229  *
230  * Do not call GNUNET_SERVER_mst_destroy in callback
231  *
232  * @param cls closure
233  * @param client identification of the client
234  * @param message the actual message
235  *
236  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
237  */
238 static int
239 tokenizer_cb (void *cls, void *client,
240               const struct GNUNET_MessageHeader *message)
241 {
242   const struct GNUNET_TESTBED_HelperInit *msg;
243   struct GNUNET_TESTBED_HelperReply *reply;
244   struct GNUNET_CONFIGURATION_Handle *cfg;
245   struct WriteContext *wc;
246   char *binary;
247   char *trusted_ip;
248   char *hostname;
249   char *config;
250   char *xconfig;
251   size_t config_size;
252   uLongf ul_config_size;
253   size_t xconfig_size;
254   uint16_t trusted_ip_size;
255   uint16_t hostname_size;
256   uint16_t msize;
257
258   msize = ntohs (message->size);
259   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
260       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
261   {
262     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
263     goto error;
264   }
265   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
266   trusted_ip_size = ntohs (msg->trusted_ip_size);
267   trusted_ip = (char *) &msg[1];
268   if ('\0' != trusted_ip[trusted_ip_size])
269   {
270     LOG (GNUNET_ERROR_TYPE_WARNING, "Trusted IP cannot be empty -- exiting\n");
271     goto error;
272   }
273   hostname_size = ntohs (msg->hostname_size);
274   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
275        hostname_size) >= msize)
276   {
277     GNUNET_break (0);
278     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
279     goto error;
280   }
281   ul_config_size = (uLongf) ntohs (msg->config_size);
282   config = GNUNET_malloc (ul_config_size);
283   xconfig_size =
284       ntohs (message->size) - (trusted_ip_size + 1 +
285                                sizeof (struct GNUNET_TESTBED_HelperInit));
286   if (Z_OK !=
287       uncompress ((Bytef *) config, &ul_config_size,
288                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 +
289                                    hostname_size), (uLongf) xconfig_size))
290   {
291     LOG (GNUNET_ERROR_TYPE_WARNING,
292          "Error while uncompressing config -- exiting\n");
293     GNUNET_free (config);
294     goto error;
295   }
296   cfg = GNUNET_CONFIGURATION_create ();
297   if (GNUNET_OK !=
298       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
299   {
300     LOG (GNUNET_ERROR_TYPE_WARNING,
301          "Unable to deserialize config -- exiting\n");
302     GNUNET_free (config);
303     goto error;
304   }
305   GNUNET_free (config);
306   hostname = NULL;
307   if (0 != hostname_size)
308   {
309     hostname = GNUNET_malloc (hostname_size + 1);
310     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1,
311                     hostname_size);
312     hostname[hostname_size] = '\0';
313   }
314   test_system =
315       GNUNET_TESTING_system_create ("testbed-helper", trusted_ip, hostname);
316   GNUNET_free_non_null (hostname);
317   hostname = NULL;
318   GNUNET_assert (NULL != test_system);
319   GNUNET_assert (GNUNET_OK ==
320                  GNUNET_TESTING_configuration_create (test_system, cfg));
321   GNUNET_assert (GNUNET_OK ==
322                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
323                                                         "DEFAULTCONFIG",
324                                                         &config));
325   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
326   {
327     LOG (GNUNET_ERROR_TYPE_WARNING,
328          "Unable to write config file: %s -- exiting\n", config);
329     GNUNET_CONFIGURATION_destroy (cfg);
330     GNUNET_free (config);
331     goto error;
332   }
333   LOG_DEBUG ("Staring testbed with config: %s\n", config);
334   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
335   testbed =
336       GNUNET_OS_start_process (PIPE_CONTROL,
337                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ , NULL,
338                                NULL, binary, "gnunet-service-testbed", "-c",
339                                config, NULL);
340   GNUNET_free (binary);
341   GNUNET_free (config);
342   if (NULL == testbed)
343   {
344     LOG (GNUNET_ERROR_TYPE_WARNING,
345          "Error starting gnunet-service-testbed -- exiting\n");
346     GNUNET_CONFIGURATION_destroy (cfg);
347     goto error;
348   }
349   done_reading = GNUNET_YES;
350   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
351   GNUNET_CONFIGURATION_destroy (cfg);
352   cfg = NULL;
353   xconfig_size =
354       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
355   GNUNET_free (config);
356   wc = GNUNET_malloc (sizeof (struct WriteContext));
357   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
358   reply = GNUNET_realloc (xconfig, wc->length);
359   memmove (&reply[1], reply, xconfig_size);
360   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
361   reply->header.size = htons ((uint16_t) wc->length);
362   reply->config_size = htons ((uint16_t) config_size);
363   wc->data = reply;
364   write_task_id =
365       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
366                                        &write_task, wc);
367   return GNUNET_OK;
368
369 error:
370   status = GNUNET_SYSERR;
371   GNUNET_SCHEDULER_shutdown ();
372   return GNUNET_SYSERR;
373 }
374
375
376 /**
377  * Task to read from stdin
378  *
379  * @param cls NULL
380  * @param tc the task context
381  */
382 static void
383 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
384 {
385   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
386   ssize_t sread;
387
388   read_task_id = GNUNET_SCHEDULER_NO_TASK;
389   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
390     return;
391   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
392   if ((GNUNET_SYSERR == sread) || (0 == sread))
393   {
394     GNUNET_SCHEDULER_shutdown ();
395     return;
396   }
397   if (GNUNET_YES == done_reading)
398   {
399     /* didn't expect any more data! */
400     GNUNET_SCHEDULER_shutdown ();
401     return;
402   }
403   LOG_DEBUG ("Read %u bytes\n", sread);
404   if (GNUNET_OK !=
405       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
406                                  GNUNET_NO))
407   {
408     GNUNET_break (0);
409     GNUNET_SCHEDULER_shutdown ();
410     return;
411   }
412   read_task_id =                /* No timeout while reading */
413       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
414                                       &read_task, NULL);
415 }
416
417
418 /**
419  * Task triggered whenever we receive a SIGCHLD (child
420  * process died).
421  *
422  * @param cls closure, NULL if we need to self-restart
423  * @param tc context
424  */
425 static void
426 child_death_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
427 {
428   const struct GNUNET_DISK_FileHandle *pr;
429   char c[16];
430
431   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
432   child_death_task_id = GNUNET_SCHEDULER_NO_TASK;
433   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
434   {
435     child_death_task_id =
436         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
437                                         pr, &child_death_task, NULL);
438     return;
439   }
440   /* consume the signal */
441   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
442   LOG_DEBUG ("Child died\n");
443   GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
444   GNUNET_OS_process_destroy (testbed);
445   testbed = NULL;
446   if (NULL != test_system)
447   {
448     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
449     test_system = NULL;
450   }
451 }
452
453
454 /**
455  * Main function that will be run.
456  *
457  * @param cls closure
458  * @param args remaining command-line arguments
459  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
460  * @param cfg configuration
461  */
462 static void
463 run (void *cls, char *const *args, const char *cfgfile,
464      const struct GNUNET_CONFIGURATION_Handle *cfg)
465 {
466   LOG_DEBUG ("Starting testbed helper...\n");
467   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
468   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
469   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
470   read_task_id =
471       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
472                                       &read_task, NULL);
473   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
474                                 NULL);
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 }
481
482
483 /**
484  * Signal handler called for SIGCHLD.
485  */
486 static void
487 sighandler_child_death ()
488 {
489   static char c;
490   int old_errno;        /* back-up errno */
491
492   old_errno = errno;
493   GNUNET_break (1 ==
494                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
495                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
496                                         &c, sizeof (c)));
497   errno = old_errno;
498 }
499
500
501 /**
502  * Main function
503  *
504  * @param argc the number of command line arguments
505  * @param argv command line arg array
506  * @return return code
507  */
508 int
509 main (int argc, char **argv)
510 {
511   struct GNUNET_SIGNAL_Context *shc_chld;
512
513   struct GNUNET_GETOPT_CommandLineOption options[] = {
514     GNUNET_GETOPT_OPTION_END
515   };
516   int ret;
517
518   status = GNUNET_OK;
519   in_shutdown = GNUNET_NO;
520   if (NULL == (sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, 
521                                            GNUNET_NO, GNUNET_NO)))
522   {
523     GNUNET_break (0);
524     ret = GNUNET_SYSERR;
525     return 1;
526   }
527   shc_chld =
528       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
529   ret =
530       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
531                           "Helper for starting gnunet-service-testbed", options,
532                           &run, NULL);
533   GNUNET_SIGNAL_handler_uninstall (shc_chld);
534   shc_chld = NULL;
535   GNUNET_DISK_pipe_close (sigpipe);
536   if (GNUNET_OK != ret)
537     return 1;
538   return (GNUNET_OK == status) ? 0 : 1;
539 }
540
541 /* end of gnunet-helper-testbed.c */