- verboser log, faster start
[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  * Task identifier for the read task
113  */
114 static GNUNET_SCHEDULER_TaskIdentifier read_task_id;
115
116 /**
117  * Task identifier for the write task
118  */
119 static GNUNET_SCHEDULER_TaskIdentifier write_task_id;
120
121 /**
122  * Are we done reading messages from stdin?
123  */
124 static int done_reading;
125
126 /**
127  * Result to return in case we fail
128  */
129 static int status;
130
131
132 /**
133  * Are we shutting down
134  */
135 static int in_shutdown;
136
137
138 /**
139  * Task to shutting down nicely
140  *
141  * @param cls NULL
142  * @param tc the task context
143  */
144 static void
145 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
146 {
147   LOG_DEBUG ("Shutting down\n");
148   in_shutdown = GNUNET_YES;
149   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
150   {
151     GNUNET_SCHEDULER_cancel (read_task_id);
152     read_task_id = GNUNET_SCHEDULER_NO_TASK;
153   }
154   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
155   {
156     GNUNET_SCHEDULER_cancel (write_task_id);
157     write_task_id = GNUNET_SCHEDULER_NO_TASK;
158   }
159   if (NULL != stdin_fd)
160     (void) GNUNET_DISK_file_close (stdin_fd);
161   if (NULL != stdout_fd)
162     (void) GNUNET_DISK_file_close (stdout_fd);
163   GNUNET_SERVER_mst_destroy (tokenizer);
164   tokenizer = NULL;
165   if (NULL != testbed)
166   {
167     LOG_DEBUG ("Killing testbed\n");
168     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, SIGTERM));
169     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
170     GNUNET_OS_process_destroy (testbed);
171     testbed = NULL;
172   }
173   if (NULL != test_system)
174   {
175     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
176     test_system = NULL;
177   }
178 }
179
180
181 /**
182  * Task to write to the standard out
183  *
184  * @param cls the WriteContext
185  * @param tc the TaskContext
186  */
187 static void
188 write_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
189 {
190   struct WriteContext *wc = cls;
191   ssize_t bytes_wrote;
192
193   GNUNET_assert (NULL != wc);
194   write_task_id = GNUNET_SCHEDULER_NO_TASK;
195   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
196   {
197     GNUNET_free (wc->data);
198     GNUNET_free (wc);
199     return;
200   }
201   bytes_wrote =
202       GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
203                               wc->length - wc->pos);
204   if (GNUNET_SYSERR == bytes_wrote)
205   {
206     LOG (GNUNET_ERROR_TYPE_WARNING, "Cannot reply back configuration\n");
207     GNUNET_free (wc->data);
208     GNUNET_free (wc);
209     return;
210   }
211   wc->pos += bytes_wrote;
212   if (wc->pos == wc->length)
213   {
214     GNUNET_free (wc->data);
215     GNUNET_free (wc);
216     return;
217   }
218   write_task_id =
219       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
220                                        &write_task, wc);
221 }
222
223
224 /**
225  * Functions with this signature are called whenever a
226  * complete message is received by the tokenizer.
227  *
228  * Do not call GNUNET_SERVER_mst_destroy in callback
229  *
230  * @param cls closure
231  * @param client identification of the client
232  * @param message the actual message
233  *
234  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
235  */
236 static int
237 tokenizer_cb (void *cls, void *client,
238               const struct GNUNET_MessageHeader *message)
239 {
240   const struct GNUNET_TESTBED_HelperInit *msg;
241   struct GNUNET_TESTBED_HelperReply *reply;
242   struct GNUNET_CONFIGURATION_Handle *cfg;
243   struct WriteContext *wc;
244   char *binary;
245   char *trusted_ip;
246   char *hostname;
247   char *config;
248   char *xconfig;
249   size_t config_size;
250   uLongf ul_config_size;
251   size_t xconfig_size;
252   uint16_t trusted_ip_size;
253   uint16_t hostname_size;
254   uint16_t msize;
255
256   msize = ntohs (message->size);
257   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
258       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
259   {
260     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
261     goto error;
262   }
263   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
264   trusted_ip_size = ntohs (msg->trusted_ip_size);
265   trusted_ip = (char *) &msg[1];
266   if ('\0' != trusted_ip[trusted_ip_size])
267   {
268     LOG (GNUNET_ERROR_TYPE_WARNING, "Trusted IP cannot be empty -- exiting\n");
269     goto error;
270   }
271   hostname_size = ntohs (msg->hostname_size);
272   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
273        hostname_size) >= msize)
274   {
275     GNUNET_break (0);
276     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
277     goto error;
278   }
279   ul_config_size = (uLongf) ntohs (msg->config_size);
280   config = GNUNET_malloc (ul_config_size);
281   xconfig_size =
282       ntohs (message->size) - (trusted_ip_size + 1 +
283                                sizeof (struct GNUNET_TESTBED_HelperInit));
284   if (Z_OK !=
285       uncompress ((Bytef *) config, &ul_config_size,
286                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 +
287                                    hostname_size), (uLongf) xconfig_size))
288   {
289     LOG (GNUNET_ERROR_TYPE_WARNING,
290          "Error while uncompressing config -- exiting\n");
291     GNUNET_free (config);
292     goto error;
293   }
294   cfg = GNUNET_CONFIGURATION_create ();
295   if (GNUNET_OK !=
296       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
297   {
298     LOG (GNUNET_ERROR_TYPE_WARNING,
299          "Unable to deserialize config -- exiting\n");
300     GNUNET_free (config);
301     goto error;
302   }
303   GNUNET_free (config);
304   hostname = NULL;
305   if (0 != hostname_size)
306   {
307     hostname = GNUNET_malloc (hostname_size + 1);
308     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1,
309                     hostname_size);
310     hostname[hostname_size] = '\0';
311   }
312   test_system =
313       GNUNET_TESTING_system_create ("testbed-helper", trusted_ip, hostname);
314   GNUNET_free_non_null (hostname);
315   hostname = NULL;
316   GNUNET_assert (NULL != test_system);
317   GNUNET_assert (GNUNET_OK ==
318                  GNUNET_TESTING_configuration_create (test_system, cfg));
319   GNUNET_assert (GNUNET_OK ==
320                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
321                                                         "DEFAULTCONFIG",
322                                                         &config));
323   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
324   {
325     LOG (GNUNET_ERROR_TYPE_WARNING,
326          "Unable to write config file: %s -- exiting\n", config);
327     GNUNET_CONFIGURATION_destroy (cfg);
328     GNUNET_free (config);
329     goto error;
330   }
331   LOG_DEBUG ("Staring testbed with config: %s\n", config);
332   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
333   testbed =
334       GNUNET_OS_start_process (PIPE_CONTROL,
335                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ , NULL,
336                                NULL, binary, "gnunet-service-testbed", "-c",
337                                config, NULL);
338   GNUNET_free (binary);
339   GNUNET_free (config);
340   if (NULL == testbed)
341   {
342     LOG (GNUNET_ERROR_TYPE_WARNING,
343          "Error starting gnunet-service-testbed -- exiting\n");
344     GNUNET_CONFIGURATION_destroy (cfg);
345     goto error;
346   }
347   done_reading = GNUNET_YES;
348   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
349   GNUNET_CONFIGURATION_destroy (cfg);
350   cfg = NULL;
351   xconfig_size =
352       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
353   GNUNET_free (config);
354   wc = GNUNET_malloc (sizeof (struct WriteContext));
355   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
356   reply = GNUNET_realloc (xconfig, wc->length);
357   memmove (&reply[1], reply, xconfig_size);
358   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
359   reply->header.size = htons ((uint16_t) wc->length);
360   reply->config_size = htons ((uint16_t) config_size);
361   wc->data = reply;
362   write_task_id =
363       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
364                                        &write_task, wc);
365   return GNUNET_OK;
366
367 error:
368   status = GNUNET_SYSERR;
369   GNUNET_SCHEDULER_shutdown ();
370   return GNUNET_SYSERR;
371 }
372
373
374 /**
375  * Task to read from stdin
376  *
377  * @param cls NULL
378  * @param tc the task context
379  */
380 static void
381 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
382 {
383   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
384   ssize_t sread;
385
386   read_task_id = GNUNET_SCHEDULER_NO_TASK;
387   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
388     return;
389   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
390   if ((GNUNET_SYSERR == sread) || (0 == sread))
391   {
392     GNUNET_SCHEDULER_shutdown ();
393     return;
394   }
395   if (GNUNET_YES == done_reading)
396   {
397     /* didn't expect any more data! */
398     GNUNET_SCHEDULER_shutdown ();
399     return;
400   }
401   LOG_DEBUG ("Read %u bytes\n", sread);
402   if (GNUNET_OK !=
403       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
404                                  GNUNET_NO))
405   {
406     GNUNET_break (0);
407     GNUNET_SCHEDULER_shutdown ();
408     return;
409   }
410   read_task_id =                /* No timeout while reading */
411       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
412                                       &read_task, NULL);
413 }
414
415
416 /**
417  * Main function that will be run.
418  *
419  * @param cls closure
420  * @param args remaining command-line arguments
421  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
422  * @param cfg configuration
423  */
424 static void
425 run (void *cls, char *const *args, const char *cfgfile,
426      const struct GNUNET_CONFIGURATION_Handle *cfg)
427 {
428   LOG_DEBUG ("Starting testbed helper...\n");
429   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
430   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
431   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
432   read_task_id =
433       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
434                                       &read_task, NULL);
435   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
436                                 NULL);
437 }
438
439
440 /**
441  * Signal handler called for SIGCHLD.
442  */
443 static void
444 sighandler_child_death ()
445 {
446   if ((NULL != testbed) && (GNUNET_NO == in_shutdown))
447   {
448     LOG_DEBUG ("Child died\n");
449     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
450     GNUNET_OS_process_destroy (testbed);
451     testbed = NULL;
452     GNUNET_SCHEDULER_shutdown ();       /* We are done too! */
453   }
454 }
455
456
457 /**
458  * Main function
459  *
460  * @param argc the number of command line arguments
461  * @param argv command line arg array
462  * @return return code
463  */
464 int
465 main (int argc, char **argv)
466 {
467   struct GNUNET_SIGNAL_Context *shc_chld;
468
469   struct GNUNET_GETOPT_CommandLineOption options[] = {
470     GNUNET_GETOPT_OPTION_END
471   };
472   int ret;
473
474   status = GNUNET_OK;
475   in_shutdown = GNUNET_NO;
476   shc_chld =
477       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
478   ret =
479       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
480                           "Helper for starting gnunet-service-testbed", options,
481                           &run, NULL);
482   GNUNET_SIGNAL_handler_uninstall (shc_chld);
483   shc_chld = NULL;
484   if (GNUNET_OK != ret)
485     return 1;
486   return (GNUNET_OK == status) ? 0 : 1;
487 }
488
489 /* end of gnunet-helper-testbed.c */