867f829b0367eac7d51f4aef1305085970d91caa
[oweals/gnunet.git] / src / testbed / testbed_api_hosts.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2013 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/testbed_api_hosts.c
23  * @brief API for manipulating 'hosts' controlled by the GNUnet testing service;
24  *        allows parsing hosts files, starting, stopping and communicating (via
25  *        SSH/stdin/stdout) with the remote (or local) processes
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_testbed_service.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_transport_service.h"
33
34 #include "testbed_api.h"
35 #include "testbed_api_hosts.h"
36 #include "testbed_helper.h"
37 #include "testbed_api_operations.h"
38
39 #include <zlib.h>
40 #include <regex.h>
41
42 /**
43  * Generic logging shorthand
44  */
45 #define LOG(kind, ...)                          \
46   GNUNET_log_from (kind, "testbed-api-hosts", __VA_ARGS__);
47
48 /**
49  * Debug logging shorthand
50  */
51 #define LOG_DEBUG(...)                          \
52   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__);
53
54 /**
55  * Prints API violation message
56  */
57 #define API_VIOLATION(cond,errstr)              \
58   do {                                          \
59     if (cond)                                   \
60       break;                                    \
61     LOG (GNUNET_ERROR_TYPE_ERROR, "API violation detected: %s\n", errstr); \
62     GNUNET_assert (0);                                                  \
63   } while (0)
64
65 /**
66  * Log an error message at log-level 'level' that indicates a failure of the
67  * command 'cmd' with the message given by gai_strerror(rc).
68  */
69 #define LOG_GAI(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gai_strerror(rc)); } while(0)
70
71 /**
72  * Number of extra elements we create space for when we grow host list
73  */
74 #define HOST_LIST_GROW_STEP 10
75
76
77 /**
78  * A list entry for registered controllers list
79  */
80 struct RegisteredController
81 {
82   /**
83    * The controller at which this host is registered
84    */
85   const struct GNUNET_TESTBED_Controller *controller;
86
87   /**
88    * The next ptr for DLL
89    */
90   struct RegisteredController *next;
91
92   /**
93    * The prev ptr for DLL
94    */
95   struct RegisteredController *prev;
96 };
97
98
99 /**
100  * Opaque handle to a host running experiments managed by the testing framework.
101  * The master process must be able to SSH to this host without password (via
102  * ssh-agent).
103  */
104 struct GNUNET_TESTBED_Host
105 {
106
107   /**
108    * The hostname of the host; NULL for localhost
109    */
110   const char *hostname;
111
112   /**
113    * The username to be used for SSH login
114    */
115   const char *username;
116
117   /**
118    * the configuration to use as a template while starting a controller on this
119    * host.  Operation queue size specific to a host are also read from this
120    * configuration handle.  After starting the controller, it points to the actual
121    * configuration with which the controller is running
122    */
123   struct GNUNET_CONFIGURATION_Handle *cfg;
124
125   /**
126    * The head for the list of controllers where this host is registered
127    */
128   struct RegisteredController *rc_head;
129
130   /**
131    * The tail for the list of controllers where this host is registered
132    */
133   struct RegisteredController *rc_tail;
134
135   /**
136    * Operation queue for simultaneous overlay connect operations target at this
137    * host
138    */
139   struct OperationQueue *opq_parallel_overlay_connect_operations;
140
141   /**
142    * Is a controller started on this host? FIXME: Is this needed?
143    */
144   int controller_started;
145
146   /**
147    * Is this host locked by GNUNET_TESTBED_controller_start()?
148    */
149   int locked;
150
151   /**
152    * Global ID we use to refer to a host on the network
153    */
154   uint32_t id;
155
156   /**
157    * The port which is to be used for SSH
158    */
159   uint16_t port;
160
161 };
162
163
164 /**
165  * Array of available hosts
166  */
167 static struct GNUNET_TESTBED_Host **host_list;
168
169 /**
170  * The size of the available hosts list
171  */
172 static unsigned int host_list_size;
173
174
175 /**
176  * Lookup a host by ID.
177  *
178  * @param id global host ID assigned to the host; 0 is
179  *        reserved to always mean 'localhost'
180  * @return handle to the host, NULL if host not found
181  */
182 struct GNUNET_TESTBED_Host *
183 GNUNET_TESTBED_host_lookup_by_id_ (uint32_t id)
184 {
185   if (host_list_size <= id)
186     return NULL;
187   return host_list[id];
188 }
189
190
191 /**
192  * Create a host by ID; given this host handle, we could not
193  * run peers at the host, but we can talk about the host
194  * internally.
195  *
196  * @param id global host ID assigned to the host; 0 is
197  *        reserved to always mean 'localhost'
198  * @param cfg the configuration to use as a template while starting a controller
199  *          on this host.  Operation queue sizes specific to a host are also
200  *          read from this configuration handle
201  * @return handle to the host, NULL on error
202  */
203 struct GNUNET_TESTBED_Host *
204 GNUNET_TESTBED_host_create_by_id_ (uint32_t id,
205                                    const struct GNUNET_CONFIGURATION_Handle
206                                    *cfg)
207 {
208   return GNUNET_TESTBED_host_create_with_id (id, NULL, NULL, cfg, 0);
209 }
210
211
212 /**
213  * Obtain the host's unique global ID.
214  *
215  * @param host handle to the host, NULL means 'localhost'
216  * @return id global host ID assigned to the host (0 is
217  *         'localhost', but then obviously not globally unique)
218  */
219 uint32_t
220 GNUNET_TESTBED_host_get_id_ (const struct GNUNET_TESTBED_Host * host)
221 {
222   return host->id;
223 }
224
225
226 /**
227  * Obtain the host's hostname.
228  *
229  * @param host handle to the host, NULL means 'localhost'
230  * @return hostname of the host
231  */
232 const char *
233 GNUNET_TESTBED_host_get_hostname (const struct GNUNET_TESTBED_Host *host)
234 {
235   return host->hostname;
236 }
237
238
239 /**
240  * Obtain the host's username
241  *
242  * @param host handle to the host, NULL means 'localhost'
243  * @return username to login to the host
244  */
245 const char *
246 GNUNET_TESTBED_host_get_username_ (const struct GNUNET_TESTBED_Host *host)
247 {
248   return host->username;
249 }
250
251
252 /**
253  * Obtain the host's ssh port
254  *
255  * @param host handle to the host, NULL means 'localhost'
256  * @return username to login to the host
257  */
258 uint16_t
259 GNUNET_TESTBED_host_get_ssh_port_ (const struct GNUNET_TESTBED_Host * host)
260 {
261   return host->port;
262 }
263
264
265 /**
266  * Check whether a controller is already started on the given host
267  *
268  * @param host the handle to the host
269  * @return GNUNET_YES if the controller is already started; GNUNET_NO if not
270  */
271 int
272 GNUNET_TESTBED_host_controller_started (const struct GNUNET_TESTBED_Host *host)
273 {
274   return host->controller_started;
275 }
276
277
278 /**
279  * Obtain the host's configuration template
280  *
281  * @param host handle to the host
282  * @return the host's configuration template
283  */
284 const struct GNUNET_CONFIGURATION_Handle *
285 GNUNET_TESTBED_host_get_cfg_ (const struct GNUNET_TESTBED_Host *host)
286 {
287   return host->cfg;
288 }
289
290
291 /**
292  * Function to replace host's configuration
293  *
294  * @param host the host handle
295  * @param new_cfg the new configuration to replace the old one
296  */
297 void
298 GNUNET_TESTBED_host_replace_cfg_ (struct GNUNET_TESTBED_Host *host,
299                                   const struct GNUNET_CONFIGURATION_Handle *new_cfg)
300 {
301   GNUNET_CONFIGURATION_destroy (host->cfg);
302   host->cfg = GNUNET_CONFIGURATION_dup (new_cfg);
303 }
304
305
306 /**
307  * Create a host to run peers and controllers on.
308  *
309  * @param id global host ID assigned to the host; 0 is
310  *        reserved to always mean 'localhost'
311  * @param hostname name of the host, use "NULL" for localhost
312  * @param username username to use for the login; may be NULL
313  * @param cfg the configuration to use as a template while starting a controller
314  *          on this host.  Operation queue sizes specific to a host are also
315  *          read from this configuration handle
316  * @param port port number to use for ssh; use 0 to let ssh decide
317  * @return handle to the host, NULL on error
318  */
319 struct GNUNET_TESTBED_Host *
320 GNUNET_TESTBED_host_create_with_id (uint32_t id, const char *hostname,
321                                     const char *username, 
322                                     const struct GNUNET_CONFIGURATION_Handle
323                                     *cfg,
324                                     uint16_t port)
325 {
326   struct GNUNET_TESTBED_Host *host;
327   unsigned int new_size;
328
329   if ((id < host_list_size) && (NULL != host_list[id]))
330   {
331     LOG (GNUNET_ERROR_TYPE_WARNING, "Host with id: %u already created\n", id);
332     return NULL;
333   }
334   host = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host));
335   host->hostname = (NULL != hostname) ? GNUNET_strdup (hostname) : NULL;
336   host->username = (NULL != username) ? GNUNET_strdup (username) : NULL;
337   host->id = id;
338   host->port = (0 == port) ? 22 : port;
339   host->cfg = GNUNET_CONFIGURATION_dup (cfg);
340   host->opq_parallel_overlay_connect_operations =
341       GNUNET_TESTBED_operation_queue_create_ (OPERATION_QUEUE_TYPE_ADAPTIVE, 
342                                               UINT_MAX);
343   new_size = host_list_size;
344   while (id >= new_size)
345     new_size += HOST_LIST_GROW_STEP;
346   if (new_size != host_list_size)
347     GNUNET_array_grow (host_list, host_list_size, new_size);
348   GNUNET_assert (id < host_list_size);
349   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding host with id: %u\n", host->id);
350   host_list[id] = host;
351   return host;
352 }
353
354
355 /**
356  * Create a host to run peers and controllers on.
357  *
358  * @param hostname name of the host, use "NULL" for localhost
359  * @param username username to use for the login; may be NULL
360  * @param cfg the configuration to use as a template while starting a controller
361  *          on this host.  Operation queue sizes specific to a host are also
362  *          read from this configuration handle
363  * @param port port number to use for ssh; use 0 to let ssh decide
364  * @return handle to the host, NULL on error
365  */
366 struct GNUNET_TESTBED_Host *
367 GNUNET_TESTBED_host_create (const char *hostname, const char *username,
368                             const struct GNUNET_CONFIGURATION_Handle *cfg,
369                             uint16_t port)
370 {
371   static uint32_t uid_generator;
372
373   if (NULL == hostname)
374     return GNUNET_TESTBED_host_create_with_id (0, hostname, username, 
375                                                cfg, port);
376   return GNUNET_TESTBED_host_create_with_id (++uid_generator, hostname,
377                                              username, cfg, port);
378 }
379
380
381 /**
382  * Load a set of hosts from a configuration file.
383  *
384  * @param filename file with the host specification
385  * @param cfg the configuration to use as a template while starting a controller
386  *          on any of the loaded hosts.  Operation queue sizes specific to a host
387  *          are also read from this configuration handle
388  * @param hosts set to the hosts found in the file; caller must free this if
389  *          number of hosts returned is greater than 0
390  * @return number of hosts returned in 'hosts', 0 on error
391  */
392 unsigned int
393 GNUNET_TESTBED_hosts_load_from_file (const char *filename,
394                                      const struct GNUNET_CONFIGURATION_Handle
395                                      *cfg,
396                                      struct GNUNET_TESTBED_Host ***hosts)
397 {
398   //struct GNUNET_TESTBED_Host **host_array;
399   struct GNUNET_TESTBED_Host *starting_host;
400   char *data;
401   char *buf;  
402   char *username;
403   char *hostname;
404   regex_t rex;
405   regmatch_t pmatch[6];
406   uint64_t fs;
407   short int port;
408   unsigned int offset;
409   unsigned int count;
410
411
412   GNUNET_assert (NULL != filename);
413   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
414   {
415     LOG (GNUNET_ERROR_TYPE_WARNING, _("Hosts file %s not found\n"), filename);
416     return 0;
417   }
418   if (GNUNET_OK !=
419       GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
420     fs = 0;  
421   if (0 == fs)
422   {
423     LOG (GNUNET_ERROR_TYPE_WARNING, _("Hosts file %s has no data\n"), filename);
424     return 0;
425   }  
426   data = GNUNET_malloc (fs);
427   if (fs != GNUNET_DISK_fn_read (filename, data, fs))
428   {
429     GNUNET_free (data);
430     LOG (GNUNET_ERROR_TYPE_WARNING, _("Hosts file %s cannot be read\n"),
431          filename);
432     return 0;
433   }
434   buf = data;
435   offset = 0;
436   starting_host = NULL;
437   count = 0;
438   /* refer RFC 952 and RFC 1123 for valid hostnames */
439   GNUNET_assert (0 == regcomp (&rex,
440                                "^(([[:alnum:]]+)@)?" /* username */
441                                "([[:alnum:]]+[-[:alnum:]_\\.]+)" /* hostname */
442                                "(:([[:digit:]]{1,5}))?", /* port */
443                                REG_EXTENDED | REG_ICASE));  
444   while (offset < (fs - 1))
445   {    
446     offset++;
447     if (((data[offset] == '\n')) && (buf != &data[offset]))
448     {
449       unsigned int size;
450
451       data[offset] = '\0';
452       username = NULL;
453       hostname = NULL;
454       port = 0;
455       if ((REG_NOMATCH == regexec (&rex, buf, 6, pmatch, 0))
456           || (-1 == pmatch[3].rm_so))
457       {
458         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
459                     "Error reading line `%s' in hostfile\n", buf);
460         buf = &data[offset + 1];
461         continue;
462       }
463       if (-1 != pmatch[2].rm_so)
464       {
465         size = pmatch[2].rm_eo - pmatch[2].rm_so;
466         username = GNUNET_malloc (size + 1);
467         username[size] = '\0';
468         GNUNET_assert (NULL != strncpy (username, buf + pmatch[2].rm_so, size));
469       }
470       if (-1 != pmatch[5].rm_so)
471       {
472         (void) SSCANF (buf + pmatch[5].rm_so, "%5hd", &port); 
473       }
474       size = pmatch[3].rm_eo - pmatch[3].rm_so;
475       hostname = GNUNET_malloc (size + 1);
476       hostname[size] = '\0';
477       GNUNET_assert (NULL != strncpy (hostname, buf + pmatch[3].rm_so, size));
478       LOG (GNUNET_ERROR_TYPE_DEBUG,
479            "Successfully read host %s, port %d and user %s from file\n",
480            (NULL == hostname) ? "NULL" : hostname,
481            port,
482            (NULL == username) ? "NULL" : username);
483       /* We store hosts in a static list; hence we only require the starting
484        * host pointer in that list to access the newly created list of hosts */
485       if (NULL == starting_host)
486         starting_host = GNUNET_TESTBED_host_create (hostname, username, cfg,
487                                                     port);
488       else
489         (void) GNUNET_TESTBED_host_create (hostname, username, cfg, port);
490       count++;
491       GNUNET_free_non_null (username);
492       GNUNET_free (hostname);        
493       buf = &data[offset + 1];
494     }
495     else if ((data[offset] == '\n') || (data[offset] == '\0'))
496       buf = &data[offset + 1];
497   }
498   regfree (&rex);
499   GNUNET_free (data);
500   if (NULL == starting_host)
501     return 0;
502   *hosts = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * count);
503   memcpy (*hosts, &host_list[GNUNET_TESTBED_host_get_id_ (starting_host)],
504           sizeof (struct GNUNET_TESTBED_Host *) * count);
505   return count;
506 }
507
508
509 /**
510  * Resolves a hostname using getaddrinfo
511  *
512  * @param host the hostname
513  * @return the string representing the IPv4 address of the given host; NULL upon error
514  */
515 const char *
516 simple_resolve (const char *host)
517 {
518   struct addrinfo *res;
519   const struct sockaddr_in *in_addr; 
520   char *hostip;
521   struct addrinfo hint;
522   unsigned int rc;
523
524   hint.ai_family = AF_INET;     /* IPv4 */
525   hint.ai_socktype = 0;
526   hint.ai_protocol = 0;
527   hint.ai_addrlen = 0;
528   hint.ai_addr = NULL;
529   hint.ai_canonname = NULL;
530   hint.ai_next = NULL;
531   hint.ai_flags = AI_NUMERICSERV;
532   res = NULL;
533   LOG_DEBUG ("Resolving [%s]\n", host);
534   if (0 != (rc = getaddrinfo (host, "22", &hint, &res)))
535   {
536     LOG_GAI (GNUNET_ERROR_TYPE_ERROR, "getaddrinfo", rc);
537     return NULL;
538   }
539   GNUNET_assert (NULL != res);
540   GNUNET_assert (NULL != res->ai_addr);
541   GNUNET_assert (sizeof (struct sockaddr_in) == res->ai_addrlen);
542   in_addr = (const struct sockaddr_in *) res->ai_addr;
543   hostip = inet_ntoa (in_addr->sin_addr);
544   GNUNET_assert (NULL != hostip);
545   freeaddrinfo (res);
546   LOG_DEBUG ("Resolved [%s] to [%s]\n", host, hostip);
547   return hostip;
548 }
549
550 #if ENABLE_LL
551 static int
552 cmpstringp(const void *p1, const void *p2)
553 {
554   /* The actual arguments to this function are "pointers to
555      pointers to char", but strcmp(3) arguments are "pointers
556      to char", hence the following cast plus dereference */
557   
558   return strcmp(* (char * const *) p1, * (char * const *) p2);
559 }
560 #endif
561
562 /**
563  * Loads the set of host allocated by the LoadLeveler Job Scheduler.  This
564  * function is only available when compiled with support for LoadLeveler and is
565  * used for running on the SuperMUC
566  *
567  * @param cfg the configuration to use as a template while starting a controller
568  *          on any of the loaded hosts.  Operation queue sizes specific to a host
569  *          are also read from this configuration handle
570  * @param hosts set to the hosts found in the file; caller must free this if
571  *          number of hosts returned is greater than 0
572  * @return number of hosts returned in 'hosts', 0 on error
573  */
574 unsigned int
575 GNUNET_TESTBED_hosts_load_from_loadleveler (const struct
576                                             GNUNET_CONFIGURATION_Handle *cfg,
577                                             struct GNUNET_TESTBED_Host ***hosts)
578 {
579 #if !ENABLE_LL
580   LOG (GNUNET_ERROR_TYPE_ERROR, 
581        _("The function %s is only available when compiled with (--with-ll)\n"),
582        __func__);
583   GNUNET_assert (0);
584 #else
585   const char *hostfile;
586   
587   if (NULL == (hostfile = getenv ("MP_SAVEHOSTFILE")))
588   {
589     GNUNET_break (0);
590     return 0;
591   }
592   return GNUNET_TESTBED_hosts_load_from_file (hostfile, cfg, hosts);
593 #endif
594 }
595
596
597 /**
598  * Destroy a host handle.  Must only be called once everything
599  * running on that host has been stopped.
600  *
601  * @param host handle to destroy
602  */
603 void
604 GNUNET_TESTBED_host_destroy (struct GNUNET_TESTBED_Host *host)
605 {
606   struct RegisteredController *rc;
607   uint32_t id;
608
609   GNUNET_assert (host->id < host_list_size);
610   GNUNET_assert (host_list[host->id] == host);
611   host_list[host->id] = NULL;
612   /* clear registered controllers list */
613   for (rc = host->rc_head; NULL != rc; rc = host->rc_head)
614   {
615     GNUNET_CONTAINER_DLL_remove (host->rc_head, host->rc_tail, rc);
616     GNUNET_free (rc);
617   }
618   GNUNET_free_non_null ((char *) host->username);
619   GNUNET_free_non_null ((char *) host->hostname);
620   GNUNET_TESTBED_operation_queue_destroy_
621       (host->opq_parallel_overlay_connect_operations);
622   GNUNET_CONFIGURATION_destroy (host->cfg);
623   GNUNET_free (host);
624   while (host_list_size >= HOST_LIST_GROW_STEP)
625   {
626     for (id = host_list_size - 1; id > host_list_size - HOST_LIST_GROW_STEP;
627          id--)
628       if (NULL != host_list[id])
629         break;
630     if (id != host_list_size - HOST_LIST_GROW_STEP)
631       break;
632     if (NULL != host_list[id])
633       break;
634     host_list_size -= HOST_LIST_GROW_STEP;
635   }
636   host_list =
637       GNUNET_realloc (host_list,
638                       sizeof (struct GNUNET_TESTBED_Host *) * host_list_size);
639 }
640
641
642 /**
643  * Marks a host as registered with a controller
644  *
645  * @param host the host to mark
646  * @param controller the controller at which this host is registered
647  */
648 void
649 GNUNET_TESTBED_mark_host_registered_at_ (struct GNUNET_TESTBED_Host *host,
650                                          const struct GNUNET_TESTBED_Controller
651                                          *const controller)
652 {
653   struct RegisteredController *rc;
654
655   for (rc = host->rc_head; NULL != rc; rc = rc->next)
656   {
657     if (controller == rc->controller)   /* already registered at controller */
658     {
659       GNUNET_break (0);
660       return;
661     }
662   }
663   rc = GNUNET_malloc (sizeof (struct RegisteredController));
664   rc->controller = controller;
665   GNUNET_CONTAINER_DLL_insert_tail (host->rc_head, host->rc_tail, rc);
666 }
667
668
669 /**
670  * Unmarks a host registered at a controller
671  *
672  * @param host the host to unmark
673  * @param controller the controller at which this host has to be unmarked
674  */
675 void
676 GNUNET_TESTBED_deregister_host_at_ (struct GNUNET_TESTBED_Host *host,
677                                     const struct GNUNET_TESTBED_Controller
678                                     *const controller)
679 {
680   struct RegisteredController *rc;
681
682   for (rc = host->rc_head; NULL != rc; rc=rc->next)
683     if (controller == rc->controller)
684       break;
685   if (NULL == rc)
686   {
687     GNUNET_break (0);
688     return;
689   }
690   GNUNET_CONTAINER_DLL_remove (host->rc_head, host->rc_tail, rc);
691   GNUNET_free (rc);
692 }
693
694
695 /**
696  * Checks whether a host has been registered
697  *
698  * @param host the host to check
699  * @param controller the controller at which host's registration is checked
700  * @return GNUNET_YES if registered; GNUNET_NO if not
701  */
702 int
703 GNUNET_TESTBED_is_host_registered_ (const struct GNUNET_TESTBED_Host *host,
704                                     const struct GNUNET_TESTBED_Controller
705                                     *const controller)
706 {
707   struct RegisteredController *rc;
708
709   for (rc = host->rc_head; NULL != rc; rc = rc->next)
710   {
711     if (controller == rc->controller)   /* already registered at controller */
712     {
713       return GNUNET_YES;
714     }
715   }
716   return GNUNET_NO;
717 }
718
719
720 /**
721  * Handle for controller process
722  */
723 struct GNUNET_TESTBED_ControllerProc
724 {
725   /**
726    * The process handle
727    */
728   struct GNUNET_HELPER_Handle *helper;
729
730   /**
731    * The arguments used to start the helper
732    */
733   char **helper_argv;
734
735   /**
736    * The host where the helper is run
737    */
738   struct GNUNET_TESTBED_Host *host;
739
740   /**
741    * The controller error callback
742    */
743   GNUNET_TESTBED_ControllerStatusCallback cb;
744
745   /**
746    * The closure for the above callback
747    */
748   void *cls;
749
750   /**
751    * The send handle for the helper
752    */
753   struct GNUNET_HELPER_SendHandle *shandle;
754
755   /**
756    * The message corresponding to send handle
757    */
758   struct GNUNET_MessageHeader *msg;
759
760 };
761
762
763 /**
764  * Function to copy NULL terminated list of arguments
765  *
766  * @param argv the NULL terminated list of arguments. Cannot be NULL.
767  * @return the copied NULL terminated arguments
768  */
769 static char **
770 copy_argv (const char *const *argv)
771 {
772   char **argv_dup;
773   unsigned int argp;
774
775   GNUNET_assert (NULL != argv);
776   for (argp = 0; NULL != argv[argp]; argp++) ;
777   argv_dup = GNUNET_malloc (sizeof (char *) * (argp + 1));
778   for (argp = 0; NULL != argv[argp]; argp++)
779     argv_dup[argp] = strdup (argv[argp]);
780   return argv_dup;
781 }
782
783
784 /**
785  * Function to join NULL terminated list of arguments
786  *
787  * @param argv1 the NULL terminated list of arguments. Cannot be NULL.
788  * @param argv2 the NULL terminated list of arguments. Cannot be NULL.
789  * @return the joined NULL terminated arguments
790  */
791 static char **
792 join_argv (const char *const *argv1, const char *const *argv2)
793 {
794   char **argvj;
795   char *argv;
796   unsigned int carg;
797   unsigned int cnt;
798
799   carg = 0;
800   argvj = NULL;
801   for (cnt = 0; NULL != argv1[cnt]; cnt++)
802   {
803     argv = GNUNET_strdup (argv1[cnt]);
804     GNUNET_array_append (argvj, carg, argv);
805   }
806   for (cnt = 0; NULL != argv2[cnt]; cnt++)
807   {
808     argv = GNUNET_strdup (argv2[cnt]);
809     GNUNET_array_append (argvj, carg, argv);
810   }
811   GNUNET_array_append (argvj, carg, NULL);
812   return argvj;
813 }
814
815
816 /**
817  * Frees the given NULL terminated arguments
818  *
819  * @param argv the NULL terminated list of arguments
820  */
821 static void
822 free_argv (char **argv)
823 {
824   unsigned int argp;
825
826   for (argp = 0; NULL != argv[argp]; argp++)
827     GNUNET_free (argv[argp]);
828   GNUNET_free (argv);
829 }
830
831
832 /**
833  * Generates arguments for opening a remote shell. Builds up the arguments
834  * from the environment variable GNUNET_TESTBED_RSH_CMD. The variable
835  * should not mention `-p' (port) option and destination address as these will
836  * be set locally in the function from its parameteres. If the environmental
837  * variable is not found then it defaults to `ssh -o BatchMode=yes -o
838  * NoHostAuthenticationForLocalhost=yes'
839  *
840  * @param port the destination port number
841  * @param hostname the hostname of the target host
842  * @param username the username to use while connecting to target host
843  * @return NULL terminated list of arguments
844  */
845 static char **
846 gen_rsh_args (const char *port, const char *hostname, const char *username)
847 {
848   static const char *default_ssh_args[] = {
849     "ssh",
850     "-o",
851     "BatchMode=yes",
852     "-o",
853     "NoHostAuthenticationForLocalhost=yes",
854     "%h",
855     NULL
856   };
857   char **ssh_args;
858   char *ssh_cmd;
859   char *ssh_cmd_cp;
860   char *arg;
861   const char *new_arg;
862   unsigned int size;
863   unsigned int cnt;
864
865   ssh_args = NULL;
866   if (NULL != (ssh_cmd = getenv ("GNUNET_TESTBED_RSH_CMD")))
867   {
868     ssh_cmd = GNUNET_strdup (ssh_cmd);
869     ssh_cmd_cp = ssh_cmd;
870     for (size = 0; NULL != (arg = strtok (ssh_cmd, " ")); ssh_cmd = NULL)
871       GNUNET_array_append (ssh_args, size, GNUNET_strdup (arg));
872     GNUNET_free (ssh_cmd_cp);
873   }
874   else
875   {
876     ssh_args = copy_argv (default_ssh_args);
877     size = (sizeof (default_ssh_args)) / (sizeof (const char *));
878     GNUNET_array_grow (ssh_args, size, size - 1);
879   }
880   for (cnt = 0; cnt < size; cnt++)
881   {
882     arg = ssh_args[cnt];
883     if ('%' != arg[0])
884       continue;
885     switch (arg[1])
886     {
887     case 'p':
888       new_arg = port;
889       break;
890
891     case 'u':
892       new_arg = username;
893       break;
894
895     case 'h':
896       new_arg = hostname;
897       break;
898
899     default:
900       continue;
901     }
902     if (NULL == new_arg)
903       continue;
904     GNUNET_free (arg);
905     ssh_args[cnt] = GNUNET_strdup (new_arg);
906   }
907   GNUNET_array_append (ssh_args, size, NULL);
908   return ssh_args;
909 }
910
911
912 /**
913  * Generates the arguments needed for executing the given binary in a remote
914  * shell. Builds the arguments from the environmental variable
915  * GNUNET_TETSBED_RSH_CMD_SUFFIX. If the environmental variable is not found,
916  * only the given binary name will be present in the returned arguments
917  *
918  * @param append_args the arguments to append after generating the suffix
919  *          arguments. Can be NULL; if not must be NULL terminated 'char *' array
920  * @return NULL-terminated args
921  */
922 static char **
923 gen_rsh_suffix_args (const char * const *append_args)
924 {
925   char **rshell_args;
926   char *rshell_cmd;
927   char *rshell_cmd_cp;
928   char *arg;
929   unsigned int cnt;
930   unsigned int append_cnt;
931
932   rshell_args = NULL;
933   cnt = 0;
934   if (NULL != (rshell_cmd = getenv ("GNUNET_TESTBED_RSH_CMD_SUFFIX")))
935   {
936     rshell_cmd = GNUNET_strdup (rshell_cmd);
937     rshell_cmd_cp = rshell_cmd;
938     for (; NULL != (arg = strtok (rshell_cmd, " ")); rshell_cmd = NULL)
939       GNUNET_array_append (rshell_args, cnt, GNUNET_strdup (arg));
940     GNUNET_free (rshell_cmd_cp);
941   }
942   if (NULL != append_args)
943   {
944     for (append_cnt = 0; NULL != append_args[append_cnt]; append_cnt++)      
945       GNUNET_array_append (rshell_args, cnt, GNUNET_strdup (append_args[append_cnt]));
946   }
947   GNUNET_array_append (rshell_args, cnt, NULL);
948   return rshell_args;
949 }
950
951
952 /**
953  * Functions with this signature are called whenever a
954  * complete message is received by the tokenizer.
955  *
956  * Do not call GNUNET_SERVER_mst_destroy in callback
957  *
958  * @param cls closure
959  * @param client identification of the client
960  * @param message the actual message
961  *
962  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
963  */
964 static int
965 helper_mst (void *cls, void *client, const struct GNUNET_MessageHeader *message)
966 {
967   struct GNUNET_TESTBED_ControllerProc *cp = cls;
968   const struct GNUNET_TESTBED_HelperReply *msg;
969   const char *hostname;
970   char *config;
971   uLongf config_size;
972   uLongf xconfig_size;
973
974   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
975   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) <
976                  ntohs (msg->header.size));
977   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY ==
978                  ntohs (msg->header.type));
979   config_size = (uLongf) ntohs (msg->config_size);
980   xconfig_size =
981       (uLongf) (ntohs (msg->header.size) -
982                 sizeof (struct GNUNET_TESTBED_HelperReply));
983   config = GNUNET_malloc (config_size);
984   GNUNET_assert (Z_OK ==
985                  uncompress ((Bytef *) config, &config_size,
986                              (const Bytef *) &msg[1], xconfig_size));
987   /* Replace the configuration template present in the host with the
988      controller's running configuration */
989   GNUNET_CONFIGURATION_destroy (cp->host->cfg);
990   cp->host->cfg = GNUNET_CONFIGURATION_create ();
991   GNUNET_assert (GNUNET_CONFIGURATION_deserialize
992                  (cp->host->cfg, config, config_size, GNUNET_NO));
993   GNUNET_free (config);
994   if (NULL == (hostname = GNUNET_TESTBED_host_get_hostname (cp->host)))
995     hostname = "localhost";
996   /* Change the hostname so that we can connect to it */
997   GNUNET_CONFIGURATION_set_value_string (cp->host->cfg, "testbed", "hostname",
998                                          hostname);
999   cp->host->locked = GNUNET_NO;
1000   cp->host->controller_started = GNUNET_YES;
1001   cp->cb (cp->cls, cp->host->cfg, GNUNET_OK);
1002   return GNUNET_OK;
1003 }
1004
1005
1006 /**
1007  * Continuation function from GNUNET_HELPER_send()
1008  *
1009  * @param cls closure
1010  * @param result GNUNET_OK on success,
1011  *               GNUNET_NO if helper process died
1012  *               GNUNET_SYSERR during GNUNET_HELPER_stop
1013  */
1014 static void
1015 clear_msg (void *cls, int result)
1016 {
1017   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1018
1019   GNUNET_assert (NULL != cp->shandle);
1020   cp->shandle = NULL;
1021   GNUNET_free (cp->msg);
1022 }
1023
1024
1025 /**
1026  * Callback that will be called when the helper process dies. This is not called
1027  * when the helper process is stoped using GNUNET_HELPER_stop()
1028  *
1029  * @param cls the closure from GNUNET_HELPER_start()
1030  */
1031 static void
1032 helper_exp_cb (void *cls)
1033 {
1034   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1035   GNUNET_TESTBED_ControllerStatusCallback cb;
1036   void *cb_cls;
1037
1038   cb = cp->cb;
1039   cb_cls = cp->cls;
1040   cp->helper = NULL;
1041   GNUNET_TESTBED_controller_stop (cp);
1042   if (NULL != cb)
1043     cb (cb_cls, NULL, GNUNET_SYSERR);
1044 }
1045
1046
1047 /**
1048  * Starts a controller process at the given host.  The given host's configration
1049  * is used as a Template configuration to use for the remote controller; the
1050  * remote controller will be started with a slightly modified configuration
1051  * (port numbers, unix domain sockets and service home values are changed as per
1052  * TESTING library on the remote host).  The modified configuration replaces the
1053  * host's existing configuration before signalling success through the
1054  * GNUNET_TESTBED_ControllerStatusCallback()
1055  *
1056  * @param trusted_ip the ip address of the controller which will be set as TRUSTED
1057  *          HOST(all connections form this ip are permitted by the testbed) when
1058  *          starting testbed controller at host. This can either be a single ip
1059  *          address or a network address in CIDR notation.
1060  * @param host the host where the controller has to be started.  CANNOT be NULL.
1061  * @param cb function called when the controller is successfully started or
1062  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
1063  *          called if cb is called with GNUNET_SYSERR as status. Will never be
1064  *          called in the same task as 'GNUNET_TESTBED_controller_start'
1065  *          (synchronous errors will be signalled by returning NULL). This
1066  *          parameter cannot be NULL.
1067  * @param cls closure for above callbacks
1068  * @return the controller process handle, NULL on errors
1069  */
1070 struct GNUNET_TESTBED_ControllerProc *
1071 GNUNET_TESTBED_controller_start (const char *trusted_ip,
1072                                  struct GNUNET_TESTBED_Host *host,
1073                                  GNUNET_TESTBED_ControllerStatusCallback cb,
1074                                  void *cls)
1075 {
1076   struct GNUNET_TESTBED_ControllerProc *cp;
1077   struct GNUNET_TESTBED_HelperInit *msg;
1078   const struct GNUNET_CONFIGURATION_Handle *cfg;
1079   const char *hostname;
1080   static char *const binary_argv[] = {
1081     HELPER_TESTBED_BINARY, NULL
1082   };
1083   
1084   GNUNET_assert (NULL != host);
1085   GNUNET_assert (NULL != (cfg = GNUNET_TESTBED_host_get_cfg_ (host)));
1086   hostname = NULL;
1087   API_VIOLATION (GNUNET_NO == host->locked,
1088                  "Host is already locked by a previous call to GNUNET_TESTBED_controller_start()");
1089   host->locked = GNUNET_YES;
1090   API_VIOLATION (GNUNET_NO == host->controller_started,
1091                  "Attempting to start a controller on a host which is already started a controller");
1092   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
1093   if (0 == GNUNET_TESTBED_host_get_id_ (host))
1094   {
1095     cp->helper =
1096         GNUNET_HELPER_start (GNUNET_YES, HELPER_TESTBED_BINARY, binary_argv,
1097                              &helper_mst, &helper_exp_cb, cp);
1098   }
1099   else
1100   {
1101     char *helper_binary_path_args[2];
1102     char **rsh_args;
1103     char **rsh_suffix_args;
1104     const char *username;
1105     char *port;
1106
1107     username = host->username;
1108     hostname = host->hostname;
1109     GNUNET_asprintf (&port, "%u", host->port);
1110     LOG_DEBUG ("Starting remote connection to destination %s\n", hostname);
1111     if (GNUNET_OK !=
1112         GNUNET_CONFIGURATION_get_value_string (cfg, "testbed",
1113                                                "HELPER_BINARY_PATH",
1114                                                &helper_binary_path_args[0]))
1115       helper_binary_path_args[0] =
1116           GNUNET_OS_get_libexec_binary_path (HELPER_TESTBED_BINARY);
1117     helper_binary_path_args[1] = NULL;
1118     rsh_args = gen_rsh_args (port, hostname, username);
1119     rsh_suffix_args = gen_rsh_suffix_args ((const char **) helper_binary_path_args);
1120     cp->helper_argv =
1121         join_argv ((const char **) rsh_args, (const char **) rsh_suffix_args);
1122     free_argv (rsh_args);
1123     free_argv (rsh_suffix_args);
1124     GNUNET_free (port);
1125     cp->helper =
1126         GNUNET_HELPER_start (GNUNET_NO, cp->helper_argv[0], cp->helper_argv, &helper_mst,
1127                              &helper_exp_cb, cp);
1128     GNUNET_free (helper_binary_path_args[0]);
1129   }
1130   if (NULL == cp->helper)
1131   {
1132     if (NULL != cp->helper_argv)
1133       free_argv (cp->helper_argv);
1134     GNUNET_free (cp);
1135     return NULL;
1136   }
1137   cp->host = host;
1138   cp->cb = cb;
1139   cp->cls = cls;
1140   msg = GNUNET_TESTBED_create_helper_init_msg_ (trusted_ip, hostname, cfg);
1141   cp->msg = &msg->header;
1142   cp->shandle =
1143       GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO, &clear_msg, cp);
1144   if (NULL == cp->shandle)
1145   {
1146     GNUNET_free (msg);
1147     GNUNET_TESTBED_controller_stop (cp);
1148     return NULL;
1149   }
1150   return cp;
1151 }
1152
1153
1154 /**
1155  * Sends termination signal to the controller's helper process
1156  *
1157  * @param cproc the handle to the controller's helper process
1158  */
1159 void
1160 GNUNET_TESTBED_controller_kill_ (struct GNUNET_TESTBED_ControllerProc *cproc)
1161 {
1162   if (NULL != cproc->shandle)
1163     GNUNET_HELPER_send_cancel (cproc->shandle);
1164   if (NULL != cproc->helper)
1165     GNUNET_HELPER_kill (cproc->helper, GNUNET_YES);
1166 }
1167
1168
1169 /**
1170  * Cleans-up the controller's helper process handle
1171  *
1172  * @param cproc the handle to the controller's helper process
1173  */
1174 void
1175 GNUNET_TESTBED_controller_destroy_ (struct GNUNET_TESTBED_ControllerProc *cproc)
1176 {
1177   if (NULL != cproc->helper)
1178   {
1179     GNUNET_break (GNUNET_OK == GNUNET_HELPER_wait (cproc->helper));
1180     GNUNET_HELPER_destroy (cproc->helper);
1181   }
1182   if (NULL != cproc->helper_argv)
1183     free_argv (cproc->helper_argv);
1184   cproc->host->controller_started = GNUNET_NO;
1185   cproc->host->locked = GNUNET_NO;
1186   GNUNET_free (cproc);
1187 }
1188
1189
1190 /**
1191  * Stop the controller process (also will terminate all peers and controllers
1192  * dependent on this controller).  This function blocks until the testbed has
1193  * been fully terminated (!). The controller status cb from
1194  * GNUNET_TESTBED_controller_start() will not be called.
1195  *
1196  * @param cproc the controller process handle
1197  */
1198 void
1199 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
1200 {
1201   GNUNET_TESTBED_controller_kill_ (cproc);
1202   GNUNET_TESTBED_controller_destroy_ (cproc);
1203 }
1204
1205
1206 /**
1207  * The handle for whether a host is habitable or not
1208  */
1209 struct GNUNET_TESTBED_HostHabitableCheckHandle
1210 {
1211   /**
1212    * The host to check
1213    */
1214   const struct GNUNET_TESTBED_Host *host;
1215
1216   /**
1217    * The callback to call once we have the status
1218    */
1219   GNUNET_TESTBED_HostHabitableCallback cb;
1220
1221   /**
1222    * The callback closure
1223    */
1224   void *cb_cls;
1225
1226   /**
1227    * The process handle for the SSH process
1228    */
1229   struct GNUNET_OS_Process *auxp;
1230
1231   /**
1232    * The arguments used to start the helper
1233    */
1234   char **helper_argv;
1235
1236   /**
1237    * Task id for the habitability check task
1238    */
1239   GNUNET_SCHEDULER_TaskIdentifier habitability_check_task;
1240
1241   /**
1242    * How long we wait before checking the process status. Should grow
1243    * exponentially
1244    */
1245   struct GNUNET_TIME_Relative wait_time;
1246
1247 };
1248
1249
1250 /**
1251  * Task for checking whether a host is habitable or not
1252  *
1253  * @param cls GNUNET_TESTBED_HostHabitableCheckHandle
1254  * @param tc the scheduler task context
1255  */
1256 static void
1257 habitability_check (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1258 {
1259   struct GNUNET_TESTBED_HostHabitableCheckHandle *h = cls;
1260   void *cb_cls;
1261   GNUNET_TESTBED_HostHabitableCallback cb;
1262   const struct GNUNET_TESTBED_Host *host;
1263   unsigned long code;
1264   enum GNUNET_OS_ProcessStatusType type;
1265   int ret;
1266
1267   h->habitability_check_task = GNUNET_SCHEDULER_NO_TASK;
1268   ret = GNUNET_OS_process_status (h->auxp, &type, &code);
1269   if (GNUNET_SYSERR == ret)
1270   {
1271     GNUNET_break (0);
1272     ret = GNUNET_NO;
1273     goto call_cb;
1274   }
1275   if (GNUNET_NO == ret)
1276   {
1277     h->wait_time = GNUNET_TIME_STD_BACKOFF (h->wait_time);
1278     h->habitability_check_task =
1279         GNUNET_SCHEDULER_add_delayed (h->wait_time, &habitability_check, h);
1280     return;
1281   }
1282   GNUNET_OS_process_destroy (h->auxp);
1283   h->auxp = NULL;
1284   ret = (0 != code) ? GNUNET_NO : GNUNET_YES;
1285
1286 call_cb:
1287   if (NULL != h->auxp)
1288     GNUNET_OS_process_destroy (h->auxp);
1289   cb = h->cb;
1290   cb_cls = h->cb_cls;
1291   host = h->host;
1292   free_argv (h->helper_argv);
1293   GNUNET_free (h);
1294   if (NULL != cb)
1295     cb (cb_cls, host, ret);
1296 }
1297
1298
1299 /**
1300  * Checks whether a host can be used to start testbed service
1301  *
1302  * @param host the host to check
1303  * @param config the configuration handle to lookup the path of the testbed
1304  *          helper
1305  * @param cb the callback to call to inform about habitability of the given host
1306  * @param cb_cls the closure for the callback
1307  * @return NULL upon any error or a handle which can be passed to
1308  *           GNUNET_TESTBED_is_host_habitable_cancel()
1309  */
1310 struct GNUNET_TESTBED_HostHabitableCheckHandle *
1311 GNUNET_TESTBED_is_host_habitable (const struct GNUNET_TESTBED_Host *host,
1312                                   const struct GNUNET_CONFIGURATION_Handle
1313                                   *config,
1314                                   GNUNET_TESTBED_HostHabitableCallback cb,
1315                                   void *cb_cls)
1316 {
1317   struct GNUNET_TESTBED_HostHabitableCheckHandle *h;
1318   char **rsh_args;
1319   char **rsh_suffix_args;
1320   char *stat_args[3];
1321   const char *hostname;
1322   char *port;
1323
1324   h = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle));
1325   h->cb = cb;
1326   h->cb_cls = cb_cls;
1327   h->host = host;
1328   hostname = (NULL == host->hostname) ? "127.0.0.1" : host->hostname;
1329   if (GNUNET_OK !=
1330       GNUNET_CONFIGURATION_get_value_string (config, "testbed",
1331                                              "HELPER_BINARY_PATH",
1332                                              &stat_args[1]))
1333     stat_args[1] =
1334         GNUNET_OS_get_libexec_binary_path (HELPER_TESTBED_BINARY);  
1335   GNUNET_asprintf (&port, "%u", host->port);
1336   rsh_args = gen_rsh_args (port, hostname, host->username);
1337   GNUNET_free (port);
1338   port = NULL;
1339   stat_args[0] = "stat";
1340   stat_args[2] = NULL;
1341   rsh_suffix_args = gen_rsh_suffix_args ((const char **) stat_args);
1342   GNUNET_free (stat_args[1]);
1343   h->helper_argv = join_argv ((const char **) rsh_args,
1344                               (const char **) rsh_suffix_args);
1345   free_argv (rsh_suffix_args);
1346   free_argv (rsh_args);
1347   h->auxp =
1348       GNUNET_OS_start_process_vap (GNUNET_NO, GNUNET_OS_INHERIT_STD_ERR, NULL,
1349                                    NULL, h->helper_argv[0], h->helper_argv);
1350   if (NULL == h->auxp)
1351   {
1352     GNUNET_break (0);           /* Cannot exec SSH? */
1353     GNUNET_free (h);
1354     return NULL;
1355   }
1356   h->wait_time = GNUNET_TIME_STD_BACKOFF (h->wait_time);
1357   h->habitability_check_task =
1358       GNUNET_SCHEDULER_add_delayed (h->wait_time, &habitability_check, h);
1359   return h;
1360 }
1361
1362
1363 /**
1364  * Function to cancel a request started using GNUNET_TESTBED_is_host_habitable()
1365  *
1366  * @param handle the habitability check handle
1367  */
1368 void
1369 GNUNET_TESTBED_is_host_habitable_cancel (struct
1370                                          GNUNET_TESTBED_HostHabitableCheckHandle
1371                                          *handle)
1372 {
1373   GNUNET_SCHEDULER_cancel (handle->habitability_check_task);
1374   (void) GNUNET_OS_process_kill (handle->auxp, SIGTERM);
1375   (void) GNUNET_OS_process_wait (handle->auxp);
1376   GNUNET_OS_process_destroy (handle->auxp);
1377   free_argv (handle->helper_argv);
1378   GNUNET_free (handle);
1379 }
1380
1381
1382 /**
1383  * handle for host registration
1384  */
1385 struct GNUNET_TESTBED_HostRegistrationHandle
1386 {
1387   /**
1388    * The host being registered
1389    */
1390   struct GNUNET_TESTBED_Host *host;
1391
1392   /**
1393    * The controller at which this host is being registered
1394    */
1395   struct GNUNET_TESTBED_Controller *c;
1396
1397   /**
1398    * The Registartion completion callback
1399    */
1400   GNUNET_TESTBED_HostRegistrationCompletion cc;
1401
1402   /**
1403    * The closure for above callback
1404    */
1405   void *cc_cls;
1406 };
1407
1408
1409 /**
1410  * Register a host with the controller
1411  *
1412  * @param controller the controller handle
1413  * @param host the host to register
1414  * @param cc the completion callback to call to inform the status of
1415  *          registration. After calling this callback the registration handle
1416  *          will be invalid. Cannot be NULL.
1417  * @param cc_cls the closure for the cc
1418  * @return handle to the host registration which can be used to cancel the
1419  *           registration
1420  */
1421 struct GNUNET_TESTBED_HostRegistrationHandle *
1422 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1423                               struct GNUNET_TESTBED_Host *host,
1424                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1425                               void *cc_cls)
1426 {
1427   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1428   struct GNUNET_TESTBED_AddHostMessage *msg;
1429   const char *username;
1430   const char *hostname;
1431   char *config;
1432   char *cconfig;
1433   void *ptr;
1434   size_t cc_size;
1435   size_t config_size;
1436   uint16_t msg_size;
1437   uint16_t username_length;
1438   uint16_t hostname_length;
1439
1440   if (NULL != controller->rh)
1441     return NULL;
1442   hostname = GNUNET_TESTBED_host_get_hostname (host);
1443   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1444   {
1445     LOG (GNUNET_ERROR_TYPE_WARNING, "Host hostname: %s already registered\n",
1446          (NULL == hostname) ? "localhost" : hostname);
1447     return NULL;
1448   }
1449   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1450   rh->host = host;
1451   rh->c = controller;
1452   GNUNET_assert (NULL != cc);
1453   rh->cc = cc;
1454   rh->cc_cls = cc_cls;
1455   controller->rh = rh;
1456   username = GNUNET_TESTBED_host_get_username_ (host);
1457   username_length = 0;
1458   if (NULL != username)
1459     username_length = strlen (username);
1460   GNUNET_assert (NULL != hostname); /* Hostname must be present */
1461   hostname_length = strlen (hostname);
1462   GNUNET_assert (NULL != host->cfg);
1463   config = GNUNET_CONFIGURATION_serialize (host->cfg, &config_size);
1464   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1465   GNUNET_free (config);
1466   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1467   msg_size += username_length;
1468   msg_size += hostname_length;
1469   msg_size += cc_size;
1470   msg = GNUNET_malloc (msg_size);
1471   msg->header.size = htons (msg_size);
1472   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST);
1473   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1474   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1475   ptr = &msg[1];
1476   if (NULL != username)
1477   {
1478     msg->username_length = htons (username_length);
1479     ptr = memcpy (ptr, username, username_length);
1480     ptr += username_length;
1481   }
1482   msg->hostname_length = htons (hostname_length);
1483   ptr = memcpy (ptr, hostname, hostname_length);
1484   ptr += hostname_length;
1485   msg->config_size = htons (config_size);
1486   ptr = memcpy (ptr, cconfig, cc_size);
1487   ptr += cc_size;
1488   GNUNET_assert ((ptr - (void *) msg) == msg_size);
1489   GNUNET_free (cconfig);
1490   GNUNET_TESTBED_queue_message_ (controller,
1491                                  (struct GNUNET_MessageHeader *) msg);
1492   return rh;
1493 }
1494
1495
1496 /**
1497  * Cancel the pending registration. Note that if the registration message is
1498  * already sent to the service the cancellation has only the effect that the
1499  * registration completion callback for the registration is never called.
1500  *
1501  * @param handle the registration handle to cancel
1502  */
1503 void
1504 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1505                                     *handle)
1506 {
1507   if (handle != handle->c->rh)
1508   {
1509     GNUNET_break (0);
1510     return;
1511   }
1512   handle->c->rh = NULL;
1513   GNUNET_free (handle);
1514 }
1515
1516
1517 /**
1518  * Queues the given operation in the queue for parallel overlay connects of the
1519  * given host
1520  *
1521  * @param h the host handle
1522  * @param op the operation to queue in the given host's parally overlay connect
1523  *          queue 
1524  */
1525 void
1526 GNUNET_TESTBED_host_queue_oc_ (struct GNUNET_TESTBED_Host *h, 
1527                                struct GNUNET_TESTBED_Operation *op)
1528 {  
1529   GNUNET_TESTBED_operation_queue_insert_
1530       (h->opq_parallel_overlay_connect_operations, op);
1531 }
1532
1533
1534 /**
1535  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
1536  * controller (testbed service)
1537  *
1538  * @param c the controller handler
1539  * @param msg message received
1540  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
1541  *           not
1542  */
1543 int
1544 GNUNET_TESTBED_host_handle_addhostconfirm_ (struct GNUNET_TESTBED_Controller *c,
1545                                             const struct
1546                                             GNUNET_TESTBED_HostConfirmedMessage
1547                                             *msg)
1548 {
1549   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1550   char *emsg;
1551   uint16_t msg_size;
1552
1553   rh = c->rh;
1554   if (NULL == rh)
1555   {
1556     return GNUNET_OK;
1557   }
1558   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
1559   {
1560     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
1561                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
1562     return GNUNET_OK;
1563   }
1564   c->rh = NULL;
1565   msg_size = ntohs (msg->header.size);
1566   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
1567   {
1568     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
1569     GNUNET_TESTBED_mark_host_registered_at_ (rh->host, c);
1570     rh->cc (rh->cc_cls, NULL);
1571     GNUNET_free (rh);
1572     return GNUNET_OK;
1573   }
1574   /* We have an error message */
1575   emsg = (char *) &msg[1];
1576   if ('\0' !=
1577       emsg[msg_size - sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
1578   {
1579     GNUNET_break (0);
1580     GNUNET_free (rh);
1581     return GNUNET_NO;
1582   }
1583   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
1584        ntohl (msg->host_id), emsg);
1585   rh->cc (rh->cc_cls, emsg);
1586   GNUNET_free (rh);
1587   return GNUNET_OK;
1588 }
1589
1590
1591 /**
1592  * Resolves the hostname of the host to an ip address
1593  *
1594  * @param host the host whose hostname is to be resolved
1595  */
1596 void
1597 GNUNET_TESTBED_host_resolve_ (struct GNUNET_TESTBED_Host *host)
1598 {
1599   char *hostname;
1600
1601   hostname = (char *) host->hostname;
1602   host->hostname = simple_resolve (hostname);
1603   if (NULL == host->hostname)
1604   {
1605     GNUNET_break (0);
1606     host->hostname = hostname;
1607     return;
1608   }
1609   GNUNET_free (hostname);
1610   host->hostname = GNUNET_strdup (host->hostname);
1611 }
1612
1613 /* end of testbed_api_hosts.c */