942a9e5495dc0c2a862479af8d168a08672faf13
[oweals/gnunet.git] / src / testbed / gnunet-testbed-helper.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-testbed-helper.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-new.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  * Context for a single write on a chunk of memory
56  */
57 struct WriteContext
58 {
59   /**
60    * The data to write
61    */
62   void *data;
63
64   /**
65    * The length of the data
66    */
67   size_t length;
68
69   /**
70    * The current position from where the write operation should begin
71    */
72   size_t pos;
73 };
74
75
76 /**
77  * Handle to the testing system
78  */
79 static struct GNUNET_TESTING_System *test_system;
80
81 /**
82  * Our message stream tokenizer
83  */
84 struct GNUNET_SERVER_MessageStreamTokenizer *tokenizer;
85
86 /**
87  * Disk handle from stdin
88  */
89 static struct GNUNET_DISK_FileHandle *stdin_fd;
90
91 /**
92  * Disk handle for stdout
93  */
94 static struct GNUNET_DISK_FileHandle *stdout_fd;
95
96 /**
97  * The process handle to the testbed service
98  */
99 static struct GNUNET_OS_Process *testbed;
100
101 /**
102  * Task identifier for the read task
103  */
104 static GNUNET_SCHEDULER_TaskIdentifier read_task_id;
105
106 /**
107  * Task identifier for the write task
108  */
109 static GNUNET_SCHEDULER_TaskIdentifier write_task_id;
110
111 /**
112  * Are we done reading messages from stdin?
113  */
114 static int done_reading;
115
116 /**
117  * Result to return in case we fail
118  */
119 static int status;
120
121
122 /**
123  * Are we shutting down
124  */
125 static int in_shutdown;
126
127
128 /**
129  * Task to shutting down nicely
130  *
131  * @param cls NULL
132  * @param tc the task context
133  */
134 static void
135 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
136 {
137   LOG_DEBUG ("Shutting down\n");
138   in_shutdown = GNUNET_YES;
139   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
140   {
141     GNUNET_SCHEDULER_cancel (read_task_id);
142     read_task_id = GNUNET_SCHEDULER_NO_TASK;
143   }
144   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
145   {
146     GNUNET_SCHEDULER_cancel (write_task_id);
147     write_task_id = GNUNET_SCHEDULER_NO_TASK;
148   }
149   if (NULL != stdin_fd)
150     (void) GNUNET_DISK_file_close (stdin_fd);
151   if (NULL != stdout_fd)
152     (void) GNUNET_DISK_file_close (stdout_fd);
153   GNUNET_SERVER_mst_destroy (tokenizer);  
154   tokenizer = NULL;
155   if (NULL != testbed)
156   {
157     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, SIGTERM));
158     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
159     GNUNET_OS_process_destroy (testbed);
160     testbed = NULL;
161   }
162   if (NULL != test_system)
163   {
164     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
165     test_system = NULL;
166   }
167 }
168
169
170 /**
171  * Task to write to the standard out
172  *
173  * @param cls the WriteContext
174  * @param tc the TaskContext
175  */
176 static void
177 write_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
178 {
179   struct WriteContext *wc = cls;
180   ssize_t bytes_wrote;
181
182   GNUNET_assert (NULL != wc);
183   write_task_id = GNUNET_SCHEDULER_NO_TASK;
184   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
185   {
186     GNUNET_free (wc->data);
187     GNUNET_free (wc);
188     return;
189   }
190   bytes_wrote = GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
191                                         wc->length - wc->pos);
192   GNUNET_assert (GNUNET_SYSERR != bytes_wrote);
193   wc->pos += bytes_wrote;
194   if (wc->pos == wc->length)
195   {
196     GNUNET_free (wc->data);
197     GNUNET_free (wc);
198     return;
199   }
200   write_task_id = GNUNET_SCHEDULER_add_write_file
201     (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd, &write_task, wc);
202 }
203
204
205 /**
206  * Functions with this signature are called whenever a
207  * complete message is received by the tokenizer.
208  *
209  * Do not call GNUNET_SERVER_mst_destroy in callback
210  *
211  * @param cls closure
212  * @param client identification of the client
213  * @param message the actual message
214  *
215  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
216  */
217 static int 
218 tokenizer_cb (void *cls, void *client,
219               const struct GNUNET_MessageHeader *message)
220 {
221   const struct GNUNET_TESTBED_HelperInit *msg;
222   struct GNUNET_TESTBED_HelperReply *reply;
223   struct GNUNET_CONFIGURATION_Handle *cfg;
224   struct WriteContext *wc;
225   char *controller;
226   char *config;
227   char *xconfig;
228   size_t config_size;
229   uLongf ul_config_size;
230   size_t xconfig_size;
231   uint16_t cname_size;
232
233   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= ntohs (message->size)) ||
234       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
235   {
236     LOG (GNUNET_ERROR_TYPE_WARNING,
237          "Received unexpected message -- exiting\n");
238     goto error;
239   }
240   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
241   cname_size = ntohs (msg->cname_size);
242   controller = (char *) &msg[1];
243   if ('\0' != controller[cname_size])
244   {
245     LOG (GNUNET_ERROR_TYPE_WARNING, 
246          "Controller name cannot be empty -- exiting\n");
247     goto error;
248   }
249   ul_config_size = (uLongf) ntohs (msg->config_size);
250   config = GNUNET_malloc (ul_config_size);
251   xconfig_size = ntohs (message->size) - 
252     (cname_size + 1 + sizeof (struct GNUNET_TESTBED_HelperInit));
253   if (Z_OK != uncompress ((Bytef *) config, &ul_config_size,
254                           (const Bytef *) (controller + cname_size + 1),
255                           (uLongf) xconfig_size))
256   {
257     LOG (GNUNET_ERROR_TYPE_WARNING, 
258          "Error while uncompressing config -- exiting\n");
259     GNUNET_free (config);
260     goto error;
261   }
262   cfg = GNUNET_CONFIGURATION_create ();  
263   if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, 
264                                                      ul_config_size, GNUNET_NO))
265   {
266     LOG (GNUNET_ERROR_TYPE_WARNING, 
267          "Unable to deserialize config -- exiting\n");
268     GNUNET_free (config);
269     goto error;
270   }
271   GNUNET_free (config);
272   test_system = GNUNET_TESTING_system_create ("testbed-helper", controller);
273   GNUNET_assert (NULL != test_system);
274   GNUNET_assert (GNUNET_OK ==  GNUNET_TESTING_configuration_create
275                  (test_system, cfg));
276   GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string 
277                  (cfg, "PATHS", "DEFAULTCONFIG", &config));
278   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
279   {
280     LOG (GNUNET_ERROR_TYPE_WARNING, 
281          "Unable to write config file: %s -- exiting\n", config);
282     GNUNET_CONFIGURATION_destroy (cfg);
283     GNUNET_free (config);
284     goto error;
285   }
286   LOG_DEBUG ("Staring testbed with config: %s\n", config);
287   testbed = GNUNET_OS_start_process 
288     (GNUNET_YES, GNUNET_OS_INHERIT_STD_ERR /*verbose? */, NULL, NULL,
289      "gnunet-service-testbed", "gnunet-service-testbed", "-c", config, NULL);
290   GNUNET_free (config);
291   if (NULL == testbed)
292   {
293     LOG (GNUNET_ERROR_TYPE_WARNING, 
294          "Error staring gnunet-service-testbed -- exiting\n");
295     GNUNET_CONFIGURATION_destroy (cfg);
296     goto error;
297   }
298   done_reading = GNUNET_YES;
299   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
300   GNUNET_CONFIGURATION_destroy (cfg);
301   cfg = NULL;
302   xconfig_size = GNUNET_TESTBED_compress_config_ (config, config_size,
303                                                   &xconfig);
304   GNUNET_free (config);
305   wc = GNUNET_malloc (sizeof (struct WriteContext));
306   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
307   reply = GNUNET_realloc (xconfig, wc->length);
308   memmove (&reply[1], reply, xconfig_size);
309   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
310   reply->header.size = htons ((uint16_t) wc->length);
311   reply->config_size = htons ((uint16_t) config_size);
312   wc->data = reply;
313   write_task_id = GNUNET_SCHEDULER_add_write_file
314     (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd, &write_task, wc);       
315   return GNUNET_OK;
316   
317  error:
318   status = GNUNET_SYSERR;
319   GNUNET_SCHEDULER_shutdown ();
320   return GNUNET_SYSERR;
321 }
322
323
324 /**
325  * Task to read from stdin
326  *
327  * @param cls NULL
328  * @param tc the task context
329  */
330 static void
331 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
332 {
333   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
334   ssize_t sread;
335
336   read_task_id = GNUNET_SCHEDULER_NO_TASK;
337   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
338     return;  
339   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
340   if (GNUNET_SYSERR == sread)
341   {
342     GNUNET_SCHEDULER_shutdown ();
343     return;
344   }
345   if (GNUNET_YES == done_reading)
346   {
347     /* didn't expect any more data! */
348     GNUNET_SCHEDULER_shutdown ();
349     return;
350   }
351   LOG_DEBUG ("Read %u bytes\n", sread);
352   if (GNUNET_OK !=
353       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread,
354                                  GNUNET_NO, GNUNET_NO))
355   {
356     GNUNET_break (0);
357     GNUNET_SCHEDULER_shutdown ();
358     return;
359   }
360   read_task_id =                /* No timeout while reading */
361     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
362                                     stdin_fd, &read_task, NULL);
363 }
364
365
366 /**
367  * Main function that will be run.
368  *
369  * @param cls closure
370  * @param args remaining command-line arguments
371  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
372  * @param cfg configuration
373  */
374 static void 
375 run (void *cls, char *const *args, const char *cfgfile,
376      const struct GNUNET_CONFIGURATION_Handle * cfg)
377 {
378   LOG_DEBUG ("Starting testbed helper...\n");
379   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
380   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
381   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
382   read_task_id =
383     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
384                                     stdin_fd, &read_task, NULL);
385   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
386                                 &shutdown_task, NULL);
387 }
388
389
390 /**
391  * Signal handler called for SIGCHLD.  Triggers the
392  * respective handler by writing to the trigger pipe.
393  */
394 static void
395 sighandler_child_death ()
396 {
397   if ((NULL != testbed) && (GNUNET_NO == in_shutdown))
398   {
399     LOG_DEBUG ("Child died\n");
400     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
401     GNUNET_OS_process_destroy (testbed);
402     testbed = NULL;
403     GNUNET_SCHEDULER_shutdown ();       /* We are done too! */
404   }  
405 }
406
407
408 /**
409  * Main function
410  *
411  * @param argc the number of command line arguments
412  * @param argv command line arg array
413  * @return return code
414  */
415 int main (int argc, char **argv)
416 {
417   struct GNUNET_SIGNAL_Context *shc_chld;
418   struct GNUNET_GETOPT_CommandLineOption options[] = {
419     GNUNET_GETOPT_OPTION_END
420   };
421   int ret;
422
423   status = GNUNET_OK;
424   in_shutdown = GNUNET_NO;
425   //sleep (60);
426   shc_chld =
427     GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
428   ret = GNUNET_PROGRAM_run (argc, argv, "gnunet-testbed-helper",
429                                  "Helper for starting gnunet-service-testbed",
430                             options, &run, NULL);
431   GNUNET_SIGNAL_handler_uninstall (shc_chld);
432   shc_chld = NULL;
433   if (GNUNET_OK != ret)
434     return 1;
435   return (GNUNET_OK == status) ? 0 : 1;
436 }
437
438 /* end of gnunet-testbed-helper.c */