c0b64cf8f052e462e2dccadb6e0fa09f60026adf
[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   char *buf;
587   char *hostname;
588   char **hostnames;
589   struct GNUNET_TESTBED_Host **host_list;
590   ssize_t rsize;
591   uint64_t size;
592   uint64_t offset;
593   enum {
594     SCAN,
595     SKIP,
596     TRIM,
597     READHOST
598   } pstep;
599   unsigned int host;
600   unsigned int nhosts;
601   
602   if (NULL == (hostfile = getenv ("MP_SAVEHOSTFILE")))
603   {
604     GNUNET_break (0);
605     return 0;
606   }
607   if (GNUNET_SYSERR == GNUNET_DISK_file_size (hostfile, &size, GNUNET_YES,
608                                               GNUNET_YES))
609   {
610     GNUNET_break (0);
611     return 0;
612   }
613   if (0 == size)
614   {
615     GNUNET_break (0);
616     return 0;
617   }
618   buf = GNUNET_malloc (size + 1);
619   rsize = GNUNET_DISK_fn_read (hostfile, buf, (size_t) size);
620   if ( (GNUNET_SYSERR == rsize) || ((ssize_t) size != rsize) )
621   {
622     GNUNET_free (buf);
623     GNUNET_break (0);
624     return 0;
625   }
626   size++;
627   offset = 0;
628   pstep = SCAN;
629   hostname = NULL;
630   hostnames = NULL;
631   nhosts = 0;
632   while (offset < size)
633   {
634     switch (pstep)
635     {
636     case SCAN:
637       if ('!' == buf[offset])
638         pstep = SKIP;
639       else 
640         pstep = TRIM;
641       break;
642     case SKIP:
643       if ('\n' == buf[offset])
644         pstep = SCAN;
645       break;
646     case TRIM:
647       if ('!' == buf[offset])
648       {
649         pstep = SKIP;
650         break;
651       }
652       if ( (' ' == buf[offset]) 
653            || ('\t' == buf[offset])
654            || ('\r' == buf[offset]) )
655         pstep = TRIM;
656       else
657       {
658         pstep = READHOST;
659         hostname = &buf[offset];        
660       }
661       break;
662     case READHOST:
663       if (isspace (buf[offset]))
664       {
665         buf[offset] = '\0';
666         for (host = 0; host < nhosts; host++)
667           if (0 == strcmp (hostnames[host], hostname))
668             break;
669         if (host == nhosts)
670         {
671           LOG_DEBUG ("Adding host [%s]\n", hostname);
672           hostname = GNUNET_strdup (hostname);
673           GNUNET_array_append (hostnames, nhosts, hostname);
674         }
675         else
676           LOG_DEBUG ("Not adding host [%s] as it is already included\n", hostname);
677         hostname = NULL;
678         pstep = SCAN;
679       }
680       break;
681     }
682     offset++;
683   }
684   GNUNET_free_non_null (buf);
685   if (NULL == hostnames)
686     return 0;
687   if (NULL == hosts)
688     goto cleanup;
689   qsort (hostnames, nhosts, sizeof (hostnames[0]), cmpstringp);
690   host_list = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * nhosts);
691   for (host = 0; host < nhosts; host++)
692     host_list[host] = GNUNET_TESTBED_host_create (hostnames[host], NULL, cfg, 0);
693   *hosts = host_list;
694
695  cleanup:
696   for (host = 0; host < nhosts; host++)
697     GNUNET_free (hostnames[host]);
698   GNUNET_free(hostnames);
699   return nhosts;
700 #endif
701 }
702
703
704 /**
705  * Destroy a host handle.  Must only be called once everything
706  * running on that host has been stopped.
707  *
708  * @param host handle to destroy
709  */
710 void
711 GNUNET_TESTBED_host_destroy (struct GNUNET_TESTBED_Host *host)
712 {
713   struct RegisteredController *rc;
714   uint32_t id;
715
716   GNUNET_assert (host->id < host_list_size);
717   GNUNET_assert (host_list[host->id] == host);
718   host_list[host->id] = NULL;
719   /* clear registered controllers list */
720   for (rc = host->rc_head; NULL != rc; rc = host->rc_head)
721   {
722     GNUNET_CONTAINER_DLL_remove (host->rc_head, host->rc_tail, rc);
723     GNUNET_free (rc);
724   }
725   GNUNET_free_non_null ((char *) host->username);
726   GNUNET_free_non_null ((char *) host->hostname);
727   GNUNET_TESTBED_operation_queue_destroy_
728       (host->opq_parallel_overlay_connect_operations);
729   GNUNET_CONFIGURATION_destroy (host->cfg);
730   GNUNET_free (host);
731   while (host_list_size >= HOST_LIST_GROW_STEP)
732   {
733     for (id = host_list_size - 1; id > host_list_size - HOST_LIST_GROW_STEP;
734          id--)
735       if (NULL != host_list[id])
736         break;
737     if (id != host_list_size - HOST_LIST_GROW_STEP)
738       break;
739     if (NULL != host_list[id])
740       break;
741     host_list_size -= HOST_LIST_GROW_STEP;
742   }
743   host_list =
744       GNUNET_realloc (host_list,
745                       sizeof (struct GNUNET_TESTBED_Host *) * host_list_size);
746 }
747
748
749 /**
750  * Marks a host as registered with a controller
751  *
752  * @param host the host to mark
753  * @param controller the controller at which this host is registered
754  */
755 void
756 GNUNET_TESTBED_mark_host_registered_at_ (struct GNUNET_TESTBED_Host *host,
757                                          const struct GNUNET_TESTBED_Controller
758                                          *const controller)
759 {
760   struct RegisteredController *rc;
761
762   for (rc = host->rc_head; NULL != rc; rc = rc->next)
763   {
764     if (controller == rc->controller)   /* already registered at controller */
765     {
766       GNUNET_break (0);
767       return;
768     }
769   }
770   rc = GNUNET_malloc (sizeof (struct RegisteredController));
771   rc->controller = controller;
772   GNUNET_CONTAINER_DLL_insert_tail (host->rc_head, host->rc_tail, rc);
773 }
774
775
776 /**
777  * Unmarks a host registered at a controller
778  *
779  * @param host the host to unmark
780  * @param controller the controller at which this host has to be unmarked
781  */
782 void
783 GNUNET_TESTBED_deregister_host_at_ (struct GNUNET_TESTBED_Host *host,
784                                     const struct GNUNET_TESTBED_Controller
785                                     *const controller)
786 {
787   struct RegisteredController *rc;
788
789   for (rc = host->rc_head; NULL != rc; rc=rc->next)
790     if (controller == rc->controller)
791       break;
792   if (NULL == rc)
793   {
794     GNUNET_break (0);
795     return;
796   }
797   GNUNET_CONTAINER_DLL_remove (host->rc_head, host->rc_tail, rc);
798   GNUNET_free (rc);
799 }
800
801
802 /**
803  * Checks whether a host has been registered
804  *
805  * @param host the host to check
806  * @param controller the controller at which host's registration is checked
807  * @return GNUNET_YES if registered; GNUNET_NO if not
808  */
809 int
810 GNUNET_TESTBED_is_host_registered_ (const struct GNUNET_TESTBED_Host *host,
811                                     const struct GNUNET_TESTBED_Controller
812                                     *const controller)
813 {
814   struct RegisteredController *rc;
815
816   for (rc = host->rc_head; NULL != rc; rc = rc->next)
817   {
818     if (controller == rc->controller)   /* already registered at controller */
819     {
820       return GNUNET_YES;
821     }
822   }
823   return GNUNET_NO;
824 }
825
826
827 /**
828  * Handle for controller process
829  */
830 struct GNUNET_TESTBED_ControllerProc
831 {
832   /**
833    * The process handle
834    */
835   struct GNUNET_HELPER_Handle *helper;
836
837   /**
838    * The arguments used to start the helper
839    */
840   char **helper_argv;
841
842   /**
843    * The host where the helper is run
844    */
845   struct GNUNET_TESTBED_Host *host;
846
847   /**
848    * The controller error callback
849    */
850   GNUNET_TESTBED_ControllerStatusCallback cb;
851
852   /**
853    * The closure for the above callback
854    */
855   void *cls;
856
857   /**
858    * The send handle for the helper
859    */
860   struct GNUNET_HELPER_SendHandle *shandle;
861
862   /**
863    * The message corresponding to send handle
864    */
865   struct GNUNET_MessageHeader *msg;
866
867 };
868
869
870 /**
871  * Function to copy NULL terminated list of arguments
872  *
873  * @param argv the NULL terminated list of arguments. Cannot be NULL.
874  * @return the copied NULL terminated arguments
875  */
876 static char **
877 copy_argv (const char *const *argv)
878 {
879   char **argv_dup;
880   unsigned int argp;
881
882   GNUNET_assert (NULL != argv);
883   for (argp = 0; NULL != argv[argp]; argp++) ;
884   argv_dup = GNUNET_malloc (sizeof (char *) * (argp + 1));
885   for (argp = 0; NULL != argv[argp]; argp++)
886     argv_dup[argp] = strdup (argv[argp]);
887   return argv_dup;
888 }
889
890
891 /**
892  * Function to join NULL terminated list of arguments
893  *
894  * @param argv1 the NULL terminated list of arguments. Cannot be NULL.
895  * @param argv2 the NULL terminated list of arguments. Cannot be NULL.
896  * @return the joined NULL terminated arguments
897  */
898 static char **
899 join_argv (const char *const *argv1, const char *const *argv2)
900 {
901   char **argvj;
902   char *argv;
903   unsigned int carg;
904   unsigned int cnt;
905
906   carg = 0;
907   argvj = NULL;
908   for (cnt = 0; NULL != argv1[cnt]; cnt++)
909   {
910     argv = GNUNET_strdup (argv1[cnt]);
911     GNUNET_array_append (argvj, carg, argv);
912   }
913   for (cnt = 0; NULL != argv2[cnt]; cnt++)
914   {
915     argv = GNUNET_strdup (argv2[cnt]);
916     GNUNET_array_append (argvj, carg, argv);
917   }
918   GNUNET_array_append (argvj, carg, NULL);
919   return argvj;
920 }
921
922
923 /**
924  * Frees the given NULL terminated arguments
925  *
926  * @param argv the NULL terminated list of arguments
927  */
928 static void
929 free_argv (char **argv)
930 {
931   unsigned int argp;
932
933   for (argp = 0; NULL != argv[argp]; argp++)
934     GNUNET_free (argv[argp]);
935   GNUNET_free (argv);
936 }
937
938
939 /**
940  * Generates arguments for opening a remote shell. Builds up the arguments
941  * from the environment variable GNUNET_TESTBED_RSH_CMD. The variable
942  * should not mention `-p' (port) option and destination address as these will
943  * be set locally in the function from its parameteres. If the environmental
944  * variable is not found then it defaults to `ssh -o BatchMode=yes -o
945  * NoHostAuthenticationForLocalhost=yes'
946  *
947  * @param port the destination port number
948  * @param dst the destination address
949  * @return NULL terminated list of arguments
950  */
951 static char **
952 gen_rsh_args (const char *port, const char *dst)
953 {
954   static const char *default_ssh_args[] = {
955     "ssh",
956     "-o",
957     "BatchMode=yes",
958     "-o",
959     "NoHostAuthenticationForLocalhost=yes",
960     NULL
961   };
962   char **ssh_args;
963   char *ssh_cmd;
964   char *ssh_cmd_cp;
965   char *arg;
966   unsigned int cnt;
967
968   ssh_args = NULL;
969   if (NULL != (ssh_cmd = getenv ("GNUNET_TESTBED_RSH_CMD")))
970   {
971     ssh_cmd = GNUNET_strdup (ssh_cmd);
972     ssh_cmd_cp = ssh_cmd;
973     for (cnt = 0; NULL != (arg = strtok (ssh_cmd, " ")); ssh_cmd = NULL)
974       GNUNET_array_append (ssh_args, cnt, GNUNET_strdup (arg));
975     GNUNET_free (ssh_cmd_cp);
976   }
977   else
978   {
979     ssh_args = copy_argv (default_ssh_args);
980     cnt = (sizeof (default_ssh_args)) / (sizeof (const char *));
981     GNUNET_array_grow (ssh_args, cnt, cnt - 1);
982   }
983   GNUNET_array_append (ssh_args, cnt, GNUNET_strdup ("-p"));
984   GNUNET_array_append (ssh_args, cnt, GNUNET_strdup (port));
985   GNUNET_array_append (ssh_args, cnt, GNUNET_strdup (dst));
986   GNUNET_array_append (ssh_args, cnt, NULL);
987   return ssh_args;
988 }
989
990
991 /**
992  * Generates the arguments needed for executing the given binary in a remote
993  * shell. Builds the arguments from the environmental variable
994  * GNUNET_TETSBED_RSH_CMD_SUFFIX. If the environmental variable is not found,
995  * only the given binary name will be present in the returned arguments
996  *
997  * @param append_args the arguments to append after generating the suffix
998  *          arguments. Can be NULL; if not must be NULL terminated 'char *' array
999  * @return NULL-terminated args
1000  */
1001 static char **
1002 gen_rsh_suffix_args (const char * const *append_args)
1003 {
1004   char **rshell_args;
1005   char *rshell_cmd;
1006   char *rshell_cmd_cp;
1007   char *arg;
1008   unsigned int cnt;
1009   unsigned int append_cnt;
1010
1011   rshell_args = NULL;
1012   cnt = 0;
1013   if (NULL != (rshell_cmd = getenv ("GNUNET_TESTBED_RSH_CMD_SUFFIX")))
1014   {
1015     rshell_cmd = GNUNET_strdup (rshell_cmd);
1016     rshell_cmd_cp = rshell_cmd;
1017     for (; NULL != (arg = strtok (rshell_cmd, " ")); rshell_cmd = NULL)
1018       GNUNET_array_append (rshell_args, cnt, GNUNET_strdup (arg));
1019     GNUNET_free (rshell_cmd_cp);
1020   }
1021   if (NULL != append_args)
1022   {
1023     for (append_cnt = 0; NULL != append_args[append_cnt]; append_cnt++)      
1024       GNUNET_array_append (rshell_args, cnt, GNUNET_strdup (append_args[append_cnt]));
1025   }
1026   GNUNET_array_append (rshell_args, cnt, NULL);
1027   return rshell_args;
1028 }
1029
1030
1031 /**
1032  * Functions with this signature are called whenever a
1033  * complete message is received by the tokenizer.
1034  *
1035  * Do not call GNUNET_SERVER_mst_destroy in callback
1036  *
1037  * @param cls closure
1038  * @param client identification of the client
1039  * @param message the actual message
1040  *
1041  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1042  */
1043 static int
1044 helper_mst (void *cls, void *client, const struct GNUNET_MessageHeader *message)
1045 {
1046   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1047   const struct GNUNET_TESTBED_HelperReply *msg;
1048   const char *hostname;
1049   char *config;
1050   uLongf config_size;
1051   uLongf xconfig_size;
1052
1053   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
1054   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) <
1055                  ntohs (msg->header.size));
1056   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY ==
1057                  ntohs (msg->header.type));
1058   config_size = (uLongf) ntohs (msg->config_size);
1059   xconfig_size =
1060       (uLongf) (ntohs (msg->header.size) -
1061                 sizeof (struct GNUNET_TESTBED_HelperReply));
1062   config = GNUNET_malloc (config_size);
1063   GNUNET_assert (Z_OK ==
1064                  uncompress ((Bytef *) config, &config_size,
1065                              (const Bytef *) &msg[1], xconfig_size));
1066   /* Replace the configuration template present in the host with the
1067      controller's running configuration */
1068   GNUNET_CONFIGURATION_destroy (cp->host->cfg);
1069   cp->host->cfg = GNUNET_CONFIGURATION_create ();
1070   GNUNET_assert (GNUNET_CONFIGURATION_deserialize
1071                  (cp->host->cfg, config, config_size, GNUNET_NO));
1072   GNUNET_free (config);
1073   if (NULL == (hostname = GNUNET_TESTBED_host_get_hostname (cp->host)))
1074     hostname = "localhost";
1075   /* Change the hostname so that we can connect to it */
1076   GNUNET_CONFIGURATION_set_value_string (cp->host->cfg, "testbed", "hostname",
1077                                          hostname);
1078   cp->host->locked = GNUNET_NO;
1079   cp->host->controller_started = GNUNET_YES;
1080   cp->cb (cp->cls, cp->host->cfg, GNUNET_OK);
1081   return GNUNET_OK;
1082 }
1083
1084
1085 /**
1086  * Continuation function from GNUNET_HELPER_send()
1087  *
1088  * @param cls closure
1089  * @param result GNUNET_OK on success,
1090  *               GNUNET_NO if helper process died
1091  *               GNUNET_SYSERR during GNUNET_HELPER_stop
1092  */
1093 static void
1094 clear_msg (void *cls, int result)
1095 {
1096   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1097
1098   GNUNET_assert (NULL != cp->shandle);
1099   cp->shandle = NULL;
1100   GNUNET_free (cp->msg);
1101 }
1102
1103
1104 /**
1105  * Callback that will be called when the helper process dies. This is not called
1106  * when the helper process is stoped using GNUNET_HELPER_stop()
1107  *
1108  * @param cls the closure from GNUNET_HELPER_start()
1109  */
1110 static void
1111 helper_exp_cb (void *cls)
1112 {
1113   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1114   GNUNET_TESTBED_ControllerStatusCallback cb;
1115   void *cb_cls;
1116
1117   cb = cp->cb;
1118   cb_cls = cp->cls;
1119   cp->helper = NULL;
1120   GNUNET_TESTBED_controller_stop (cp);
1121   if (NULL != cb)
1122     cb (cb_cls, NULL, GNUNET_SYSERR);
1123 }
1124
1125
1126 /**
1127  * Starts a controller process at the given host.  The given host's configration
1128  * is used as a Template configuration to use for the remote controller; the
1129  * remote controller will be started with a slightly modified configuration
1130  * (port numbers, unix domain sockets and service home values are changed as per
1131  * TESTING library on the remote host).  The modified configuration replaces the
1132  * host's existing configuration before signalling success through the
1133  * GNUNET_TESTBED_ControllerStatusCallback()
1134  *
1135  * @param trusted_ip the ip address of the controller which will be set as TRUSTED
1136  *          HOST(all connections form this ip are permitted by the testbed) when
1137  *          starting testbed controller at host. This can either be a single ip
1138  *          address or a network address in CIDR notation.
1139  * @param host the host where the controller has to be started.  CANNOT be NULL.
1140  * @param cb function called when the controller is successfully started or
1141  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
1142  *          called if cb is called with GNUNET_SYSERR as status. Will never be
1143  *          called in the same task as 'GNUNET_TESTBED_controller_start'
1144  *          (synchronous errors will be signalled by returning NULL). This
1145  *          parameter cannot be NULL.
1146  * @param cls closure for above callbacks
1147  * @return the controller process handle, NULL on errors
1148  */
1149 struct GNUNET_TESTBED_ControllerProc *
1150 GNUNET_TESTBED_controller_start (const char *trusted_ip,
1151                                  struct GNUNET_TESTBED_Host *host,
1152                                  GNUNET_TESTBED_ControllerStatusCallback cb,
1153                                  void *cls)
1154 {
1155   struct GNUNET_TESTBED_ControllerProc *cp;
1156   struct GNUNET_TESTBED_HelperInit *msg;
1157   const struct GNUNET_CONFIGURATION_Handle *cfg;
1158   const char *hostname;
1159   static char *const binary_argv[] = {
1160     HELPER_TESTBED_BINARY, NULL
1161   };
1162   
1163   GNUNET_assert (NULL != host);
1164   GNUNET_assert (NULL != (cfg = GNUNET_TESTBED_host_get_cfg_ (host)));
1165   hostname = NULL;
1166   API_VIOLATION (GNUNET_NO == host->locked,
1167                  "Host is already locked by a previous call to GNUNET_TESTBED_controller_start()");
1168   host->locked = GNUNET_YES;
1169   API_VIOLATION (GNUNET_NO == host->controller_started,
1170                  "Attempting to start a controller on a host which is already started a controller");
1171   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
1172   if (0 == GNUNET_TESTBED_host_get_id_ (host))
1173   {
1174     cp->helper =
1175         GNUNET_HELPER_start (GNUNET_YES, HELPER_TESTBED_BINARY, binary_argv,
1176                              &helper_mst, &helper_exp_cb, cp);
1177   }
1178   else
1179   {
1180     char *helper_binary_path_args[2];
1181     char **rsh_args;
1182     char **rsh_suffix_args;
1183     const char *username;
1184     char *port;
1185     char *dst;
1186
1187     username = GNUNET_TESTBED_host_get_username_ (host);
1188     hostname = GNUNET_TESTBED_host_get_hostname (host);
1189     GNUNET_asprintf (&port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
1190     if (NULL == username)
1191       GNUNET_asprintf (&dst, "%s", hostname);
1192     else
1193       GNUNET_asprintf (&dst, "%s@%s", username, hostname);
1194     LOG_DEBUG ("Starting SSH to destination %s\n", dst);
1195
1196     if (GNUNET_OK !=
1197         GNUNET_CONFIGURATION_get_value_string (cfg, "testbed",
1198                                                "HELPER_BINARY_PATH",
1199                                                &helper_binary_path_args[0]))
1200       helper_binary_path_args[0] =
1201           GNUNET_OS_get_libexec_binary_path (HELPER_TESTBED_BINARY);
1202     helper_binary_path_args[1] = NULL;
1203     rsh_args = gen_rsh_args (port, dst);
1204     rsh_suffix_args = gen_rsh_suffix_args ((const char **) helper_binary_path_args);
1205     cp->helper_argv =
1206         join_argv ((const char **) rsh_args, (const char **) rsh_suffix_args);
1207     free_argv (rsh_args);
1208     free_argv (rsh_suffix_args);
1209     GNUNET_free (port);
1210     GNUNET_free (dst);
1211     cp->helper =
1212         GNUNET_HELPER_start (GNUNET_NO, cp->helper_argv[0], cp->helper_argv, &helper_mst,
1213                              &helper_exp_cb, cp);
1214     GNUNET_free (helper_binary_path_args[0]);
1215   }
1216   if (NULL == cp->helper)
1217   {
1218     if (NULL != cp->helper_argv)
1219       free_argv (cp->helper_argv);
1220     GNUNET_free (cp);
1221     return NULL;
1222   }
1223   cp->host = host;
1224   cp->cb = cb;
1225   cp->cls = cls;
1226   msg = GNUNET_TESTBED_create_helper_init_msg_ (trusted_ip, hostname, cfg);
1227   cp->msg = &msg->header;
1228   cp->shandle =
1229       GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO, &clear_msg, cp);
1230   if (NULL == cp->shandle)
1231   {
1232     GNUNET_free (msg);
1233     GNUNET_TESTBED_controller_stop (cp);
1234     return NULL;
1235   }
1236   return cp;
1237 }
1238
1239
1240 /**
1241  * Sends termination signal to the controller's helper process
1242  *
1243  * @param cproc the handle to the controller's helper process
1244  */
1245 void
1246 GNUNET_TESTBED_controller_kill_ (struct GNUNET_TESTBED_ControllerProc *cproc)
1247 {
1248   if (NULL != cproc->shandle)
1249     GNUNET_HELPER_send_cancel (cproc->shandle);
1250   if (NULL != cproc->helper)
1251     GNUNET_HELPER_kill (cproc->helper, GNUNET_YES);
1252 }
1253
1254
1255 /**
1256  * Cleans-up the controller's helper process handle
1257  *
1258  * @param cproc the handle to the controller's helper process
1259  */
1260 void
1261 GNUNET_TESTBED_controller_destroy_ (struct GNUNET_TESTBED_ControllerProc *cproc)
1262 {
1263   if (NULL != cproc->helper)
1264   {
1265     GNUNET_break (GNUNET_OK == GNUNET_HELPER_wait (cproc->helper));
1266     GNUNET_HELPER_destroy (cproc->helper);
1267   }
1268   if (NULL != cproc->helper_argv)
1269     free_argv (cproc->helper_argv);
1270   cproc->host->controller_started = GNUNET_NO;
1271   cproc->host->locked = GNUNET_NO;
1272   GNUNET_free (cproc);
1273 }
1274
1275
1276 /**
1277  * Stop the controller process (also will terminate all peers and controllers
1278  * dependent on this controller).  This function blocks until the testbed has
1279  * been fully terminated (!). The controller status cb from
1280  * GNUNET_TESTBED_controller_start() will not be called.
1281  *
1282  * @param cproc the controller process handle
1283  */
1284 void
1285 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
1286 {
1287   GNUNET_TESTBED_controller_kill_ (cproc);
1288   GNUNET_TESTBED_controller_destroy_ (cproc);
1289 }
1290
1291
1292 /**
1293  * The handle for whether a host is habitable or not
1294  */
1295 struct GNUNET_TESTBED_HostHabitableCheckHandle
1296 {
1297   /**
1298    * The host to check
1299    */
1300   const struct GNUNET_TESTBED_Host *host;
1301
1302   /**
1303    * The callback to call once we have the status
1304    */
1305   GNUNET_TESTBED_HostHabitableCallback cb;
1306
1307   /**
1308    * The callback closure
1309    */
1310   void *cb_cls;
1311
1312   /**
1313    * The process handle for the SSH process
1314    */
1315   struct GNUNET_OS_Process *auxp;
1316
1317   /**
1318    * The arguments used to start the helper
1319    */
1320   char **helper_argv;
1321
1322   /**
1323    * Task id for the habitability check task
1324    */
1325   GNUNET_SCHEDULER_TaskIdentifier habitability_check_task;
1326
1327   /**
1328    * How long we wait before checking the process status. Should grow
1329    * exponentially
1330    */
1331   struct GNUNET_TIME_Relative wait_time;
1332
1333 };
1334
1335
1336 /**
1337  * Task for checking whether a host is habitable or not
1338  *
1339  * @param cls GNUNET_TESTBED_HostHabitableCheckHandle
1340  * @param tc the scheduler task context
1341  */
1342 static void
1343 habitability_check (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1344 {
1345   struct GNUNET_TESTBED_HostHabitableCheckHandle *h = cls;
1346   void *cb_cls;
1347   GNUNET_TESTBED_HostHabitableCallback cb;
1348   const struct GNUNET_TESTBED_Host *host;
1349   unsigned long code;
1350   enum GNUNET_OS_ProcessStatusType type;
1351   int ret;
1352
1353   h->habitability_check_task = GNUNET_SCHEDULER_NO_TASK;
1354   ret = GNUNET_OS_process_status (h->auxp, &type, &code);
1355   if (GNUNET_SYSERR == ret)
1356   {
1357     GNUNET_break (0);
1358     ret = GNUNET_NO;
1359     goto call_cb;
1360   }
1361   if (GNUNET_NO == ret)
1362   {
1363     h->wait_time = GNUNET_TIME_STD_BACKOFF (h->wait_time);
1364     h->habitability_check_task =
1365         GNUNET_SCHEDULER_add_delayed (h->wait_time, &habitability_check, h);
1366     return;
1367   }
1368   GNUNET_OS_process_destroy (h->auxp);
1369   h->auxp = NULL;
1370   ret = (0 != code) ? GNUNET_NO : GNUNET_YES;
1371
1372 call_cb:
1373   if (NULL != h->auxp)
1374     GNUNET_OS_process_destroy (h->auxp);
1375   cb = h->cb;
1376   cb_cls = h->cb_cls;
1377   host = h->host;
1378   free_argv (h->helper_argv);
1379   GNUNET_free (h);
1380   if (NULL != cb)
1381     cb (cb_cls, host, ret);
1382 }
1383
1384
1385 /**
1386  * Checks whether a host can be used to start testbed service
1387  *
1388  * @param host the host to check
1389  * @param config the configuration handle to lookup the path of the testbed
1390  *          helper
1391  * @param cb the callback to call to inform about habitability of the given host
1392  * @param cb_cls the closure for the callback
1393  * @return NULL upon any error or a handle which can be passed to
1394  *           GNUNET_TESTBED_is_host_habitable_cancel()
1395  */
1396 struct GNUNET_TESTBED_HostHabitableCheckHandle *
1397 GNUNET_TESTBED_is_host_habitable (const struct GNUNET_TESTBED_Host *host,
1398                                   const struct GNUNET_CONFIGURATION_Handle
1399                                   *config,
1400                                   GNUNET_TESTBED_HostHabitableCallback cb,
1401                                   void *cb_cls)
1402 {
1403   struct GNUNET_TESTBED_HostHabitableCheckHandle *h;
1404   char **rsh_args;
1405   char **rsh_suffix_args;
1406   char *stat_args[3];
1407   const char *hostname;
1408   char *port;
1409   char *dst;
1410
1411   h = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle));
1412   h->cb = cb;
1413   h->cb_cls = cb_cls;
1414   h->host = host;
1415   hostname = (NULL == host->hostname) ? "127.0.0.1" : host->hostname;
1416   if (NULL == host->username)
1417     dst = GNUNET_strdup (hostname);
1418   else
1419     GNUNET_asprintf (&dst, "%s@%s", host->username, hostname);
1420   if (GNUNET_OK !=
1421       GNUNET_CONFIGURATION_get_value_string (config, "testbed",
1422                                              "HELPER_BINARY_PATH",
1423                                              &stat_args[1]))
1424     stat_args[1] =
1425         GNUNET_OS_get_libexec_binary_path (HELPER_TESTBED_BINARY);  
1426   GNUNET_asprintf (&port, "%u", host->port);
1427   rsh_args = gen_rsh_args (port, dst);
1428   GNUNET_free (port);
1429   GNUNET_free (dst);
1430   port = NULL;
1431   dst = NULL;
1432   stat_args[0] = "stat";
1433   stat_args[2] = NULL;
1434   rsh_suffix_args = gen_rsh_suffix_args ((const char **) stat_args);
1435   GNUNET_free (stat_args[1]);
1436   h->helper_argv = join_argv ((const char **) rsh_args,
1437                               (const char **) rsh_suffix_args);
1438   free_argv (rsh_suffix_args);
1439   free_argv (rsh_args);
1440   h->auxp =
1441       GNUNET_OS_start_process_vap (GNUNET_NO, GNUNET_OS_INHERIT_STD_ERR, NULL,
1442                                    NULL, h->helper_argv[0], h->helper_argv);
1443   if (NULL == h->auxp)
1444   {
1445     GNUNET_break (0);           /* Cannot exec SSH? */
1446     GNUNET_free (h);
1447     return NULL;
1448   }
1449   h->wait_time = GNUNET_TIME_STD_BACKOFF (h->wait_time);
1450   h->habitability_check_task =
1451       GNUNET_SCHEDULER_add_delayed (h->wait_time, &habitability_check, h);
1452   return h;
1453 }
1454
1455
1456 /**
1457  * Function to cancel a request started using GNUNET_TESTBED_is_host_habitable()
1458  *
1459  * @param handle the habitability check handle
1460  */
1461 void
1462 GNUNET_TESTBED_is_host_habitable_cancel (struct
1463                                          GNUNET_TESTBED_HostHabitableCheckHandle
1464                                          *handle)
1465 {
1466   GNUNET_SCHEDULER_cancel (handle->habitability_check_task);
1467   (void) GNUNET_OS_process_kill (handle->auxp, SIGTERM);
1468   (void) GNUNET_OS_process_wait (handle->auxp);
1469   GNUNET_OS_process_destroy (handle->auxp);
1470   free_argv (handle->helper_argv);
1471   GNUNET_free (handle);
1472 }
1473
1474
1475 /**
1476  * handle for host registration
1477  */
1478 struct GNUNET_TESTBED_HostRegistrationHandle
1479 {
1480   /**
1481    * The host being registered
1482    */
1483   struct GNUNET_TESTBED_Host *host;
1484
1485   /**
1486    * The controller at which this host is being registered
1487    */
1488   struct GNUNET_TESTBED_Controller *c;
1489
1490   /**
1491    * The Registartion completion callback
1492    */
1493   GNUNET_TESTBED_HostRegistrationCompletion cc;
1494
1495   /**
1496    * The closure for above callback
1497    */
1498   void *cc_cls;
1499 };
1500
1501
1502 /**
1503  * Register a host with the controller
1504  *
1505  * @param controller the controller handle
1506  * @param host the host to register
1507  * @param cc the completion callback to call to inform the status of
1508  *          registration. After calling this callback the registration handle
1509  *          will be invalid. Cannot be NULL.
1510  * @param cc_cls the closure for the cc
1511  * @return handle to the host registration which can be used to cancel the
1512  *           registration
1513  */
1514 struct GNUNET_TESTBED_HostRegistrationHandle *
1515 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1516                               struct GNUNET_TESTBED_Host *host,
1517                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1518                               void *cc_cls)
1519 {
1520   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1521   struct GNUNET_TESTBED_AddHostMessage *msg;
1522   const char *username;
1523   const char *hostname;
1524   char *config;
1525   char *cconfig;
1526   void *ptr;
1527   size_t cc_size;
1528   size_t config_size;
1529   uint16_t msg_size;
1530   uint16_t username_length;
1531   uint16_t hostname_length;
1532
1533   if (NULL != controller->rh)
1534     return NULL;
1535   hostname = GNUNET_TESTBED_host_get_hostname (host);
1536   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1537   {
1538     LOG (GNUNET_ERROR_TYPE_WARNING, "Host hostname: %s already registered\n",
1539          (NULL == hostname) ? "localhost" : hostname);
1540     return NULL;
1541   }
1542   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1543   rh->host = host;
1544   rh->c = controller;
1545   GNUNET_assert (NULL != cc);
1546   rh->cc = cc;
1547   rh->cc_cls = cc_cls;
1548   controller->rh = rh;
1549   username = GNUNET_TESTBED_host_get_username_ (host);
1550   username_length = 0;
1551   if (NULL != username)
1552     username_length = strlen (username);
1553   GNUNET_assert (NULL != hostname); /* Hostname must be present */
1554   hostname_length = strlen (hostname);
1555   GNUNET_assert (NULL != host->cfg);
1556   config = GNUNET_CONFIGURATION_serialize (host->cfg, &config_size);
1557   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1558   GNUNET_free (config);
1559   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1560   msg_size += username_length;
1561   msg_size += hostname_length;
1562   msg_size += cc_size;
1563   msg = GNUNET_malloc (msg_size);
1564   msg->header.size = htons (msg_size);
1565   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST);
1566   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1567   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1568   ptr = &msg[1];
1569   if (NULL != username)
1570   {
1571     msg->username_length = htons (username_length);
1572     ptr = memcpy (ptr, username, username_length);
1573     ptr += username_length;
1574   }
1575   msg->hostname_length = htons (hostname_length);
1576   ptr = memcpy (ptr, hostname, hostname_length);
1577   ptr += hostname_length;
1578   msg->config_size = htons (config_size);
1579   ptr = memcpy (ptr, cconfig, cc_size);
1580   ptr += cc_size;
1581   GNUNET_assert ((ptr - (void *) msg) == msg_size);
1582   GNUNET_free (cconfig);
1583   GNUNET_TESTBED_queue_message_ (controller,
1584                                  (struct GNUNET_MessageHeader *) msg);
1585   return rh;
1586 }
1587
1588
1589 /**
1590  * Cancel the pending registration. Note that if the registration message is
1591  * already sent to the service the cancellation has only the effect that the
1592  * registration completion callback for the registration is never called.
1593  *
1594  * @param handle the registration handle to cancel
1595  */
1596 void
1597 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1598                                     *handle)
1599 {
1600   if (handle != handle->c->rh)
1601   {
1602     GNUNET_break (0);
1603     return;
1604   }
1605   handle->c->rh = NULL;
1606   GNUNET_free (handle);
1607 }
1608
1609
1610 /**
1611  * Queues the given operation in the queue for parallel overlay connects of the
1612  * given host
1613  *
1614  * @param h the host handle
1615  * @param op the operation to queue in the given host's parally overlay connect
1616  *          queue 
1617  */
1618 void
1619 GNUNET_TESTBED_host_queue_oc_ (struct GNUNET_TESTBED_Host *h, 
1620                                struct GNUNET_TESTBED_Operation *op)
1621 {  
1622   GNUNET_TESTBED_operation_queue_insert_
1623       (h->opq_parallel_overlay_connect_operations, op);
1624 }
1625
1626
1627 /**
1628  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
1629  * controller (testbed service)
1630  *
1631  * @param c the controller handler
1632  * @param msg message received
1633  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
1634  *           not
1635  */
1636 int
1637 GNUNET_TESTBED_host_handle_addhostconfirm_ (struct GNUNET_TESTBED_Controller *c,
1638                                             const struct
1639                                             GNUNET_TESTBED_HostConfirmedMessage
1640                                             *msg)
1641 {
1642   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1643   char *emsg;
1644   uint16_t msg_size;
1645
1646   rh = c->rh;
1647   if (NULL == rh)
1648   {
1649     return GNUNET_OK;
1650   }
1651   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
1652   {
1653     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
1654                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
1655     return GNUNET_OK;
1656   }
1657   c->rh = NULL;
1658   msg_size = ntohs (msg->header.size);
1659   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
1660   {
1661     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
1662     GNUNET_TESTBED_mark_host_registered_at_ (rh->host, c);
1663     rh->cc (rh->cc_cls, NULL);
1664     GNUNET_free (rh);
1665     return GNUNET_OK;
1666   }
1667   /* We have an error message */
1668   emsg = (char *) &msg[1];
1669   if ('\0' !=
1670       emsg[msg_size - sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
1671   {
1672     GNUNET_break (0);
1673     GNUNET_free (rh);
1674     return GNUNET_NO;
1675   }
1676   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
1677        ntohl (msg->host_id), emsg);
1678   rh->cc (rh->cc_cls, emsg);
1679   GNUNET_free (rh);
1680   return GNUNET_OK;
1681 }
1682
1683
1684 /**
1685  * Resolves the hostname of the host to an ip address
1686  *
1687  * @param host the host whose hostname is to be resolved
1688  */
1689 void
1690 GNUNET_TESTBED_host_resolve_ (struct GNUNET_TESTBED_Host *host)
1691 {
1692   char *hostname;
1693
1694   hostname = (char *) host->hostname;
1695   host->hostname = simple_resolve (hostname);
1696   if (NULL == host->hostname)
1697   {
1698     GNUNET_break (0);
1699     host->hostname = hostname;
1700     return;
1701   }
1702   GNUNET_free (hostname);
1703   host->hostname = GNUNET_strdup (host->hostname);
1704 }
1705
1706 /* end of testbed_api_hosts.c */