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