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