added ssh batch mode param
[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 #include "testbed_api_operations.h"
44
45 /**
46  * Generic logging shorthand
47  */
48 #define LOG(kind, ...)                          \
49   GNUNET_log_from (kind, "testbed-api", __VA_ARGS__);
50
51 /**
52  * Debug logging
53  */
54 #define LOG_DEBUG(...)                          \
55   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__);
56
57 /**
58  * Relative time seconds shorthand
59  */
60 #define TIME_REL_SECS(sec) \
61   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, sec)
62
63
64 /**
65  * Default server message sending retry timeout
66  */
67 #define TIMEOUT_REL TIME_REL_SECS(1)
68
69
70 /**
71  * The message queue for sending messages to the controller service
72  */
73 struct MessageQueue
74 {
75   /**
76    * The message to be sent
77    */
78   struct GNUNET_MessageHeader *msg;
79
80   /**
81    * next pointer for DLL
82    */
83   struct MessageQueue *next;
84   
85   /**
86    * prev pointer for DLL
87    */
88   struct MessageQueue *prev;
89 };
90
91
92 /**
93  * Structure for a controller link
94  */
95 struct ControllerLink
96 {
97   /**
98    * The next ptr for DLL
99    */
100   struct ControllerLink *next;
101
102   /**
103    * The prev ptr for DLL
104    */
105   struct ControllerLink *prev;
106
107   /**
108    * The host which will be referred in the peer start request. This is the
109    * host where the peer should be started
110    */
111   struct GNUNET_TESTBED_Host *delegated_host;
112
113   /**
114    * The host which will contacted to delegate the peer start request
115    */
116   struct GNUNET_TESTBED_Host *slave_host;
117
118   /**
119    * The configuration to be used to connect to slave host
120    */
121   const struct GNUNET_CONFIGURATION_Handle *slave_cfg;
122
123   /**
124    * GNUNET_YES if the slave should be started (and stopped) by us; GNUNET_NO
125    * if we are just allowed to use the slave via TCP/IP
126    */
127   int is_subordinate;
128 };
129
130
131 /**
132  * handle for host registration
133  */
134 struct GNUNET_TESTBED_HostRegistrationHandle
135 {
136   /**
137    * The host being registered
138    */
139   struct GNUNET_TESTBED_Host *host;
140
141   /**
142    * The controller at which this host is being registered
143    */
144   struct GNUNET_TESTBED_Controller *c;
145
146   /**
147    * The Registartion completion callback
148    */
149   GNUNET_TESTBED_HostRegistrationCompletion cc;
150
151   /**
152    * The closure for above callback
153    */
154   void *cc_cls;
155 };
156
157
158 /**
159  * Context data for forwarded Operation
160  */
161 struct ForwardedOperationData
162 {
163   
164   /**
165    * The callback to call when reply is available
166    */
167   GNUNET_CLIENT_MessageHandler cc;  
168
169   /**
170    * The closure for the above callback
171    */
172   void *cc_cls;
173   
174 };
175
176
177 /**
178  * Returns the operation context with the given id if found in the Operation
179  * context queues of the controller
180  *
181  * @param c the controller whose queues are searched
182  * @param id the id which has to be checked
183  * @return the matching operation context; NULL if no match found
184  */
185 static struct OperationContext *
186 find_opc (const struct GNUNET_TESTBED_Controller *c, const uint64_t id)
187 {
188   struct OperationContext *opc;
189
190   for (opc = c->ocq_head; NULL != opc; opc = opc->next)
191   {
192     if (id == opc->id)
193       return opc;
194   }
195   return NULL;
196 }
197
198
199 /**
200  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
201  * controller (testbed service)
202  *
203  * @param c the controller handler
204  * @param msg message received
205  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
206  *           not
207  */
208 static int
209 handle_addhostconfirm (struct GNUNET_TESTBED_Controller *c,
210                        const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
211 {
212   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
213   char *emsg;
214   uint16_t msg_size;
215
216   rh = c->rh;
217   if (NULL == rh)
218   {  
219     return GNUNET_OK;    
220   }
221   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
222   {
223     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
224                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
225     return GNUNET_OK;
226   }
227   c->rh = NULL;
228   msg_size = ntohs (msg->header.size);
229   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
230   {
231     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
232     GNUNET_TESTBED_mark_host_registered_at_  (rh->host, c);
233     rh->cc (rh->cc_cls, NULL);
234     GNUNET_free (rh);
235     return GNUNET_OK;
236   } 
237   /* We have an error message */
238   emsg = (char *) &msg[1];
239   if ('\0' != emsg[msg_size - 
240                    sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
241   {
242     GNUNET_break (0);
243     GNUNET_free (rh);
244     return GNUNET_NO;
245   }  
246   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
247        ntohl (msg->host_id), emsg);
248   rh->cc (rh->cc_cls, emsg);
249   GNUNET_free (rh);
250   return GNUNET_OK;
251 }
252
253
254 /**
255  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
256  * controller (testbed service)
257  *
258  * @param c the controller handler
259  * @param msg message received
260  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
261  *           not
262  */
263 static int
264 handle_opsuccess (struct GNUNET_TESTBED_Controller *c,
265                   const struct
266                   GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg)
267 {
268   struct OperationContext *opc;
269   struct GNUNET_TESTBED_EventInformation *event;
270   uint64_t op_id;
271   
272   op_id = GNUNET_ntohll (msg->operation_id);
273   LOG_DEBUG ("Operation %ul successful\n", op_id);
274   if (NULL == (opc = find_opc (c, op_id)))
275   {
276     LOG_DEBUG ("Operation not found\n");
277     return GNUNET_YES;
278   }
279   event = NULL;
280   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
281     event = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_EventInformation));
282   if (NULL != event)
283     event->type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
284   switch (opc->type)
285   {
286   case OP_FORWARDED:
287     {
288       struct ForwardedOperationData *fo_data;
289     
290       fo_data = opc->data;
291       if (NULL != fo_data->cc)
292         fo_data->cc (fo_data->cc_cls, (const struct GNUNET_MessageHeader *) msg);
293       GNUNET_CONTAINER_DLL_remove (c->ocq_head, c->ocq_tail, opc);
294       GNUNET_free (fo_data);
295       GNUNET_free (opc);    
296       return GNUNET_YES;    
297     }
298     break;
299   case OP_PEER_DESTROY:
300     {
301       struct GNUNET_TESTBED_Peer *peer;     
302       peer = opc->data;
303       GNUNET_free (peer);
304       opc->data = NULL;
305       //PEERDESTROYDATA
306     }
307     break;
308   case OP_LINK_CONTROLLERS:    
309     break;
310   default:
311     GNUNET_assert (0);
312   }
313   if (NULL != event)
314   {
315     event->details.operation_finished.operation = opc->op;
316     event->details.operation_finished.op_cls = NULL;
317     event->details.operation_finished.emsg = NULL;
318     event->details.operation_finished.pit = GNUNET_TESTBED_PIT_GENERIC;
319     event->details.operation_finished.op_result.generic = NULL;
320   }
321   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
322   opc->state = OPC_STATE_FINISHED;
323   if (NULL != event)
324   {
325     if (NULL != c->cc)
326       c->cc (c->cc_cls, event);
327     GNUNET_free (event);
328   }  
329   return GNUNET_YES;  
330 }
331
332
333 /**
334  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS message from
335  * controller (testbed service)
336  *
337  * @param c the controller handler
338  * @param msg message received
339  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
340  *           not
341  */
342 static int
343 handle_peer_create_success (struct GNUNET_TESTBED_Controller *c,
344                             const struct
345                             GNUNET_TESTBED_PeerCreateSuccessEventMessage *msg)
346 {
347   struct OperationContext *opc;
348   struct PeerCreateData *data;
349   struct GNUNET_TESTBED_Peer *peer;
350   GNUNET_TESTBED_PeerCreateCallback cb;
351   void *cls;
352   uint64_t op_id;
353
354   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage)
355                  == ntohs (msg->header.size));
356   op_id = GNUNET_ntohll (msg->operation_id);
357   if (NULL == (opc = find_opc (c, op_id)))
358   {
359     LOG_DEBUG ("Operation context for PeerCreateSuccessEvent not found\n");
360     return GNUNET_YES;
361   }
362   if (OP_FORWARDED == opc->type)
363   {
364     struct ForwardedOperationData *fo_data;
365     
366     fo_data = opc->data;
367     if (NULL != fo_data->cc)
368       fo_data->cc (fo_data->cc_cls, (const struct GNUNET_MessageHeader *) msg);
369     GNUNET_CONTAINER_DLL_remove (c->ocq_head, c->ocq_tail, opc);
370     GNUNET_free (fo_data);
371     GNUNET_free (opc);    
372     return GNUNET_YES;    
373   }  
374   GNUNET_assert (OP_PEER_CREATE == opc->type);
375   GNUNET_assert (NULL != opc->data);
376   data = opc->data;
377   GNUNET_assert (NULL != data->peer);
378   peer = data->peer;
379   GNUNET_assert (peer->unique_id == ntohl (msg->peer_id));
380   peer->state = PS_CREATED;
381   cb = data->cb;
382   cls = data->cls;
383   GNUNET_free (opc->data);  
384   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
385   opc->state = OPC_STATE_FINISHED;
386   if (NULL != cb)
387     cb (cls, peer, NULL);
388   return GNUNET_YES;
389 }
390
391
392 /**
393  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT message from
394  * controller (testbed service)
395  *
396  * @param c the controller handler
397  * @param msg message received
398  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
399  *           not
400  */
401 static int
402 handle_peer_event (struct GNUNET_TESTBED_Controller *c,
403                    const struct GNUNET_TESTBED_PeerEventMessage *msg)
404 {
405   struct OperationContext *opc;
406   struct GNUNET_TESTBED_Peer *peer;
407   struct GNUNET_TESTBED_EventInformation event;
408   uint64_t op_id;
409
410   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerEventMessage)
411                  == ntohs (msg->header.size));
412   op_id = GNUNET_ntohll (msg->operation_id);
413   if (NULL == (opc = find_opc (c, op_id)))
414   {
415     LOG_DEBUG ("Operation not found\n");
416     return GNUNET_YES;
417   }
418   GNUNET_assert ((OP_PEER_START == opc->type) || (OP_PEER_STOP == opc->type));
419   peer = opc->data;
420   GNUNET_assert (NULL != peer);
421   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
422   switch (event.type)
423   {
424   case GNUNET_TESTBED_ET_PEER_START:
425     peer->state = PS_STARTED;
426     event.details.peer_start.host = peer->host;
427     event.details.peer_start.peer = peer;
428     break;
429   case GNUNET_TESTBED_ET_PEER_STOP:
430     peer->state = PS_STOPPED;    
431     event.details.peer_stop.peer = peer;  
432     break;
433   default:
434     GNUNET_assert (0);          /* We should never reach this state */
435   }
436   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
437   opc->state = OPC_STATE_FINISHED;
438   if (0 != ((GNUNET_TESTBED_ET_PEER_START | GNUNET_TESTBED_ET_PEER_STOP)
439             & c->event_mask))
440   {
441     if (NULL != c->cc)
442       c->cc (c->cc_cls, &event);
443   }    
444   return GNUNET_YES;
445 }
446
447
448 /**
449  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT message from
450  * controller (testbed service)
451  *
452  * @param c the controller handler
453  * @param msg message received
454  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
455  *           not
456  */
457 static int
458 handle_peer_conevent (struct GNUNET_TESTBED_Controller *c,
459                       const struct GNUNET_TESTBED_ConnectionEventMessage *msg)
460 {
461   struct OperationContext *opc;
462   struct OverlayConnectData *data;
463   struct GNUNET_TESTBED_EventInformation event;
464   uint64_t op_id;
465
466   op_id = GNUNET_ntohll (msg->operation_id);
467   if (NULL == (opc = find_opc (c, op_id)))
468   {
469     LOG_DEBUG ("Operation not found\n");
470     return GNUNET_YES;
471   }
472   data = opc->data;
473   GNUNET_assert (NULL != data);
474   GNUNET_assert ((ntohl (msg->peer1) == data->p1->unique_id)
475                   && (ntohl (msg->peer2) == data->p2->unique_id));
476   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
477   switch (event.type)
478   {
479   case GNUNET_TESTBED_ET_CONNECT:
480     event.details.peer_connect.peer1 = data->p1;
481     event.details.peer_connect.peer2 = data->p2;
482     break;
483   case GNUNET_TESTBED_ET_DISCONNECT:
484     GNUNET_assert (0);          /* FIXME: implement */
485     break;
486   default:
487     GNUNET_assert (0);          /* Should never reach here */
488     break;
489   }
490   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
491   opc->state = OPC_STATE_FINISHED;
492   GNUNET_free (data);
493   if (0 != ((GNUNET_TESTBED_ET_CONNECT | GNUNET_TESTBED_ET_DISCONNECT)
494             & c->event_mask))
495   {
496     if (NULL != c->cc)
497       c->cc (c->cc_cls, &event);
498   }
499   return GNUNET_YES;
500 }
501
502
503 /**
504  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG message from
505  * controller (testbed service)
506  *
507  * @param c the controller handler
508  * @param msg message received
509  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
510  *           not
511  */
512 static int
513 handle_peer_config (struct GNUNET_TESTBED_Controller *c,
514                     const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *msg)
515 {
516   struct OperationContext *opc;
517   struct GNUNET_TESTBED_Peer *peer;
518   struct PeerInfoData *data;
519   struct PeerInfoData2 *response_data;
520   struct GNUNET_TESTBED_EventInformation info;
521   uint64_t op_id;
522   
523   op_id = GNUNET_ntohll (msg->operation_id);
524   if (NULL == (opc = find_opc (c, op_id)))
525   {
526     LOG_DEBUG ("Operation not found\n");
527     return GNUNET_YES;
528   }
529   data = opc->data;
530   GNUNET_assert (NULL != data);
531   peer = data->peer;
532   GNUNET_assert (NULL != peer);
533   GNUNET_assert (ntohl (msg->peer_id) == peer->unique_id);
534   if (0 == (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
535   {
536     LOG_DEBUG ("Skipping operation callback as flag not set\n");
537     return GNUNET_YES;
538   }
539   response_data = GNUNET_malloc (sizeof (struct PeerInfoData2));
540   response_data->pit = data->pit;
541   GNUNET_free (data);
542   opc->data = NULL;
543   info.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
544   info.details.operation_finished.operation = opc->op;
545   info.details.operation_finished.op_cls = NULL;
546   info.details.operation_finished.emsg = NULL;
547   info.details.operation_finished.pit = response_data->pit;
548   switch (response_data->pit)
549   {
550   case GNUNET_TESTBED_PIT_IDENTITY:
551     {
552       struct GNUNET_PeerIdentity *peer_identity;
553
554       peer_identity = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
555       (void) memcpy (peer_identity, &msg->peer_identity, 
556                      sizeof (struct GNUNET_PeerIdentity));
557       response_data->details.peer_identity = peer_identity;      
558       info.details.operation_finished.op_result.pid = peer_identity;
559     }
560     break;
561   case GNUNET_TESTBED_PIT_CONFIGURATION:
562     {
563       struct GNUNET_CONFIGURATION_Handle *cfg;
564       char *config;
565       uLong config_size;
566       int ret;
567       uint16_t msize;
568       
569       config_size = (uLong) ntohs (msg->config_size);
570       config = GNUNET_malloc (config_size);
571       msize = ntohs (msg->header.size);
572       msize -= sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
573       if (Z_OK != (ret = uncompress ((Bytef *) config, &config_size,
574                                      (const Bytef *) &msg[1], (uLong) msize)))
575         GNUNET_assert (0);
576       cfg = GNUNET_CONFIGURATION_create (); /* Freed in oprelease_peer_getinfo */
577       GNUNET_assert (GNUNET_OK == 
578                      GNUNET_CONFIGURATION_deserialize (cfg, config,
579                                                        (size_t) config_size,
580                                                        GNUNET_NO));
581       GNUNET_free (config);
582       response_data->details.cfg = cfg;
583       info.details.operation_finished.op_result.cfg = cfg;
584     }
585     break;
586   case GNUNET_TESTBED_PIT_GENERIC:
587     GNUNET_assert (0);          /* never reach here */
588     break;
589   }
590   opc->data = response_data;
591   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
592   opc->state = OPC_STATE_FINISHED;
593   c->cc (c->cc_cls, &info);  
594   return GNUNET_YES;
595 }
596
597
598 /**
599  * Handler for messages from controller (testbed service)
600  *
601  * @param cls the controller handler
602  * @param msg message received, NULL on timeout or fatal error
603  */
604 static void 
605 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
606 {
607   struct GNUNET_TESTBED_Controller *c = cls;
608   int status;
609   uint16_t msize;
610
611   c->in_receive = GNUNET_NO;
612   /* FIXME: Add checks for message integrity */
613   if (NULL == msg)
614   {
615     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
616     return;
617   }
618   status = GNUNET_OK;
619   msize = ntohs (msg->size);
620   switch (ntohs (msg->type))
621   {
622   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
623     GNUNET_assert (msize >= sizeof (struct
624                                     GNUNET_TESTBED_HostConfirmedMessage));
625     status =
626       handle_addhostconfirm (c, (const struct GNUNET_TESTBED_HostConfirmedMessage *) msg);
627     break;
628   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
629     GNUNET_assert 
630       (msize == sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage));
631     status =
632       handle_opsuccess (c, (const struct
633                             GNUNET_TESTBED_GenericOperationSuccessEventMessage
634                             *) msg);
635     break;
636   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS:
637     GNUNET_assert (msize == 
638                    sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
639     status =
640       handle_peer_create_success 
641       (c, (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *)msg);
642     break;
643   case GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT:
644     GNUNET_assert (msize == sizeof (struct GNUNET_TESTBED_PeerEventMessage));
645     status =
646       handle_peer_event (c, (const struct GNUNET_TESTBED_PeerEventMessage *) msg);
647     
648     break;
649   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG:
650     GNUNET_assert (msize >= 
651                    sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage));
652     status = 
653       handle_peer_config 
654       (c, (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *)
655   msg);
656     break;
657   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT:
658     GNUNET_assert (msize ==
659                    sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
660     status = 
661       handle_peer_conevent (c, (const struct
662                                 GNUNET_TESTBED_ConnectionEventMessage *) msg);
663     break;
664   default:
665     GNUNET_break (0);
666   }
667   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
668   {
669     c->in_receive = GNUNET_YES;
670     GNUNET_CLIENT_receive (c->client, &message_handler, c,
671                            GNUNET_TIME_UNIT_FOREVER_REL);    
672   }
673 }
674
675
676 /**
677  * Function called to notify a client about the connection begin ready to queue
678  * more data.  "buf" will be NULL and "size" zero if the connection was closed
679  * for writing in the meantime.
680  *
681  * @param cls closure
682  * @param size number of bytes available in buf
683  * @param buf where the callee should write the message
684  * @return number of bytes written to buf
685  */
686 static size_t
687 transmit_ready_notify (void *cls, size_t size, void *buf)
688 {
689   struct GNUNET_TESTBED_Controller *c = cls;
690   struct MessageQueue *mq_entry;
691
692   c->th = NULL;
693   mq_entry = c->mq_head;
694   GNUNET_assert (NULL != mq_entry);
695   if ((0 == size) && (NULL == buf)) /* Timeout */
696   {
697     LOG_DEBUG ("Message sending timed out -- retrying\n");
698     c->th =
699       GNUNET_CLIENT_notify_transmit_ready (c->client,
700                                            ntohs (mq_entry->msg->size),
701                                            TIMEOUT_REL,
702                                            GNUNET_YES, &transmit_ready_notify,
703                                            c);
704     return 0;
705   }
706   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
707   size = ntohs (mq_entry->msg->size);  
708   memcpy (buf, mq_entry->msg, size);
709   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
710              ntohs (mq_entry->msg->type), size);
711   GNUNET_free (mq_entry->msg);
712   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
713   GNUNET_free (mq_entry);
714   mq_entry = c->mq_head;
715   if (NULL != mq_entry)
716     c->th = 
717       GNUNET_CLIENT_notify_transmit_ready (c->client,
718                                            ntohs (mq_entry->msg->size),
719                                            TIMEOUT_REL,
720                                            GNUNET_YES, &transmit_ready_notify,
721                                            c);
722   if (GNUNET_NO == c->in_receive)
723   {
724     c->in_receive = GNUNET_YES;
725     GNUNET_CLIENT_receive (c->client, &message_handler, c,
726                            GNUNET_TIME_UNIT_FOREVER_REL);
727   }
728   return size;
729 }
730
731
732 /**
733  * Queues a message in send queue for sending to the service
734  *
735  * @param controller the handle to the controller
736  * @param msg the message to queue
737  */
738 void
739 GNUNET_TESTBED_queue_message_ (struct GNUNET_TESTBED_Controller *controller,
740                                struct GNUNET_MessageHeader *msg)
741 {
742   struct MessageQueue *mq_entry;
743   uint16_t type;
744   uint16_t size;
745
746   type = ntohs (msg->type);
747   size = ntohs (msg->size);
748   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
749                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
750   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
751   mq_entry->msg = msg;
752   LOG (GNUNET_ERROR_TYPE_DEBUG,
753        "Queueing message of type %u, size %u for sending\n", type,
754        ntohs (msg->size));
755   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
756                                     mq_entry);
757   if (NULL == controller->th)
758     controller->th = 
759       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
760                                            TIMEOUT_REL,
761                                            GNUNET_YES, &transmit_ready_notify,
762                                            controller);
763 }
764
765
766 /**
767  * Sends the given message as an operation. The given callback is called when a
768  * reply for the operation is available.  Call
769  * GNUNET_TESTBED_forward_operation_msg_cancel_() to cleanup the returned
770  * operation context if the cc hasn't been called
771  *
772  * @param controller the controller to which the message has to be sent
773  * @param operation_id the operation id of the message
774  * @param msg the message to send
775  * @param cc the callback to call when reply is available
776  * @param cc_cls the closure for the above callback
777  * @return the operation context which can be used to cancel the forwarded
778  *           operation 
779  */
780 struct OperationContext *
781 GNUNET_TESTBED_forward_operation_msg_ (struct GNUNET_TESTBED_Controller
782                                        * controller,
783                                        uint64_t operation_id,
784                                        const struct GNUNET_MessageHeader *msg,
785                                        GNUNET_CLIENT_MessageHandler cc,
786                                        void *cc_cls)
787 {
788   struct OperationContext *opc;
789   struct ForwardedOperationData *data;
790   struct GNUNET_MessageHeader *dup_msg;  
791   uint16_t msize;
792   
793   data = GNUNET_malloc (sizeof (struct ForwardedOperationData));
794   data->cc = cc;
795   data->cc_cls = cc_cls;  
796   opc = GNUNET_malloc (sizeof (struct OperationContext));
797   opc->c = controller;  
798   opc->type = OP_FORWARDED;
799   opc->data = data;
800   opc->id = operation_id;
801   msize = ntohs (msg->size);
802   dup_msg = GNUNET_malloc (msize);
803   (void) memcpy (dup_msg, msg, msize);  
804   GNUNET_TESTBED_queue_message_ (opc->c, dup_msg);
805   GNUNET_CONTAINER_DLL_insert_tail (controller->ocq_head,
806                                     controller->ocq_tail, opc);
807   return opc;  
808 }
809
810
811 /**
812  * Function to cancel an operation created by simply forwarding an operation
813  * message.
814  *
815  * @param opc the operation context from GNUNET_TESTBED_forward_operation_msg_()
816  */
817 void
818 GNUNET_TESTBED_forward_operation_msg_cancel_ (struct OperationContext *opc)
819 {
820   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
821   GNUNET_free (opc->data);
822   GNUNET_free (opc);  
823 }
824
825
826 /**
827  * Handle for controller process
828  */
829 struct GNUNET_TESTBED_ControllerProc
830 {
831   /**
832    * The process handle
833    */
834   struct GNUNET_HELPER_Handle *helper;
835
836   /**
837    * The host where the helper is run
838    */
839   struct GNUNET_TESTBED_Host *host;
840
841   /**
842    * The controller error callback
843    */
844   GNUNET_TESTBED_ControllerStatusCallback cb;
845
846   /**
847    * The closure for the above callback
848    */
849   void *cls;
850
851   /**
852    * The send handle for the helper
853    */
854   struct GNUNET_HELPER_SendHandle *shandle;
855
856   /**
857    * The message corresponding to send handle
858    */
859   struct GNUNET_MessageHeader *msg;
860
861   /**
862    * The port number for ssh; used for helpers starting ssh
863    */
864   char *port;
865
866   /**
867    * The ssh destination string; used for helpers starting ssh
868    */
869   char *dst;
870
871   /**
872    * The configuration of the running testbed service
873    */
874   struct GNUNET_CONFIGURATION_Handle *cfg;
875
876 };
877
878
879 /**
880  * Functions with this signature are called whenever a
881  * complete message is received by the tokenizer.
882  *
883  * Do not call GNUNET_SERVER_mst_destroy in callback
884  *
885  * @param cls closure
886  * @param client identification of the client
887  * @param message the actual message
888  *
889  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
890  */
891 static int 
892 helper_mst (void *cls, void *client,
893             const struct GNUNET_MessageHeader *message)
894 {
895   struct GNUNET_TESTBED_ControllerProc *cp = cls;
896   const struct GNUNET_TESTBED_HelperReply *msg;
897   const char *hostname;
898   char *config;
899   uLongf config_size;
900   uLongf xconfig_size;
901     
902   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
903   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) 
904                  < ntohs (msg->header.size));
905   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY 
906                  == ntohs (msg->header.type));
907   config_size = (uLongf) ntohs (msg->config_size);
908   xconfig_size = (uLongf) (ntohs (msg->header.size)
909                            - sizeof (struct GNUNET_TESTBED_HelperReply));
910   config = GNUNET_malloc (config_size);
911   GNUNET_assert (Z_OK == uncompress ((Bytef *) config, &config_size,
912                                      (const Bytef *) &msg[1], xconfig_size));
913   GNUNET_assert (NULL == cp->cfg);
914   cp->cfg = GNUNET_CONFIGURATION_create ();
915   GNUNET_assert (GNUNET_CONFIGURATION_deserialize (cp->cfg, config, 
916                                                    config_size, GNUNET_NO));
917   GNUNET_free (config);
918   if ((NULL == cp->host) || 
919       (NULL == (hostname = GNUNET_TESTBED_host_get_hostname_ (cp->host))))
920     hostname = "localhost";
921   /* Change the hostname so that we can connect to it */
922   GNUNET_CONFIGURATION_set_value_string (cp->cfg, "testbed", "hostname", 
923                                          hostname);
924   cp->cb (cp->cls, cp->cfg, GNUNET_OK);
925   return GNUNET_OK;
926 }
927
928
929 /**
930  * Continuation function from GNUNET_HELPER_send()
931  * 
932  * @param cls closure
933  * @param result GNUNET_OK on success,
934  *               GNUNET_NO if helper process died
935  *               GNUNET_SYSERR during GNUNET_HELPER_stop
936  */
937 static void 
938 clear_msg (void *cls, int result)
939 {
940   struct GNUNET_TESTBED_ControllerProc *cp = cls;
941   
942   GNUNET_assert (NULL != cp->shandle);
943   cp->shandle = NULL;
944   GNUNET_free (cp->msg);
945 }
946
947
948 /**
949  * Callback that will be called when the helper process dies. This is not called
950  * when the helper process is stoped using GNUNET_HELPER_stop()
951  *
952  * @param cls the closure from GNUNET_HELPER_start()
953  */
954 static void 
955 helper_exp_cb (void *cls)
956 {
957   struct GNUNET_TESTBED_ControllerProc *cp = cls;
958   GNUNET_TESTBED_ControllerStatusCallback cb;
959   void *cb_cls;
960
961   cb = cp->cb;
962   cb_cls = cp->cls;
963   cp->helper = NULL;
964   GNUNET_TESTBED_controller_stop (cp);
965   if (NULL != cb)
966     cb (cb_cls, NULL, GNUNET_SYSERR);
967 }
968
969
970 /**
971  * Function to call to start a link-controllers type operation once all queues
972  * the operation is part of declare that the operation can be activated.
973  *
974  * @param cls the closure from GNUNET_TESTBED_operation_create_()
975  */
976 static void 
977 opstart_link_controllers (void *cls)
978 {
979   struct OperationContext *opc = cls;
980   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
981
982   GNUNET_assert (NULL != opc->data);
983   msg = opc->data;
984   opc->data = NULL;
985   opc->state = OPC_STATE_STARTED;
986   GNUNET_CONTAINER_DLL_insert_tail (opc->c->ocq_head, opc->c->ocq_tail, opc);
987   GNUNET_TESTBED_queue_message_ (opc->c, &msg->header);
988 }
989
990
991 /**
992  * Callback which will be called when link-controllers type operation is released
993  *
994  * @param cls the closure from GNUNET_TESTBED_operation_create_()
995  */
996 static void 
997 oprelease_link_controllers (void *cls)
998 {
999   struct OperationContext *opc = cls;
1000
1001   if (OPC_STATE_INIT == opc->state)
1002     GNUNET_free (opc->data);
1003   if (OPC_STATE_STARTED == opc->state)
1004     GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
1005   GNUNET_free (opc);
1006 }
1007
1008
1009 /**
1010  * Starts a controller process at the host. FIXME: add controller start callback
1011  * with the configuration with which the controller is started
1012  *
1013  * @param controller_ip the ip address of the controller. Will be set as TRUSTED
1014  *          host when starting testbed controller at host
1015  * @param host the host where the controller has to be started; NULL for
1016  *          localhost
1017  * @param cfg template configuration to use for the remote controller; the
1018  *          remote controller will be started with a slightly modified
1019  *          configuration (port numbers, unix domain sockets and service home
1020  *          values are changed as per TESTING library on the remote host)
1021  * @param cb function called when the controller is successfully started or
1022  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
1023  *          called if cb is called with GNUNET_SYSERR as status. Will never be
1024  *          called in the same task as 'GNUNET_TESTBED_controller_start'
1025  *          (synchronous errors will be signalled by returning NULL). This
1026  *          parameter cannot be NULL.
1027  * @param cls closure for above callbacks
1028  * @return the controller process handle, NULL on errors
1029  */
1030 struct GNUNET_TESTBED_ControllerProc *
1031 GNUNET_TESTBED_controller_start (const char *controller_ip,
1032                                  struct GNUNET_TESTBED_Host *host,
1033                                  const struct GNUNET_CONFIGURATION_Handle *cfg,
1034                                  GNUNET_TESTBED_ControllerStatusCallback cb,
1035                                  void *cls)
1036 {
1037   struct GNUNET_TESTBED_ControllerProc *cp;
1038   struct GNUNET_TESTBED_HelperInit *msg;
1039   
1040   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
1041   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
1042   {
1043     char * const binary_argv[] = {
1044       "gnunet-testbed-helper", NULL
1045     };
1046
1047     cp->helper = GNUNET_HELPER_start ("gnunet-testbed-helper", binary_argv, 
1048                                       &helper_mst, &helper_exp_cb, cp);
1049   }
1050   else
1051   {
1052     char *remote_args[8];
1053     unsigned int argp;
1054     const char *username;
1055     const char *hostname;
1056
1057     username = GNUNET_TESTBED_host_get_username_ (host);
1058     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1059     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
1060     if (NULL == username)
1061       GNUNET_asprintf (&cp->dst, "%s", hostname);
1062     else 
1063       GNUNET_asprintf (&cp->dst, "%s@%s", username, hostname);
1064     LOG_DEBUG ("Starting SSH to destination %s\n", cp->dst);
1065     argp = 0;
1066     remote_args[argp++] = "ssh";
1067     remote_args[argp++] = "-p";
1068     remote_args[argp++] = cp->port;
1069     remote_args[argp++] = "-o";
1070     remote_args[argp++] = "BatchMode=yes";
1071     remote_args[argp++] = cp->dst;
1072     remote_args[argp++] = "gnunet-testbed-helper";
1073     remote_args[argp++] = NULL;
1074     GNUNET_assert (argp == 8);
1075     cp->helper = GNUNET_HELPER_start ("ssh", remote_args,
1076                                       &helper_mst, &helper_exp_cb, cp);
1077   }
1078   if (NULL == cp->helper)
1079   {
1080     GNUNET_free_non_null (cp->port);
1081     GNUNET_free_non_null (cp->dst);
1082     GNUNET_free (cp);
1083     return NULL;
1084   }
1085   cp->host = host;
1086   cp->cb = cb;
1087   cp->cls = cls;
1088   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, cfg);
1089   cp->msg = &msg->header;
1090   cp->shandle = GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO,
1091                                     &clear_msg, cp);
1092   if (NULL == cp->shandle)
1093   {
1094     GNUNET_free (msg);
1095     GNUNET_TESTBED_controller_stop (cp);
1096     return NULL;
1097   }
1098   return cp;
1099 }
1100
1101
1102 /**
1103  * Stop the controller process (also will terminate all peers and controllers
1104  * dependent on this controller).  This function blocks until the testbed has
1105  * been fully terminated (!).
1106  *
1107  * @param cproc the controller process handle
1108  */
1109 void
1110 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
1111 {
1112   if (NULL != cproc->shandle)
1113     GNUNET_HELPER_send_cancel (cproc->shandle);
1114   if (NULL != cproc->helper)
1115     GNUNET_HELPER_stop (cproc->helper);
1116   if (NULL != cproc->cfg)
1117     GNUNET_CONFIGURATION_destroy (cproc->cfg);
1118   GNUNET_free_non_null (cproc->port);
1119   GNUNET_free_non_null (cproc->dst);
1120   GNUNET_free (cproc);
1121 }
1122
1123
1124 /**
1125  * Start a controller process using the given configuration at the
1126  * given host.
1127  *
1128  * @param cfg configuration to use
1129  * @param host host to run the controller on; This should be the same host if
1130  *          the controller was previously started with
1131  *          GNUNET_TESTBED_controller_start; NULL for localhost
1132  * @param event_mask bit mask with set of events to call 'cc' for;
1133  *                   or-ed values of "1LL" shifted by the
1134  *                   respective 'enum GNUNET_TESTBED_EventType'
1135  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
1136  * @param cc controller callback to invoke on events
1137  * @param cc_cls closure for cc
1138  * @return handle to the controller
1139  */
1140 struct GNUNET_TESTBED_Controller *
1141 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1142                                    struct GNUNET_TESTBED_Host *host,
1143                                    uint64_t event_mask,
1144                                    GNUNET_TESTBED_ControllerCallback cc,
1145                                    void *cc_cls)
1146 {
1147   struct GNUNET_TESTBED_Controller *controller;
1148   struct GNUNET_TESTBED_InitMessage *msg;
1149   const char *controller_hostname;
1150   unsigned long long max_parallel_peer_create;
1151
1152   if (GNUNET_OK !=
1153       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1154                                              "MAX_PARALLEL_PEER_CREATE",
1155                                              &max_parallel_peer_create))
1156   {
1157     GNUNET_break (0);
1158     return NULL;
1159   }                                                          
1160   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
1161   controller->cc = cc;
1162   controller->cc_cls = cc_cls;
1163   controller->event_mask = event_mask;
1164   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
1165   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);  
1166   if (NULL == controller->client)
1167   {
1168     GNUNET_TESTBED_controller_disconnect (controller);
1169     return NULL;
1170   }
1171   if (NULL == host)
1172   {
1173     host = GNUNET_TESTBED_host_create_by_id_ (0);
1174     if (NULL == host)           /* If the above host create fails */
1175     {
1176       LOG (GNUNET_ERROR_TYPE_WARNING,
1177            "Treating NULL host as localhost. Multiple references to localhost "
1178            "may break when localhost freed before calling disconnect \n");
1179       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
1180     }
1181     else
1182     {
1183       controller->aux_host = GNUNET_YES;
1184     }
1185   }
1186   GNUNET_assert (NULL != host);
1187   GNUNET_TESTBED_mark_host_registered_at_ (host, controller);
1188   controller->host = host;
1189   controller->opq_peer_create =
1190     GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1191                                             max_parallel_peer_create);
1192   controller_hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1193   if (NULL == controller_hostname)
1194     controller_hostname = "127.0.0.1";
1195   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage)
1196                        + strlen (controller_hostname) + 1);
1197   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
1198   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage)
1199                             + strlen (controller_hostname) + 1);
1200   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1201   msg->event_mask = GNUNET_htonll (controller->event_mask);
1202   strcpy ((char *) &msg[1], controller_hostname);
1203   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *)
1204                                  msg);  
1205   return controller;
1206 }
1207
1208
1209 /**
1210  * Configure shared services at a controller.  Using this function,
1211  * you can specify that certain services (such as "resolver")
1212  * should not be run for each peer but instead be shared
1213  * across N peers on the specified host.  This function
1214  * must be called before any peers are created at the host.
1215  * 
1216  * @param controller controller to configure
1217  * @param service_name name of the service to share
1218  * @param num_peers number of peers that should share one instance
1219  *        of the specified service (1 for no sharing is the default),
1220  *        use 0 to disable the service
1221  */
1222 void
1223 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
1224                                              const char *service_name,
1225                                              uint32_t num_peers)
1226 {
1227   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1228   uint16_t service_name_size;
1229   uint16_t msg_size;
1230   
1231   service_name_size = strlen (service_name) + 1;
1232   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
1233     + service_name_size;
1234   msg = GNUNET_malloc (msg_size);
1235   msg->header.size = htons (msg_size);
1236   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
1237   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
1238   msg->num_peers = htonl (num_peers);
1239   memcpy (&msg[1], service_name, service_name_size);
1240   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
1241 }
1242
1243
1244 /**
1245  * disconnects from the controller.
1246  *
1247  * @param controller handle to controller to stop
1248  */
1249 void
1250 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *controller)
1251 {
1252   struct MessageQueue *mq_entry;
1253
1254   if (NULL != controller->th)
1255     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
1256  /* Clear the message queue */
1257   while (NULL != (mq_entry = controller->mq_head))
1258   {
1259     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
1260                                  controller->mq_tail,
1261                                  mq_entry);
1262     GNUNET_free (mq_entry->msg);
1263     GNUNET_free (mq_entry);
1264   }
1265   if (NULL != controller->client)
1266     GNUNET_CLIENT_disconnect (controller->client);
1267   GNUNET_CONFIGURATION_destroy (controller->cfg);
1268   if (GNUNET_YES == controller->aux_host)
1269     GNUNET_TESTBED_host_destroy (controller->host);
1270   GNUNET_TESTBED_operation_queue_destroy_ (controller->opq_peer_create);
1271   GNUNET_free (controller);
1272 }
1273
1274
1275 /**
1276  * Register a host with the controller
1277  *
1278  * @param controller the controller handle
1279  * @param host the host to register
1280  * @param cc the completion callback to call to inform the status of
1281  *          registration. After calling this callback the registration handle
1282  *          will be invalid. Cannot be NULL.
1283  * @param cc_cls the closure for the cc
1284  * @return handle to the host registration which can be used to cancel the
1285  *           registration 
1286  */
1287 struct GNUNET_TESTBED_HostRegistrationHandle *
1288 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1289                               struct GNUNET_TESTBED_Host *host,
1290                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1291                               void *cc_cls)
1292 {
1293   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1294   struct GNUNET_TESTBED_AddHostMessage *msg;
1295   const char *username;
1296   const char *hostname;
1297   uint16_t msg_size;
1298   uint16_t user_name_length;
1299
1300   if (NULL != controller->rh)
1301     return NULL;
1302   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1303   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1304   {
1305     LOG (GNUNET_ERROR_TYPE_WARNING,
1306          "Host hostname: %s already registered\n",
1307          (NULL == hostname) ? "localhost" : hostname);
1308     return NULL;
1309   }  
1310   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1311   rh->host = host;
1312   rh->c = controller;
1313   GNUNET_assert (NULL != cc);
1314   rh->cc = cc;
1315   rh->cc_cls = cc_cls;
1316   controller->rh = rh;
1317   username = GNUNET_TESTBED_host_get_username_ (host);
1318   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1319   user_name_length = 0;
1320   if (NULL != username)
1321   {
1322     user_name_length = strlen (username) + 1;
1323     msg_size += user_name_length;
1324   }
1325   /* FIXME: what happens when hostname is NULL? localhost */
1326   GNUNET_assert (NULL != hostname);
1327   msg_size += strlen (hostname) + 1;
1328   msg = GNUNET_malloc (msg_size);
1329   msg->header.size = htons (msg_size);
1330   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
1331   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1332   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1333   msg->user_name_length = htons (user_name_length);
1334   if (NULL != username)
1335     memcpy (&msg[1], username, user_name_length);
1336   strcpy (((void *) &msg[1]) + user_name_length, hostname);
1337   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
1338   return rh;
1339 }
1340
1341
1342 /**
1343  * Cancel the pending registration. Note that if the registration message is
1344  * already sent to the service the cancellation has only the effect that the
1345  * registration completion callback for the registration is never called.
1346  *
1347  * @param handle the registration handle to cancel
1348  */
1349 void
1350 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1351                                     *handle)
1352 {
1353   if (handle != handle->c->rh)
1354   {
1355     GNUNET_break (0);
1356     return;
1357   }
1358   handle->c->rh = NULL;
1359   GNUNET_free (handle);  
1360 }
1361
1362
1363 /**
1364  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
1365  * serialized and compressed
1366  *
1367  * @param master handle to the master controller who creates the association
1368  * @param delegated_host requests to which host should be delegated; cannot be NULL
1369  * @param slave_host which host is used to run the slave controller; use NULL to
1370  *          make the master controller connect to the delegated host
1371  * @param sxcfg serialized and compressed configuration
1372  * @param sxcfg_size the size scfg
1373  * @param scfg_size the size of uncompressed serialized configuration
1374  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1375  *          be started by the master controller; GNUNET_NO if we are just
1376  *          allowed to use the slave via TCP/IP
1377  */
1378 struct GNUNET_TESTBED_Operation *
1379 GNUNET_TESTBED_controller_link_2 (struct GNUNET_TESTBED_Controller *master,
1380                                   struct GNUNET_TESTBED_Host *delegated_host,
1381                                   struct GNUNET_TESTBED_Host *slave_host,
1382                                   const char *sxcfg,
1383                                   size_t sxcfg_size,
1384                                   size_t scfg_size,
1385                                   int is_subordinate)
1386 {
1387   struct OperationContext *opc;
1388   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1389   uint16_t msg_size;
1390
1391   GNUNET_assert (GNUNET_YES == 
1392                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1393   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1394     GNUNET_assert (GNUNET_YES == 
1395                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1396   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1397   msg = GNUNET_malloc (msg_size);
1398   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);  
1399   msg->header.size = htons (msg_size);
1400   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
1401   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ 
1402                               ((NULL != slave_host) ? slave_host : master->host));
1403   msg->config_size = htons ((uint16_t) scfg_size);
1404   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
1405   memcpy (&msg[1], sxcfg, sxcfg_size);
1406   opc = GNUNET_malloc (sizeof (struct OperationContext));
1407   opc->c = master;
1408   opc->data = msg;
1409   opc->type = OP_LINK_CONTROLLERS;
1410   opc->id = master->operation_counter++;
1411   opc->state = OPC_STATE_INIT;
1412   msg->operation_id = GNUNET_htonll (opc->id);
1413   opc->op = GNUNET_TESTBED_operation_create_ (opc, &opstart_link_controllers,
1414                                               &oprelease_link_controllers);
1415   GNUNET_TESTBED_operation_queue_insert_ (master->opq_peer_create, opc->op);
1416   return opc->op;
1417 }
1418
1419
1420 /**
1421  * Compresses given configuration using zlib compress
1422  *
1423  * @param config the serialized configuration
1424  * @param size the size of config
1425  * @param xconfig will be set to the compressed configuration (memory is fresly
1426  *          allocated) 
1427  * @return the size of the xconfig
1428  */
1429 size_t
1430 GNUNET_TESTBED_compress_config_ (const char *config, size_t size,
1431                                  char **xconfig)
1432 {
1433   size_t xsize;
1434   
1435   xsize = compressBound ((uLong) size);
1436   *xconfig = GNUNET_malloc (xsize);
1437   GNUNET_assert (Z_OK ==
1438                  compress2 ((Bytef *)* xconfig, (uLongf *) &xsize,
1439                             (const Bytef *) config, (uLongf) size, 
1440                             Z_BEST_SPEED));
1441   return xsize;
1442 }
1443                                 
1444
1445 /**
1446  * Create a link from slave controller to delegated controller. Whenever the
1447  * master controller is asked to start a peer at the delegated controller the
1448  * request will be routed towards slave controller (if a route exists). The
1449  * slave controller will then route it to the delegated controller. The
1450  * configuration of the slave controller is given and to be used to either
1451  * create the slave controller or to connect to an existing slave controller
1452  * process.  'is_subordinate' specifies if the given slave controller should be
1453  * started and managed by the master controller, or if the slave already has a
1454  * master and this is just a secondary master that is also allowed to use the
1455  * existing slave.
1456  *
1457  * @param master handle to the master controller who creates the association
1458  * @param delegated_host requests to which host should be delegated
1459  * @param slave_host which host is used to run the slave controller 
1460  * @param slave_cfg configuration to use for the slave controller
1461  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
1462  *                       by the master controller; GNUNET_NO if we are just
1463  *                       allowed to use the slave via TCP/IP
1464  * @return the operation handle
1465  */
1466 struct GNUNET_TESTBED_Operation *
1467 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
1468                                 struct GNUNET_TESTBED_Host *delegated_host,
1469                                 struct GNUNET_TESTBED_Host *slave_host,
1470                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
1471                                 int is_subordinate)
1472 {
1473   struct GNUNET_TESTBED_Operation *op;
1474   char *config;
1475   char *cconfig;
1476   size_t cc_size;
1477   size_t config_size;  
1478   
1479   GNUNET_assert (GNUNET_YES ==
1480                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1481   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1482     GNUNET_assert (GNUNET_YES ==
1483                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1484   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
1485   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1486   GNUNET_free (config);
1487   GNUNET_assert ((UINT16_MAX -
1488                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
1489                   >= cc_size); /* Configuration doesn't fit in 1 message */
1490   op = GNUNET_TESTBED_controller_link_2 (master, delegated_host, slave_host,
1491                                     (const char *) cconfig,
1492                                     cc_size, config_size, is_subordinate);
1493   GNUNET_free (cconfig);
1494   return op;
1495 }
1496
1497
1498 /**
1499  * Ask the testbed controller to write the current overlay topology to
1500  * a file.  Naturally, the file will only contain a snapshot as the
1501  * topology may evolve all the time.
1502  *
1503  * @param controller overlay controller to inspect
1504  * @param filename name of the file the topology should
1505  *        be written to.
1506  */
1507 void
1508 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
1509                                                const char *filename)
1510 {
1511   GNUNET_break (0);
1512 }
1513
1514
1515 /**
1516  * Creates a helper initialization message. This function is here because we
1517  * want to use this in testing
1518  *
1519  * @param cname the ip address of the controlling host
1520  * @param cfg the configuration that has to used to start the testbed service
1521  *          thru helper
1522  * @return the initialization message
1523  */
1524 struct GNUNET_TESTBED_HelperInit *
1525 GNUNET_TESTBED_create_helper_init_msg_ (const char *cname,
1526                                          const struct GNUNET_CONFIGURATION_Handle *cfg)
1527 {
1528   struct GNUNET_TESTBED_HelperInit *msg;
1529   char *config;
1530   char *xconfig;
1531   size_t config_size;
1532   size_t xconfig_size;
1533   uint16_t cname_len;
1534   uint16_t msg_size;
1535
1536   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
1537   GNUNET_assert (NULL != config);
1538   xconfig_size =
1539     GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
1540   GNUNET_free (config);
1541   cname_len = strlen (cname);
1542   msg_size = xconfig_size + cname_len + 1 + 
1543     sizeof (struct GNUNET_TESTBED_HelperInit);
1544   msg = GNUNET_realloc (xconfig, msg_size);
1545   (void) memmove ( ((void *) &msg[1]) + cname_len + 1, msg, xconfig_size);
1546   msg->header.size = htons (msg_size);
1547   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
1548   msg->cname_size = htons (cname_len);
1549   msg->config_size = htons (config_size);
1550   (void) strcpy ((char *) &msg[1], cname);
1551   return msg;
1552 }
1553
1554
1555 /**
1556  * Cancel a pending operation.  Releases all resources
1557  * of the operation and will ensure that no event
1558  * is generated for the operation.  Does NOT guarantee
1559  * that the operation will be fully undone (or that
1560  * nothing ever happened).  
1561  * 
1562  * @param operation operation to cancel
1563  */
1564 void
1565 GNUNET_TESTBED_operation_cancel (struct GNUNET_TESTBED_Operation *operation)
1566 {
1567   GNUNET_TESTBED_operation_done (operation);
1568 }
1569
1570
1571 /**
1572  * Signal that the information from an operation has been fully
1573  * processed.  This function MUST be called for each event
1574  * of type 'operation_finished' to fully remove the operation
1575  * from the operation queue.  After calling this function, the
1576  * 'op_result' becomes invalid (!).
1577  * 
1578  * @param operation operation to signal completion for
1579  */
1580 void
1581 GNUNET_TESTBED_operation_done (struct GNUNET_TESTBED_Operation *operation)
1582 {
1583   switch (operation->type)
1584   {
1585   case OP_PEER_CREATE:
1586   case OP_PEER_DESTROY:
1587   case OP_PEER_START:
1588   case OP_PEER_STOP:
1589   case OP_PEER_INFO:
1590   case OP_OVERLAY_CONNECT:
1591   case OP_LINK_CONTROLLERS:
1592     GNUNET_TESTBED_operation_release_ (operation);
1593     return;
1594   default:
1595     GNUNET_assert (0);
1596     break;
1597   }
1598 }
1599
1600 /* end of testbed_api.c */