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