-handling peer get configuration at client
[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   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
277   GNUNET_free (op);
278   if (NULL != event)
279   {
280     if (NULL != c->cc)
281       c->cc (c->cc_cls, event);
282     GNUNET_free (event);
283   }
284   return GNUNET_YES;  
285 }
286
287
288 /**
289  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS message from
290  * controller (testbed service)
291  *
292  * @param c the controller handler
293  * @param msg message received
294  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
295  *           not
296  */
297 static int
298 handle_peer_create_success (struct GNUNET_TESTBED_Controller *c,
299                             const struct
300                             GNUNET_TESTBED_PeerCreateSuccessEventMessage *msg)
301 {
302   struct GNUNET_TESTBED_Operation *op;
303   struct PeerCreateData *data;
304   struct GNUNET_TESTBED_Peer *peer;
305   GNUNET_TESTBED_PeerCreateCallback cb;
306   void *cls;
307   uint64_t op_id;
308
309   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage)
310                  == ntohs (msg->header.size));
311   op_id = GNUNET_ntohll (msg->operation_id);
312   for (op = c->op_head; NULL != op; op = op->next)
313   {
314     if (op->operation_id == op_id)
315       break;
316   }
317   if (NULL == op)
318   {
319     LOG_DEBUG ("Operation not found\n");
320     return GNUNET_YES;
321   }
322   GNUNET_assert (OP_PEER_CREATE == op->type);
323   GNUNET_assert (NULL != op->data);
324   data = op->data;
325   GNUNET_assert (NULL != data->peer);
326   peer = data->peer;
327   GNUNET_assert (peer->unique_id == ntohl (msg->peer_id));
328   cb = data->cb;
329   cls = data->cls;
330   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
331   GNUNET_free (data);
332   GNUNET_free (op);
333   if (NULL != cb)
334     cb (cls, peer, NULL);
335   return GNUNET_YES;
336 }
337
338
339 /**
340  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT message from
341  * controller (testbed service)
342  *
343  * @param c the controller handler
344  * @param msg message received
345  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
346  *           not
347  */
348 static int
349 handle_peer_event (struct GNUNET_TESTBED_Controller *c,
350                    const struct GNUNET_TESTBED_PeerEventMessage *msg)
351 {
352   struct GNUNET_TESTBED_Operation *op;
353   struct GNUNET_TESTBED_Peer *peer;
354   struct GNUNET_TESTBED_EventInformation event;
355   uint64_t op_id;
356
357   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerEventMessage)
358                  == ntohs (msg->header.size));
359   op_id = GNUNET_ntohll (msg->operation_id);
360   for (op = c->op_head; NULL != op; op = op->next)
361   {
362     if (op->operation_id == op_id)
363       break;
364   }
365   if (NULL == op)
366   {
367     LOG_DEBUG ("Operation not found\n");
368     return GNUNET_YES;
369   }
370   GNUNET_assert ((OP_PEER_START == op->type) || (OP_PEER_STOP == op->type));
371   peer = op->data;
372   GNUNET_assert (NULL != peer);
373   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
374   switch (event.type)
375   {
376   case GNUNET_TESTBED_ET_PEER_START:
377     event.details.peer_start.host = peer->host;
378     event.details.peer_start.peer = peer;
379     break;
380   case GNUNET_TESTBED_ET_PEER_STOP:
381     event.details.peer_stop.peer = peer;  
382     break;
383   default:
384     GNUNET_assert (0);          /* We should never reach this state */
385   }  
386   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
387   GNUNET_free (op);
388   if (0 != ((GNUNET_TESTBED_ET_PEER_START | GNUNET_TESTBED_ET_PEER_STOP)
389             & c->event_mask))
390   {
391     if (NULL != c->cc)
392       c->cc (c->cc_cls, &event);
393   }
394   return GNUNET_YES;
395 }
396
397
398 /**
399  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG message from
400  * controller (testbed service)
401  *
402  * @param c the controller handler
403  * @param msg message received
404  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
405  *           not
406  */
407 static int
408 handle_peer_config (struct GNUNET_TESTBED_Controller *c,
409                     const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *msg)
410 {
411   struct GNUNET_TESTBED_Operation *op;
412   struct GNUNET_TESTBED_Peer *peer;
413   struct GNUNET_TESTBED_EventInformation info;
414   uint64_t op_id;
415   
416   op_id = GNUNET_ntohll (msg->operation_id);
417   for (op = c->op_head; NULL != op; op = op->next)
418   {
419     if (op->operation_id == op_id)
420       break;
421   }
422   if (NULL == op)
423   {
424     LOG_DEBUG ("Operation not found");
425     return GNUNET_YES;
426   }
427   peer = op->data;  
428   GNUNET_assert (NULL != peer);
429   GNUNET_assert (ntohl (msg->peer_id) == peer->unique_id);
430   if (0 == (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
431   {
432     GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
433     GNUNET_free (op);
434     return GNUNET_YES;
435   }
436   info.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
437   info.details.operation_finished.operation = op;
438   info.details.operation_finished.op_cls = NULL;
439   info.details.operation_finished.emsg = NULL;
440   info.details.operation_finished.pit = op->operation_id;
441   switch (op->operation_id)
442   {
443   case GNUNET_TESTBED_PIT_IDENTITY:
444     {
445       struct GNUNET_PeerIdentity *peer_identity;
446
447       peer_identity = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
448       (void) memcpy (peer_identity, &msg->peer_identity, sizeof (struct GNUNET_PeerIdentity));
449       info.details.operation_finished.op_result.pid = peer_identity;
450     }
451     break;
452   case GNUNET_TESTBED_PIT_CONFIGURATION:
453     {
454       struct GNUNET_CONFIGURATION_Handle *cfg;
455       char *config;
456       uLong config_size;
457       int ret;
458       uint16_t msize;
459       
460       config_size = (uLong) ntohs (msg->config_size);
461       config = GNUNET_malloc (config_size);
462       msize = ntohs (msg->header.size);
463       msize -= sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
464       if (Z_OK != (ret = uncompress ((Bytef *) config, &config_size,
465                                      (const Bytef *) &msg[1], (uLong) msize)))
466         GNUNET_assert (0);
467       cfg = GNUNET_CONFIGURATION_create ();
468       GNUNET_assert (GNUNET_OK == 
469                      GNUNET_CONFIGURATION_deserialize (cfg, config,
470                                                        (size_t) config_size, GNUNET_NO));
471       info.details.operation_finished.op_result.cfg = cfg;
472     }
473     break;
474   case GNUNET_TESTBED_PIT_GENERIC:
475     GNUNET_assert (0);          /* never reach here */
476     break;
477   }
478   c->cc (c->cc_cls, &info);
479   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
480   GNUNET_free (op);
481   return GNUNET_YES;
482 }
483
484
485 /**
486  * Handler for messages from controller (testbed service)
487  *
488  * @param cls the controller handler
489  * @param msg message received, NULL on timeout or fatal error
490  */
491 static void 
492 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
493 {
494   struct GNUNET_TESTBED_Controller *c = cls;  
495   int status;
496
497   c->in_receive = GNUNET_NO;
498   /* FIXME: Add checks for message integrity */
499   if (NULL == msg)
500   {
501     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
502     return;
503   }
504   status = GNUNET_OK;
505   switch (ntohs (msg->type))
506   {
507   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
508     status =
509       handle_addhostconfirm (c, (const struct
510                                  GNUNET_TESTBED_HostConfirmedMessage *) msg);
511     break;
512   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
513     status =
514       handle_opsuccess (c, (const struct
515                             GNUNET_TESTBED_GenericOperationSuccessEventMessage
516                             *) msg);
517     break;
518   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS:
519     status =
520       handle_peer_create_success 
521       (c, (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *)msg);
522     break;
523   case GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT:
524     status =
525       handle_peer_event (c, (const struct GNUNET_TESTBED_PeerEventMessage *) msg);
526     break;
527   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG:
528     status = 
529       handle_peer_config 
530       (c, (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *) msg);
531   default:
532     GNUNET_break (0);
533   }
534   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
535   {
536     c->in_receive = GNUNET_YES;
537     GNUNET_CLIENT_receive (c->client, &message_handler, c,
538                            GNUNET_TIME_UNIT_FOREVER_REL);    
539   }
540 }
541
542
543 /**
544  * Function called to notify a client about the connection begin ready to queue
545  * more data.  "buf" will be NULL and "size" zero if the connection was closed
546  * for writing in the meantime.
547  *
548  * @param cls closure
549  * @param size number of bytes available in buf
550  * @param buf where the callee should write the message
551  * @return number of bytes written to buf
552  */
553 static size_t
554 transmit_ready_notify (void *cls, size_t size, void *buf)
555 {
556   struct GNUNET_TESTBED_Controller *c = cls;
557   struct MessageQueue *mq_entry;
558
559   c->th = NULL;
560   mq_entry = c->mq_head;
561   GNUNET_assert (NULL != mq_entry);
562   if ((0 == size) && (NULL == buf)) /* Timeout */
563   {
564     LOG_DEBUG ("Message sending timed out -- retrying\n");
565     c->th =
566       GNUNET_CLIENT_notify_transmit_ready (c->client,
567                                            ntohs (mq_entry->msg->size),
568                                            TIMEOUT_REL,
569                                            GNUNET_YES, &transmit_ready_notify,
570                                            c);
571     return 0;
572   }
573   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
574   size = ntohs (mq_entry->msg->size);  
575   memcpy (buf, mq_entry->msg, size);
576   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
577              ntohs (mq_entry->msg->type), size);
578   GNUNET_free (mq_entry->msg);
579   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
580   GNUNET_free (mq_entry);
581   mq_entry = c->mq_head;
582   if (NULL != mq_entry)
583     c->th = 
584       GNUNET_CLIENT_notify_transmit_ready (c->client,
585                                            ntohs (mq_entry->msg->size),
586                                            TIMEOUT_REL,
587                                            GNUNET_YES, &transmit_ready_notify,
588                                            c);
589   if (GNUNET_NO == c->in_receive)
590   {
591     c->in_receive = GNUNET_YES;
592     GNUNET_CLIENT_receive (c->client, &message_handler, c,
593                            GNUNET_TIME_UNIT_FOREVER_REL);
594   }
595   return size;
596 }
597
598
599 /**
600  * Queues a message in send queue for sending to the service
601  *
602  * @param controller the handle to the controller
603  * @param msg the message to queue
604  */
605 void
606 GNUNET_TESTBED_queue_message_ (struct GNUNET_TESTBED_Controller *controller,
607                                struct GNUNET_MessageHeader *msg)
608 {
609   struct MessageQueue *mq_entry;
610   uint16_t type;
611   uint16_t size;
612
613   type = ntohs (msg->type);
614   size = ntohs (msg->size);
615   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
616                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
617   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
618   mq_entry->msg = msg;
619   LOG (GNUNET_ERROR_TYPE_DEBUG,
620        "Queueing message of type %u, size %u for sending\n", type,
621        ntohs (msg->size));
622   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
623                                     mq_entry);
624   if (NULL == controller->th)
625     controller->th = 
626       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
627                                            TIMEOUT_REL,
628                                            GNUNET_YES, &transmit_ready_notify,
629                                            controller);
630 }
631
632
633 /**
634  * Handle for controller process
635  */
636 struct GNUNET_TESTBED_ControllerProc
637 {
638   /**
639    * The process handle
640    */
641   struct GNUNET_HELPER_Handle *helper;
642
643   /**
644    * The host where the helper is run
645    */
646   struct GNUNET_TESTBED_Host *host;
647
648   /**
649    * The controller error callback
650    */
651   GNUNET_TESTBED_ControllerStatusCallback cb;
652
653   /**
654    * The closure for the above callback
655    */
656   void *cls;
657
658   /**
659    * The send handle for the helper
660    */
661   struct GNUNET_HELPER_SendHandle *shandle;
662
663   /**
664    * The message corresponding to send handle
665    */
666   struct GNUNET_MessageHeader *msg;
667
668   /**
669    * The port number for ssh; used for helpers starting ssh
670    */
671   char *port;
672
673   /**
674    * The ssh destination string; used for helpers starting ssh
675    */
676   char *dst;
677
678   /**
679    * The configuration of the running testbed service
680    */
681   struct GNUNET_CONFIGURATION_Handle *cfg;
682
683 };
684
685
686 /**
687  * Functions with this signature are called whenever a
688  * complete message is received by the tokenizer.
689  *
690  * Do not call GNUNET_SERVER_mst_destroy in callback
691  *
692  * @param cls closure
693  * @param client identification of the client
694  * @param message the actual message
695  *
696  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
697  */
698 static int helper_mst (void *cls, void *client,
699                        const struct GNUNET_MessageHeader *message)
700 {
701   struct GNUNET_TESTBED_ControllerProc *cp = cls;
702   const struct GNUNET_TESTBED_HelperReply *msg;
703   const char *hostname;
704   char *config;
705   uLongf config_size;
706   uLongf xconfig_size;
707     
708   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
709   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) 
710                  < ntohs (msg->header.size));
711   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY 
712                  == ntohs (msg->header.type));
713   config_size = (uLongf) ntohs (msg->config_size);
714   xconfig_size = (uLongf) (ntohs (msg->header.size)
715                            - sizeof (struct GNUNET_TESTBED_HelperReply));
716   config = GNUNET_malloc (config_size);
717   GNUNET_assert (Z_OK == uncompress ((Bytef *) config, &config_size,
718                                      (const Bytef *) &msg[1], xconfig_size));
719   GNUNET_assert (NULL == cp->cfg);
720   cp->cfg = GNUNET_CONFIGURATION_create ();
721   GNUNET_assert (GNUNET_CONFIGURATION_deserialize (cp->cfg, config, 
722                                                    config_size, GNUNET_NO));
723   GNUNET_free (config);
724   if ((NULL == cp->host) || 
725       (NULL == (hostname = GNUNET_TESTBED_host_get_hostname_ (cp->host))))
726     hostname = "localhost";
727   /* Change the hostname so that we can connect to it */
728   GNUNET_CONFIGURATION_set_value_string (cp->cfg, "testbed", "hostname", 
729                                          hostname);
730   cp->cb (cp->cls, cp->cfg, GNUNET_OK);
731   return GNUNET_OK;
732 }
733
734
735 /**
736  * Continuation function from GNUNET_HELPER_send()
737  * 
738  * @param cls closure
739  * @param result GNUNET_OK on success,
740  *               GNUNET_NO if helper process died
741  *               GNUNET_SYSERR during GNUNET_HELPER_stop
742  */
743 static void 
744 clear_msg (void *cls, int result)
745 {
746   struct GNUNET_TESTBED_ControllerProc *cp = cls;
747   
748   GNUNET_assert (NULL != cp->shandle);
749   cp->shandle = NULL;
750   GNUNET_free (cp->msg);
751 }
752
753
754 /**
755  * Callback that will be called when the helper process dies. This is not called
756  * when the helper process is stoped using GNUNET_HELPER_stop()
757  *
758  * @param cls the closure from GNUNET_HELPER_start()
759  */
760 static void 
761 helper_exp_cb (void *cls)
762 {
763   struct GNUNET_TESTBED_ControllerProc *cp = cls;
764   GNUNET_TESTBED_ControllerStatusCallback cb;
765   void *cb_cls;
766
767   cb = cp->cb;
768   cb_cls = cp->cls;
769   GNUNET_TESTBED_controller_stop (cp);
770   if (NULL != cb)
771     cb (cb_cls, NULL, GNUNET_SYSERR);
772 }
773
774
775 /**
776  * Starts a controller process at the host. FIXME: add controller start callback
777  * with the configuration with which the controller is started
778  *
779  * @param controller_ip the ip address of the controller. Will be set as TRUSTED
780  *          host when starting testbed controller at host
781  * @param host the host where the controller has to be started; NULL for
782  *          localhost
783  * @param cfg template configuration to use for the remote controller; the
784  *          remote controller will be started with a slightly modified
785  *          configuration (port numbers, unix domain sockets and service home
786  *          values are changed as per TESTING library on the remote host)
787  * @param cb function called when the controller is successfully started or
788  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
789  *          called if cb is called with GNUNET_SYSERR as status. Will never be
790  *          called in the same task as 'GNUNET_TESTBED_controller_start'
791  *          (synchronous errors will be signalled by returning NULL). This
792  *          parameter cannot be NULL.
793  * @param cls closure for above callbacks
794  * @return the controller process handle, NULL on errors
795  */
796 struct GNUNET_TESTBED_ControllerProc *
797 GNUNET_TESTBED_controller_start (const char *controller_ip,
798                                  struct GNUNET_TESTBED_Host *host,
799                                  const struct GNUNET_CONFIGURATION_Handle *cfg,
800                                  GNUNET_TESTBED_ControllerStatusCallback cb,
801                                  void *cls)
802 {
803   struct GNUNET_TESTBED_ControllerProc *cp;
804   struct GNUNET_TESTBED_HelperInit *msg;
805   
806   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
807   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
808   {
809     char * const binary_argv[] = {
810       "gnunet-testbed-helper", NULL
811     };
812
813     cp->helper = GNUNET_HELPER_start ("gnunet-testbed-helper", binary_argv, 
814                                       &helper_mst, &helper_exp_cb, cp);
815   }
816   else
817   {
818     char *remote_args[6 + 1];
819     unsigned int argp;
820     const char *username;
821     const char *hostname;
822
823     username = GNUNET_TESTBED_host_get_username_ (host);
824     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
825     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
826     if (NULL == username)
827       GNUNET_asprintf (&cp->dst, "%s", hostname);
828     else 
829       GNUNET_asprintf (&cp->dst, "%s@%s", hostname, username);
830     argp = 0;
831     remote_args[argp++] = "ssh";
832     remote_args[argp++] = "-p";
833     remote_args[argp++] = cp->port;
834     remote_args[argp++] = "-q";
835     remote_args[argp++] = cp->dst;
836     remote_args[argp++] = "gnunet-testbed-helper";
837     remote_args[argp++] = NULL;
838     GNUNET_assert (argp == 6 + 1);
839     cp->helper = GNUNET_HELPER_start ("ssh", remote_args,
840                                       &helper_mst, &helper_exp_cb, cp);
841   }
842   if (NULL == cp->helper)
843   {
844     GNUNET_free_non_null (cp->port);
845     GNUNET_free_non_null (cp->dst);
846     GNUNET_free (cp);
847     return NULL;
848   }
849   cp->host = host;
850   cp->cb = cb;
851   cp->cls = cls;
852   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, cfg);
853   cp->msg = &msg->header;
854   cp->shandle = GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO,
855                                     &clear_msg, cp);
856   if (NULL == cp->shandle)
857   {
858     GNUNET_free (msg);
859     GNUNET_TESTBED_controller_stop (cp);
860     return NULL;
861   }
862   return cp;
863 }
864
865
866 /**
867  * Stop the controller process (also will terminate all peers and controllers
868  * dependent on this controller).  This function blocks until the testbed has
869  * been fully terminated (!).
870  *
871  * @param cproc the controller process handle
872  */
873 void
874 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
875 {
876   if (NULL != cproc->shandle)
877     GNUNET_HELPER_send_cancel (cproc->shandle);
878   GNUNET_HELPER_stop (cproc->helper);
879   if (NULL != cproc->cfg)
880     GNUNET_CONFIGURATION_destroy (cproc->cfg);
881   GNUNET_free_non_null (cproc->port);
882   GNUNET_free_non_null (cproc->dst);
883   GNUNET_free (cproc);
884 }
885
886
887 /**
888  * Start a controller process using the given configuration at the
889  * given host.
890  *
891  * @param cfg configuration to use
892  * @param host host to run the controller on; This should be the same host if
893  *          the controller was previously started with
894  *          GNUNET_TESTBED_controller_start; NULL for localhost
895  * @param event_mask bit mask with set of events to call 'cc' for;
896  *                   or-ed values of "1LL" shifted by the
897  *                   respective 'enum GNUNET_TESTBED_EventType'
898  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
899  * @param cc controller callback to invoke on events
900  * @param cc_cls closure for cc
901  * @return handle to the controller
902  */
903 struct GNUNET_TESTBED_Controller *
904 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
905                                    struct GNUNET_TESTBED_Host *host,
906                                    uint64_t event_mask,
907                                    GNUNET_TESTBED_ControllerCallback cc,
908                                    void *cc_cls)
909 {
910   struct GNUNET_TESTBED_Controller *controller;
911   struct GNUNET_TESTBED_InitMessage *msg;
912
913   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
914   controller->cc = cc;
915   controller->cc_cls = cc_cls;
916   controller->event_mask = event_mask;
917   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
918   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);  
919   if (NULL == controller->client)
920   {
921     GNUNET_TESTBED_controller_disconnect (controller);
922     return NULL;
923   }
924   if (NULL == host)
925   {
926     host = GNUNET_TESTBED_host_create_by_id_ (0);
927     if (NULL == host)
928     {
929       LOG (GNUNET_ERROR_TYPE_WARNING,
930            "Treating NULL host as localhost. Multiple references to localhost. "
931            " May break when localhost freed before calling disconnect \n");
932       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
933     }
934     else
935     {
936       controller->aux_host = GNUNET_YES;
937     }
938   }
939   GNUNET_assert (NULL != host);
940   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage));
941   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
942   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage));
943   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
944   msg->event_mask = GNUNET_htonll (controller->event_mask);
945   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
946   return controller;
947 }
948
949
950 /**
951  * Configure shared services at a controller.  Using this function,
952  * you can specify that certain services (such as "resolver")
953  * should not be run for each peer but instead be shared
954  * across N peers on the specified host.  This function
955  * must be called before any peers are created at the host.
956  * 
957  * @param controller controller to configure
958  * @param service_name name of the service to share
959  * @param num_peers number of peers that should share one instance
960  *        of the specified service (1 for no sharing is the default),
961  *        use 0 to disable the service
962  */
963 void
964 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
965                                              const char *service_name,
966                                              uint32_t num_peers)
967 {
968   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
969   uint16_t service_name_size;
970   uint16_t msg_size;
971   
972   service_name_size = strlen (service_name) + 1;
973   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
974     + service_name_size;
975   msg = GNUNET_malloc (msg_size);
976   msg->header.size = htons (msg_size);
977   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
978   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
979   msg->num_peers = htonl (num_peers);
980   memcpy (&msg[1], service_name, service_name_size);
981   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
982 }
983
984
985 /**
986  * disconnects from the controller.
987  *
988  * @param controller handle to controller to stop
989  */
990 void
991 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *controller)
992 {
993   struct MessageQueue *mq_entry;
994
995   if (NULL != controller->th)
996     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
997  /* Clear the message queue */
998   while (NULL != (mq_entry = controller->mq_head))
999   {
1000     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
1001                                  controller->mq_tail,
1002                                  mq_entry);
1003     GNUNET_free (mq_entry->msg);
1004     GNUNET_free (mq_entry);
1005   }
1006   if (NULL != controller->client)
1007     GNUNET_CLIENT_disconnect (controller->client);
1008   GNUNET_CONFIGURATION_destroy (controller->cfg);
1009   if (GNUNET_YES == controller->aux_host)
1010     GNUNET_TESTBED_host_destroy (controller->host);
1011   GNUNET_free (controller);
1012 }
1013
1014
1015 /**
1016  * Register a host with the controller
1017  *
1018  * @param controller the controller handle
1019  * @param host the host to register
1020  * @param cc the completion callback to call to inform the status of
1021  *          registration. After calling this callback the registration handle
1022  *          will be invalid. Cannot be NULL.
1023  * @param cc_cls the closure for the cc
1024  * @return handle to the host registration which can be used to cancel the
1025  *           registration 
1026  */
1027 struct GNUNET_TESTBED_HostRegistrationHandle *
1028 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1029                               struct GNUNET_TESTBED_Host *host,
1030                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1031                               void *cc_cls)
1032 {
1033   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1034   struct GNUNET_TESTBED_AddHostMessage *msg;
1035   const char *username;
1036   const char *hostname;
1037   uint16_t msg_size;
1038   uint16_t user_name_length;
1039
1040   if (NULL != controller->rh)
1041     return NULL;
1042   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1043   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1044   {
1045     LOG (GNUNET_ERROR_TYPE_WARNING,
1046          "Host hostname: %s already registered\n",
1047          (NULL == hostname) ? "localhost" : hostname);
1048     return NULL;
1049   }  
1050   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1051   rh->host = host;
1052   rh->c = controller;
1053   GNUNET_assert (NULL != cc);
1054   rh->cc = cc;
1055   rh->cc_cls = cc_cls;
1056   controller->rh = rh;
1057   username = GNUNET_TESTBED_host_get_username_ (host);
1058   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1059   user_name_length = 0;
1060   if (NULL != username)
1061   {
1062     user_name_length = strlen (username) + 1;
1063     msg_size += user_name_length;
1064   }
1065   /* FIXME: what happens when hostname is NULL? localhost */
1066   GNUNET_assert (NULL != hostname);
1067   msg_size += strlen (hostname) + 1;
1068   msg = GNUNET_malloc (msg_size);
1069   msg->header.size = htons (msg_size);
1070   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
1071   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1072   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1073   msg->user_name_length = htons (user_name_length);
1074   if (NULL != username)
1075     memcpy (&msg[1], username, user_name_length);
1076   strcpy (((void *) &msg[1]) + user_name_length, hostname);
1077   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
1078   return rh;
1079 }
1080
1081
1082 /**
1083  * Cancel the pending registration. Note that if the registration message is
1084  * already sent to the service the cancellation has only the effect that the
1085  * registration completion callback for the registration is never called.
1086  *
1087  * @param handle the registration handle to cancel
1088  */
1089 void
1090 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1091                                     *handle)
1092 {
1093   if (handle != handle->c->rh)
1094   {
1095     GNUNET_break (0);
1096     return;
1097   }
1098   handle->c->rh = NULL;
1099   GNUNET_free (handle);  
1100 }
1101
1102
1103 /**
1104  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
1105  * serialized and compressed
1106  *
1107  * @param master handle to the master controller who creates the association
1108  * @param delegated_host requests to which host should be delegated; cannot be NULL
1109  * @param slave_host which host is used to run the slave controller; use NULL to
1110  *          make the master controller connect to the delegated host
1111  * @param sxcfg serialized and compressed configuration
1112  * @param sxcfg_size the size scfg
1113  * @param scfg_size the size of uncompressed serialized configuration
1114  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1115  *          be started by the master controller; GNUNET_NO if we are just
1116  *          allowed to use the slave via TCP/IP
1117  */
1118 void
1119 GNUNET_TESTBED_controller_link_2 (struct GNUNET_TESTBED_Controller *master,
1120                                   struct GNUNET_TESTBED_Host *delegated_host,
1121                                   struct GNUNET_TESTBED_Host *slave_host,
1122                                   const char *sxcfg,
1123                                   size_t sxcfg_size,
1124                                   size_t scfg_size,
1125                                   int is_subordinate)
1126 {
1127   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1128   uint16_t msg_size;
1129
1130   GNUNET_assert (GNUNET_YES == 
1131                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1132   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1133     GNUNET_assert (GNUNET_YES == 
1134                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1135   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1136   msg = GNUNET_malloc (msg_size);
1137   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);  
1138   msg->header.size = htons (msg_size);
1139   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
1140   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ 
1141                               ((NULL != slave_host) ? slave_host : master->host));
1142   msg->config_size = htons ((uint16_t) scfg_size);
1143   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
1144   memcpy (&msg[1], sxcfg, sxcfg_size);
1145   GNUNET_TESTBED_queue_message_ (master, (struct GNUNET_MessageHeader *) msg);
1146 }
1147
1148
1149 /**
1150  * Compresses given configuration using zlib compress
1151  *
1152  * @param config the serialized configuration
1153  * @param size the size of config
1154  * @param xconfig will be set to the compressed configuration (memory is fresly
1155  *          allocated) 
1156  * @return the size of the xconfig
1157  */
1158 size_t
1159 GNUNET_TESTBED_compress_config_ (const char *config, size_t size,
1160                                  char **xconfig)
1161 {
1162   size_t xsize;
1163   
1164   xsize = compressBound ((uLong) size);
1165   *xconfig = GNUNET_malloc (xsize);
1166   GNUNET_assert (Z_OK ==
1167                  compress2 ((Bytef *)* xconfig, (uLongf *) &xsize,
1168                             (const Bytef *) config, (uLongf) size, 
1169                             Z_BEST_SPEED));
1170   return xsize;
1171 }
1172                                 
1173
1174 /**
1175  * Create a link from slave controller to delegated controller. Whenever the
1176  * master controller is asked to start a peer at the delegated controller the
1177  * request will be routed towards slave controller (if a route exists). The
1178  * slave controller will then route it to the delegated controller. The
1179  * configuration of the slave controller is given and to be used to either
1180  * create the slave controller or to connect to an existing slave controller
1181  * process.  'is_subordinate' specifies if the given slave controller should be
1182  * started and managed by the master controller, or if the slave already has a
1183  * master and this is just a secondary master that is also allowed to use the
1184  * existing slave.
1185  *
1186  * @param master handle to the master controller who creates the association
1187  * @param delegated_host requests to which host should be delegated
1188  * @param slave_host which host is used to run the slave controller 
1189  * @param slave_cfg configuration to use for the slave controller
1190  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
1191  *                       by the master controller; GNUNET_NO if we are just
1192  *                       allowed to use the slave via TCP/IP
1193  */
1194 void
1195 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
1196                                 struct GNUNET_TESTBED_Host *delegated_host,
1197                                 struct GNUNET_TESTBED_Host *slave_host,
1198                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
1199                                 int is_subordinate)
1200 {
1201   char *config;
1202   char *cconfig;
1203   size_t cc_size;
1204   size_t config_size;  
1205   
1206   GNUNET_assert (GNUNET_YES == 
1207                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1208   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1209     GNUNET_assert (GNUNET_YES == 
1210                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1211   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
1212   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1213   GNUNET_free (config);
1214   GNUNET_assert ((UINT16_MAX -
1215                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
1216                   >= cc_size); /* Configuration doesn't fit in 1 message */
1217   GNUNET_TESTBED_controller_link_2 (master, delegated_host, slave_host,
1218                                     (const char *) cconfig,
1219                                     cc_size, config_size, is_subordinate);
1220   GNUNET_free (cconfig);
1221 }
1222
1223
1224 /**
1225  * Ask the testbed controller to write the current overlay topology to
1226  * a file.  Naturally, the file will only contain a snapshot as the
1227  * topology may evolve all the time.
1228  *
1229  * @param controller overlay controller to inspect
1230  * @param filename name of the file the topology should
1231  *        be written to.
1232  */
1233 void
1234 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
1235                                                const char *filename)
1236 {
1237   GNUNET_break (0);
1238 }
1239
1240
1241 /**
1242  * Creates a helper initialization message. Only for testing.
1243  *
1244  * @param cname the ip address of the controlling host
1245  * @param cfg the configuration that has to used to start the testbed service
1246  *          thru helper
1247  * @return the initialization message
1248  */
1249 struct GNUNET_TESTBED_HelperInit *
1250 GNUNET_TESTBED_create_helper_init_msg_ (const char *cname,
1251                                          const struct GNUNET_CONFIGURATION_Handle *cfg)
1252 {
1253   struct GNUNET_TESTBED_HelperInit *msg;
1254   char *config;
1255   char *xconfig;
1256   size_t config_size;
1257   size_t xconfig_size;
1258   uint16_t cname_len;
1259   uint16_t msg_size;
1260
1261   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
1262   GNUNET_assert (NULL != config);
1263   xconfig_size =
1264     GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
1265   GNUNET_free (config);
1266   cname_len = strlen (cname);
1267   msg_size = xconfig_size + cname_len + 1 + 
1268     sizeof (struct GNUNET_TESTBED_HelperInit);
1269   msg = GNUNET_realloc (xconfig, msg_size);
1270   (void) memmove ( ((void *) &msg[1]) + cname_len + 1, msg, xconfig_size);
1271   msg->header.size = htons (msg_size);
1272   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
1273   msg->cname_size = htons (cname_len);
1274   msg->config_size = htons (config_size);
1275   (void) strcpy ((char *) &msg[1], cname);
1276   return msg;
1277 }
1278
1279
1280 /* end of testbed_api.c */