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