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