fix; modified testcase for test_testbed_api; valigrind suppression for zlib
[oweals/gnunet.git] / src / testbed / testbed_api.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2012 Christian Grothoff (and other contributing authors)
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file testbed/testbed_api.c
23  * @brief API for accessing the GNUnet testing service.
24  *        This library is supposed to make it easier to write
25  *        testcases and script large-scale benchmarks.
26  * @author Christian Grothoff
27  * @author Sree Harsha Totakura
28  */
29
30
31 #include "platform.h"
32 #include "gnunet_testbed_service.h"
33 #include "gnunet_core_service.h"
34 #include "gnunet_constants.h"
35 #include "gnunet_transport_service.h"
36 #include "gnunet_hello_lib.h"
37 #include <zlib.h>
38
39 #include "testbed.h"
40 #include "testbed_api.h"
41 #include "testbed_api_hosts.h"
42 #include "testbed_api_peers.h"
43
44 /**
45  * Generic logging shorthand
46  */
47 #define LOG(kind, ...)                          \
48   GNUNET_log_from (kind, "testbed-api", __VA_ARGS__);
49
50 /**
51  * Debug logging
52  */
53 #define LOG_DEBUG(...)                          \
54   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__);
55
56 /**
57  * Relative time seconds shorthand
58  */
59 #define TIME_REL_SECS(sec) \
60   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, sec)
61
62
63 /**
64  * Default server message sending retry timeout
65  */
66 #define TIMEOUT_REL TIME_REL_SECS(1)
67
68
69 /**
70  * The message queue for sending messages to the controller service
71  */
72 struct MessageQueue
73 {
74   /**
75    * The message to be sent
76    */
77   struct GNUNET_MessageHeader *msg;
78
79   /**
80    * next pointer for DLL
81    */
82   struct MessageQueue *next;
83   
84   /**
85    * prev pointer for DLL
86    */
87   struct MessageQueue *prev;
88 };
89
90
91 /**
92  * Structure for a controller link
93  */
94 struct ControllerLink
95 {
96   /**
97    * The next ptr for DLL
98    */
99   struct ControllerLink *next;
100
101   /**
102    * The prev ptr for DLL
103    */
104   struct ControllerLink *prev;
105
106   /**
107    * The host which will be referred in the peer start request. This is the
108    * host where the peer should be started
109    */
110   struct GNUNET_TESTBED_Host *delegated_host;
111
112   /**
113    * The host which will contacted to delegate the peer start request
114    */
115   struct GNUNET_TESTBED_Host *slave_host;
116
117   /**
118    * The configuration to be used to connect to slave host
119    */
120   const struct GNUNET_CONFIGURATION_Handle *slave_cfg;
121
122   /**
123    * GNUNET_YES if the slave should be started (and stopped) by us; GNUNET_NO
124    * if we are just allowed to use the slave via TCP/IP
125    */
126   int is_subordinate;
127 };
128
129
130 /**
131  * handle for host registration
132  */
133 struct GNUNET_TESTBED_HostRegistrationHandle
134 {
135   /**
136    * The host being registered
137    */
138   struct GNUNET_TESTBED_Host *host;
139
140   /**
141    * The controller at which this host is being registered
142    */
143   struct GNUNET_TESTBED_Controller *c;
144
145   /**
146    * The Registartion completion callback
147    */
148   GNUNET_TESTBED_HostRegistrationCompletion cc;
149
150   /**
151    * The closure for above callback
152    */
153   void *cc_cls;
154 };
155
156
157 /**
158  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
159  * controller (testbed service)
160  *
161  * @param c the controller handler
162  * @param msg message received
163  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
164  *           not
165  */
166 static int
167 handle_addhostconfirm (struct GNUNET_TESTBED_Controller *c,
168                        const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
169 {
170   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
171   char *emsg;
172   uint16_t msg_size;
173
174   rh = c->rh;
175   if (NULL == rh)
176   {  
177     return GNUNET_OK;    
178   }
179   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
180   {
181     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
182                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
183     return GNUNET_OK;
184   }
185   c->rh = NULL;
186   msg_size = ntohs (msg->header.size);
187   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
188   {
189     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
190     GNUNET_TESTBED_mark_host_registered_at_  (rh->host, c);
191     rh->cc (rh->cc_cls, NULL);
192     GNUNET_free (rh);
193     return GNUNET_OK;
194   } 
195   /* We have an error message */
196   emsg = (char *) &msg[1];
197   if ('\0' != emsg[msg_size - 
198                    sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
199   {
200     GNUNET_break (0);
201     GNUNET_free (rh);
202     return GNUNET_NO;
203   }  
204   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
205        ntohl (msg->host_id), emsg);
206   rh->cc (rh->cc_cls, emsg);
207   GNUNET_free (rh);
208   return GNUNET_OK;
209 }
210
211
212 /**
213  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
214  * controller (testbed service)
215  *
216  * @param c the controller handler
217  * @param msg message received
218  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
219  *           not
220  */
221 static int
222 handle_opsuccess (struct GNUNET_TESTBED_Controller *c,
223                   const struct
224                   GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg)
225 {
226   struct GNUNET_TESTBED_Operation *op;
227   struct GNUNET_TESTBED_EventInformation *event;
228   uint64_t op_id;
229   
230   op_id = GNUNET_ntohll (msg->operation_id);
231   LOG_DEBUG ("Operation %ul successful\n", op_id);
232   for (op = c->op_head; NULL != op; op = op->next)
233   {
234     if (op->operation_id == op_id)
235       break;
236   }
237   if (NULL == op)
238   {
239     LOG_DEBUG ("Operation not found\n");
240     return GNUNET_YES;
241   }
242   event = NULL;
243   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
244     event = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_EventInformation));
245   if (NULL != event)
246     event->type = GNUNET_TESTBED_ET_OPERATION_FINISHED; 
247   switch (op->type)
248   {
249   case OP_PEER_DESTROY:
250     {
251       struct PeerDestroyData *data;
252       
253       if (NULL != event)
254       {
255         event->details.operation_finished.operation = op;
256         event->details.operation_finished.op_cls = NULL;
257         event->details.operation_finished.emsg = NULL;
258         event->details.operation_finished.pit = GNUNET_TESTBED_PIT_GENERIC;
259         event->details.operation_finished.op_result.generic = NULL;
260       }
261       data = (struct PeerDestroyData *) op->data;
262       if (NULL != data->peer->details)
263       {
264         if (NULL != data->peer->details->cfg)
265           GNUNET_CONFIGURATION_destroy (data->peer->details->cfg);
266         //PEER_DETAILS
267       }
268       GNUNET_free (data->peer);
269       GNUNET_free (data);
270       //PEERDESTROYDATA
271     }
272     break;
273   default:
274     GNUNET_break (0);
275   }
276   if (NULL != event)
277   {
278     if (NULL != c->cc)
279       c->cc (c->cc_cls, event);
280     GNUNET_free (event);
281   }
282   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
283   GNUNET_free (op);
284   return GNUNET_YES;  
285 }
286
287
288 /**
289  * Handler for messages from controller (testbed service)
290  *
291  * @param cls the controller handler
292  * @param msg message received, NULL on timeout or fatal error
293  */
294 static void 
295 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
296 {
297   struct GNUNET_TESTBED_Controller *c = cls;  
298   int status;
299
300   c->in_receive = GNUNET_NO;
301   /* FIXME: Add checks for message integrity */
302   if (NULL == msg)
303   {
304     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
305     return;
306   }
307   status = GNUNET_OK;
308   switch (ntohs (msg->type))
309   {
310   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
311     status =
312       handle_addhostconfirm (c, (const struct
313                                  GNUNET_TESTBED_HostConfirmedMessage *) msg);
314     break;
315   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
316     status =
317       handle_opsuccess (c, (const struct
318                             GNUNET_TESTBED_GenericOperationSuccessEventMessage
319                             *) msg);
320     break;
321   default:
322     GNUNET_break (0);
323   }
324   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
325   {
326     c->in_receive = GNUNET_YES;
327     GNUNET_CLIENT_receive (c->client, &message_handler, c,
328                            GNUNET_TIME_UNIT_FOREVER_REL);    
329   }
330 }
331
332
333 /**
334  * Function called to notify a client about the connection begin ready to queue
335  * more data.  "buf" will be NULL and "size" zero if the connection was closed
336  * for writing in the meantime.
337  *
338  * @param cls closure
339  * @param size number of bytes available in buf
340  * @param buf where the callee should write the message
341  * @return number of bytes written to buf
342  */
343 static size_t
344 transmit_ready_notify (void *cls, size_t size, void *buf)
345 {
346   struct GNUNET_TESTBED_Controller *c = cls;
347   struct MessageQueue *mq_entry;
348
349   c->th = NULL;
350   mq_entry = c->mq_head;
351   GNUNET_assert (NULL != mq_entry);
352   if ((0 == size) && (NULL == buf)) /* Timeout */
353   {
354     LOG_DEBUG ("Message sending timed out -- retrying\n");
355     c->th =
356       GNUNET_CLIENT_notify_transmit_ready (c->client,
357                                            ntohs (mq_entry->msg->size),
358                                            TIMEOUT_REL,
359                                            GNUNET_YES, &transmit_ready_notify,
360                                            c);
361     return 0;
362   }
363   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
364   size = ntohs (mq_entry->msg->size);  
365   memcpy (buf, mq_entry->msg, size);
366   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
367              ntohs (mq_entry->msg->type), size);
368   GNUNET_free (mq_entry->msg);
369   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
370   GNUNET_free (mq_entry);
371   mq_entry = c->mq_head;
372   if (NULL != mq_entry)
373     c->th = 
374       GNUNET_CLIENT_notify_transmit_ready (c->client,
375                                            ntohs (mq_entry->msg->size),
376                                            TIMEOUT_REL,
377                                            GNUNET_YES, &transmit_ready_notify,
378                                            c);
379   if (GNUNET_NO == c->in_receive)
380   {
381     c->in_receive = GNUNET_YES;
382     GNUNET_CLIENT_receive (c->client, &message_handler, c,
383                            GNUNET_TIME_UNIT_FOREVER_REL);
384   }
385   return size;
386 }
387
388
389 /**
390  * Queues a message in send queue for sending to the service
391  *
392  * @param controller the handle to the controller
393  * @param msg the message to queue
394  */
395 void
396 GNUNET_TESTBED_queue_message (struct GNUNET_TESTBED_Controller *controller,
397                               struct GNUNET_MessageHeader *msg)
398 {
399   struct MessageQueue *mq_entry;
400   uint16_t type;
401   uint16_t size;
402
403   type = ntohs (msg->type);
404   size = ntohs (msg->size);
405   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
406                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
407   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
408   mq_entry->msg = msg;
409   LOG (GNUNET_ERROR_TYPE_DEBUG,
410        "Queueing message of type %u, size %u for sending\n", type,
411        ntohs (msg->size));
412   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
413                                     mq_entry);
414   if (NULL == controller->th)
415     controller->th = 
416       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
417                                            TIMEOUT_REL,
418                                            GNUNET_YES, &transmit_ready_notify,
419                                            controller);
420 }
421
422
423 /**
424  * Handle for controller process
425  */
426 struct GNUNET_TESTBED_ControllerProc
427 {
428   /**
429    * The process handle
430    */
431   struct GNUNET_HELPER_Handle *helper;
432
433   /**
434    * The host where the helper is run
435    */
436   struct GNUNET_TESTBED_Host *host;
437
438   /**
439    * The controller error callback
440    */
441   GNUNET_TESTBED_ControllerStatusCallback cb;
442
443   /**
444    * The closure for the above callback
445    */
446   void *cls;
447
448   /**
449    * The send handle for the helper
450    */
451   struct GNUNET_HELPER_SendHandle *shandle;
452
453   /**
454    * The message corresponding to send handle
455    */
456   struct GNUNET_MessageHeader *msg;
457
458   /**
459    * The port number for ssh; used for helpers starting ssh
460    */
461   char *port;
462
463   /**
464    * The ssh destination string; used for helpers starting ssh
465    */
466   char *dst;
467
468   /**
469    * The configuration of the running testbed service
470    */
471   struct GNUNET_CONFIGURATION_Handle *cfg;
472
473 };
474
475
476 /**
477  * Functions with this signature are called whenever a
478  * complete message is received by the tokenizer.
479  *
480  * Do not call GNUNET_SERVER_mst_destroy in callback
481  *
482  * @param cls closure
483  * @param client identification of the client
484  * @param message the actual message
485  *
486  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
487  */
488 static int helper_mst (void *cls, void *client,
489                        const struct GNUNET_MessageHeader *message)
490 {
491   struct GNUNET_TESTBED_ControllerProc *cp = cls;
492   const struct GNUNET_TESTBED_HelperReply *msg;
493   const char *hostname;
494   char *config;
495   uLongf config_size;
496   uLongf xconfig_size;
497     
498   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
499   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) 
500                  < ntohs (msg->header.size));
501   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY 
502                  == ntohs (msg->header.type));
503   config_size = (uLongf) ntohs (msg->config_size);
504   xconfig_size = (uLongf) (ntohs (msg->header.size)
505                            - sizeof (struct GNUNET_TESTBED_HelperReply));
506   config = GNUNET_malloc (config_size);
507   GNUNET_assert (Z_OK == uncompress ((Bytef *) config, &config_size,
508                                      (const Bytef *) &msg[1], xconfig_size));
509   GNUNET_assert (NULL == cp->cfg);
510   cp->cfg = GNUNET_CONFIGURATION_create ();
511   GNUNET_assert (GNUNET_CONFIGURATION_deserialize (cp->cfg, config, 
512                                                    config_size, GNUNET_NO));
513   GNUNET_free (config);
514   if ((NULL == cp->host) || 
515       (NULL == (hostname = GNUNET_TESTBED_host_get_hostname_ (cp->host))))
516     hostname = "localhost";
517   /* Change the hostname so that we can connect to it */
518   GNUNET_CONFIGURATION_set_value_string (cp->cfg, "testbed", "hostname", 
519                                          hostname);
520   cp->cb (cp->cls, cp->cfg, GNUNET_OK);
521   return GNUNET_OK;
522 }
523
524
525 /**
526  * Continuation function from GNUNET_HELPER_send()
527  * 
528  * @param cls closure
529  * @param result GNUNET_OK on success,
530  *               GNUNET_NO if helper process died
531  *               GNUNET_SYSERR during GNUNET_HELPER_stop
532  */
533 static void 
534 clear_msg (void *cls, int result)
535 {
536   struct GNUNET_TESTBED_ControllerProc *cp = cls;
537   
538   GNUNET_assert (NULL != cp->shandle);
539   cp->shandle = NULL;
540   GNUNET_free (cp->msg);
541 }
542
543
544 /**
545  * Callback that will be called when the helper process dies. This is not called
546  * when the helper process is stoped using GNUNET_HELPER_stop()
547  *
548  * @param cls the closure from GNUNET_HELPER_start()
549  */
550 static void 
551 helper_exp_cb (void *cls)
552 {
553   struct GNUNET_TESTBED_ControllerProc *cp = cls;
554   GNUNET_TESTBED_ControllerStatusCallback cb;
555   void *cb_cls;
556
557   cb = cp->cb;
558   cb_cls = cp->cls;
559   GNUNET_TESTBED_controller_stop (cp);
560   if (NULL != cb)
561     cb (cb_cls, NULL, GNUNET_SYSERR);
562 }
563
564
565 /**
566  * Starts a controller process at the host. FIXME: add controller start callback
567  * with the configuration with which the controller is started
568  *
569  * @param controller_ip the ip address of the controller. Will be set as TRUSTED
570  *          host when starting testbed controller at host
571  * @param host the host where the controller has to be started; NULL for
572  *          localhost
573  * @param cfg template configuration to use for the remote controller; the
574  *          remote controller will be started with a slightly modified
575  *          configuration (port numbers, unix domain sockets and service home
576  *          values are changed as per TESTING library on the remote host)
577  * @param cb function called when the controller is successfully started or
578  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
579  *          called if cb is called with GNUNET_SYSERR as status. Will never be
580  *          called in the same task as 'GNUNET_TESTBED_controller_start'
581  *          (synchronous errors will be signalled by returning NULL). This
582  *          parameter cannot be NULL.
583  * @param cls closure for above callbacks
584  * @return the controller process handle, NULL on errors
585  */
586 struct GNUNET_TESTBED_ControllerProc *
587 GNUNET_TESTBED_controller_start (const char *controller_ip,
588                                  struct GNUNET_TESTBED_Host *host,
589                                  const struct GNUNET_CONFIGURATION_Handle *cfg,
590                                  GNUNET_TESTBED_ControllerStatusCallback cb,
591                                  void *cls)
592 {
593   struct GNUNET_TESTBED_ControllerProc *cp;
594   struct GNUNET_TESTBED_HelperInit *msg;
595   
596   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
597   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
598   {
599     char * const binary_argv[] = {
600       "gnunet-testbed-helper", NULL
601     };
602
603     cp->helper = GNUNET_HELPER_start ("gnunet-testbed-helper", binary_argv, 
604                                       &helper_mst, &helper_exp_cb, cp);
605   }
606   else
607   {
608     char *remote_args[6 + 1];
609     unsigned int argp;
610     const char *username;
611     const char *hostname;
612
613     username = GNUNET_TESTBED_host_get_username_ (host);
614     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
615     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
616     if (NULL == username)
617       GNUNET_asprintf (&cp->dst, "%s", hostname);
618     else 
619       GNUNET_asprintf (&cp->dst, "%s@%s", hostname, username);
620     argp = 0;
621     remote_args[argp++] = "ssh";
622     remote_args[argp++] = "-p";
623     remote_args[argp++] = cp->port;
624     remote_args[argp++] = "-q";
625     remote_args[argp++] = cp->dst;
626     remote_args[argp++] = "gnunet-testbed-helper";
627     remote_args[argp++] = NULL;
628     GNUNET_assert (argp == 6 + 1);
629     cp->helper = GNUNET_HELPER_start ("ssh", remote_args,
630                                       &helper_mst, &helper_exp_cb, cp);
631   }
632   if (NULL == cp->helper)
633   {
634     GNUNET_free_non_null (cp->port);
635     GNUNET_free_non_null (cp->dst);
636     GNUNET_free (cp);
637     return NULL;
638   }
639   cp->host = host;
640   cp->cb = cb;
641   cp->cls = cls;
642   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, cfg);
643   cp->msg = &msg->header;
644   cp->shandle = GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO,
645                                     &clear_msg, cp);
646   if (NULL == cp->shandle)
647   {
648     GNUNET_free (msg);
649     GNUNET_TESTBED_controller_stop (cp);
650     return NULL;
651   }
652   return cp;
653 }
654
655
656 /**
657  * Stop the controller process (also will terminate all peers and controllers
658  * dependent on this controller).  This function blocks until the testbed has
659  * been fully terminated (!).
660  *
661  * @param cproc the controller process handle
662  */
663 void
664 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cp)
665 {
666   if (NULL != cp->shandle)
667     GNUNET_HELPER_send_cancel (cp->shandle);
668   GNUNET_HELPER_stop (cp->helper);
669   if (NULL != cp->cfg)
670     GNUNET_CONFIGURATION_destroy (cp->cfg);
671   GNUNET_free_non_null (cp->port);
672   GNUNET_free_non_null (cp->dst);
673   GNUNET_free (cp);
674 }
675
676
677 /**
678  * Start a controller process using the given configuration at the
679  * given host.
680  *
681  * @param cfg configuration to use
682  * @param host host to run the controller on; This should be the same host if
683  *          the controller was previously started with
684  *          GNUNET_TESTBED_controller_start; NULL for localhost
685  * @param event_mask bit mask with set of events to call 'cc' for;
686  *                   or-ed values of "1LL" shifted by the
687  *                   respective 'enum GNUNET_TESTBED_EventType'
688  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
689  * @param cc controller callback to invoke on events
690  * @param cc_cls closure for cc
691  * @return handle to the controller
692  */
693 struct GNUNET_TESTBED_Controller *
694 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
695                                    struct GNUNET_TESTBED_Host *host,
696                                    uint64_t event_mask,
697                                    GNUNET_TESTBED_ControllerCallback cc,
698                                    void *cc_cls)
699 {
700   struct GNUNET_TESTBED_Controller *controller;
701   struct GNUNET_TESTBED_InitMessage *msg;
702
703   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
704   controller->cc = cc;
705   controller->cc_cls = cc_cls;
706   controller->event_mask = event_mask;
707   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
708   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);  
709   if (NULL == controller->client)
710   {
711     GNUNET_TESTBED_controller_disconnect (controller);
712     return NULL;
713   }
714   if (NULL == host)
715   {
716     host = GNUNET_TESTBED_host_create_by_id_ (0);
717     if (NULL == host)
718     {
719       LOG (GNUNET_ERROR_TYPE_WARNING,
720            "Treating NULL host as localhost. Multiple references to localhost. "
721            " May break when localhost freed before calling disconnect \n");
722       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
723     }
724     else
725     {
726       controller->aux_host = GNUNET_YES;
727     }
728   }
729   GNUNET_assert (NULL != host);
730   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage));
731   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
732   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage));
733   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
734   msg->event_mask = GNUNET_htonll (controller->event_mask);
735   GNUNET_TESTBED_queue_message (controller, (struct GNUNET_MessageHeader *) msg);
736   return controller;
737 }
738
739
740 /**
741  * Configure shared services at a controller.  Using this function,
742  * you can specify that certain services (such as "resolver")
743  * should not be run for each peer but instead be shared
744  * across N peers on the specified host.  This function
745  * must be called before any peers are created at the host.
746  * 
747  * @param controller controller to configure
748  * @param service_name name of the service to share
749  * @param num_peers number of peers that should share one instance
750  *        of the specified service (1 for no sharing is the default),
751  *        use 0 to disable the service
752  */
753 void
754 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
755                                              const char *service_name,
756                                              uint32_t num_peers)
757 {
758   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
759   uint16_t service_name_size;
760   uint16_t msg_size;
761   
762   service_name_size = strlen (service_name) + 1;
763   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
764     + service_name_size;
765   msg = GNUNET_malloc (msg_size);
766   msg->header.size = htons (msg_size);
767   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
768   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
769   msg->num_peers = htonl (num_peers);
770   memcpy (&msg[1], service_name, service_name_size);
771   GNUNET_TESTBED_queue_message (controller, (struct GNUNET_MessageHeader *) msg);
772 }
773
774
775 /**
776  * disconnects from the controller.
777  *
778  * @param controller handle to controller to stop
779  */
780 void
781 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *controller)
782 {
783   struct MessageQueue *mq_entry;
784
785   if (NULL != controller->th)
786     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
787  /* Clear the message queue */
788   while (NULL != (mq_entry = controller->mq_head))
789   {
790     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
791                                  controller->mq_tail,
792                                  mq_entry);
793     GNUNET_free (mq_entry->msg);
794     GNUNET_free (mq_entry);
795   }
796   if (NULL != controller->client)
797     GNUNET_CLIENT_disconnect (controller->client);
798   GNUNET_CONFIGURATION_destroy (controller->cfg);
799   if (GNUNET_YES == controller->aux_host)
800     GNUNET_TESTBED_host_destroy (controller->host);
801   GNUNET_free (controller);
802 }
803
804
805 /**
806  * Register a host with the controller
807  *
808  * @param controller the controller handle
809  * @param host the host to register
810  * @param cc the completion callback to call to inform the status of
811  *          registration. After calling this callback the registration handle
812  *          will be invalid. Cannot be NULL.
813  * @param cc_cls the closure for the cc
814  * @return handle to the host registration which can be used to cancel the
815  *           registration 
816  */
817 struct GNUNET_TESTBED_HostRegistrationHandle *
818 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
819                               struct GNUNET_TESTBED_Host *host,
820                               GNUNET_TESTBED_HostRegistrationCompletion cc,
821                               void *cc_cls)
822 {
823   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
824   struct GNUNET_TESTBED_AddHostMessage *msg;
825   const char *username;
826   const char *hostname;
827   uint16_t msg_size;
828   uint16_t user_name_length;
829
830   if (NULL != controller->rh)
831     return NULL;
832   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
833   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
834   {
835     LOG (GNUNET_ERROR_TYPE_WARNING,
836          "Host hostname: %s already registered\n",
837          (NULL == hostname) ? "localhost" : hostname);
838     return NULL;
839   }  
840   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
841   rh->host = host;
842   rh->c = controller;
843   GNUNET_assert (NULL != cc);
844   rh->cc = cc;
845   rh->cc_cls = cc_cls;
846   controller->rh = rh;
847   username = GNUNET_TESTBED_host_get_username_ (host);
848   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
849   user_name_length = 0;
850   if (NULL != username)
851   {
852     user_name_length = strlen (username) + 1;
853     msg_size += user_name_length;
854   }
855   /* FIXME: what happens when hostname is NULL? localhost */
856   GNUNET_assert (NULL != hostname);
857   msg_size += strlen (hostname) + 1;
858   msg = GNUNET_malloc (msg_size);
859   msg->header.size = htons (msg_size);
860   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
861   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
862   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
863   msg->user_name_length = htons (user_name_length);
864   if (NULL != username)
865     memcpy (&msg[1], username, user_name_length);
866   strcpy (((void *) &msg[1]) + user_name_length, hostname);
867   GNUNET_TESTBED_queue_message (controller, (struct GNUNET_MessageHeader *) msg);
868   return rh;
869 }
870
871
872 /**
873  * Cancel the pending registration. Note that if the registration message is
874  * already sent to the service the cancellation has only the effect that the
875  * registration completion callback for the registration is never called.
876  *
877  * @param handle the registration handle to cancel
878  */
879 void
880 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
881                                     *handle)
882 {
883   if (handle != handle->c->rh)
884   {
885     GNUNET_break (0);
886     return;
887   }
888   handle->c->rh = NULL;
889   GNUNET_free (handle);  
890 }
891
892
893 /**
894  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
895  * serialized and compressed
896  *
897  * @param master handle to the master controller who creates the association
898  * @param delegated_host requests to which host should be delegated; cannot be NULL
899  * @param slave_host which host is used to run the slave controller; use NULL to
900  *          make the master controller connect to the delegated host
901  * @param sxcfg serialized and compressed configuration
902  * @param sxcfg_size the size scfg
903  * @param scfg_size the size of uncompressed serialized configuration
904  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
905  *          be started by the master controller; GNUNET_NO if we are just
906  *          allowed to use the slave via TCP/IP
907  */
908 void
909 GNUNET_TESTBED_controller_link_2 (struct GNUNET_TESTBED_Controller *master,
910                                   struct GNUNET_TESTBED_Host *delegated_host,
911                                   struct GNUNET_TESTBED_Host *slave_host,
912                                   const char *sxcfg,
913                                   size_t sxcfg_size,
914                                   size_t scfg_size,
915                                   int is_subordinate)
916 {
917   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
918   uint16_t msg_size;
919
920   GNUNET_assert (GNUNET_YES == 
921                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
922   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
923     GNUNET_assert (GNUNET_YES == 
924                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
925   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
926   msg = GNUNET_malloc (msg_size);
927   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);  
928   msg->header.size = htons (msg_size);
929   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
930   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ 
931                               ((NULL != slave_host) ? slave_host : master->host));
932   msg->config_size = htons ((uint16_t) scfg_size);
933   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
934   memcpy (&msg[1], sxcfg, sxcfg_size);
935   GNUNET_TESTBED_queue_message (master, (struct GNUNET_MessageHeader *) msg);
936 }
937
938
939 /**
940  * Compresses given configuration using zlib compress
941  *
942  * @param config the serialized configuration
943  * @param size the size of config
944  * @param xconfig will be set to the compressed configuration (memory is fresly
945  *          allocated) 
946  * @return the size of the xconfig
947  */
948 size_t
949 GNUNET_TESTBED_compress_config (const char *config, size_t size,
950                                 char **xconfig)
951 {
952   size_t xsize;
953   
954   xsize = compressBound ((uLong) size);
955   *xconfig = GNUNET_malloc (xsize);
956   GNUNET_assert (Z_OK ==
957                  compress2 ((Bytef *)* xconfig, (uLongf *) &xsize,
958                             (const Bytef *) config, (uLongf) size, 
959                             Z_BEST_SPEED));
960   return xsize;
961 }
962                                 
963
964 /**
965  * Create a link from slave controller to delegated controller. Whenever the
966  * master controller is asked to start a peer at the delegated controller the
967  * request will be routed towards slave controller (if a route exists). The
968  * slave controller will then route it to the delegated controller. The
969  * configuration of the slave controller is given and to be used to either
970  * create the slave controller or to connect to an existing slave controller
971  * process.  'is_subordinate' specifies if the given slave controller should be
972  * started and managed by the master controller, or if the slave already has a
973  * master and this is just a secondary master that is also allowed to use the
974  * existing slave.
975  *
976  * @param master handle to the master controller who creates the association
977  * @param delegated_host requests to which host should be delegated
978  * @param slave_host which host is used to run the slave controller 
979  * @param slave_cfg configuration to use for the slave controller
980  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
981  *                       by the master controller; GNUNET_NO if we are just
982  *                       allowed to use the slave via TCP/IP
983  */
984 void
985 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
986                                 struct GNUNET_TESTBED_Host *delegated_host,
987                                 struct GNUNET_TESTBED_Host *slave_host,
988                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
989                                 int is_subordinate)
990 {
991   char *config;
992   char *cconfig;
993   size_t cc_size;
994   size_t config_size;  
995   
996   GNUNET_assert (GNUNET_YES == 
997                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
998   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
999     GNUNET_assert (GNUNET_YES == 
1000                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1001   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
1002   cc_size = GNUNET_TESTBED_compress_config (config, config_size, &cconfig);
1003   GNUNET_free (config);
1004   GNUNET_assert ((UINT16_MAX -
1005                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
1006                   >= cc_size); /* Configuration doesn't fit in 1 message */
1007   GNUNET_TESTBED_controller_link_2 (master, delegated_host, slave_host,
1008                                     (const char *) cconfig,
1009                                     cc_size, config_size, is_subordinate);
1010   GNUNET_free (cconfig);
1011 }
1012
1013
1014 /**
1015  * Ask the testbed controller to write the current overlay topology to
1016  * a file.  Naturally, the file will only contain a snapshot as the
1017  * topology may evolve all the time.
1018  *
1019  * @param controller overlay controller to inspect
1020  * @param filename name of the file the topology should
1021  *        be written to.
1022  */
1023 void
1024 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
1025                                                const char *filename)
1026 {
1027   GNUNET_break (0);
1028 }
1029
1030
1031
1032 /* end of testbed_api.c */