-renaming testing-new.h to testing.h, bumping library versions
[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,
269          "Trusted IP cannot be empty -- exiting\n");
270     goto error;
271   }
272   hostname_size = ntohs (msg->hostname_size);
273   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
274        hostname_size) >= msize)
275   {
276     GNUNET_break (0);
277     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
278     goto error;
279   }  
280   ul_config_size = (uLongf) ntohs (msg->config_size);
281   config = GNUNET_malloc (ul_config_size);
282   xconfig_size =
283       ntohs (message->size) - (trusted_ip_size + 1 +
284                                sizeof (struct GNUNET_TESTBED_HelperInit));
285   if (Z_OK !=
286       uncompress ((Bytef *) config, &ul_config_size,
287                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 + hostname_size),
288                   (uLongf) xconfig_size))
289   {
290     LOG (GNUNET_ERROR_TYPE_WARNING,
291          "Error while uncompressing config -- exiting\n");
292     GNUNET_free (config);
293     goto error;
294   }
295   cfg = GNUNET_CONFIGURATION_create ();
296   if (GNUNET_OK !=
297       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
298   {
299     LOG (GNUNET_ERROR_TYPE_WARNING,
300          "Unable to deserialize config -- exiting\n");
301     GNUNET_free (config);
302     goto error;
303   }
304   GNUNET_free (config);
305   hostname = NULL;
306   if (0 != hostname_size)
307   {
308     hostname = GNUNET_malloc (hostname_size + 1);
309     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1, hostname_size);
310     hostname[hostname_size] = '\0';
311   }
312   test_system = GNUNET_TESTING_system_create ("testbed-helper", trusted_ip,
313                                               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, 
337                                binary,
338                                "gnunet-service-testbed", "-c", config, NULL);
339   GNUNET_free (binary);
340   GNUNET_free (config);
341   if (NULL == testbed)
342   {
343     LOG (GNUNET_ERROR_TYPE_WARNING,
344          "Error starting gnunet-service-testbed -- exiting\n");
345     GNUNET_CONFIGURATION_destroy (cfg);
346     goto error;
347   }
348   done_reading = GNUNET_YES;
349   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
350   GNUNET_CONFIGURATION_destroy (cfg);
351   cfg = NULL;
352   xconfig_size =
353       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
354   GNUNET_free (config);
355   wc = GNUNET_malloc (sizeof (struct WriteContext));
356   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
357   reply = GNUNET_realloc (xconfig, wc->length);
358   memmove (&reply[1], reply, xconfig_size);
359   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
360   reply->header.size = htons ((uint16_t) wc->length);
361   reply->config_size = htons ((uint16_t) config_size);
362   wc->data = reply;
363   write_task_id =
364       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
365                                        &write_task, wc);
366   return GNUNET_OK;
367
368 error:
369   status = GNUNET_SYSERR;
370   GNUNET_SCHEDULER_shutdown ();
371   return GNUNET_SYSERR;
372 }
373
374
375 /**
376  * Task to read from stdin
377  *
378  * @param cls NULL
379  * @param tc the task context
380  */
381 static void
382 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
383 {
384   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
385   ssize_t sread;
386
387   read_task_id = GNUNET_SCHEDULER_NO_TASK;
388   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
389     return;
390   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
391   if ((GNUNET_SYSERR == sread) || (0 == sread))
392   {
393     GNUNET_SCHEDULER_shutdown ();
394     return;
395   }
396   if (GNUNET_YES == done_reading)
397   {
398     /* didn't expect any more data! */
399     GNUNET_SCHEDULER_shutdown ();
400     return;
401   }
402   LOG_DEBUG ("Read %u bytes\n", sread);
403   if (GNUNET_OK !=
404       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
405                                  GNUNET_NO))
406   {
407     GNUNET_break (0);
408     GNUNET_SCHEDULER_shutdown ();
409     return;
410   }
411   read_task_id =                /* No timeout while reading */
412       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
413                                       &read_task, NULL);
414 }
415
416
417 /**
418  * Main function that will be run.
419  *
420  * @param cls closure
421  * @param args remaining command-line arguments
422  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
423  * @param cfg configuration
424  */
425 static void
426 run (void *cls, char *const *args, const char *cfgfile,
427      const struct GNUNET_CONFIGURATION_Handle *cfg)
428 {
429   LOG_DEBUG ("Starting testbed helper...\n");
430   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
431   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
432   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
433   read_task_id =
434       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
435                                       &read_task, NULL);
436   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
437                                 NULL);
438 }
439
440
441 /**
442  * Signal handler called for SIGCHLD.
443  */
444 static void
445 sighandler_child_death ()
446 {
447   if ((NULL != testbed) && (GNUNET_NO == in_shutdown))
448   {
449     LOG_DEBUG ("Child died\n");
450     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
451     GNUNET_OS_process_destroy (testbed);
452     testbed = NULL;
453     GNUNET_SCHEDULER_shutdown ();       /* We are done too! */
454   }
455 }
456
457
458 /**
459  * Main function
460  *
461  * @param argc the number of command line arguments
462  * @param argv command line arg array
463  * @return return code
464  */
465 int
466 main (int argc, char **argv)
467 {
468   struct GNUNET_SIGNAL_Context *shc_chld;
469
470   struct GNUNET_GETOPT_CommandLineOption options[] = {
471     GNUNET_GETOPT_OPTION_END
472   };
473   int ret;
474
475   status = GNUNET_OK;
476   in_shutdown = GNUNET_NO;
477   shc_chld =
478       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
479   ret =
480       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
481                           "Helper for starting gnunet-service-testbed", options,
482                           &run, NULL);
483   GNUNET_SIGNAL_handler_uninstall (shc_chld);
484   shc_chld = NULL;
485   if (GNUNET_OK != ret)
486     return 1;
487   return (GNUNET_OK == status) ? 0 : 1;
488 }
489
490 /* end of gnunet-helper-testbed.c */