- remove dead assignments
[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 #include "testbed_api_sd.h"
39
40 #include <zlib.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  * A slot to record time taken by an overlay connect operation
101  */
102 struct TimeSlot
103 {
104   /**
105    * A key to identify this timeslot
106    */
107   void *key;
108
109   /**
110    * Time
111    */
112   struct GNUNET_TIME_Relative time;
113
114   /**
115    * Number of timing values accumulated
116    */
117   unsigned int nvals;
118 };
119
120
121 /**
122  * Opaque handle to a host running experiments managed by the testing framework.
123  * The master process must be able to SSH to this host without password (via
124  * ssh-agent).
125  */
126 struct GNUNET_TESTBED_Host
127 {
128
129   /**
130    * The hostname of the host; NULL for localhost
131    */
132   const char *hostname;
133
134   /**
135    * The username to be used for SSH login
136    */
137   const char *username;
138
139   /**
140    * the configuration to use as a template while starting a controller on this
141    * host.  Operation queue size specific to a host are also read from this
142    * configuration handle.  After starting the controller, it points to the actual
143    * configuration with which the controller is running
144    */
145   struct GNUNET_CONFIGURATION_Handle *cfg;
146
147   /**
148    * The head for the list of controllers where this host is registered
149    */
150   struct RegisteredController *rc_head;
151
152   /**
153    * The tail for the list of controllers where this host is registered
154    */
155   struct RegisteredController *rc_tail;
156
157   /**
158    * Operation queue for simultaneous overlay connect operations target at this
159    * host
160    */
161   struct OperationQueue *opq_parallel_overlay_connect_operations;
162
163   /**
164    * An array of timing slots; size should be equal to the current number of parallel
165    * overlay connects
166    */
167   struct TimeSlot *tslots;
168
169   /**
170    * Handle for SD calculations amount parallel overlay connect operation finish
171    * times
172    */
173   struct SDHandle *poc_sd;  
174
175   /**
176    * The number of parallel overlay connects we do currently
177    */
178   unsigned int num_parallel_connects;
179
180   /**
181    * Counter to indicate when all the available time slots are filled
182    */
183   unsigned int tslots_filled;
184
185   /**
186    * Is a controller started on this host? FIXME: Is this needed?
187    */
188   int controller_started;
189
190   /**
191    * Is this host locked by GNUNET_TESTBED_controller_start()?
192    */
193   int locked;
194
195   /**
196    * Global ID we use to refer to a host on the network
197    */
198   uint32_t id;
199
200   /**
201    * The port which is to be used for SSH
202    */
203   uint16_t port;
204
205 };
206
207
208 /**
209  * Array of available hosts
210  */
211 static struct GNUNET_TESTBED_Host **host_list;
212
213 /**
214  * The size of the available hosts list
215  */
216 static unsigned int host_list_size;
217
218
219 /**
220  * Lookup a host by ID.
221  *
222  * @param id global host ID assigned to the host; 0 is
223  *        reserved to always mean 'localhost'
224  * @return handle to the host, NULL if host not found
225  */
226 struct GNUNET_TESTBED_Host *
227 GNUNET_TESTBED_host_lookup_by_id_ (uint32_t id)
228 {
229   if (host_list_size <= id)
230     return NULL;
231   return host_list[id];
232 }
233
234
235 /**
236  * Create a host by ID; given this host handle, we could not
237  * run peers at the host, but we can talk about the host
238  * internally.
239  *
240  * @param id global host ID assigned to the host; 0 is
241  *        reserved to always mean 'localhost'
242  * @param cfg the configuration to use as a template while starting a controller
243  *          on this host.  Operation queue sizes specific to a host are also
244  *          read from this configuration handle
245  * @return handle to the host, NULL on error
246  */
247 struct GNUNET_TESTBED_Host *
248 GNUNET_TESTBED_host_create_by_id_ (uint32_t id,
249                                    const struct GNUNET_CONFIGURATION_Handle
250                                    *cfg)
251 {
252   return GNUNET_TESTBED_host_create_with_id (id, NULL, NULL, cfg, 0);
253 }
254
255
256 /**
257  * Obtain the host's unique global ID.
258  *
259  * @param host handle to the host, NULL means 'localhost'
260  * @return id global host ID assigned to the host (0 is
261  *         'localhost', but then obviously not globally unique)
262  */
263 uint32_t
264 GNUNET_TESTBED_host_get_id_ (const struct GNUNET_TESTBED_Host * host)
265 {
266   return host->id;
267 }
268
269
270 /**
271  * Obtain the host's hostname.
272  *
273  * @param host handle to the host, NULL means 'localhost'
274  * @return hostname of the host
275  */
276 const char *
277 GNUNET_TESTBED_host_get_hostname (const struct GNUNET_TESTBED_Host *host)
278 {
279   return host->hostname;
280 }
281
282
283 /**
284  * Obtain the host's username
285  *
286  * @param host handle to the host, NULL means 'localhost'
287  * @return username to login to the host
288  */
289 const char *
290 GNUNET_TESTBED_host_get_username_ (const struct GNUNET_TESTBED_Host *host)
291 {
292   return host->username;
293 }
294
295
296 /**
297  * Obtain the host's ssh port
298  *
299  * @param host handle to the host, NULL means 'localhost'
300  * @return username to login to the host
301  */
302 uint16_t
303 GNUNET_TESTBED_host_get_ssh_port_ (const struct GNUNET_TESTBED_Host * host)
304 {
305   return host->port;
306 }
307
308
309 /**
310  * Check whether a controller is already started on the given host
311  *
312  * @param host the handle to the host
313  * @return GNUNET_YES if the controller is already started; GNUNET_NO if not
314  */
315 int
316 GNUNET_TESTBED_host_controller_started (const struct GNUNET_TESTBED_Host *host)
317 {
318   return host->controller_started;
319 }
320
321
322 /**
323  * Obtain the host's configuration template
324  *
325  * @param host handle to the host
326  * @return the host's configuration template
327  */
328 const struct GNUNET_CONFIGURATION_Handle *
329 GNUNET_TESTBED_host_get_cfg_ (const struct GNUNET_TESTBED_Host *host)
330 {
331   return host->cfg;
332 }
333
334
335 /**
336  * Function to replace host's configuration
337  *
338  * @param host the host handle
339  * @param new_cfg the new configuration to replace the old one
340  */
341 void
342 GNUNET_TESTBED_host_replace_cfg_ (struct GNUNET_TESTBED_Host *host,
343                                   const struct GNUNET_CONFIGURATION_Handle *new_cfg)
344 {
345   GNUNET_CONFIGURATION_destroy (host->cfg);
346   host->cfg = GNUNET_CONFIGURATION_dup (new_cfg);
347 }
348
349
350 /**
351  * Create a host to run peers and controllers on.
352  *
353  * @param id global host ID assigned to the host; 0 is
354  *        reserved to always mean 'localhost'
355  * @param hostname name of the host, use "NULL" for localhost
356  * @param username username to use for the login; may be NULL
357  * @param cfg the configuration to use as a template while starting a controller
358  *          on this host.  Operation queue sizes specific to a host are also
359  *          read from this configuration handle
360  * @param port port number to use for ssh; use 0 to let ssh decide
361  * @return handle to the host, NULL on error
362  */
363 struct GNUNET_TESTBED_Host *
364 GNUNET_TESTBED_host_create_with_id (uint32_t id, const char *hostname,
365                                     const char *username, 
366                                     const struct GNUNET_CONFIGURATION_Handle
367                                     *cfg,
368                                     uint16_t port)
369 {
370   struct GNUNET_TESTBED_Host *host;
371   unsigned int new_size;
372
373   if ((id < host_list_size) && (NULL != host_list[id]))
374   {
375     LOG (GNUNET_ERROR_TYPE_WARNING, "Host with id: %u already created\n", id);
376     return NULL;
377   }
378   host = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host));
379   host->hostname = (NULL != hostname) ? GNUNET_strdup (hostname) : NULL;
380   host->username = (NULL != username) ? GNUNET_strdup (username) : NULL;
381   host->id = id;
382   host->port = (0 == port) ? 22 : port;
383   host->cfg = GNUNET_CONFIGURATION_dup (cfg);
384   host->opq_parallel_overlay_connect_operations =
385       GNUNET_TESTBED_operation_queue_create_ (0);
386   GNUNET_TESTBED_set_num_parallel_overlay_connects_ (host, 1);
387   host->poc_sd = GNUNET_TESTBED_SD_init_ (10);
388   new_size = host_list_size;
389   while (id >= new_size)
390     new_size += HOST_LIST_GROW_STEP;
391   if (new_size != host_list_size)
392     GNUNET_array_grow (host_list, host_list_size, new_size);
393   GNUNET_assert (id < host_list_size);
394   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding host with id: %u\n", host->id);
395   host_list[id] = host;
396   return host;
397 }
398
399
400 /**
401  * Create a host to run peers and controllers on.
402  *
403  * @param hostname name of the host, use "NULL" for localhost
404  * @param username username to use for the login; may be NULL
405  * @param cfg the configuration to use as a template while starting a controller
406  *          on this host.  Operation queue sizes specific to a host are also
407  *          read from this configuration handle
408  * @param port port number to use for ssh; use 0 to let ssh decide
409  * @return handle to the host, NULL on error
410  */
411 struct GNUNET_TESTBED_Host *
412 GNUNET_TESTBED_host_create (const char *hostname, const char *username,
413                             const struct GNUNET_CONFIGURATION_Handle *cfg,
414                             uint16_t port)
415 {
416   static uint32_t uid_generator;
417
418   if (NULL == hostname)
419     return GNUNET_TESTBED_host_create_with_id (0, hostname, username, 
420                                                cfg, port);
421   return GNUNET_TESTBED_host_create_with_id (++uid_generator, hostname,
422                                              username, cfg, port);
423 }
424
425
426 /**
427  * Load a set of hosts from a configuration file.
428  *
429  * @param filename file with the host specification
430  * @param cfg the configuration to use as a template while starting a controller
431  *          on any of the loaded hosts.  Operation queue sizes specific to a host
432  *          are also read from this configuration handle
433  * @param hosts set to the hosts found in the file; caller must free this if
434  *          number of hosts returned is greater than 0
435  * @return number of hosts returned in 'hosts', 0 on error
436  */
437 unsigned int
438 GNUNET_TESTBED_hosts_load_from_file (const char *filename,
439                                      const struct GNUNET_CONFIGURATION_Handle
440                                      *cfg,
441                                      struct GNUNET_TESTBED_Host ***hosts)
442 {
443   //struct GNUNET_TESTBED_Host **host_array;
444   struct GNUNET_TESTBED_Host *starting_host;
445   char *data;
446   char *buf;
447   char username[256];
448   char hostname[256];
449   uint64_t fs;
450   short int port;
451   int ret;
452   unsigned int offset;
453   unsigned int count;
454
455
456   GNUNET_assert (NULL != filename);
457   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
458   {
459     LOG (GNUNET_ERROR_TYPE_WARNING, _("Hosts file %s not found\n"), filename);
460     return 0;
461   }
462   if (GNUNET_OK !=
463       GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
464     fs = 0;
465   if (0 == fs)
466   {
467     LOG (GNUNET_ERROR_TYPE_WARNING, _("Hosts file %s has no data\n"), filename);
468     return 0;
469   }
470   data = GNUNET_malloc (fs);
471   if (fs != GNUNET_DISK_fn_read (filename, data, fs))
472   {
473     GNUNET_free (data);
474     LOG (GNUNET_ERROR_TYPE_WARNING, _("Hosts file %s cannot be read\n"),
475          filename);
476     return 0;
477   }
478   buf = data;
479   offset = 0;
480   starting_host = NULL;
481   count = 0;
482   while (offset < (fs - 1))
483   {
484     offset++;
485     if (((data[offset] == '\n')) && (buf != &data[offset]))
486     {
487       data[offset] = '\0';
488       ret =
489           SSCANF (buf, "%255[a-zA-Z0-9_]@%255[.a-zA-Z0-9-]:%5hd", username,
490                   hostname, &port);
491       if (3 == ret)
492       {
493         LOG (GNUNET_ERROR_TYPE_DEBUG,
494              "Successfully read host %s, port %d and user %s from file\n",
495              hostname, port, username);
496         /* We store hosts in a static list; hence we only require the starting
497          * host pointer in that list to access the newly created list of hosts */
498         if (NULL == starting_host)
499           starting_host = GNUNET_TESTBED_host_create (hostname, username, cfg,
500                                                       port);
501         else
502           (void) GNUNET_TESTBED_host_create (hostname, username, cfg, port);
503         count++;
504       }
505       else
506         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
507                     "Error reading line `%s' in hostfile\n", buf);
508       buf = &data[offset + 1];
509     }
510     else if ((data[offset] == '\n') || (data[offset] == '\0'))
511       buf = &data[offset + 1];
512   }
513   GNUNET_free (data);
514   if (NULL == starting_host)
515     return 0;
516   *hosts = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * count);
517   memcpy (*hosts, &host_list[GNUNET_TESTBED_host_get_id_ (starting_host)],
518           sizeof (struct GNUNET_TESTBED_Host *) * count);
519   return count;
520 }
521
522
523 /**
524  * Resolves a hostname using getaddrinfo
525  *
526  * @param host the hostname
527  * @return the string representing the IPv4 address of the given host; NULL upon error
528  */
529 const char *
530 simple_resolve (const char *host)
531 {
532   struct addrinfo *res;
533   const struct sockaddr_in *in_addr; 
534   char *hostip;
535   struct addrinfo hint;
536   unsigned int rc;
537
538   hint.ai_family = AF_INET;     /* IPv4 */
539   hint.ai_socktype = 0;
540   hint.ai_protocol = 0;
541   hint.ai_addrlen = 0;
542   hint.ai_addr = NULL;
543   hint.ai_canonname = NULL;
544   hint.ai_next = NULL;
545   hint.ai_flags = AI_NUMERICSERV;
546   res = NULL;
547   LOG_DEBUG ("Resolving [%s]\n", host);
548   if (0 != (rc = getaddrinfo (host, "22", &hint, &res)))
549   {
550     LOG_GAI (GNUNET_ERROR_TYPE_ERROR, "getaddrinfo", rc);
551     return NULL;
552   }
553   GNUNET_assert (NULL != res);
554   GNUNET_assert (NULL != res->ai_addr);
555   GNUNET_assert (sizeof (struct sockaddr_in) == res->ai_addrlen);
556   in_addr = (const struct sockaddr_in *) res->ai_addr;
557   hostip = inet_ntoa (in_addr->sin_addr);
558   GNUNET_assert (NULL != hostip);
559   freeaddrinfo (res);
560   LOG_DEBUG ("Resolved [%s] to [%s]\n", host, hostip);
561   return hostip;
562 }
563
564 #if ENABLE_LL
565 static int
566 cmpstringp(const void *p1, const void *p2)
567 {
568   /* The actual arguments to this function are "pointers to
569      pointers to char", but strcmp(3) arguments are "pointers
570      to char", hence the following cast plus dereference */
571   
572   return strcmp(* (char * const *) p1, * (char * const *) p2);
573 }
574 #endif
575
576 /**
577  * Loads the set of host allocated by the LoadLeveler Job Scheduler.  This
578  * function is only available when compiled with support for LoadLeveler and is
579  * used for running on the SuperMUC
580  *
581  * @param cfg the configuration to use as a template while starting a controller
582  *          on any of the loaded hosts.  Operation queue sizes specific to a host
583  *          are also read from this configuration handle
584  * @param hosts set to the hosts found in the file; caller must free this if
585  *          number of hosts returned is greater than 0
586  * @return number of hosts returned in 'hosts', 0 on error
587  */
588 unsigned int
589 GNUNET_TESTBED_hosts_load_from_loadleveler (const struct
590                                             GNUNET_CONFIGURATION_Handle *cfg,
591                                             struct GNUNET_TESTBED_Host ***hosts)
592 {
593 #if !ENABLE_LL
594   LOG (GNUNET_ERROR_TYPE_ERROR, 
595        _("The function %s is only available when compiled with (--with-ll)\n"),
596        __func__);
597   GNUNET_assert (0);
598 #else
599   const char *hostfile;
600   char *buf;
601   char *hostname;
602   char **hostnames;
603   struct GNUNET_TESTBED_Host **host_list;
604   ssize_t rsize;
605   uint64_t size;
606   uint64_t offset;
607   enum {
608     SCAN,
609     SKIP,
610     TRIM,
611     READHOST
612   } pstep;
613   unsigned int host;
614   unsigned int nhosts;
615   
616   if (NULL == (hostfile = getenv ("MP_SAVEHOSTFILE")))
617   {
618     GNUNET_break (0);
619     return 0;
620   }
621   if (GNUNET_SYSERR == GNUNET_DISK_file_size (hostfile, &size, GNUNET_YES,
622                                               GNUNET_YES))
623   {
624     GNUNET_break (0);
625     return 0;
626   }
627   if (0 == size)
628   {
629     GNUNET_break (0);
630     return 0;
631   }
632   buf = GNUNET_malloc (size + 1);
633   rsize = GNUNET_DISK_fn_read (hostfile, buf, (size_t) size);
634   if ( (GNUNET_SYSERR == rsize) || ((ssize_t) size != rsize) )
635   {
636     GNUNET_free (buf);
637     GNUNET_break (0);
638     return 0;
639   }
640   size++;
641   offset = 0;
642   pstep = SCAN;
643   hostname = NULL;
644   hostnames = NULL;
645   nhosts = 0;
646   while (offset < size)
647   {
648     switch (pstep)
649     {
650     case SCAN:
651       if ('!' == buf[offset])
652         pstep = SKIP;
653       else 
654         pstep = TRIM;
655       break;
656     case SKIP:
657       if ('\n' == buf[offset])
658         pstep = SCAN;
659       break;
660     case TRIM:
661       if ('!' == buf[offset])
662       {
663         pstep = SKIP;
664         break;
665       }
666       if ( (' ' == buf[offset]) 
667            || ('\t' == buf[offset])
668            || ('\r' == buf[offset]) )
669         pstep = TRIM;
670       else
671       {
672         pstep = READHOST;
673         hostname = &buf[offset];        
674       }
675       break;
676     case READHOST:
677       if (isspace (buf[offset]))
678       {
679         buf[offset] = '\0';
680         for (host = 0; host < nhosts; host++)
681           if (0 == strcmp (hostnames[host], hostname))
682             break;
683         if (host == nhosts)
684         {
685           LOG_DEBUG ("Adding host [%s]\n", hostname);
686           hostname = GNUNET_strdup (hostname);
687           GNUNET_array_append (hostnames, nhosts, hostname);
688         }
689         else
690           LOG_DEBUG ("Not adding host [%s] as it is already included\n", hostname);
691         hostname = NULL;
692         pstep = SCAN;
693       }
694       break;
695     }
696     offset++;
697   }
698   GNUNET_free_non_null (buf);
699   if (NULL == hostnames)
700     return 0;
701   if (NULL == hosts)
702     goto cleanup;
703   qsort (hostnames, nhosts, sizeof (hostnames[0]), cmpstringp);
704   host_list = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * nhosts);
705   for (host = 0; host < nhosts; host++)
706     host_list[host] = GNUNET_TESTBED_host_create (hostnames[host], NULL, cfg, 0);
707   *hosts = host_list;
708
709  cleanup:
710   for (host = 0; host < nhosts; host++)
711     GNUNET_free (hostnames[host]);
712   GNUNET_free(hostnames);
713   return nhosts;
714 #endif
715 }
716
717
718 /**
719  * Destroy a host handle.  Must only be called once everything
720  * running on that host has been stopped.
721  *
722  * @param host handle to destroy
723  */
724 void
725 GNUNET_TESTBED_host_destroy (struct GNUNET_TESTBED_Host *host)
726 {
727   struct RegisteredController *rc;
728   uint32_t id;
729
730   GNUNET_assert (host->id < host_list_size);
731   GNUNET_assert (host_list[host->id] == host);
732   host_list[host->id] = NULL;
733   /* clear registered controllers list */
734   for (rc = host->rc_head; NULL != rc; rc = host->rc_head)
735   {
736     GNUNET_CONTAINER_DLL_remove (host->rc_head, host->rc_tail, rc);
737     GNUNET_free (rc);
738   }
739   GNUNET_free_non_null ((char *) host->username);
740   GNUNET_free_non_null ((char *) host->hostname);
741   GNUNET_TESTBED_operation_queue_destroy_
742       (host->opq_parallel_overlay_connect_operations);
743   GNUNET_TESTBED_SD_destroy_ (host->poc_sd);
744   GNUNET_free_non_null (host->tslots);
745   GNUNET_CONFIGURATION_destroy (host->cfg);
746   GNUNET_free (host);
747   while (host_list_size >= HOST_LIST_GROW_STEP)
748   {
749     for (id = host_list_size - 1; id > host_list_size - HOST_LIST_GROW_STEP;
750          id--)
751       if (NULL != host_list[id])
752         break;
753     if (id != host_list_size - HOST_LIST_GROW_STEP)
754       break;
755     if (NULL != host_list[id])
756       break;
757     host_list_size -= HOST_LIST_GROW_STEP;
758   }
759   host_list =
760       GNUNET_realloc (host_list,
761                       sizeof (struct GNUNET_TESTBED_Host *) * host_list_size);
762 }
763
764
765 /**
766  * Marks a host as registered with a controller
767  *
768  * @param host the host to mark
769  * @param controller the controller at which this host is registered
770  */
771 void
772 GNUNET_TESTBED_mark_host_registered_at_ (struct GNUNET_TESTBED_Host *host,
773                                          const struct GNUNET_TESTBED_Controller
774                                          *const controller)
775 {
776   struct RegisteredController *rc;
777
778   for (rc = host->rc_head; NULL != rc; rc = rc->next)
779   {
780     if (controller == rc->controller)   /* already registered at controller */
781     {
782       GNUNET_break (0);
783       return;
784     }
785   }
786   rc = GNUNET_malloc (sizeof (struct RegisteredController));
787   rc->controller = controller;
788   GNUNET_CONTAINER_DLL_insert_tail (host->rc_head, host->rc_tail, rc);
789 }
790
791
792 /**
793  * Unmarks a host registered at a controller
794  *
795  * @param host the host to unmark
796  * @param controller the controller at which this host has to be unmarked
797  */
798 void
799 GNUNET_TESTBED_deregister_host_at_ (struct GNUNET_TESTBED_Host *host,
800                                     const struct GNUNET_TESTBED_Controller
801                                     *const controller)
802 {
803   struct RegisteredController *rc;
804
805   for (rc = host->rc_head; NULL != rc; rc=rc->next)
806     if (controller == rc->controller)
807       break;
808   if (NULL == rc)
809   {
810     GNUNET_break (0);
811     return;
812   }
813   GNUNET_CONTAINER_DLL_remove (host->rc_head, host->rc_tail, rc);
814   GNUNET_free (rc);
815 }
816
817
818 /**
819  * Checks whether a host has been registered
820  *
821  * @param host the host to check
822  * @param controller the controller at which host's registration is checked
823  * @return GNUNET_YES if registered; GNUNET_NO if not
824  */
825 int
826 GNUNET_TESTBED_is_host_registered_ (const struct GNUNET_TESTBED_Host *host,
827                                     const struct GNUNET_TESTBED_Controller
828                                     *const controller)
829 {
830   struct RegisteredController *rc;
831
832   for (rc = host->rc_head; NULL != rc; rc = rc->next)
833   {
834     if (controller == rc->controller)   /* already registered at controller */
835     {
836       return GNUNET_YES;
837     }
838   }
839   return GNUNET_NO;
840 }
841
842
843 /**
844  * Handle for controller process
845  */
846 struct GNUNET_TESTBED_ControllerProc
847 {
848   /**
849    * The process handle
850    */
851   struct GNUNET_HELPER_Handle *helper;
852
853   /**
854    * The arguments used to start the helper
855    */
856   char **helper_argv;
857
858   /**
859    * The host where the helper is run
860    */
861   struct GNUNET_TESTBED_Host *host;
862
863   /**
864    * The controller error callback
865    */
866   GNUNET_TESTBED_ControllerStatusCallback cb;
867
868   /**
869    * The closure for the above callback
870    */
871   void *cls;
872
873   /**
874    * The send handle for the helper
875    */
876   struct GNUNET_HELPER_SendHandle *shandle;
877
878   /**
879    * The message corresponding to send handle
880    */
881   struct GNUNET_MessageHeader *msg;
882
883 };
884
885
886 /**
887  * Function to copy NULL terminated list of arguments
888  *
889  * @param argv the NULL terminated list of arguments. Cannot be NULL.
890  * @return the copied NULL terminated arguments
891  */
892 static char **
893 copy_argv (const char *const *argv)
894 {
895   char **argv_dup;
896   unsigned int argp;
897
898   GNUNET_assert (NULL != argv);
899   for (argp = 0; NULL != argv[argp]; argp++) ;
900   argv_dup = GNUNET_malloc (sizeof (char *) * (argp + 1));
901   for (argp = 0; NULL != argv[argp]; argp++)
902     argv_dup[argp] = strdup (argv[argp]);
903   return argv_dup;
904 }
905
906
907 /**
908  * Function to join NULL terminated list of arguments
909  *
910  * @param argv1 the NULL terminated list of arguments. Cannot be NULL.
911  * @param argv2 the NULL terminated list of arguments. Cannot be NULL.
912  * @return the joined NULL terminated arguments
913  */
914 static char **
915 join_argv (const char *const *argv1, const char *const *argv2)
916 {
917   char **argvj;
918   char *argv;
919   unsigned int carg;
920   unsigned int cnt;
921
922   carg = 0;
923   argvj = NULL;
924   for (cnt = 0; NULL != argv1[cnt]; cnt++)
925   {
926     argv = GNUNET_strdup (argv1[cnt]);
927     GNUNET_array_append (argvj, carg, argv);
928   }
929   for (cnt = 0; NULL != argv2[cnt]; cnt++)
930   {
931     argv = GNUNET_strdup (argv2[cnt]);
932     GNUNET_array_append (argvj, carg, argv);
933   }
934   GNUNET_array_append (argvj, carg, NULL);
935   return argvj;
936 }
937
938
939 /**
940  * Frees the given NULL terminated arguments
941  *
942  * @param argv the NULL terminated list of arguments
943  */
944 static void
945 free_argv (char **argv)
946 {
947   unsigned int argp;
948
949   for (argp = 0; NULL != argv[argp]; argp++)
950     GNUNET_free (argv[argp]);
951   GNUNET_free (argv);
952 }
953
954
955 /**
956  * Generates arguments for opening a remote shell. Builds up the arguments
957  * from the environment variable GNUNET_TESTBED_RSH_CMD. The variable
958  * should not mention `-p' (port) option and destination address as these will
959  * be set locally in the function from its parameteres. If the environmental
960  * variable is not found then it defaults to `ssh -o BatchMode=yes -o
961  * NoHostAuthenticationForLocalhost=yes'
962  *
963  * @param port the destination port number
964  * @param dst the destination address
965  * @return NULL terminated list of arguments
966  */
967 static char **
968 gen_rsh_args (const char *port, const char *dst)
969 {
970   static const char *default_ssh_args[] = {
971     "ssh",
972     "-o",
973     "BatchMode=yes",
974     "-o",
975     "NoHostAuthenticationForLocalhost=yes",
976     NULL
977   };
978   char **ssh_args;
979   char *ssh_cmd;
980   char *ssh_cmd_cp;
981   char *arg;
982   unsigned int cnt;
983
984   ssh_args = NULL;
985   if (NULL != (ssh_cmd = getenv ("GNUNET_TESTBED_RSH_CMD")))
986   {
987     ssh_cmd = GNUNET_strdup (ssh_cmd);
988     ssh_cmd_cp = ssh_cmd;
989     for (cnt = 0; NULL != (arg = strtok (ssh_cmd, " ")); ssh_cmd = NULL)
990       GNUNET_array_append (ssh_args, cnt, GNUNET_strdup (arg));
991     GNUNET_free (ssh_cmd_cp);
992   }
993   else
994   {
995     ssh_args = copy_argv (default_ssh_args);
996     cnt = (sizeof (default_ssh_args)) / (sizeof (const char *));
997     GNUNET_array_grow (ssh_args, cnt, cnt - 1);
998   }
999   GNUNET_array_append (ssh_args, cnt, GNUNET_strdup ("-p"));
1000   GNUNET_array_append (ssh_args, cnt, GNUNET_strdup (port));
1001   GNUNET_array_append (ssh_args, cnt, GNUNET_strdup (dst));
1002   GNUNET_array_append (ssh_args, cnt, NULL);
1003   return ssh_args;
1004 }
1005
1006
1007 /**
1008  * Generates the arguments needed for executing the given binary in a remote
1009  * shell. Builds the arguments from the environmental variable
1010  * GNUNET_TETSBED_RSH_CMD_SUFFIX. If the environmental variable is not found,
1011  * only the given binary name will be present in the returned arguments
1012  *
1013  * @param append_args the arguments to append after generating the suffix
1014  *          arguments. Can be NULL; if not must be NULL terminated 'char *' array
1015  * @return NULL-terminated args
1016  */
1017 static char **
1018 gen_rsh_suffix_args (const char * const *append_args)
1019 {
1020   char **rshell_args;
1021   char *rshell_cmd;
1022   char *rshell_cmd_cp;
1023   char *arg;
1024   unsigned int cnt;
1025   unsigned int append_cnt;
1026
1027   rshell_args = NULL;
1028   cnt = 0;
1029   if (NULL != (rshell_cmd = getenv ("GNUNET_TESTBED_RSH_CMD_SUFFIX")))
1030   {
1031     rshell_cmd = GNUNET_strdup (rshell_cmd);
1032     rshell_cmd_cp = rshell_cmd;
1033     for (; NULL != (arg = strtok (rshell_cmd, " ")); rshell_cmd = NULL)
1034       GNUNET_array_append (rshell_args, cnt, GNUNET_strdup (arg));
1035     GNUNET_free (rshell_cmd_cp);
1036   }
1037   if (NULL != append_args)
1038   {
1039     for (append_cnt = 0; NULL != append_args[append_cnt]; append_cnt++)      
1040       GNUNET_array_append (rshell_args, cnt, GNUNET_strdup (append_args[append_cnt]));
1041   }
1042   GNUNET_array_append (rshell_args, cnt, NULL);
1043   return rshell_args;
1044 }
1045
1046
1047 /**
1048  * Functions with this signature are called whenever a
1049  * complete message is received by the tokenizer.
1050  *
1051  * Do not call GNUNET_SERVER_mst_destroy in callback
1052  *
1053  * @param cls closure
1054  * @param client identification of the client
1055  * @param message the actual message
1056  *
1057  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1058  */
1059 static int
1060 helper_mst (void *cls, void *client, const struct GNUNET_MessageHeader *message)
1061 {
1062   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1063   const struct GNUNET_TESTBED_HelperReply *msg;
1064   const char *hostname;
1065   char *config;
1066   uLongf config_size;
1067   uLongf xconfig_size;
1068
1069   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
1070   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) <
1071                  ntohs (msg->header.size));
1072   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY ==
1073                  ntohs (msg->header.type));
1074   config_size = (uLongf) ntohs (msg->config_size);
1075   xconfig_size =
1076       (uLongf) (ntohs (msg->header.size) -
1077                 sizeof (struct GNUNET_TESTBED_HelperReply));
1078   config = GNUNET_malloc (config_size);
1079   GNUNET_assert (Z_OK ==
1080                  uncompress ((Bytef *) config, &config_size,
1081                              (const Bytef *) &msg[1], xconfig_size));
1082   /* Replace the configuration template present in the host with the
1083      controller's running configuration */
1084   GNUNET_CONFIGURATION_destroy (cp->host->cfg);
1085   cp->host->cfg = GNUNET_CONFIGURATION_create ();
1086   GNUNET_assert (GNUNET_CONFIGURATION_deserialize
1087                  (cp->host->cfg, config, config_size, GNUNET_NO));
1088   GNUNET_free (config);
1089   if (NULL == (hostname = GNUNET_TESTBED_host_get_hostname (cp->host)))
1090     hostname = "localhost";
1091   /* Change the hostname so that we can connect to it */
1092   GNUNET_CONFIGURATION_set_value_string (cp->host->cfg, "testbed", "hostname",
1093                                          hostname);
1094   cp->host->locked = GNUNET_NO;
1095   cp->host->controller_started = GNUNET_YES;
1096   cp->cb (cp->cls, cp->host->cfg, GNUNET_OK);
1097   return GNUNET_OK;
1098 }
1099
1100
1101 /**
1102  * Continuation function from GNUNET_HELPER_send()
1103  *
1104  * @param cls closure
1105  * @param result GNUNET_OK on success,
1106  *               GNUNET_NO if helper process died
1107  *               GNUNET_SYSERR during GNUNET_HELPER_stop
1108  */
1109 static void
1110 clear_msg (void *cls, int result)
1111 {
1112   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1113
1114   GNUNET_assert (NULL != cp->shandle);
1115   cp->shandle = NULL;
1116   GNUNET_free (cp->msg);
1117 }
1118
1119
1120 /**
1121  * Callback that will be called when the helper process dies. This is not called
1122  * when the helper process is stoped using GNUNET_HELPER_stop()
1123  *
1124  * @param cls the closure from GNUNET_HELPER_start()
1125  */
1126 static void
1127 helper_exp_cb (void *cls)
1128 {
1129   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1130   GNUNET_TESTBED_ControllerStatusCallback cb;
1131   void *cb_cls;
1132
1133   cb = cp->cb;
1134   cb_cls = cp->cls;
1135   cp->helper = NULL;
1136   GNUNET_TESTBED_controller_stop (cp);
1137   if (NULL != cb)
1138     cb (cb_cls, NULL, GNUNET_SYSERR);
1139 }
1140
1141
1142 /**
1143  * Starts a controller process at the given host.  The given host's configration
1144  * is used as a Template configuration to use for the remote controller; the
1145  * remote controller will be started with a slightly modified configuration
1146  * (port numbers, unix domain sockets and service home values are changed as per
1147  * TESTING library on the remote host).  The modified configuration replaces the
1148  * host's existing configuration before signalling success through the
1149  * GNUNET_TESTBED_ControllerStatusCallback()
1150  *
1151  * @param trusted_ip the ip address of the controller which will be set as TRUSTED
1152  *          HOST(all connections form this ip are permitted by the testbed) when
1153  *          starting testbed controller at host. This can either be a single ip
1154  *          address or a network address in CIDR notation.
1155  * @param host the host where the controller has to be started.  CANNOT be NULL.
1156  * @param cb function called when the controller is successfully started or
1157  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
1158  *          called if cb is called with GNUNET_SYSERR as status. Will never be
1159  *          called in the same task as 'GNUNET_TESTBED_controller_start'
1160  *          (synchronous errors will be signalled by returning NULL). This
1161  *          parameter cannot be NULL.
1162  * @param cls closure for above callbacks
1163  * @return the controller process handle, NULL on errors
1164  */
1165 struct GNUNET_TESTBED_ControllerProc *
1166 GNUNET_TESTBED_controller_start (const char *trusted_ip,
1167                                  struct GNUNET_TESTBED_Host *host,
1168                                  GNUNET_TESTBED_ControllerStatusCallback cb,
1169                                  void *cls)
1170 {
1171   struct GNUNET_TESTBED_ControllerProc *cp;
1172   struct GNUNET_TESTBED_HelperInit *msg;
1173   const struct GNUNET_CONFIGURATION_Handle *cfg;
1174   const char *hostname;
1175   static char *const binary_argv[] = {
1176     HELPER_TESTBED_BINARY, NULL
1177   };
1178   
1179   GNUNET_assert (NULL != host);
1180   GNUNET_assert (NULL != (cfg = GNUNET_TESTBED_host_get_cfg_ (host)));
1181   hostname = NULL;
1182   API_VIOLATION (GNUNET_NO == host->locked,
1183                  "Host is already locked by a previous call to GNUNET_TESTBED_controller_start()");
1184   host->locked = GNUNET_YES;
1185   API_VIOLATION (GNUNET_NO == host->controller_started,
1186                  "Attempting to start a controller on a host which is already started a controller");
1187   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
1188   if (0 == GNUNET_TESTBED_host_get_id_ (host))
1189   {
1190     cp->helper =
1191         GNUNET_HELPER_start (GNUNET_YES, HELPER_TESTBED_BINARY, binary_argv,
1192                              &helper_mst, &helper_exp_cb, cp);
1193   }
1194   else
1195   {
1196     char *helper_binary_path_args[2];
1197     char **rsh_args;
1198     char **rsh_suffix_args;
1199     const char *username;
1200     char *port;
1201     char *dst;
1202
1203     username = GNUNET_TESTBED_host_get_username_ (host);
1204     hostname = GNUNET_TESTBED_host_get_hostname (host);
1205     GNUNET_asprintf (&port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
1206     if (NULL == username)
1207       GNUNET_asprintf (&dst, "%s", hostname);
1208     else
1209       GNUNET_asprintf (&dst, "%s@%s", username, hostname);
1210     LOG_DEBUG ("Starting SSH to destination %s\n", dst);
1211
1212     if (GNUNET_OK !=
1213         GNUNET_CONFIGURATION_get_value_string (cfg, "testbed",
1214                                                "HELPER_BINARY_PATH",
1215                                                &helper_binary_path_args[0]))
1216       helper_binary_path_args[0] =
1217           GNUNET_OS_get_libexec_binary_path (HELPER_TESTBED_BINARY);
1218     helper_binary_path_args[1] = NULL;
1219     rsh_args = gen_rsh_args (port, dst);
1220     rsh_suffix_args = gen_rsh_suffix_args ((const char **) helper_binary_path_args);
1221     cp->helper_argv =
1222         join_argv ((const char **) rsh_args, (const char **) rsh_suffix_args);
1223     free_argv (rsh_args);
1224     free_argv (rsh_suffix_args);
1225     GNUNET_free (port);
1226     GNUNET_free (dst);
1227     cp->helper =
1228         GNUNET_HELPER_start (GNUNET_NO, cp->helper_argv[0], cp->helper_argv, &helper_mst,
1229                              &helper_exp_cb, cp);
1230     GNUNET_free (helper_binary_path_args[0]);
1231   }
1232   if (NULL == cp->helper)
1233   {
1234     if (NULL != cp->helper_argv)
1235       free_argv (cp->helper_argv);
1236     GNUNET_free (cp);
1237     return NULL;
1238   }
1239   cp->host = host;
1240   cp->cb = cb;
1241   cp->cls = cls;
1242   msg = GNUNET_TESTBED_create_helper_init_msg_ (trusted_ip, hostname, cfg);
1243   cp->msg = &msg->header;
1244   cp->shandle =
1245       GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO, &clear_msg, cp);
1246   if (NULL == cp->shandle)
1247   {
1248     GNUNET_free (msg);
1249     GNUNET_TESTBED_controller_stop (cp);
1250     return NULL;
1251   }
1252   return cp;
1253 }
1254
1255
1256 /**
1257  * Sends termination signal to the controller's helper process
1258  *
1259  * @param cproc the handle to the controller's helper process
1260  */
1261 void
1262 GNUNET_TESTBED_controller_kill_ (struct GNUNET_TESTBED_ControllerProc *cproc)
1263 {
1264   if (NULL != cproc->shandle)
1265     GNUNET_HELPER_send_cancel (cproc->shandle);
1266   if (NULL != cproc->helper)
1267     GNUNET_HELPER_kill (cproc->helper, GNUNET_YES);
1268 }
1269
1270
1271 /**
1272  * Cleans-up the controller's helper process handle
1273  *
1274  * @param cproc the handle to the controller's helper process
1275  */
1276 void
1277 GNUNET_TESTBED_controller_destroy_ (struct GNUNET_TESTBED_ControllerProc *cproc)
1278 {
1279   if (NULL != cproc->helper)
1280   {
1281     GNUNET_break (GNUNET_OK == GNUNET_HELPER_wait (cproc->helper));
1282     GNUNET_HELPER_destroy (cproc->helper);
1283   }
1284   if (NULL != cproc->helper_argv)
1285     free_argv (cproc->helper_argv);
1286   cproc->host->controller_started = GNUNET_NO;
1287   cproc->host->locked = GNUNET_NO;
1288   GNUNET_free (cproc);
1289 }
1290
1291
1292 /**
1293  * Stop the controller process (also will terminate all peers and controllers
1294  * dependent on this controller).  This function blocks until the testbed has
1295  * been fully terminated (!). The controller status cb from
1296  * GNUNET_TESTBED_controller_start() will not be called.
1297  *
1298  * @param cproc the controller process handle
1299  */
1300 void
1301 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
1302 {
1303   GNUNET_TESTBED_controller_kill_ (cproc);
1304   GNUNET_TESTBED_controller_destroy_ (cproc);
1305 }
1306
1307
1308 /**
1309  * The handle for whether a host is habitable or not
1310  */
1311 struct GNUNET_TESTBED_HostHabitableCheckHandle
1312 {
1313   /**
1314    * The host to check
1315    */
1316   const struct GNUNET_TESTBED_Host *host;
1317
1318   /**
1319    * The callback to call once we have the status
1320    */
1321   GNUNET_TESTBED_HostHabitableCallback cb;
1322
1323   /**
1324    * The callback closure
1325    */
1326   void *cb_cls;
1327
1328   /**
1329    * The process handle for the SSH process
1330    */
1331   struct GNUNET_OS_Process *auxp;
1332
1333   /**
1334    * The arguments used to start the helper
1335    */
1336   char **helper_argv;
1337
1338   /**
1339    * Task id for the habitability check task
1340    */
1341   GNUNET_SCHEDULER_TaskIdentifier habitability_check_task;
1342
1343   /**
1344    * How long we wait before checking the process status. Should grow
1345    * exponentially
1346    */
1347   struct GNUNET_TIME_Relative wait_time;
1348
1349 };
1350
1351
1352 /**
1353  * Task for checking whether a host is habitable or not
1354  *
1355  * @param cls GNUNET_TESTBED_HostHabitableCheckHandle
1356  * @param tc the scheduler task context
1357  */
1358 static void
1359 habitability_check (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1360 {
1361   struct GNUNET_TESTBED_HostHabitableCheckHandle *h = cls;
1362   void *cb_cls;
1363   GNUNET_TESTBED_HostHabitableCallback cb;
1364   const struct GNUNET_TESTBED_Host *host;
1365   unsigned long code;
1366   enum GNUNET_OS_ProcessStatusType type;
1367   int ret;
1368
1369   h->habitability_check_task = GNUNET_SCHEDULER_NO_TASK;
1370   ret = GNUNET_OS_process_status (h->auxp, &type, &code);
1371   if (GNUNET_SYSERR == ret)
1372   {
1373     GNUNET_break (0);
1374     ret = GNUNET_NO;
1375     goto call_cb;
1376   }
1377   if (GNUNET_NO == ret)
1378   {
1379     h->wait_time = GNUNET_TIME_STD_BACKOFF (h->wait_time);
1380     h->habitability_check_task =
1381         GNUNET_SCHEDULER_add_delayed (h->wait_time, &habitability_check, h);
1382     return;
1383   }
1384   GNUNET_OS_process_destroy (h->auxp);
1385   h->auxp = NULL;
1386   ret = (0 != code) ? GNUNET_NO : GNUNET_YES;
1387
1388 call_cb:
1389   if (NULL != h->auxp)
1390     GNUNET_OS_process_destroy (h->auxp);
1391   cb = h->cb;
1392   cb_cls = h->cb_cls;
1393   host = h->host;
1394   free_argv (h->helper_argv);
1395   GNUNET_free (h);
1396   if (NULL != cb)
1397     cb (cb_cls, host, ret);
1398 }
1399
1400
1401 /**
1402  * Checks whether a host can be used to start testbed service
1403  *
1404  * @param host the host to check
1405  * @param config the configuration handle to lookup the path of the testbed
1406  *          helper
1407  * @param cb the callback to call to inform about habitability of the given host
1408  * @param cb_cls the closure for the callback
1409  * @return NULL upon any error or a handle which can be passed to
1410  *           GNUNET_TESTBED_is_host_habitable_cancel()
1411  */
1412 struct GNUNET_TESTBED_HostHabitableCheckHandle *
1413 GNUNET_TESTBED_is_host_habitable (const struct GNUNET_TESTBED_Host *host,
1414                                   const struct GNUNET_CONFIGURATION_Handle
1415                                   *config,
1416                                   GNUNET_TESTBED_HostHabitableCallback cb,
1417                                   void *cb_cls)
1418 {
1419   struct GNUNET_TESTBED_HostHabitableCheckHandle *h;
1420   char **rsh_args;
1421   char **rsh_suffix_args;
1422   char *stat_args[3];
1423   const char *hostname;
1424   char *port;
1425   char *dst;
1426
1427   h = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle));
1428   h->cb = cb;
1429   h->cb_cls = cb_cls;
1430   h->host = host;
1431   hostname = (NULL == host->hostname) ? "127.0.0.1" : host->hostname;
1432   if (NULL == host->username)
1433     dst = GNUNET_strdup (hostname);
1434   else
1435     GNUNET_asprintf (&dst, "%s@%s", host->username, hostname);
1436   if (GNUNET_OK !=
1437       GNUNET_CONFIGURATION_get_value_string (config, "testbed",
1438                                              "HELPER_BINARY_PATH",
1439                                              &stat_args[1]))
1440     stat_args[1] =
1441         GNUNET_OS_get_libexec_binary_path (HELPER_TESTBED_BINARY);  
1442   GNUNET_asprintf (&port, "%u", host->port);
1443   rsh_args = gen_rsh_args (port, dst);
1444   GNUNET_free (port);
1445   GNUNET_free (dst);
1446   port = NULL;
1447   dst = NULL;
1448   stat_args[0] = "stat";
1449   stat_args[2] = NULL;
1450   rsh_suffix_args = gen_rsh_suffix_args ((const char **) stat_args);
1451   GNUNET_free (stat_args[1]);
1452   h->helper_argv = join_argv ((const char **) rsh_args,
1453                               (const char **) rsh_suffix_args);
1454   free_argv (rsh_suffix_args);
1455   free_argv (rsh_args);
1456   h->auxp =
1457       GNUNET_OS_start_process_vap (GNUNET_NO, GNUNET_OS_INHERIT_STD_ERR, NULL,
1458                                    NULL, h->helper_argv[0], h->helper_argv);
1459   if (NULL == h->auxp)
1460   {
1461     GNUNET_break (0);           /* Cannot exec SSH? */
1462     GNUNET_free (h);
1463     return NULL;
1464   }
1465   h->wait_time = GNUNET_TIME_STD_BACKOFF (h->wait_time);
1466   h->habitability_check_task =
1467       GNUNET_SCHEDULER_add_delayed (h->wait_time, &habitability_check, h);
1468   return h;
1469 }
1470
1471
1472 /**
1473  * Function to cancel a request started using GNUNET_TESTBED_is_host_habitable()
1474  *
1475  * @param handle the habitability check handle
1476  */
1477 void
1478 GNUNET_TESTBED_is_host_habitable_cancel (struct
1479                                          GNUNET_TESTBED_HostHabitableCheckHandle
1480                                          *handle)
1481 {
1482   GNUNET_SCHEDULER_cancel (handle->habitability_check_task);
1483   (void) GNUNET_OS_process_kill (handle->auxp, SIGTERM);
1484   (void) GNUNET_OS_process_wait (handle->auxp);
1485   GNUNET_OS_process_destroy (handle->auxp);
1486   free_argv (handle->helper_argv);
1487   GNUNET_free (handle);
1488 }
1489
1490
1491 /**
1492  * handle for host registration
1493  */
1494 struct GNUNET_TESTBED_HostRegistrationHandle
1495 {
1496   /**
1497    * The host being registered
1498    */
1499   struct GNUNET_TESTBED_Host *host;
1500
1501   /**
1502    * The controller at which this host is being registered
1503    */
1504   struct GNUNET_TESTBED_Controller *c;
1505
1506   /**
1507    * The Registartion completion callback
1508    */
1509   GNUNET_TESTBED_HostRegistrationCompletion cc;
1510
1511   /**
1512    * The closure for above callback
1513    */
1514   void *cc_cls;
1515 };
1516
1517
1518 /**
1519  * Register a host with the controller
1520  *
1521  * @param controller the controller handle
1522  * @param host the host to register
1523  * @param cc the completion callback to call to inform the status of
1524  *          registration. After calling this callback the registration handle
1525  *          will be invalid. Cannot be NULL.
1526  * @param cc_cls the closure for the cc
1527  * @return handle to the host registration which can be used to cancel the
1528  *           registration
1529  */
1530 struct GNUNET_TESTBED_HostRegistrationHandle *
1531 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1532                               struct GNUNET_TESTBED_Host *host,
1533                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1534                               void *cc_cls)
1535 {
1536   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1537   struct GNUNET_TESTBED_AddHostMessage *msg;
1538   const char *username;
1539   const char *hostname;
1540   char *config;
1541   char *cconfig;
1542   void *ptr;
1543   size_t cc_size;
1544   size_t config_size;
1545   uint16_t msg_size;
1546   uint16_t username_length;
1547   uint16_t hostname_length;
1548
1549   if (NULL != controller->rh)
1550     return NULL;
1551   hostname = GNUNET_TESTBED_host_get_hostname (host);
1552   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1553   {
1554     LOG (GNUNET_ERROR_TYPE_WARNING, "Host hostname: %s already registered\n",
1555          (NULL == hostname) ? "localhost" : hostname);
1556     return NULL;
1557   }
1558   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1559   rh->host = host;
1560   rh->c = controller;
1561   GNUNET_assert (NULL != cc);
1562   rh->cc = cc;
1563   rh->cc_cls = cc_cls;
1564   controller->rh = rh;
1565   username = GNUNET_TESTBED_host_get_username_ (host);
1566   username_length = 0;
1567   if (NULL != username)
1568     username_length = strlen (username);
1569   GNUNET_assert (NULL != hostname); /* Hostname must be present */
1570   hostname_length = strlen (hostname);
1571   GNUNET_assert (NULL != host->cfg);
1572   config = GNUNET_CONFIGURATION_serialize (host->cfg, &config_size);
1573   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1574   GNUNET_free (config);
1575   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1576   msg_size += username_length;
1577   msg_size += hostname_length;
1578   msg_size += cc_size;
1579   msg = GNUNET_malloc (msg_size);
1580   msg->header.size = htons (msg_size);
1581   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST);
1582   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1583   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1584   ptr = &msg[1];
1585   if (NULL != username)
1586   {
1587     msg->username_length = htons (username_length);
1588     ptr = memcpy (ptr, username, username_length);
1589     ptr += username_length;
1590   }
1591   msg->hostname_length = htons (hostname_length);
1592   ptr = memcpy (ptr, hostname, hostname_length);
1593   ptr += hostname_length;
1594   msg->config_size = htons (config_size);
1595   ptr = memcpy (ptr, cconfig, cc_size);
1596   ptr += cc_size;
1597   GNUNET_assert ((ptr - (void *) msg) == msg_size);
1598   GNUNET_free (cconfig);
1599   GNUNET_TESTBED_queue_message_ (controller,
1600                                  (struct GNUNET_MessageHeader *) msg);
1601   return rh;
1602 }
1603
1604
1605 /**
1606  * Cancel the pending registration. Note that if the registration message is
1607  * already sent to the service the cancellation has only the effect that the
1608  * registration completion callback for the registration is never called.
1609  *
1610  * @param handle the registration handle to cancel
1611  */
1612 void
1613 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1614                                     *handle)
1615 {
1616   if (handle != handle->c->rh)
1617   {
1618     GNUNET_break (0);
1619     return;
1620   }
1621   handle->c->rh = NULL;
1622   GNUNET_free (handle);
1623 }
1624
1625
1626 /**
1627  * Initializes the operation queue for parallel overlay connects
1628  *
1629  * @param h the host handle
1630  * @param npoc the number of parallel overlay connects - the queue size
1631  */
1632 void
1633 GNUNET_TESTBED_set_num_parallel_overlay_connects_ (struct
1634                                                    GNUNET_TESTBED_Host *h,
1635                                                    unsigned int npoc)
1636 {
1637   //fprintf (stderr, "%d", npoc);
1638   GNUNET_free_non_null (h->tslots);
1639   h->tslots_filled = 0;
1640   h->num_parallel_connects = npoc;
1641   h->tslots = GNUNET_malloc (npoc * sizeof (struct TimeSlot));
1642   GNUNET_TESTBED_operation_queue_reset_max_active_
1643       (h->opq_parallel_overlay_connect_operations, npoc);
1644 }
1645
1646
1647 /**
1648  * Returns a timing slot which will be exclusively locked
1649  *
1650  * @param h the host handle
1651  * @param key a pointer which is associated to the returned slot; should not be
1652  *          NULL. It serves as a key to determine the correct owner of the slot
1653  * @return the time slot index in the array of time slots in the controller
1654  *           handle
1655  */
1656 unsigned int
1657 GNUNET_TESTBED_get_tslot_ (struct GNUNET_TESTBED_Host *h, void *key)
1658 {
1659   unsigned int slot;
1660
1661   GNUNET_assert (NULL != h->tslots);
1662   GNUNET_assert (NULL != key);
1663   for (slot = 0; slot < h->num_parallel_connects; slot++)
1664     if (NULL == h->tslots[slot].key)
1665     {
1666       h->tslots[slot].key = key;
1667       return slot;
1668     }
1669   GNUNET_assert (0);            /* We should always find a free tslot */
1670 }
1671
1672
1673 /**
1674  * Decides whether any change in the number of parallel overlay connects is
1675  * necessary to adapt to the load on the system
1676  *
1677  * @param h the host handle
1678  */
1679 static void
1680 decide_npoc (struct GNUNET_TESTBED_Host *h)
1681 {
1682   struct GNUNET_TIME_Relative avg;
1683   int sd;
1684   unsigned int slot;
1685   unsigned int nvals;
1686
1687   if (h->tslots_filled != h->num_parallel_connects)
1688     return;
1689   avg = GNUNET_TIME_UNIT_ZERO;
1690   nvals = 0;
1691   for (slot = 0; slot < h->num_parallel_connects; slot++)
1692   {
1693     avg = GNUNET_TIME_relative_add (avg, h->tslots[slot].time);
1694     nvals += h->tslots[slot].nvals;
1695   }
1696   GNUNET_assert (nvals >= h->num_parallel_connects);
1697   avg = GNUNET_TIME_relative_divide (avg, nvals);
1698   GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != avg.rel_value_us);
1699   sd = GNUNET_TESTBED_SD_deviation_factor_ (h->poc_sd, (unsigned int) avg.rel_value_us);
1700   if ( (sd <= 5) ||
1701        (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1702                                        h->num_parallel_connects)) )
1703     GNUNET_TESTBED_SD_add_data_ (h->poc_sd, (unsigned int) avg.rel_value_us);
1704   if (GNUNET_SYSERR == sd)
1705   {
1706     GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h,
1707                                                        h->num_parallel_connects);
1708     return;
1709   }
1710   GNUNET_assert (0 <= sd);
1711   if (0 == sd)
1712   {
1713     GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h,
1714                                                        h->num_parallel_connects
1715                                                        * 2);
1716     return;
1717   }
1718   if (1 == sd)
1719   {
1720     GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h,
1721                                                        h->num_parallel_connects
1722                                                        + 1);
1723     return;
1724   }
1725   if (1 == h->num_parallel_connects)
1726   {
1727     GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h, 1);
1728     return;
1729   }
1730   if (2 == sd)
1731   {
1732     GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h,
1733                                                        h->num_parallel_connects
1734                                                        - 1);
1735     return;
1736   }
1737   GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h,
1738                                                      h->num_parallel_connects /
1739                                                      2);
1740 }
1741
1742
1743 /**
1744  * Releases a time slot thus making it available for be used again
1745  *
1746  * @param h the host handle
1747  * @param index the index of the the time slot
1748  * @param key the key to prove ownership of the timeslot
1749  * @return GNUNET_YES if the time slot is successfully removed; GNUNET_NO if the
1750  *           time slot cannot be removed - this could be because of the index
1751  *           greater than existing number of time slots or `key' being different
1752  */
1753 int
1754 GNUNET_TESTBED_release_time_slot_ (struct GNUNET_TESTBED_Host *h,
1755                                    unsigned int index, void *key)
1756 {
1757   struct TimeSlot *slot;
1758
1759   GNUNET_assert (NULL != key);
1760   if (index >= h->num_parallel_connects)
1761     return GNUNET_NO;
1762   slot = &h->tslots[index];
1763   if (key != slot->key)
1764     return GNUNET_NO;
1765   slot->key = NULL;
1766   return GNUNET_YES;
1767 }
1768
1769
1770 /**
1771  * Function to update a time slot
1772  *
1773  * @param h the host handle
1774  * @param index the index of the time slot to update
1775  * @param key the key to identify ownership of the slot
1776  * @param time the new time
1777  * @param failed should this reading be treated as coming from a fail event
1778  */
1779 void
1780 GNUNET_TESTBED_update_time_slot_ (struct GNUNET_TESTBED_Host *h,
1781                                   unsigned int index, void *key,
1782                                   struct GNUNET_TIME_Relative time, int failed)
1783 {
1784   struct TimeSlot *slot;
1785
1786   if (GNUNET_YES == failed)
1787   {
1788     if (1 == h->num_parallel_connects)
1789     {
1790       GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h, 1);
1791       return;
1792     }
1793     GNUNET_TESTBED_set_num_parallel_overlay_connects_ (h,
1794                                                        h->num_parallel_connects
1795                                                        - 1);
1796   }
1797   if (GNUNET_NO == GNUNET_TESTBED_release_time_slot_ (h, index, key))
1798     return;
1799   slot = &h->tslots[index];
1800   slot->nvals++;
1801   if (GNUNET_TIME_UNIT_ZERO.rel_value_us == slot->time.rel_value_us)
1802   {
1803     slot->time = time;
1804     h->tslots_filled++;
1805     decide_npoc (h);
1806     return;
1807   }
1808   slot->time = GNUNET_TIME_relative_add (slot->time, time);
1809 }
1810
1811
1812 /**
1813  * Queues the given operation in the queue for parallel overlay connects of the
1814  * given host
1815  *
1816  * @param h the host handle
1817  * @param op the operation to queue in the given host's parally overlay connect
1818  *          queue 
1819  */
1820 void
1821 GNUNET_TESTBED_host_queue_oc_ (struct GNUNET_TESTBED_Host *h, 
1822                                struct GNUNET_TESTBED_Operation *op)
1823 {  
1824   GNUNET_TESTBED_operation_queue_insert_
1825       (h->opq_parallel_overlay_connect_operations, op);
1826 }
1827
1828
1829 /**
1830  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
1831  * controller (testbed service)
1832  *
1833  * @param c the controller handler
1834  * @param msg message received
1835  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
1836  *           not
1837  */
1838 int
1839 GNUNET_TESTBED_host_handle_addhostconfirm_ (struct GNUNET_TESTBED_Controller *c,
1840                                             const struct
1841                                             GNUNET_TESTBED_HostConfirmedMessage
1842                                             *msg)
1843 {
1844   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1845   char *emsg;
1846   uint16_t msg_size;
1847
1848   rh = c->rh;
1849   if (NULL == rh)
1850   {
1851     return GNUNET_OK;
1852   }
1853   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
1854   {
1855     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
1856                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
1857     return GNUNET_OK;
1858   }
1859   c->rh = NULL;
1860   msg_size = ntohs (msg->header.size);
1861   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
1862   {
1863     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
1864     GNUNET_TESTBED_mark_host_registered_at_ (rh->host, c);
1865     rh->cc (rh->cc_cls, NULL);
1866     GNUNET_free (rh);
1867     return GNUNET_OK;
1868   }
1869   /* We have an error message */
1870   emsg = (char *) &msg[1];
1871   if ('\0' !=
1872       emsg[msg_size - sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
1873   {
1874     GNUNET_break (0);
1875     GNUNET_free (rh);
1876     return GNUNET_NO;
1877   }
1878   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
1879        ntohl (msg->host_id), emsg);
1880   rh->cc (rh->cc_cls, emsg);
1881   GNUNET_free (rh);
1882   return GNUNET_OK;
1883 }
1884
1885
1886 /**
1887  * Resolves the hostname of the host to an ip address
1888  *
1889  * @param host the host whose hostname is to be resolved
1890  */
1891 void
1892 GNUNET_TESTBED_host_resolve_ (struct GNUNET_TESTBED_Host *host)
1893 {
1894   char *hostname;
1895
1896   hostname = (char *) host->hostname;
1897   host->hostname = simple_resolve (hostname);
1898   if (NULL == host->hostname)
1899   {
1900     GNUNET_break (0);
1901     host->hostname = hostname;
1902     return;
1903   }
1904   GNUNET_free (hostname);
1905   host->hostname = GNUNET_strdup (host->hostname);
1906 }
1907
1908 /* end of testbed_api_hosts.c */