-fixes mem leaks
[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  * Pipe handle to child's stdin
103  */
104 static struct GNUNET_DISK_PipeHandle *pipe_in;
105
106 /**
107  * Pipe handle to child's stdout
108  */
109 static struct GNUNET_DISK_PipeHandle *pipe_out;
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 ret;
130
131
132 /**
133  * Task to shutting down nicely
134  *
135  * @param cls NULL
136  * @param tc the task context
137  */
138 static void
139 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
140 {
141   LOG_DEBUG ("Shutting down\n");
142   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
143   {
144     GNUNET_SCHEDULER_cancel (read_task_id);
145     read_task_id = GNUNET_SCHEDULER_NO_TASK;
146   }
147   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
148   {
149     GNUNET_SCHEDULER_cancel (write_task_id);
150     write_task_id = GNUNET_SCHEDULER_NO_TASK;
151   }
152   if (NULL != stdin_fd)
153     (void) GNUNET_DISK_file_close (stdin_fd);
154   if (NULL != stdout_fd)
155     (void) GNUNET_DISK_file_close (stdout_fd);
156   GNUNET_SERVER_mst_destroy (tokenizer);  
157   tokenizer = NULL;
158   if (NULL != testbed)
159   {
160     (void) GNUNET_OS_process_kill (testbed, SIGTERM);
161     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
162     GNUNET_OS_process_destroy (testbed);
163     testbed = NULL;
164   }
165   if (NULL != pipe_in)
166   {
167     (void) GNUNET_DISK_pipe_close (pipe_in);
168     pipe_in = NULL;
169   }
170   if (NULL != pipe_out)
171   {
172     (void) GNUNET_DISK_pipe_close (pipe_out);
173     pipe_out = NULL;
174   }
175   if (NULL != test_system)
176   {
177     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
178     test_system = NULL;
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 = GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
204                                         wc->length - wc->pos);
205   GNUNET_assert (GNUNET_SYSERR != bytes_wrote);
206   wc->pos += bytes_wrote;
207   if (wc->pos == wc->length)
208   {
209     GNUNET_free (wc->data);
210     GNUNET_free (wc);
211     return;
212   }
213   write_task_id = GNUNET_SCHEDULER_add_write_file
214     (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd, &write_task, wc);
215 }
216
217
218 /**
219  * Functions with this signature are called whenever a
220  * complete message is received by the tokenizer.
221  *
222  * Do not call GNUNET_SERVER_mst_destroy in callback
223  *
224  * @param cls closure
225  * @param client identification of the client
226  * @param message the actual message
227  *
228  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
229  */
230 static int 
231 tokenizer_cb (void *cls, void *client,
232               const struct GNUNET_MessageHeader *message)
233 {
234   const struct GNUNET_TESTBED_HelperInit *msg;
235   struct GNUNET_TESTBED_HelperReply *reply;
236   struct GNUNET_CONFIGURATION_Handle *cfg;
237   struct WriteContext *wc;
238   char *controller;
239   char *config;
240   char *xconfig;
241   size_t config_size;
242   uLongf ul_config_size;
243   size_t xconfig_size;
244   uint16_t cname_size;
245
246   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= ntohs (message->size)) ||
247       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
248   {
249     LOG (GNUNET_ERROR_TYPE_WARNING,
250          "Received unexpected message -- exiting\n");
251     goto error;
252   }
253   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
254   cname_size = ntohs (msg->cname_size);
255   controller = (char *) &msg[1];
256   if ('\0' != controller[cname_size])
257   {
258     LOG (GNUNET_ERROR_TYPE_WARNING, 
259          "Controller name cannot be empty -- exiting\n");
260     goto error;
261   }
262   ul_config_size = (uLongf) ntohs (msg->config_size);
263   config = GNUNET_malloc (ul_config_size);
264   xconfig_size = ntohs (message->size) - 
265     (cname_size + 1 + sizeof (struct GNUNET_TESTBED_HelperInit));
266   if (Z_OK != uncompress ((Bytef *) config, &ul_config_size,
267                           (const Bytef *) (controller + cname_size + 1),
268                           (uLongf) xconfig_size))
269   {
270     LOG (GNUNET_ERROR_TYPE_WARNING, 
271          "Error while uncompressing config -- exiting\n");
272     GNUNET_free (config);
273     goto error;
274   }
275   cfg = GNUNET_CONFIGURATION_create ();  
276   if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, 
277                                                      ul_config_size, GNUNET_NO))
278   {
279     LOG (GNUNET_ERROR_TYPE_WARNING, 
280          "Unable to deserialize config -- exiting\n");
281     GNUNET_free (config);
282     goto error;
283   }
284   GNUNET_free (config);
285   test_system = GNUNET_TESTING_system_create ("testbed-helper", controller);
286   GNUNET_assert (NULL != test_system);
287   GNUNET_assert (GNUNET_OK ==  GNUNET_TESTING_configuration_create
288                  (test_system, cfg));
289   GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string 
290                  (cfg, "PATHS", "DEFAULTCONFIG", &config));
291   pipe_in = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
292   pipe_out = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_YES);
293   if ((NULL == pipe_in) || (NULL == pipe_out))
294   {
295     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
296     GNUNET_free (config);
297     goto error;
298   }
299   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
300   {
301     LOG (GNUNET_ERROR_TYPE_WARNING, 
302          "Unable to write config file: %s -- exiting\n", config);
303     GNUNET_CONFIGURATION_destroy (cfg);
304     GNUNET_free (config);
305     goto error;
306   }
307   LOG_DEBUG ("Staring testbed with config: %s\n", config);
308   testbed = GNUNET_OS_start_process 
309     (GNUNET_YES, GNUNET_OS_INHERIT_STD_ERR /*verbose? */, pipe_in, pipe_out,
310      "gnunet-service-testbed", "gnunet-service-testbed", "-c", config, NULL);
311   GNUNET_free (config);
312   if (NULL == testbed)
313   {
314     LOG (GNUNET_ERROR_TYPE_WARNING, 
315          "Error staring gnunet-service-testbed -- exiting\n");
316     GNUNET_CONFIGURATION_destroy (cfg);
317     goto error;
318   }
319   GNUNET_DISK_pipe_close_end (pipe_out, GNUNET_DISK_PIPE_END_WRITE);
320   GNUNET_DISK_pipe_close_end (pipe_in, GNUNET_DISK_PIPE_END_READ);
321   done_reading = GNUNET_YES;
322   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
323   GNUNET_CONFIGURATION_destroy (cfg);
324   cfg = NULL;
325   xconfig_size = GNUNET_TESTBED_compress_config_ (config, config_size,
326                                                   &xconfig);
327   GNUNET_free (config);
328   wc = GNUNET_malloc (sizeof (struct WriteContext));
329   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
330   reply = GNUNET_realloc (xconfig, wc->length);
331   memmove (&reply[1], reply, xconfig_size);
332   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
333   reply->header.size = htons ((uint16_t) wc->length);
334   reply->config_size = htons ((uint16_t) config_size);
335   wc->data = reply;
336   write_task_id = GNUNET_SCHEDULER_add_write_file
337     (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd, &write_task, wc);       
338   return GNUNET_OK;
339   
340  error:
341   ret = GNUNET_SYSERR;
342   GNUNET_SCHEDULER_shutdown ();
343   return GNUNET_SYSERR;
344 }
345
346
347 /**
348  * Task to read from stdin
349  *
350  * @param cls NULL
351  * @param tc the task context
352  */
353 static void
354 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
355 {
356   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
357   ssize_t sread;
358
359   read_task_id = GNUNET_SCHEDULER_NO_TASK;
360   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
361     return;  
362   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
363   if (GNUNET_SYSERR == sread)
364   {
365     GNUNET_break (0);           /* FIXME: stdin closed - kill child */
366     GNUNET_SCHEDULER_shutdown ();
367     return;
368   }
369   if (GNUNET_YES == done_reading)
370   {
371     /* didn't expect any more data! */
372     GNUNET_break (0);
373     GNUNET_SCHEDULER_shutdown ();
374     return;
375   }
376   LOG_DEBUG ("Read %u bytes\n", sread);
377   if (GNUNET_OK !=
378       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread,
379                                  GNUNET_NO, GNUNET_NO))
380   {
381     GNUNET_break (0);
382     GNUNET_SCHEDULER_shutdown ();
383     return;
384   }
385   read_task_id =                /* No timeout while reading */
386     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
387                                     stdin_fd, &read_task, NULL);
388 }
389
390
391 /**
392  * Main function that will be run.
393  *
394  * @param cls closure
395  * @param args remaining command-line arguments
396  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
397  * @param cfg configuration
398  */
399 static void 
400 run (void *cls, char *const *args, const char *cfgfile,
401      const struct GNUNET_CONFIGURATION_Handle * cfg)
402 {
403   LOG_DEBUG ("Starting testbed helper...\n");
404   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
405   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
406   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
407   read_task_id =
408     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
409                                     stdin_fd, &read_task, NULL);
410   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
411                                 &shutdown_task, NULL);
412 }
413
414
415 /**
416  * Main function
417  *
418  * @param argc the number of command line arguments
419  * @param argv command line arg array
420  * @return return code
421  */
422 int main (int argc, char **argv)
423 {
424   struct GNUNET_GETOPT_CommandLineOption options[] = {
425     GNUNET_GETOPT_OPTION_END
426   };
427
428   ret = GNUNET_OK;
429   //sleep (60);
430   if (GNUNET_OK != 
431       GNUNET_PROGRAM_run (argc, argv, "gnunet-testbed-helper",
432                           "Helper for starting gnunet-service-testbed",
433                           options, &run, NULL))
434     return 1;
435   return (GNUNET_OK == ret) ? 0 : 1;
436 }
437
438 /* end of gnunet-testbed-helper.c */