working overlay connect with implicit suboperations
[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  * Testbed Helper binary name
72  */
73 #define HELPER_TESTBED_BINARY "gnunet-helper-testbed"
74 #define HELPER_TESTBED_BINARY_SSH ". ~/.bashrc; gnunet-helper-testbed"
75
76
77 /**
78  * Handle for controller process
79  */
80 struct GNUNET_TESTBED_ControllerProc
81 {
82   /**
83    * The process handle
84    */
85   struct GNUNET_HELPER_Handle *helper;
86
87   /**
88    * The host where the helper is run
89    */
90   struct GNUNET_TESTBED_Host *host;
91
92   /**
93    * The controller error callback
94    */
95   GNUNET_TESTBED_ControllerStatusCallback cb;
96
97   /**
98    * The closure for the above callback
99    */
100   void *cls;
101
102   /**
103    * The send handle for the helper
104    */
105   struct GNUNET_HELPER_SendHandle *shandle;
106
107   /**
108    * The message corresponding to send handle
109    */
110   struct GNUNET_MessageHeader *msg;
111
112   /**
113    * The port number for ssh; used for helpers starting ssh
114    */
115   char *port;
116
117   /**
118    * The ssh destination string; used for helpers starting ssh
119    */
120   char *dst;
121
122   /**
123    * The configuration of the running testbed service
124    */
125   struct GNUNET_CONFIGURATION_Handle *cfg;
126
127 };
128
129
130 /**
131  * The message queue for sending messages to the controller service
132  */
133 struct MessageQueue
134 {
135   /**
136    * The message to be sent
137    */
138   struct GNUNET_MessageHeader *msg;
139
140   /**
141    * next pointer for DLL
142    */
143   struct MessageQueue *next;
144
145   /**
146    * prev pointer for DLL
147    */
148   struct MessageQueue *prev;
149 };
150
151
152 /**
153  * Structure for a controller link
154  */
155 struct ControllerLink
156 {
157   /**
158    * The next ptr for DLL
159    */
160   struct ControllerLink *next;
161
162   /**
163    * The prev ptr for DLL
164    */
165   struct ControllerLink *prev;
166
167   /**
168    * The host which will be referred in the peer start request. This is the
169    * host where the peer should be started
170    */
171   struct GNUNET_TESTBED_Host *delegated_host;
172
173   /**
174    * The host which will contacted to delegate the peer start request
175    */
176   struct GNUNET_TESTBED_Host *slave_host;
177
178   /**
179    * The configuration to be used to connect to slave host
180    */
181   const struct GNUNET_CONFIGURATION_Handle *slave_cfg;
182
183   /**
184    * GNUNET_YES if the slave should be started (and stopped) by us; GNUNET_NO
185    * if we are just allowed to use the slave via TCP/IP
186    */
187   int is_subordinate;
188 };
189
190
191 /**
192  * handle for host registration
193  */
194 struct GNUNET_TESTBED_HostRegistrationHandle
195 {
196   /**
197    * The host being registered
198    */
199   struct GNUNET_TESTBED_Host *host;
200
201   /**
202    * The controller at which this host is being registered
203    */
204   struct GNUNET_TESTBED_Controller *c;
205
206   /**
207    * The Registartion completion callback
208    */
209   GNUNET_TESTBED_HostRegistrationCompletion cc;
210
211   /**
212    * The closure for above callback
213    */
214   void *cc_cls;
215 };
216
217
218 /**
219  * Context data for forwarded Operation
220  */
221 struct ForwardedOperationData
222 {
223
224   /**
225    * The callback to call when reply is available
226    */
227   GNUNET_CLIENT_MessageHandler cc;
228
229   /**
230    * The closure for the above callback
231    */
232   void *cc_cls;
233
234 };
235
236
237 /**
238  * Context data for get slave config operations
239  */
240 struct GetSlaveConfigData
241 {
242   /**
243    * The id of the slave controller
244    */
245   uint32_t slave_id;
246
247 };
248
249
250 /**
251  * Context data for controller link operations
252  */
253 struct ControllerLinkData
254 {
255   /**
256    * The controller link message
257    */
258   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
259
260 };
261
262
263 /**
264  * Returns the operation context with the given id if found in the Operation
265  * context queues of the controller
266  *
267  * @param c the controller whose queues are searched
268  * @param id the id which has to be checked
269  * @return the matching operation context; NULL if no match found
270  */
271 static struct OperationContext *
272 find_opc (const struct GNUNET_TESTBED_Controller *c, const uint64_t id)
273 {
274   struct OperationContext *opc;
275
276   for (opc = c->ocq_head; NULL != opc; opc = opc->next)
277   {
278     if (id == opc->id)
279       return opc;
280   }
281   return NULL;
282 }
283
284
285 /**
286  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
287  * controller (testbed service)
288  *
289  * @param c the controller handler
290  * @param msg message received
291  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
292  *           not
293  */
294 static int
295 handle_addhostconfirm (struct GNUNET_TESTBED_Controller *c,
296                        const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
297 {
298   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
299   char *emsg;
300   uint16_t msg_size;
301
302   rh = c->rh;
303   if (NULL == rh)
304   {
305     return GNUNET_OK;
306   }
307   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
308   {
309     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
310                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
311     return GNUNET_OK;
312   }
313   c->rh = NULL;
314   msg_size = ntohs (msg->header.size);
315   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
316   {
317     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
318     GNUNET_TESTBED_mark_host_registered_at_ (rh->host, c);
319     rh->cc (rh->cc_cls, NULL);
320     GNUNET_free (rh);
321     return GNUNET_OK;
322   }
323   /* We have an error message */
324   emsg = (char *) &msg[1];
325   if ('\0' !=
326       emsg[msg_size - sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
327   {
328     GNUNET_break (0);
329     GNUNET_free (rh);
330     return GNUNET_NO;
331   }
332   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
333        ntohl (msg->host_id), emsg);
334   rh->cc (rh->cc_cls, emsg);
335   GNUNET_free (rh);
336   return GNUNET_OK;
337 }
338
339
340 /**
341  * Handler for forwarded operations
342  *
343  * @param c the controller handle
344  * @param opc the opearation context
345  * @param msg the message
346  */
347 static void
348 handle_forwarded_operation_msg (struct GNUNET_TESTBED_Controller *c,
349                                 struct OperationContext *opc,
350                                 const struct GNUNET_MessageHeader *msg)
351 {
352   struct ForwardedOperationData *fo_data;
353
354   fo_data = opc->data;
355   if (NULL != fo_data->cc)
356     fo_data->cc (fo_data->cc_cls, msg);
357   GNUNET_CONTAINER_DLL_remove (c->ocq_head, c->ocq_tail, opc);
358   GNUNET_free (fo_data);
359   GNUNET_free (opc);
360 }
361
362
363 /**
364  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
365  * controller (testbed service)
366  *
367  * @param c the controller handler
368  * @param msg message received
369  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
370  *           not
371  */
372 static int
373 handle_opsuccess (struct GNUNET_TESTBED_Controller *c,
374                   const struct
375                   GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg)
376 {
377   struct OperationContext *opc;
378   struct GNUNET_TESTBED_EventInformation event;
379   uint64_t op_id;
380
381   op_id = GNUNET_ntohll (msg->operation_id);
382   LOG_DEBUG ("Operation %ul successful\n", op_id);
383   if (NULL == (opc = find_opc (c, op_id)))
384   {
385     LOG_DEBUG ("Operation not found\n");
386     return GNUNET_YES;
387   }
388   event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
389   event.details.operation_finished.operation = opc->op;
390   event.details.operation_finished.op_cls = opc->op_cls;
391   event.details.operation_finished.emsg = NULL;
392   event.details.operation_finished.generic = NULL;
393   switch (opc->type)
394   {
395   case OP_FORWARDED:
396     {
397       handle_forwarded_operation_msg
398           (c, opc, (const struct GNUNET_MessageHeader *) msg);
399       return GNUNET_YES;
400     }
401     break;
402   case OP_PEER_DESTROY:
403     {
404       struct GNUNET_TESTBED_Peer *peer;
405       
406       peer = opc->data;
407       GNUNET_free (peer);
408       opc->data = NULL;
409       //PEERDESTROYDATA
410     }
411     break;
412   case OP_LINK_CONTROLLERS:
413     {
414       struct ControllerLinkData *data;
415       
416       data = opc->data;
417       GNUNET_assert (NULL != data);      
418       GNUNET_free (data);
419       opc->data = NULL;
420     }
421     break;
422   default:
423     GNUNET_assert (0);
424   }  
425   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
426   opc->state = OPC_STATE_FINISHED;
427   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
428   {
429     if (NULL != c->cc)
430       c->cc (c->cc_cls, &event);
431   }
432   else
433     LOG_DEBUG ("Not calling callback\n");
434   return GNUNET_YES;
435 }
436
437
438 /**
439  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS message from
440  * controller (testbed service)
441  *
442  * @param c the controller handle
443  * @param msg message received
444  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
445  *           not
446  */
447 static int
448 handle_peer_create_success (struct GNUNET_TESTBED_Controller *c,
449                             const struct
450                             GNUNET_TESTBED_PeerCreateSuccessEventMessage *msg)
451 {
452   struct OperationContext *opc;
453   struct PeerCreateData *data;
454   struct GNUNET_TESTBED_Peer *peer;
455   GNUNET_TESTBED_PeerCreateCallback cb;
456   void *cls;
457   uint64_t op_id;
458
459   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage) ==
460                  ntohs (msg->header.size));
461   op_id = GNUNET_ntohll (msg->operation_id);
462   if (NULL == (opc = find_opc (c, op_id)))
463   {
464     LOG_DEBUG ("Operation context for PeerCreateSuccessEvent not found\n");
465     return GNUNET_YES;
466   }
467   if (OP_FORWARDED == opc->type)
468   {
469     handle_forwarded_operation_msg (c, opc,
470                                     (const struct GNUNET_MessageHeader *) msg);
471     return GNUNET_YES;
472   }
473   GNUNET_assert (OP_PEER_CREATE == opc->type);
474   GNUNET_assert (NULL != opc->data);
475   data = opc->data;
476   GNUNET_assert (NULL != data->peer);
477   peer = data->peer;
478   GNUNET_assert (peer->unique_id == ntohl (msg->peer_id));
479   peer->state = PS_CREATED;
480   cb = data->cb;
481   cls = data->cls;
482   GNUNET_free (opc->data);
483   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
484   opc->state = OPC_STATE_FINISHED;
485   if (NULL != cb)
486     cb (cls, peer, NULL);
487   return GNUNET_YES;
488 }
489
490
491 /**
492  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT message from
493  * controller (testbed service)
494  *
495  * @param c the controller handler
496  * @param msg message received
497  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
498  *           not
499  */
500 static int
501 handle_peer_event (struct GNUNET_TESTBED_Controller *c,
502                    const struct GNUNET_TESTBED_PeerEventMessage *msg)
503 {
504   struct OperationContext *opc;
505   struct GNUNET_TESTBED_Peer *peer;
506   struct PeerEventData *data;
507   GNUNET_TESTBED_PeerChurnCallback pcc;
508   void *pcc_cls;
509   struct GNUNET_TESTBED_EventInformation event;
510   uint64_t op_id;
511
512   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerEventMessage) ==
513                  ntohs (msg->header.size));
514   op_id = GNUNET_ntohll (msg->operation_id);
515   if (NULL == (opc = find_opc (c, op_id)))
516   {
517     LOG_DEBUG ("Operation not found\n");
518     return GNUNET_YES;
519   }
520   if (OP_FORWARDED == opc->type)
521   {
522     handle_forwarded_operation_msg (c, opc,
523                                     (const struct GNUNET_MessageHeader *) msg);
524     return GNUNET_YES;
525   }
526   GNUNET_assert ((OP_PEER_START == opc->type) || (OP_PEER_STOP == opc->type));
527   data = opc->data;
528   GNUNET_assert (NULL != data);
529   peer = data->peer;
530   GNUNET_assert (NULL != peer);
531   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
532   switch (event.type)
533   {
534   case GNUNET_TESTBED_ET_PEER_START:
535     peer->state = PS_STARTED;
536     event.details.peer_start.host = peer->host;
537     event.details.peer_start.peer = peer;
538     break;
539   case GNUNET_TESTBED_ET_PEER_STOP:
540     peer->state = PS_STOPPED;
541     event.details.peer_stop.peer = peer;
542     break;
543   default:
544     GNUNET_assert (0);          /* We should never reach this state */
545   }
546   pcc = data->pcc;
547   pcc_cls = data->pcc_cls;
548   GNUNET_free (data);
549   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
550   opc->state = OPC_STATE_FINISHED;
551   if (0 !=
552       ((GNUNET_TESTBED_ET_PEER_START | GNUNET_TESTBED_ET_PEER_STOP) &
553        c->event_mask))
554   {
555     if (NULL != c->cc)
556       c->cc (c->cc_cls, &event);
557   }
558   if (NULL != pcc)
559     pcc (pcc_cls, NULL);
560   return GNUNET_YES;
561 }
562
563
564 /**
565  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT message from
566  * controller (testbed service)
567  *
568  * @param c the controller handler
569  * @param msg message received
570  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
571  *           not
572  */
573 static int
574 handle_peer_conevent (struct GNUNET_TESTBED_Controller *c,
575                       const struct GNUNET_TESTBED_ConnectionEventMessage *msg)
576 {
577   struct OperationContext *opc;
578   struct OverlayConnectData *data;
579   GNUNET_TESTBED_OperationCompletionCallback cb;
580   void *cb_cls;
581   struct GNUNET_TESTBED_EventInformation event;
582   uint64_t op_id;
583
584   op_id = GNUNET_ntohll (msg->operation_id);
585   if (NULL == (opc = find_opc (c, op_id)))
586   {
587     LOG_DEBUG ("Operation not found\n");
588     return GNUNET_YES;
589   }
590   if (OP_FORWARDED == opc->type)
591   {
592     handle_forwarded_operation_msg (c, opc,
593                                     (const struct GNUNET_MessageHeader *) msg);
594     return GNUNET_YES;
595   }
596   GNUNET_assert (OP_OVERLAY_CONNECT == opc->type);
597   data = opc->data;
598   GNUNET_assert (NULL != data);
599   GNUNET_assert ((ntohl (msg->peer1) == data->p1->unique_id) &&
600                  (ntohl (msg->peer2) == data->p2->unique_id));
601   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
602   switch (event.type)
603   {
604   case GNUNET_TESTBED_ET_CONNECT:
605     event.details.peer_connect.peer1 = data->p1;
606     event.details.peer_connect.peer2 = data->p2;
607     break;
608   case GNUNET_TESTBED_ET_DISCONNECT:
609     GNUNET_assert (0);          /* FIXME: implement */
610     break;
611   default:
612     GNUNET_assert (0);          /* Should never reach here */
613     break;
614   }
615   cb = data->cb;
616   cb_cls = data->cb_cls;
617   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
618   opc->state = OPC_STATE_FINISHED;
619   GNUNET_free (data);
620   if (0 !=
621       ((GNUNET_TESTBED_ET_CONNECT | GNUNET_TESTBED_ET_DISCONNECT) &
622        c->event_mask))
623   {
624     if (NULL != c->cc)
625       c->cc (c->cc_cls, &event);
626   }
627   if (NULL != cb)
628     cb (cb_cls, opc->op, NULL);
629   return GNUNET_YES;
630 }
631
632
633 /**
634  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG message from
635  * controller (testbed service)
636  *
637  * @param c the controller handler
638  * @param msg message received
639  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
640  *           not
641  */
642 static int
643 handle_peer_config (struct GNUNET_TESTBED_Controller *c,
644                     const struct
645                     GNUNET_TESTBED_PeerConfigurationInformationMessage *msg)
646 {
647   struct OperationContext *opc;
648   struct GNUNET_TESTBED_Peer *peer;
649   struct PeerInfoData *data;
650   struct GNUNET_TESTBED_PeerInformation *pinfo;
651   GNUNET_TESTBED_PeerInfoCallback cb;
652   void *cb_cls;
653   uint64_t op_id;
654
655   op_id = GNUNET_ntohll (msg->operation_id);
656   if (NULL == (opc = find_opc (c, op_id)))
657   {
658     LOG_DEBUG ("Operation not found\n");
659     return GNUNET_YES;
660   }
661   if (OP_FORWARDED == opc->type)
662   {
663     handle_forwarded_operation_msg (c, opc,
664                                     (const struct GNUNET_MessageHeader *) msg);
665     return GNUNET_YES;
666   }
667   data = opc->data;
668   GNUNET_assert (NULL != data);
669   peer = data->peer;
670   GNUNET_assert (NULL != peer);
671   GNUNET_assert (ntohl (msg->peer_id) == peer->unique_id);
672   pinfo = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerInformation));
673   pinfo->pit = data->pit;
674   cb = data->cb;
675   cb_cls = data->cb_cls;
676   GNUNET_free (data);
677   opc->data = NULL;
678   switch (pinfo->pit)
679   {
680   case GNUNET_TESTBED_PIT_IDENTITY:
681     pinfo->result.id = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
682     (void) memcpy (pinfo->result.id, &msg->peer_identity,
683                    sizeof (struct GNUNET_PeerIdentity));
684     break;
685   case GNUNET_TESTBED_PIT_CONFIGURATION:
686     pinfo->result.cfg =        /* Freed in oprelease_peer_getinfo */
687         GNUNET_TESTBED_extract_config_ (&msg->header);
688     break;
689   case GNUNET_TESTBED_PIT_GENERIC:
690     GNUNET_assert (0);          /* never reach here */
691     break;
692   }
693   opc->data = pinfo;
694   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
695   opc->state = OPC_STATE_FINISHED;
696   if (NULL != cb)
697     cb (cb_cls, opc->op, pinfo, NULL);
698   return GNUNET_YES;
699 }
700
701
702 /**
703  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONFAILEVENT message from
704  * controller (testbed service)
705  *
706  * @param c the controller handler
707  * @param msg message received
708  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
709  *           not
710  */
711 static int
712 handle_op_fail_event (struct GNUNET_TESTBED_Controller *c,
713                       const struct GNUNET_TESTBED_OperationFailureEventMessage
714                       *msg)
715 {
716   struct OperationContext *opc;
717   const char *emsg;
718   uint64_t op_id;
719   struct GNUNET_TESTBED_EventInformation event;
720
721   op_id = GNUNET_ntohll (msg->operation_id);
722   if (NULL == (opc = find_opc (c, op_id)))
723   {
724     LOG_DEBUG ("Operation not found\n");
725     return GNUNET_YES;
726   }
727   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
728   if (OP_FORWARDED == opc->type)
729   {
730     handle_forwarded_operation_msg (c, opc,
731                                     (const struct GNUNET_MessageHeader *) msg);
732     return GNUNET_YES;
733   }
734   opc->state = OPC_STATE_FINISHED;
735   emsg = GNUNET_TESTBED_parse_error_string_ (msg);
736   if (NULL == emsg)
737     emsg = "Unknown error";
738   if (OP_PEER_INFO == opc->type)
739   {
740     struct PeerInfoData *data;
741     data = opc->data;
742     if (NULL != data->cb)
743       data->cb (data->cb_cls, opc->op, NULL, emsg);
744     GNUNET_free (data);
745     return GNUNET_YES;  /* We do not call controller callback for peer info */
746   }
747   if ((0 != (GNUNET_TESTBED_ET_OPERATION_FINISHED & c->event_mask)) &&
748       (NULL != c->cc))
749   {
750     event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
751     event.details.operation_finished.operation = opc->op;
752     event.details.operation_finished.op_cls = opc->op_cls;
753     event.details.operation_finished.emsg = emsg;
754     event.details.operation_finished.generic = NULL;
755     c->cc (c->cc_cls, &event);
756   }
757   switch (opc->type)
758   {
759   case OP_PEER_CREATE:
760     {
761       struct PeerCreateData *data;      
762       data = opc->data;
763       GNUNET_free (data->peer);
764       if (NULL != data->cb)
765         data->cb (data->cls, NULL, emsg);
766       GNUNET_free (data);      
767     }
768     break;
769   case OP_PEER_START:
770   case OP_PEER_STOP:
771     {
772       struct PeerEventData *data;
773       data = opc->data;
774       if (NULL != data->pcc)
775         data->pcc (data->pcc_cls, emsg);
776       GNUNET_free (data);
777     }
778     break;
779   case OP_PEER_DESTROY:
780     break;
781   case OP_PEER_INFO:
782     GNUNET_assert (0);
783   case OP_OVERLAY_CONNECT:
784     {
785       struct OverlayConnectData *data;
786       data = opc->data;
787       if (NULL != data->cb)
788         data->cb (data->cb_cls, opc->op, emsg);
789       GNUNET_free (data);
790     }
791     break;
792   case OP_FORWARDED:
793     GNUNET_assert (0);
794   case OP_LINK_CONTROLLERS:     /* No secondary callback */
795     break;
796   default:
797     GNUNET_break (0);
798   }  
799   return GNUNET_YES;
800 }
801
802
803 /**
804  * Function to build GET_SLAVE_CONFIG message
805  *
806  * @param op_id the id this message should contain in its operation id field
807  * @param slave_id the id this message should contain in its slave id field
808  * @return newly allocated SlaveGetConfigurationMessage
809  */
810 static struct GNUNET_TESTBED_SlaveGetConfigurationMessage *
811 GNUNET_TESTBED_generate_slavegetconfig_msg_ (uint64_t op_id, uint32_t slave_id)
812 {
813   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
814   uint16_t msize;
815   
816   msize = sizeof (struct GNUNET_TESTBED_SlaveGetConfigurationMessage);
817   msg = GNUNET_malloc (msize);
818   msg->header.size = htons (msize);
819   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GETSLAVECONFIG);
820   msg->operation_id = GNUNET_htonll (op_id);
821   msg->slave_id = htonl (slave_id);
822   return msg;
823 }
824
825
826 /**
827  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG message from controller
828  * (testbed service)
829  *
830  * @param c the controller handler
831  * @param msg message received
832  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
833  *           not
834  */
835 static int
836 handle_slave_config (struct GNUNET_TESTBED_Controller *c,
837                      const struct GNUNET_TESTBED_SlaveConfiguration * msg)
838 {
839   struct OperationContext *opc;
840   uint64_t op_id;
841   struct GNUNET_TESTBED_EventInformation event;  
842
843   op_id = GNUNET_ntohll (msg->operation_id);
844   if (NULL == (opc = find_opc (c, op_id)))
845   {
846     LOG_DEBUG ("Operation not found\n");
847     return GNUNET_YES;
848   }
849   if (OP_GET_SLAVE_CONFIG != opc->type)
850   {
851     GNUNET_break (0);
852     return GNUNET_YES;
853   }
854   GNUNET_free (opc->data);
855   opc->data = NULL;
856   opc->state = OPC_STATE_FINISHED;
857   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
858   if ((0 != (GNUNET_TESTBED_ET_OPERATION_FINISHED & c->event_mask)) &&
859       (NULL != c->cc))
860   {
861     opc->data = GNUNET_TESTBED_extract_config_ (&msg->header);
862     event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;   
863     event.details.operation_finished.generic = opc->data;
864     event.details.operation_finished.operation = opc->op;
865     event.details.operation_finished.op_cls = opc->op_cls;
866     event.details.operation_finished.emsg = NULL;
867     c->cc (c->cc_cls, &event);
868   }
869   return GNUNET_YES;
870 }
871
872
873 /**
874  * Callback to check status for suboperations generated during overlay connect.
875  *
876  * @param cls the OverlayConnectData
877  * @param message the reply message to the suboperation
878  */
879 static void
880 overlay_connect_ondemand_handler (void *cls,
881                                   const struct GNUNET_MessageHeader *message)
882 {
883   struct OverlayConnectData *oc_data = cls;
884
885   switch (oc_data->state)
886   {
887   case OCD_CFG_ACQUIRE:
888     {
889       struct GNUNET_CONFIGURATION_Handle *cfg;
890
891       if (GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG != ntohs (message->type))
892       {
893         GNUNET_break (0);       /* treat operation as failed */
894       }
895       cfg = GNUNET_TESTBED_extract_config_ (message);
896       if (NULL == cfg)
897       {
898         GNUNET_break (0);       /* failed operation */
899       }
900       oc_data->state = OCD_LINK_CONTROLLERS;
901     }
902   default:
903     GNUNET_assert (0);
904   }
905 }
906
907
908 /**
909  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_NEEDCONTROLLERCONFIG message from
910  * controller (testbed service)
911  *
912  * @param c the controller handler
913  * @param msg message received
914  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
915  *           not
916  */
917 static int
918 handle_need_controller_config (struct GNUNET_TESTBED_Controller *c,
919                                const struct GNUNET_TESTBED_NeedControllerConfig * msg)
920 {
921   struct OperationContext *opc;
922   struct OverlayConnectData *oc_data;
923   uint64_t op_id;
924
925   op_id = GNUNET_ntohll (msg->operation_id);
926   if (NULL == (opc = find_opc (c, op_id)))
927   {
928     LOG_DEBUG ("Operation not found\n");
929     return GNUNET_YES;
930   }
931   if (OP_FORWARDED == opc->type)
932   {
933     handle_forwarded_operation_msg (c, opc,
934                                     (const struct GNUNET_MessageHeader *) msg);
935     return GNUNET_YES;
936   }
937   GNUNET_assert (OP_OVERLAY_CONNECT == opc->type);
938   oc_data = opc->data;
939   /* FIXME: Should spawn operations to:
940      1. Acquire configuration of peer2's controller,
941      2. link peer1's controller to peer2's controller
942      3. ask them to attempt overlay connect on peer1 and peer2 again */
943   switch (oc_data->state)
944   {
945   case OCD_INIT:
946     {
947       struct GNUNET_TESTBED_SlaveGetConfigurationMessage *get_cfg_msg;
948       uint64_t sub_op_id;
949       
950       GNUNET_assert (NULL == oc_data->sub_opc);
951       sub_op_id = GNUNET_TESTBED_get_next_op_id (oc_data->p1->controller);
952       get_cfg_msg = 
953           GNUNET_TESTBED_generate_slavegetconfig_msg_ 
954           (sub_op_id, GNUNET_TESTBED_host_get_id_ (oc_data->p2->host));
955       oc_data->state = OCD_CFG_ACQUIRE;
956       oc_data->sub_opc =
957           GNUNET_TESTBED_forward_operation_msg_ (oc_data->p1->controller,
958                                                  sub_op_id, &get_cfg_msg->header,
959                                                  overlay_connect_ondemand_handler,
960                                                  oc_data);
961     }
962     break;
963   default:
964     GNUNET_assert (0);
965   }
966   return GNUNET_YES;
967 }
968
969
970 /**
971  * Handler for messages from controller (testbed service)
972  *
973  * @param cls the controller handler
974  * @param msg message received, NULL on timeout or fatal error
975  */
976 static void
977 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
978 {
979   struct GNUNET_TESTBED_Controller *c = cls;
980   int status;
981   uint16_t msize;
982
983   c->in_receive = GNUNET_NO;
984   /* FIXME: Add checks for message integrity */
985   if (NULL == msg)
986   {
987     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
988     return;
989   }
990   status = GNUNET_OK;
991   msize = ntohs (msg->size);
992   switch (ntohs (msg->type))
993   {
994   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
995     GNUNET_assert (msize >=
996                    sizeof (struct GNUNET_TESTBED_HostConfirmedMessage));
997     status =
998         handle_addhostconfirm (c,
999                                (const struct GNUNET_TESTBED_HostConfirmedMessage
1000                                 *) msg);
1001     break;
1002   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
1003     GNUNET_assert (msize ==
1004                    sizeof (struct
1005                            GNUNET_TESTBED_GenericOperationSuccessEventMessage));
1006     status =
1007         handle_opsuccess (c,
1008                           (const struct
1009                            GNUNET_TESTBED_GenericOperationSuccessEventMessage *)
1010                           msg);
1011     break;
1012   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS:
1013     GNUNET_assert (msize ==
1014                    sizeof (struct
1015                            GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1016     status =
1017         handle_peer_create_success (c,
1018                                     (const struct
1019                                      GNUNET_TESTBED_PeerCreateSuccessEventMessage
1020                                      *) msg);
1021     break;
1022   case GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT:
1023     GNUNET_assert (msize == sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1024     status =
1025         handle_peer_event (c,
1026                            (const struct GNUNET_TESTBED_PeerEventMessage *)
1027                            msg);
1028
1029     break;
1030   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG:
1031     GNUNET_assert (msize >=
1032                    sizeof (struct
1033                            GNUNET_TESTBED_PeerConfigurationInformationMessage));
1034     status =
1035         handle_peer_config (c,
1036                             (const struct
1037                              GNUNET_TESTBED_PeerConfigurationInformationMessage
1038                              *) msg);
1039     break;
1040   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT:
1041     GNUNET_assert (msize ==
1042                    sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
1043     status =
1044         handle_peer_conevent (c,
1045                               (const struct
1046                                GNUNET_TESTBED_ConnectionEventMessage *) msg);
1047     break;
1048   case GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONFAILEVENT:
1049     GNUNET_assert (msize >=
1050                    sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage));
1051     status =
1052         handle_op_fail_event (c,
1053                               (const struct
1054                                GNUNET_TESTBED_OperationFailureEventMessage *)
1055                               msg);
1056     break;
1057   case GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG:
1058     GNUNET_assert (msize >
1059                    sizeof (struct GNUNET_TESTBED_SlaveConfiguration));
1060     status = 
1061         handle_slave_config (c, (const struct 
1062                                  GNUNET_TESTBED_SlaveConfiguration *) msg);
1063     break;
1064   case GNUNET_MESSAGE_TYPE_TESTBED_NEEDCONTROLLERCONFIG:
1065     GNUNET_assert (msize == sizeof (struct
1066                                     GNUNET_TESTBED_NeedControllerConfig));
1067     status = 
1068         handle_need_controller_config (c, (const struct
1069                                            GNUNET_TESTBED_NeedControllerConfig
1070                                            *) msg);
1071     break;
1072   default:
1073     GNUNET_assert (0);
1074   }
1075   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
1076   {
1077     c->in_receive = GNUNET_YES;
1078     GNUNET_CLIENT_receive (c->client, &message_handler, c,
1079                            GNUNET_TIME_UNIT_FOREVER_REL);
1080   }
1081 }
1082
1083
1084 /**
1085  * Function called to notify a client about the connection begin ready to queue
1086  * more data.  "buf" will be NULL and "size" zero if the connection was closed
1087  * for writing in the meantime.
1088  *
1089  * @param cls closure
1090  * @param size number of bytes available in buf
1091  * @param buf where the callee should write the message
1092  * @return number of bytes written to buf
1093  */
1094 static size_t
1095 transmit_ready_notify (void *cls, size_t size, void *buf)
1096 {
1097   struct GNUNET_TESTBED_Controller *c = cls;
1098   struct MessageQueue *mq_entry;
1099
1100   c->th = NULL;
1101   mq_entry = c->mq_head;
1102   GNUNET_assert (NULL != mq_entry);
1103   if ((0 == size) && (NULL == buf))     /* Timeout */
1104   {
1105     LOG_DEBUG ("Message sending timed out -- retrying\n");
1106     c->th =
1107         GNUNET_CLIENT_notify_transmit_ready (c->client,
1108                                              ntohs (mq_entry->msg->size),
1109                                              TIMEOUT_REL, GNUNET_YES,
1110                                              &transmit_ready_notify, c);
1111     return 0;
1112   }
1113   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
1114   size = ntohs (mq_entry->msg->size);
1115   memcpy (buf, mq_entry->msg, size);
1116   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
1117              ntohs (mq_entry->msg->type), size);
1118   GNUNET_free (mq_entry->msg);
1119   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
1120   GNUNET_free (mq_entry);
1121   mq_entry = c->mq_head;
1122   if (NULL != mq_entry)
1123     c->th =
1124         GNUNET_CLIENT_notify_transmit_ready (c->client,
1125                                              ntohs (mq_entry->msg->size),
1126                                              TIMEOUT_REL, GNUNET_YES,
1127                                              &transmit_ready_notify, c);
1128   if (GNUNET_NO == c->in_receive)
1129   {
1130     c->in_receive = GNUNET_YES;
1131     GNUNET_CLIENT_receive (c->client, &message_handler, c,
1132                            GNUNET_TIME_UNIT_FOREVER_REL);
1133   }
1134   return size;
1135 }
1136
1137
1138 /**
1139  * Queues a message in send queue for sending to the service
1140  *
1141  * @param controller the handle to the controller
1142  * @param msg the message to queue
1143  */
1144 void
1145 GNUNET_TESTBED_queue_message_ (struct GNUNET_TESTBED_Controller *controller,
1146                                struct GNUNET_MessageHeader *msg)
1147 {
1148   struct MessageQueue *mq_entry;
1149   uint16_t type;
1150   uint16_t size;
1151
1152   type = ntohs (msg->type);
1153   size = ntohs (msg->size);
1154   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
1155                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));
1156   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
1157   mq_entry->msg = msg;
1158   LOG (GNUNET_ERROR_TYPE_DEBUG,
1159        "Queueing message of type %u, size %u for sending\n", type,
1160        ntohs (msg->size));
1161   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
1162                                     mq_entry);
1163   if (NULL == controller->th)
1164     controller->th =
1165         GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
1166                                              TIMEOUT_REL, GNUNET_YES,
1167                                              &transmit_ready_notify,
1168                                              controller);
1169 }
1170
1171
1172 /**
1173  * Sends the given message as an operation. The given callback is called when a
1174  * reply for the operation is available.  Call
1175  * GNUNET_TESTBED_forward_operation_msg_cancel_() to cleanup the returned
1176  * operation context if the cc hasn't been called
1177  *
1178  * @param controller the controller to which the message has to be sent
1179  * @param operation_id the operation id of the message
1180  * @param msg the message to send
1181  * @param cc the callback to call when reply is available
1182  * @param cc_cls the closure for the above callback
1183  * @return the operation context which can be used to cancel the forwarded
1184  *           operation
1185  */
1186 struct OperationContext *
1187 GNUNET_TESTBED_forward_operation_msg_ (struct GNUNET_TESTBED_Controller
1188                                        *controller, uint64_t operation_id,
1189                                        const struct GNUNET_MessageHeader *msg,
1190                                        GNUNET_CLIENT_MessageHandler cc,
1191                                        void *cc_cls)
1192 {
1193   struct OperationContext *opc;
1194   struct ForwardedOperationData *data;
1195   struct GNUNET_MessageHeader *dup_msg;
1196   uint16_t msize;
1197
1198   data = GNUNET_malloc (sizeof (struct ForwardedOperationData));
1199   data->cc = cc;
1200   data->cc_cls = cc_cls;
1201   opc = GNUNET_malloc (sizeof (struct OperationContext));
1202   opc->c = controller;
1203   opc->type = OP_FORWARDED;
1204   opc->data = data;
1205   opc->id = operation_id;
1206   msize = ntohs (msg->size);
1207   dup_msg = GNUNET_malloc (msize);
1208   (void) memcpy (dup_msg, msg, msize);
1209   GNUNET_TESTBED_queue_message_ (opc->c, dup_msg);
1210   GNUNET_CONTAINER_DLL_insert_tail (controller->ocq_head, controller->ocq_tail,
1211                                     opc);
1212   return opc;
1213 }
1214
1215
1216 /**
1217  * Function to cancel an operation created by simply forwarding an operation
1218  * message.
1219  *
1220  * @param opc the operation context from GNUNET_TESTBED_forward_operation_msg_()
1221  */
1222 void
1223 GNUNET_TESTBED_forward_operation_msg_cancel_ (struct OperationContext *opc)
1224 {
1225   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
1226   GNUNET_free (opc->data);
1227   GNUNET_free (opc);
1228 }
1229
1230
1231 /**
1232  * Functions with this signature are called whenever a
1233  * complete message is received by the tokenizer.
1234  *
1235  * Do not call GNUNET_SERVER_mst_destroy in callback
1236  *
1237  * @param cls closure
1238  * @param client identification of the client
1239  * @param message the actual message
1240  *
1241  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1242  */
1243 static int
1244 helper_mst (void *cls, void *client, const struct GNUNET_MessageHeader *message)
1245 {
1246   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1247   const struct GNUNET_TESTBED_HelperReply *msg;
1248   const char *hostname;
1249   char *config;
1250   uLongf config_size;
1251   uLongf xconfig_size;
1252
1253   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
1254   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) <
1255                  ntohs (msg->header.size));
1256   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY ==
1257                  ntohs (msg->header.type));
1258   config_size = (uLongf) ntohs (msg->config_size);
1259   xconfig_size =
1260       (uLongf) (ntohs (msg->header.size) -
1261                 sizeof (struct GNUNET_TESTBED_HelperReply));
1262   config = GNUNET_malloc (config_size);
1263   GNUNET_assert (Z_OK ==
1264                  uncompress ((Bytef *) config, &config_size,
1265                              (const Bytef *) &msg[1], xconfig_size));
1266   GNUNET_assert (NULL == cp->cfg);
1267   cp->cfg = GNUNET_CONFIGURATION_create ();
1268   GNUNET_assert (GNUNET_CONFIGURATION_deserialize
1269                  (cp->cfg, config, config_size, GNUNET_NO));
1270   GNUNET_free (config);
1271   if ((NULL == cp->host) ||
1272       (NULL == (hostname = GNUNET_TESTBED_host_get_hostname_ (cp->host))))
1273     hostname = "localhost";
1274   /* Change the hostname so that we can connect to it */
1275   GNUNET_CONFIGURATION_set_value_string (cp->cfg, "testbed", "hostname",
1276                                          hostname);
1277   cp->cb (cp->cls, cp->cfg, GNUNET_OK);
1278   return GNUNET_OK;
1279 }
1280
1281
1282 /**
1283  * Continuation function from GNUNET_HELPER_send()
1284  *
1285  * @param cls closure
1286  * @param result GNUNET_OK on success,
1287  *               GNUNET_NO if helper process died
1288  *               GNUNET_SYSERR during GNUNET_HELPER_stop
1289  */
1290 static void
1291 clear_msg (void *cls, int result)
1292 {
1293   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1294
1295   GNUNET_assert (NULL != cp->shandle);
1296   cp->shandle = NULL;
1297   GNUNET_free (cp->msg);
1298 }
1299
1300
1301 /**
1302  * Callback that will be called when the helper process dies. This is not called
1303  * when the helper process is stoped using GNUNET_HELPER_stop()
1304  *
1305  * @param cls the closure from GNUNET_HELPER_start()
1306  */
1307 static void
1308 helper_exp_cb (void *cls)
1309 {
1310   struct GNUNET_TESTBED_ControllerProc *cp = cls;
1311   GNUNET_TESTBED_ControllerStatusCallback cb;
1312   void *cb_cls;
1313
1314   cb = cp->cb;
1315   cb_cls = cp->cls;
1316   cp->helper = NULL;
1317   GNUNET_TESTBED_controller_stop (cp);
1318   if (NULL != cb)
1319     cb (cb_cls, NULL, GNUNET_SYSERR);
1320 }
1321
1322
1323 /**
1324  * Function to call to start a link-controllers type operation once all queues
1325  * the operation is part of declare that the operation can be activated.
1326  *
1327  * @param cls the closure from GNUNET_TESTBED_operation_create_()
1328  */
1329 static void
1330 opstart_link_controllers (void *cls)
1331 {
1332   struct OperationContext *opc = cls;
1333   struct ControllerLinkData *data;
1334   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1335
1336   GNUNET_assert (NULL != opc->data);
1337   data = opc->data;
1338   msg = data->msg;
1339   data->msg = NULL;
1340   opc->state = OPC_STATE_STARTED;
1341   GNUNET_CONTAINER_DLL_insert_tail (opc->c->ocq_head, opc->c->ocq_tail, opc);
1342   GNUNET_TESTBED_queue_message_ (opc->c, &msg->header);
1343 }
1344
1345
1346 /**
1347  * Callback which will be called when link-controllers type operation is released
1348  *
1349  * @param cls the closure from GNUNET_TESTBED_operation_create_()
1350  */
1351 static void
1352 oprelease_link_controllers (void *cls)
1353 {
1354   struct OperationContext *opc = cls;
1355   struct ControllerLinkData *data;
1356
1357   data = opc->data;
1358   switch (opc->state)
1359   {
1360   case OPC_STATE_INIT:
1361     GNUNET_free (data->msg);
1362     break;
1363   case OPC_STATE_STARTED:
1364     GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
1365     break;
1366   case OPC_STATE_FINISHED:
1367     break;
1368   }
1369   GNUNET_free_non_null (data);
1370   GNUNET_free (opc);
1371 }
1372
1373
1374 /**
1375  * Function to be called when get slave config operation is ready
1376  *
1377  * @param cls the OperationContext of type OP_GET_SLAVE_CONFIG
1378  */
1379 static void
1380 opstart_get_slave_config (void *cls)
1381 {
1382   struct OperationContext *opc = cls;
1383   struct GetSlaveConfigData *data;
1384   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
1385
1386   data = opc->data;
1387   msg = GNUNET_TESTBED_generate_slavegetconfig_msg_ (opc->id, data->slave_id);
1388   GNUNET_CONTAINER_DLL_insert_tail (opc->c->ocq_head, opc->c->ocq_tail, opc);
1389   GNUNET_TESTBED_queue_message_ (opc->c, &msg->header);
1390   opc->state = OPC_STATE_STARTED;
1391 }
1392
1393
1394 /**
1395  * Function to be called when get slave config operation is cancelled or finished
1396  *
1397  * @param cls the OperationContext of type OP_GET_SLAVE_CONFIG
1398  */
1399 static void
1400 oprelease_get_slave_config (void *cls)
1401 {
1402   struct OperationContext *opc = cls;
1403
1404   switch (opc->state)
1405   {
1406   case OPC_STATE_INIT:
1407     GNUNET_free (opc->data);
1408     break;
1409   case OPC_STATE_STARTED:
1410     GNUNET_free (opc->data);
1411     GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
1412     break;
1413   case OPC_STATE_FINISHED:
1414     if (NULL != opc->data)
1415       GNUNET_CONFIGURATION_destroy (opc->data);
1416     break;
1417   }
1418   GNUNET_free (opc);
1419 }
1420
1421
1422 /**
1423  * Starts a controller process at the host. FIXME: add controller start callback
1424  * with the configuration with which the controller is started
1425  *
1426  * @param controller_ip the ip address of the controller. Will be set as TRUSTED
1427  *          host when starting testbed controller at host
1428  * @param host the host where the controller has to be started; NULL for
1429  *          localhost
1430  * @param cfg template configuration to use for the remote controller; the
1431  *          remote controller will be started with a slightly modified
1432  *          configuration (port numbers, unix domain sockets and service home
1433  *          values are changed as per TESTING library on the remote host)
1434  * @param cb function called when the controller is successfully started or
1435  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
1436  *          called if cb is called with GNUNET_SYSERR as status. Will never be
1437  *          called in the same task as 'GNUNET_TESTBED_controller_start'
1438  *          (synchronous errors will be signalled by returning NULL). This
1439  *          parameter cannot be NULL.
1440  * @param cls closure for above callbacks
1441  * @return the controller process handle, NULL on errors
1442  */
1443 struct GNUNET_TESTBED_ControllerProc *
1444 GNUNET_TESTBED_controller_start (const char *controller_ip,
1445                                  struct GNUNET_TESTBED_Host *host,
1446                                  const struct GNUNET_CONFIGURATION_Handle *cfg,
1447                                  GNUNET_TESTBED_ControllerStatusCallback cb,
1448                                  void *cls)
1449 {
1450   struct GNUNET_TESTBED_ControllerProc *cp;
1451   struct GNUNET_TESTBED_HelperInit *msg;
1452   const char *hostname;
1453   static char *const binary_argv[] = {
1454     HELPER_TESTBED_BINARY, NULL
1455   };
1456   
1457   hostname = NULL;
1458   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
1459   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
1460     cp->helper =
1461         GNUNET_HELPER_start (GNUNET_YES, HELPER_TESTBED_BINARY, binary_argv,
1462                              &helper_mst, &helper_exp_cb, cp);
1463   else
1464   {
1465     char *remote_args[8];
1466     unsigned int argp;
1467     const char *username;
1468
1469     username = GNUNET_TESTBED_host_get_username_ (host);
1470     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1471     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
1472     if (NULL == username)
1473       GNUNET_asprintf (&cp->dst, "%s", hostname);
1474     else
1475       GNUNET_asprintf (&cp->dst, "%s@%s", username, hostname);
1476     LOG_DEBUG ("Starting SSH to destination %s\n", cp->dst);
1477     argp = 0;
1478     remote_args[argp++] = "ssh";
1479     remote_args[argp++] = "-p";
1480     remote_args[argp++] = cp->port;
1481     remote_args[argp++] = "-o";
1482     remote_args[argp++] = "BatchMode=yes";
1483     remote_args[argp++] = cp->dst;
1484     remote_args[argp++] = HELPER_TESTBED_BINARY_SSH;
1485     remote_args[argp++] = NULL;
1486     GNUNET_assert (argp == 8);
1487     cp->helper =
1488         GNUNET_HELPER_start (GNUNET_NO, "ssh", remote_args, &helper_mst,
1489                              &helper_exp_cb, cp);
1490   }
1491   if (NULL == cp->helper)
1492   {
1493     GNUNET_free_non_null (cp->port);
1494     GNUNET_free_non_null (cp->dst);
1495     GNUNET_free (cp);
1496     return NULL;
1497   }
1498   cp->host = host;
1499   cp->cb = cb;
1500   cp->cls = cls;
1501   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, hostname, cfg);
1502   cp->msg = &msg->header;
1503   cp->shandle =
1504       GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO, &clear_msg, cp);
1505   if (NULL == cp->shandle)
1506   {
1507     GNUNET_free (msg);
1508     GNUNET_TESTBED_controller_stop (cp);
1509     return NULL;
1510   }
1511   return cp;
1512 }
1513
1514
1515 /**
1516  * Stop the controller process (also will terminate all peers and controllers
1517  * dependent on this controller).  This function blocks until the testbed has
1518  * been fully terminated (!). The controller status cb from
1519  * GNUNET_TESTBED_controller_start() will not be called.
1520  *
1521  * @param cproc the controller process handle
1522  */
1523 void
1524 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
1525 {
1526   if (NULL != cproc->shandle)
1527     GNUNET_HELPER_send_cancel (cproc->shandle);
1528   if (NULL != cproc->helper)
1529     GNUNET_HELPER_stop (cproc->helper);
1530   if (NULL != cproc->cfg)
1531     GNUNET_CONFIGURATION_destroy (cproc->cfg);
1532   GNUNET_free_non_null (cproc->port);
1533   GNUNET_free_non_null (cproc->dst);
1534   GNUNET_free (cproc);
1535 }
1536
1537
1538 /**
1539  * Start a controller process using the given configuration at the
1540  * given host.
1541  *
1542  * @param cfg configuration to use
1543  * @param host host to run the controller on; This should be the same host if
1544  *          the controller was previously started with
1545  *          GNUNET_TESTBED_controller_start; NULL for localhost
1546  * @param event_mask bit mask with set of events to call 'cc' for;
1547  *                   or-ed values of "1LL" shifted by the
1548  *                   respective 'enum GNUNET_TESTBED_EventType'
1549  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
1550  * @param cc controller callback to invoke on events
1551  * @param cc_cls closure for cc
1552  * @return handle to the controller
1553  */
1554 struct GNUNET_TESTBED_Controller *
1555 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle
1556                                    *cfg, struct GNUNET_TESTBED_Host *host,
1557                                    uint64_t event_mask,
1558                                    GNUNET_TESTBED_ControllerCallback cc,
1559                                    void *cc_cls)
1560 {
1561   struct GNUNET_TESTBED_Controller *controller;
1562   struct GNUNET_TESTBED_InitMessage *msg;
1563   const char *controller_hostname;
1564   unsigned long long max_parallel_operations;
1565   unsigned long long max_parallel_service_connections;
1566   unsigned long long max_parallel_topology_config_operations;
1567
1568   if (GNUNET_OK !=
1569       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1570                                              "MAX_PARALLEL_OPERATIONS",
1571                                              &max_parallel_operations))
1572   {
1573     GNUNET_break (0);
1574     return NULL;
1575   }
1576   if (GNUNET_OK !=
1577       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1578                                              "MAX_PARALLEL_SERVICE_CONNECTIONS",
1579                                              &max_parallel_service_connections))
1580   {
1581     GNUNET_break (0);
1582     return NULL;
1583   }
1584   if (GNUNET_OK !=
1585       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1586                                              "MAX_PARALLEL_TOPOLOGY_CONFIG_OPERATIONS",
1587                                              &max_parallel_topology_config_operations))
1588   {
1589     GNUNET_break (0);
1590     return NULL;
1591   }
1592   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
1593   controller->cc = cc;
1594   controller->cc_cls = cc_cls;
1595   controller->event_mask = event_mask;
1596   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
1597   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);
1598   if (NULL == controller->client)
1599   {
1600     GNUNET_TESTBED_controller_disconnect (controller);
1601     return NULL;
1602   }
1603   if (NULL == host)
1604   {
1605     host = GNUNET_TESTBED_host_create_by_id_ (0);
1606     if (NULL == host)           /* If the above host create fails */
1607     {
1608       LOG (GNUNET_ERROR_TYPE_WARNING,
1609            "Treating NULL host as localhost. Multiple references to localhost "
1610            "may break when localhost freed before calling disconnect \n");
1611       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
1612     }
1613     else
1614     {
1615       controller->aux_host = GNUNET_YES;
1616     }
1617   }
1618   GNUNET_assert (NULL != host);
1619   GNUNET_TESTBED_mark_host_registered_at_ (host, controller);
1620   controller->host = host;
1621   controller->opq_parallel_operations =
1622       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1623                                               max_parallel_operations);
1624   controller->opq_parallel_service_connections =
1625       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1626                                               max_parallel_service_connections);
1627   controller->opq_parallel_topology_config_operations=
1628       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1629                                               max_parallel_service_connections);
1630   controller_hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1631   if (NULL == controller_hostname)
1632     controller_hostname = "127.0.0.1";
1633   msg =
1634       GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage) +
1635                      strlen (controller_hostname) + 1);
1636   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
1637   msg->header.size =
1638       htons (sizeof (struct GNUNET_TESTBED_InitMessage) +
1639              strlen (controller_hostname) + 1);
1640   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1641   msg->event_mask = GNUNET_htonll (controller->event_mask);
1642   strcpy ((char *) &msg[1], controller_hostname);
1643   GNUNET_TESTBED_queue_message_ (controller,
1644                                  (struct GNUNET_MessageHeader *) msg);
1645   return controller;
1646 }
1647
1648
1649 /**
1650  * Configure shared services at a controller.  Using this function,
1651  * you can specify that certain services (such as "resolver")
1652  * should not be run for each peer but instead be shared
1653  * across N peers on the specified host.  This function
1654  * must be called before any peers are created at the host.
1655  *
1656  * @param controller controller to configure
1657  * @param service_name name of the service to share
1658  * @param num_peers number of peers that should share one instance
1659  *        of the specified service (1 for no sharing is the default),
1660  *        use 0 to disable the service
1661  */
1662 void
1663 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller
1664                                              *controller,
1665                                              const char *service_name,
1666                                              uint32_t num_peers)
1667 {
1668   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1669   uint16_t service_name_size;
1670   uint16_t msg_size;
1671
1672   service_name_size = strlen (service_name) + 1;
1673   msg_size =
1674       sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage) +
1675       service_name_size;
1676   msg = GNUNET_malloc (msg_size);
1677   msg->header.size = htons (msg_size);
1678   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
1679   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
1680   msg->num_peers = htonl (num_peers);
1681   memcpy (&msg[1], service_name, service_name_size);
1682   GNUNET_TESTBED_queue_message_ (controller,
1683                                  (struct GNUNET_MessageHeader *) msg);
1684 }
1685
1686
1687 /**
1688  * disconnects from the controller.
1689  *
1690  * @param controller handle to controller to stop
1691  */
1692 void
1693 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller
1694                                       *controller)
1695 {
1696   struct MessageQueue *mq_entry;
1697
1698   if (NULL != controller->th)
1699     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
1700   /* Clear the message queue */
1701   while (NULL != (mq_entry = controller->mq_head))
1702   {
1703     GNUNET_CONTAINER_DLL_remove (controller->mq_head, controller->mq_tail,
1704                                  mq_entry);
1705     GNUNET_free (mq_entry->msg);
1706     GNUNET_free (mq_entry);
1707   }
1708   if (NULL != controller->client)
1709     GNUNET_CLIENT_disconnect (controller->client);
1710   GNUNET_CONFIGURATION_destroy (controller->cfg);
1711   if (GNUNET_YES == controller->aux_host)
1712     GNUNET_TESTBED_host_destroy (controller->host);
1713   GNUNET_TESTBED_operation_queue_destroy_ (controller->opq_parallel_operations);
1714   GNUNET_TESTBED_operation_queue_destroy_
1715       (controller->opq_parallel_service_connections);
1716   GNUNET_TESTBED_operation_queue_destroy_
1717       (controller->opq_parallel_topology_config_operations);
1718   GNUNET_free (controller);
1719 }
1720
1721
1722 /**
1723  * Register a host with the controller
1724  *
1725  * @param controller the controller handle
1726  * @param host the host to register
1727  * @param cc the completion callback to call to inform the status of
1728  *          registration. After calling this callback the registration handle
1729  *          will be invalid. Cannot be NULL.
1730  * @param cc_cls the closure for the cc
1731  * @return handle to the host registration which can be used to cancel the
1732  *           registration
1733  */
1734 struct GNUNET_TESTBED_HostRegistrationHandle *
1735 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1736                               struct GNUNET_TESTBED_Host *host,
1737                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1738                               void *cc_cls)
1739 {
1740   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1741   struct GNUNET_TESTBED_AddHostMessage *msg;
1742   const char *username;
1743   const char *hostname;
1744   uint16_t msg_size;
1745   uint16_t user_name_length;
1746
1747   if (NULL != controller->rh)
1748     return NULL;
1749   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1750   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1751   {
1752     LOG (GNUNET_ERROR_TYPE_WARNING, "Host hostname: %s already registered\n",
1753          (NULL == hostname) ? "localhost" : hostname);
1754     return NULL;
1755   }
1756   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1757   rh->host = host;
1758   rh->c = controller;
1759   GNUNET_assert (NULL != cc);
1760   rh->cc = cc;
1761   rh->cc_cls = cc_cls;
1762   controller->rh = rh;
1763   username = GNUNET_TESTBED_host_get_username_ (host);
1764   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1765   user_name_length = 0;
1766   if (NULL != username)
1767   {
1768     user_name_length = strlen (username) + 1;
1769     msg_size += user_name_length;
1770   }
1771   /* FIXME: what happens when hostname is NULL? localhost */
1772   GNUNET_assert (NULL != hostname);
1773   msg_size += strlen (hostname) + 1;
1774   msg = GNUNET_malloc (msg_size);
1775   msg->header.size = htons (msg_size);
1776   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
1777   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1778   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1779   msg->user_name_length = htons (user_name_length);
1780   if (NULL != username)
1781     memcpy (&msg[1], username, user_name_length);
1782   strcpy (((void *) &msg[1]) + user_name_length, hostname);
1783   GNUNET_TESTBED_queue_message_ (controller,
1784                                  (struct GNUNET_MessageHeader *) msg);
1785   return rh;
1786 }
1787
1788
1789 /**
1790  * Cancel the pending registration. Note that if the registration message is
1791  * already sent to the service the cancellation has only the effect that the
1792  * registration completion callback for the registration is never called.
1793  *
1794  * @param handle the registration handle to cancel
1795  */
1796 void
1797 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1798                                     *handle)
1799 {
1800   if (handle != handle->c->rh)
1801   {
1802     GNUNET_break (0);
1803     return;
1804   }
1805   handle->c->rh = NULL;
1806   GNUNET_free (handle);
1807 }
1808
1809
1810 /**
1811  * Same as the GNUNET_TESTBED_controller_link_2, but with ids for delegated host
1812  * and slave host
1813  *
1814  * @param op_cls the operation closure for the event which is generated to
1815  *          signal success or failure of this operation
1816  * @param master handle to the master controller who creates the association
1817  * @param delegated_host_id id of the host to which requests should be delegated
1818  * @param slave_host_id id of the host which is used to run the slave controller
1819  * @param sxcfg serialized and compressed configuration
1820  * @param sxcfg_size the size sxcfg
1821  * @param scfg_size the size of uncompressed serialized configuration
1822  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1823  *          be started by the slave controller; GNUNET_NO if the slave
1824  *          controller has to connect to the already started delegated
1825  *          controller via TCP/IP
1826  * @return the operation handle
1827  */
1828 struct GNUNET_TESTBED_Operation *
1829 GNUNET_TESTBED_controller_link_2_ (void *op_cls,
1830                                    struct GNUNET_TESTBED_Controller *master,
1831                                    uint32_t delegated_host_id,
1832                                    uint32_t slave_host_id,
1833                                    const char *sxcfg, size_t sxcfg_size,
1834                                    size_t scfg_size, int is_subordinate)
1835 {
1836   struct OperationContext *opc;
1837   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1838   struct ControllerLinkData *data;
1839   uint16_t msg_size;
1840
1841   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1842   msg = GNUNET_malloc (msg_size);
1843   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);
1844   msg->header.size = htons (msg_size);
1845   msg->delegated_host_id = htonl (delegated_host_id);
1846   msg->slave_host_id = htonl (slave_host_id);
1847   msg->config_size = htons ((uint16_t) scfg_size);
1848   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
1849   memcpy (&msg[1], sxcfg, sxcfg_size);
1850   data = GNUNET_malloc (sizeof (struct ControllerLinkData));
1851   data->msg = msg;
1852   opc = GNUNET_malloc (sizeof (struct OperationContext));
1853   opc->c = master;
1854   opc->data = data;
1855   opc->type = OP_LINK_CONTROLLERS;
1856   opc->id = GNUNET_TESTBED_get_next_op_id (opc->c);
1857   opc->state = OPC_STATE_INIT;
1858   opc->op_cls = op_cls;
1859   msg->operation_id = GNUNET_htonll (opc->id);
1860   opc->op =
1861       GNUNET_TESTBED_operation_create_ (opc, &opstart_link_controllers,
1862                                         &oprelease_link_controllers);
1863   GNUNET_TESTBED_operation_queue_insert_ (master->opq_parallel_operations,
1864                                           opc->op);
1865   return opc->op;
1866 }
1867
1868
1869 /**
1870  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
1871  * serialized and compressed
1872  *
1873  * @param op_cls the operation closure for the event which is generated to
1874  *          signal success or failure of this operation
1875  * @param master handle to the master controller who creates the association
1876  * @param delegated_host requests to which host should be delegated; cannot be NULL
1877  * @param slave_host which host is used to run the slave controller; use NULL to
1878  *          make the master controller connect to the delegated host
1879  * @param sxcfg serialized and compressed configuration
1880  * @param sxcfg_size the size sxcfg
1881  * @param scfg_size the size of uncompressed serialized configuration
1882  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1883  *          be started by the slave controller; GNUNET_NO if the slave
1884  *          controller has to connect to the already started delegated
1885  *          controller via TCP/IP
1886  * @return the operation handle
1887  */
1888 struct GNUNET_TESTBED_Operation *
1889 GNUNET_TESTBED_controller_link_2 (void *op_cls,
1890                                   struct GNUNET_TESTBED_Controller *master,
1891                                   struct GNUNET_TESTBED_Host *delegated_host,
1892                                   struct GNUNET_TESTBED_Host *slave_host,
1893                                   const char *sxcfg, size_t sxcfg_size,
1894                                   size_t scfg_size, int is_subordinate)
1895
1896   uint32_t delegated_host_id;
1897   uint32_t slave_host_id;
1898
1899   GNUNET_assert (GNUNET_YES ==
1900                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1901   delegated_host_id = GNUNET_TESTBED_host_get_id_ (delegated_host);
1902   slave_host_id = 
1903       GNUNET_TESTBED_host_get_id_ ((NULL != slave_host)
1904                                    ? slave_host : master->host);
1905   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1906     GNUNET_assert (GNUNET_YES ==
1907                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1908   
1909   return GNUNET_TESTBED_controller_link_2_ (op_cls,
1910                                             master,
1911                                             delegated_host_id,
1912                                             slave_host_id,
1913                                             sxcfg, sxcfg_size,
1914                                             scfg_size, is_subordinate);
1915   GNUNET_break (0);
1916 }
1917
1918
1919 /**
1920  * Compresses given configuration using zlib compress
1921  *
1922  * @param config the serialized configuration
1923  * @param size the size of config
1924  * @param xconfig will be set to the compressed configuration (memory is fresly
1925  *          allocated)
1926  * @return the size of the xconfig
1927  */
1928 size_t
1929 GNUNET_TESTBED_compress_config_ (const char *config, size_t size,
1930                                  char **xconfig)
1931 {
1932   size_t xsize;
1933
1934   xsize = compressBound ((uLong) size);
1935   *xconfig = GNUNET_malloc (xsize);
1936   GNUNET_assert (Z_OK ==
1937                  compress2 ((Bytef *) * xconfig, (uLongf *) & xsize,
1938                             (const Bytef *) config, (uLongf) size,
1939                             Z_BEST_SPEED));
1940   return xsize;
1941 }
1942
1943
1944 /**
1945  * Same as the GNUNET_TESTBED_controller_link, but with ids for delegated host
1946  * and slave host
1947  *
1948  * @param op_cls the operation closure for the event which is generated to
1949  *          signal success or failure of this operation
1950  * @param master handle to the master controller who creates the association
1951  * @param delegated_host requests to which host should be delegated; cannot be NULL
1952  * @param slave_host which host is used to run the slave controller; use NULL to
1953  *          make the master controller connect to the delegated host
1954  * @param slave_cfg configuration to use for the slave controller
1955  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1956  *          be started by the slave controller; GNUNET_NO if the slave
1957  *          controller has to connect to the already started delegated
1958  *          controller via TCP/IP
1959  * @return the operation handle
1960  */
1961 struct GNUNET_TESTBED_Operation *
1962 GNUNET_TESTBED_controller_link_ (void *op_cls,
1963                                 struct GNUNET_TESTBED_Controller *master,
1964                                 uint32_t delegated_host_id,
1965                                 uint32_t slave_host_id,
1966                                 const struct GNUNET_CONFIGURATION_Handle
1967                                 *slave_cfg,
1968                                 int is_subordinate)
1969 {
1970   struct GNUNET_TESTBED_Operation *op;
1971   char *config;
1972   char *cconfig;
1973   size_t cc_size;
1974   size_t config_size;
1975
1976   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
1977   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1978   GNUNET_free (config);
1979   /* Configuration doesn't fit in 1 message */
1980   GNUNET_assert ((UINT16_MAX - 
1981                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage)) >=
1982                  cc_size);
1983   op = GNUNET_TESTBED_controller_link_2_ (op_cls, master, delegated_host_id,
1984                                           slave_host_id, (const char *) cconfig,
1985                                           cc_size, config_size, is_subordinate);
1986   GNUNET_free (cconfig);
1987   return op;
1988 }
1989
1990
1991 /**
1992  * Create a link from slave controller to delegated controller. Whenever the
1993  * master controller is asked to start a peer at the delegated controller the
1994  * request will be routed towards slave controller (if a route exists). The
1995  * slave controller will then route it to the delegated controller. The
1996  * configuration of the delegated controller is given and is used to either
1997  * create the delegated controller or to connect to an existing controller. Note
1998  * that while starting the delegated controller the configuration will be
1999  * modified to accommodate available free ports.  the 'is_subordinate' specifies
2000  * if the given delegated controller should be started and managed by the slave
2001  * controller, or if the delegated controller already has a master and the slave
2002  * controller connects to it as a non master controller. The success or failure
2003  * of this operation will be signalled through the
2004  * GNUNET_TESTBED_ControllerCallback() with an event of type
2005  * GNUNET_TESTBED_ET_OPERATION_FINISHED
2006  *
2007  * @param op_cls the operation closure for the event which is generated to
2008  *          signal success or failure of this operation
2009  * @param master handle to the master controller who creates the association
2010  * @param delegated_host requests to which host should be delegated; cannot be NULL
2011  * @param slave_host which host is used to run the slave controller; use NULL to
2012  *          make the master controller connect to the delegated host
2013  * @param slave_cfg configuration to use for the slave controller
2014  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
2015  *          be started by the slave controller; GNUNET_NO if the slave
2016  *          controller has to connect to the already started delegated
2017  *          controller via TCP/IP
2018  * @return the operation handle
2019  */
2020 struct GNUNET_TESTBED_Operation *
2021 GNUNET_TESTBED_controller_link (void *op_cls,
2022                                 struct GNUNET_TESTBED_Controller *master,
2023                                 struct GNUNET_TESTBED_Host *delegated_host,
2024                                 struct GNUNET_TESTBED_Host *slave_host,
2025                                 const struct GNUNET_CONFIGURATION_Handle
2026                                 *slave_cfg, int is_subordinate)
2027 {
2028   uint32_t slave_host_id;
2029   uint32_t delegated_host_id;
2030
2031   GNUNET_assert (GNUNET_YES ==
2032                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
2033   slave_host_id = (NULL == slave_host) ?
2034       0 : GNUNET_TESTBED_host_get_id_ (slave_host);
2035   delegated_host_id = GNUNET_TESTBED_host_get_id_ (delegated_host);
2036   if ((NULL != slave_host) && (0 != slave_host_id))
2037     GNUNET_assert (GNUNET_YES ==
2038                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
2039   return GNUNET_TESTBED_controller_link_ (op_cls, master,
2040                                           delegated_host_id,
2041                                           slave_host_id,
2042                                           slave_cfg,
2043                                           is_subordinate);
2044                                           
2045 }
2046
2047
2048 /**
2049  * Like GNUNET_TESTBED_get_slave_config(), however without the host registration
2050  * check. Another difference is that this function takes the id of the slave
2051  * host.
2052  *
2053  * @param op_cls the closure for the operation
2054  * @param master the handle to master controller
2055  * @param slave_host the host where the slave controller is running; the handle
2056  *          to the slave_host should remain valid until this operation is
2057  *          cancelled or marked as finished
2058  * @return the operation handle;
2059  */
2060 struct GNUNET_TESTBED_Operation *
2061 GNUNET_TESTBED_get_slave_config_ (void *op_cls,
2062                                   struct GNUNET_TESTBED_Controller *master,
2063                                   uint32_t slave_host_id)
2064 {  
2065   struct OperationContext *opc;
2066   struct GetSlaveConfigData *data;
2067
2068   data = GNUNET_malloc (sizeof (struct GetSlaveConfigData));
2069   data->slave_id = slave_host_id;
2070   opc = GNUNET_malloc (sizeof (struct OperationContext));
2071   opc->state = OPC_STATE_INIT;
2072   opc->c = master;
2073   opc->id = GNUNET_TESTBED_get_next_op_id (master);
2074   opc->type = OP_GET_SLAVE_CONFIG;
2075   opc->data = data;
2076   opc->op_cls = op_cls;
2077   opc->op =
2078       GNUNET_TESTBED_operation_create_ (opc, &opstart_get_slave_config,
2079                                         &oprelease_get_slave_config);
2080   GNUNET_TESTBED_operation_queue_insert_ (master->opq_parallel_operations,
2081                                           opc->op); 
2082   return opc->op;
2083 }
2084
2085
2086 /**
2087  * Function to acquire the configuration of a running slave controller. The
2088  * completion of the operation is signalled through the controller_cb from
2089  * GNUNET_TESTBED_controller_connect(). If the operation is successful the
2090  * handle to the configuration is available in the generic pointer of
2091  * operation_finished field of struct GNUNET_TESTBED_EventInformation.
2092  *
2093  * @param op_cls the closure for the operation
2094  * @param master the handle to master controller
2095  * @param slave_host the host where the slave controller is running; the handle
2096  *          to the slave_host should remain valid until this operation is
2097  *          cancelled or marked as finished
2098  * @return the operation handle; NULL if the slave_host is not registered at
2099  *           master
2100  */
2101 struct GNUNET_TESTBED_Operation *
2102 GNUNET_TESTBED_get_slave_config (void *op_cls,
2103                                  struct GNUNET_TESTBED_Controller *master,
2104                                  struct GNUNET_TESTBED_Host *slave_host)
2105 {
2106   if (GNUNET_NO == GNUNET_TESTBED_is_host_registered_ (slave_host, master))
2107     return NULL;
2108   return GNUNET_TESTBED_get_slave_config_ (op_cls, master,
2109                                            GNUNET_TESTBED_host_get_id_ (slave_host));
2110 }
2111
2112
2113 /**
2114  * Ask the testbed controller to write the current overlay topology to
2115  * a file.  Naturally, the file will only contain a snapshot as the
2116  * topology may evolve all the time.
2117  *
2118  * @param controller overlay controller to inspect
2119  * @param filename name of the file the topology should
2120  *        be written to.
2121  */
2122 void
2123 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller
2124                                                *controller,
2125                                                const char *filename)
2126 {
2127   GNUNET_break (0);
2128 }
2129
2130
2131 /**
2132  * Creates a helper initialization message. This function is here because we
2133  * want to use this in testing
2134  *
2135  * @param cname the ip address of the controlling host
2136  * @param hostname the hostname of the destination this message is intended for
2137  * @param cfg the configuration that has to used to start the testbed service
2138  *          thru helper
2139  * @return the initialization message
2140  */
2141 struct GNUNET_TESTBED_HelperInit *
2142 GNUNET_TESTBED_create_helper_init_msg_ (const char *cname,
2143                                         const char *hostname,
2144                                         const struct GNUNET_CONFIGURATION_Handle
2145                                         *cfg)
2146 {
2147   struct GNUNET_TESTBED_HelperInit *msg;
2148   char *config;
2149   char *xconfig;
2150   size_t config_size;
2151   size_t xconfig_size;
2152   uint16_t cname_len;
2153   uint16_t hostname_len;
2154   uint16_t msg_size;
2155
2156   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
2157   GNUNET_assert (NULL != config);
2158   xconfig_size =
2159       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
2160   GNUNET_free (config);
2161   cname_len = strlen (cname);
2162   hostname_len = (NULL == hostname) ? 0 : strlen (hostname);
2163   msg_size =
2164       xconfig_size + cname_len + 1 + sizeof (struct GNUNET_TESTBED_HelperInit);
2165   msg_size += hostname_len;
2166   msg = GNUNET_realloc (xconfig, msg_size);
2167   (void) memmove (((void *) &msg[1]) + cname_len + 1 + hostname_len,
2168                   msg,
2169                   xconfig_size);
2170   msg->header.size = htons (msg_size);
2171   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
2172   msg->cname_size = htons (cname_len);
2173   msg->hostname_size = htons (hostname_len);
2174   msg->config_size = htons (config_size);
2175   (void) strcpy ((char *) &msg[1], cname);
2176   if (0 != hostname_len)
2177     (void) strncpy (((char *) &msg[1]) + cname_len + 1, hostname, hostname_len);
2178   return msg;
2179 }
2180
2181
2182 /**
2183  * Cancel a pending operation.  Releases all resources
2184  * of the operation and will ensure that no event
2185  * is generated for the operation.  Does NOT guarantee
2186  * that the operation will be fully undone (or that
2187  * nothing ever happened).
2188  *
2189  * @param operation operation to cancel
2190  */
2191 void
2192 GNUNET_TESTBED_operation_cancel (struct GNUNET_TESTBED_Operation *operation)
2193 {
2194   GNUNET_TESTBED_operation_done (operation);
2195 }
2196
2197
2198 /**
2199  * Signal that the information from an operation has been fully
2200  * processed.  This function MUST be called for each event
2201  * of type 'operation_finished' to fully remove the operation
2202  * from the operation queue.  After calling this function, the
2203  * 'op_result' becomes invalid (!).
2204  *
2205  * @param operation operation to signal completion for
2206  */
2207 void
2208 GNUNET_TESTBED_operation_done (struct GNUNET_TESTBED_Operation *operation)
2209 {
2210   switch (operation->type)
2211   {
2212   case OP_PEER_CREATE:
2213   case OP_PEER_DESTROY:
2214   case OP_PEER_START:
2215   case OP_PEER_STOP:
2216   case OP_PEER_INFO:
2217   case OP_OVERLAY_CONNECT:
2218   case OP_LINK_CONTROLLERS:
2219     GNUNET_TESTBED_operation_release_ (operation);
2220     return;
2221   default:
2222     GNUNET_assert (0);
2223     break;
2224   }
2225 }
2226
2227
2228 /**
2229  * Generates configuration by uncompressing configuration in given message. The
2230  * given message should be of the following types:
2231  * GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG,
2232  * GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG
2233  *
2234  * @param msg the message containing compressed configuration
2235  * @return handle to the parsed configuration
2236  */
2237 struct GNUNET_CONFIGURATION_Handle *
2238 GNUNET_TESTBED_extract_config_ (const struct GNUNET_MessageHeader *msg)
2239 {  
2240   struct GNUNET_CONFIGURATION_Handle *cfg;
2241   Bytef *data;
2242   const Bytef *xdata;
2243   uLong data_len;
2244   uLong xdata_len;
2245   int ret;
2246
2247   switch (ntohs (msg->type))
2248   {
2249   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG:
2250     {
2251       const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *imsg;
2252
2253       imsg = (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *)
2254           msg;
2255       data_len = (uLong) ntohs (imsg->config_size);
2256       xdata_len = ntohs (imsg->header.size)
2257           - sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
2258       xdata = (const Bytef *) &imsg[1];
2259     }
2260     break;
2261   case GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG:
2262     {
2263       const struct GNUNET_TESTBED_SlaveConfiguration *imsg;
2264
2265       imsg = (const struct GNUNET_TESTBED_SlaveConfiguration *) msg;
2266       data_len = (uLong) ntohs (imsg->config_size);
2267       xdata_len =  ntohs (imsg->header.size) 
2268           - sizeof (struct GNUNET_TESTBED_SlaveConfiguration);
2269       xdata = (const Bytef *) &imsg[1];
2270     }
2271     break;
2272   default:
2273     GNUNET_assert (0);
2274   }  
2275   data = GNUNET_malloc (data_len);
2276   if (Z_OK !=
2277       (ret =
2278        uncompress (data, &data_len, xdata, xdata_len)))
2279     GNUNET_assert (0);
2280   cfg = GNUNET_CONFIGURATION_create ();
2281   GNUNET_assert (GNUNET_OK ==
2282                  GNUNET_CONFIGURATION_deserialize (cfg, (const char *) data,
2283                                                    (size_t) data_len,
2284                                                    GNUNET_NO));
2285   GNUNET_free (data);
2286   return cfg;
2287 }
2288
2289
2290 /**
2291  * Checks the integrity of the OperationFailureEventMessage and if good returns
2292  * the error message it contains.
2293  *
2294  * @param msg the OperationFailureEventMessage
2295  * @return the error message
2296  */
2297 const char *
2298 GNUNET_TESTBED_parse_error_string_ (const struct
2299                                     GNUNET_TESTBED_OperationFailureEventMessage
2300                                     *msg)
2301 {
2302   uint16_t msize;
2303   const char *emsg;
2304   
2305   msize = ntohs (msg->header.size);
2306   if (sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage) >= msize)
2307     return NULL;
2308   msize -= sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
2309   emsg = (const char *) &msg[1];
2310   if ('\0' != emsg[msize - 1])
2311   {
2312     GNUNET_break (0);
2313     return NULL;
2314   }
2315   return emsg;
2316 }
2317
2318
2319 /**
2320  * Function to return the operation id for a controller. The operation id is
2321  * created from the controllers host id and its internal operation counter.
2322  *
2323  * @param controller the handle to the controller whose operation id has to be incremented
2324  * @return the incremented operation id.
2325  */
2326 uint64_t
2327 GNUNET_TESTBED_get_next_op_id (struct GNUNET_TESTBED_Controller *controller)
2328 {
2329   uint64_t op_id;  
2330
2331   op_id = (uint64_t) GNUNET_TESTBED_host_get_id_ (controller->host);
2332   op_id = op_id <<  32;
2333   op_id |= (uint64_t) controller->operation_counter++;
2334   return op_id;
2335 }
2336
2337 /* end of testbed_api.c */