9696785f3e1f962606054dc86d97fcd9d5378864
[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 %lu 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   if (OP_FORWARDED == opc->type)
728   {
729     handle_forwarded_operation_msg (c, opc,
730                                     (const struct GNUNET_MessageHeader *) msg);
731     return GNUNET_YES;
732   }
733   GNUNET_CONTAINER_DLL_remove (opc->c->ocq_head, opc->c->ocq_tail, opc);
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   {
1461     cp->helper =
1462         GNUNET_HELPER_start (GNUNET_YES, HELPER_TESTBED_BINARY, binary_argv,
1463                              &helper_mst, &helper_exp_cb, cp);
1464   }
1465   else
1466   {
1467     char *remote_args[10];
1468     unsigned int argp;
1469     const char *username;
1470
1471     username = GNUNET_TESTBED_host_get_username_ (host);
1472     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1473     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
1474     if (NULL == username)
1475       GNUNET_asprintf (&cp->dst, "%s", hostname);
1476     else
1477       GNUNET_asprintf (&cp->dst, "%s@%s", username, hostname);
1478     LOG_DEBUG ("Starting SSH to destination %s\n", cp->dst);
1479     argp = 0;
1480     remote_args[argp++] = "ssh";
1481     remote_args[argp++] = "-p";
1482     remote_args[argp++] = cp->port;
1483     remote_args[argp++] = "-o";
1484     remote_args[argp++] = "BatchMode=yes";
1485     remote_args[argp++] = "-o";
1486     remote_args[argp++] = "NoHostAuthenticationForLocalhost=yes";
1487     remote_args[argp++] = cp->dst;
1488     // FIXME: lib/gnunet/libexec/-prefix missing here!!!
1489     remote_args[argp++] = HELPER_TESTBED_BINARY_SSH;
1490     remote_args[argp++] = NULL;
1491     GNUNET_assert (argp == 10);
1492     cp->helper =
1493         GNUNET_HELPER_start (GNUNET_NO, "ssh", remote_args, &helper_mst,
1494                              &helper_exp_cb, cp);
1495   }
1496   if (NULL == cp->helper)
1497   {
1498     GNUNET_free_non_null (cp->port);
1499     GNUNET_free_non_null (cp->dst);
1500     GNUNET_free (cp);
1501     return NULL;
1502   }
1503   cp->host = host;
1504   cp->cb = cb;
1505   cp->cls = cls;
1506   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, hostname, cfg);
1507   cp->msg = &msg->header;
1508   cp->shandle =
1509       GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO, &clear_msg, cp);
1510   if (NULL == cp->shandle)
1511   {
1512     GNUNET_free (msg);
1513     GNUNET_TESTBED_controller_stop (cp);
1514     return NULL;
1515   }
1516   return cp;
1517 }
1518
1519
1520 /**
1521  * Stop the controller process (also will terminate all peers and controllers
1522  * dependent on this controller).  This function blocks until the testbed has
1523  * been fully terminated (!). The controller status cb from
1524  * GNUNET_TESTBED_controller_start() will not be called.
1525  *
1526  * @param cproc the controller process handle
1527  */
1528 void
1529 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
1530 {
1531   if (NULL != cproc->shandle)
1532     GNUNET_HELPER_send_cancel (cproc->shandle);
1533   if (NULL != cproc->helper)
1534     GNUNET_HELPER_stop (cproc->helper);
1535   if (NULL != cproc->cfg)
1536     GNUNET_CONFIGURATION_destroy (cproc->cfg);
1537   GNUNET_free_non_null (cproc->port);
1538   GNUNET_free_non_null (cproc->dst);
1539   GNUNET_free (cproc);
1540 }
1541
1542
1543 /**
1544  * Start a controller process using the given configuration at the
1545  * given host.
1546  *
1547  * @param cfg configuration to use
1548  * @param host host to run the controller on; This should be the same host if
1549  *          the controller was previously started with
1550  *          GNUNET_TESTBED_controller_start; NULL for localhost
1551  * @param event_mask bit mask with set of events to call 'cc' for;
1552  *                   or-ed values of "1LL" shifted by the
1553  *                   respective 'enum GNUNET_TESTBED_EventType'
1554  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
1555  * @param cc controller callback to invoke on events
1556  * @param cc_cls closure for cc
1557  * @return handle to the controller
1558  */
1559 struct GNUNET_TESTBED_Controller *
1560 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle
1561                                    *cfg, struct GNUNET_TESTBED_Host *host,
1562                                    uint64_t event_mask,
1563                                    GNUNET_TESTBED_ControllerCallback cc,
1564                                    void *cc_cls)
1565 {
1566   struct GNUNET_TESTBED_Controller *controller;
1567   struct GNUNET_TESTBED_InitMessage *msg;
1568   const char *controller_hostname;
1569   unsigned long long max_parallel_operations;
1570   unsigned long long max_parallel_service_connections;
1571   unsigned long long max_parallel_topology_config_operations;
1572   unsigned long long max_parallel_overlay_connect_operations;
1573
1574   if (GNUNET_OK !=
1575       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1576                                              "MAX_PARALLEL_OPERATIONS",
1577                                              &max_parallel_operations))
1578   {
1579     GNUNET_break (0);
1580     return NULL;
1581   }
1582   if (GNUNET_OK !=
1583       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1584                                              "MAX_PARALLEL_SERVICE_CONNECTIONS",
1585                                              &max_parallel_service_connections))
1586   {
1587     GNUNET_break (0);
1588     return NULL;
1589   }
1590   if (GNUNET_OK !=
1591       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1592                                              "MAX_PARALLEL_TOPOLOGY_CONFIG_OPERATIONS",
1593                                              &max_parallel_topology_config_operations))
1594   {
1595     GNUNET_break (0);
1596     return NULL;
1597   }
1598   if (GNUNET_OK !=
1599       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1600                                              "MAX_PARALLEL_OVERLAY_CONNECT_OPERATIONS",
1601                                              &max_parallel_overlay_connect_operations))
1602   {
1603     GNUNET_break (0);
1604     return NULL;
1605   }
1606   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
1607   controller->cc = cc;
1608   controller->cc_cls = cc_cls;
1609   controller->event_mask = event_mask;
1610   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
1611   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);
1612   if (NULL == controller->client)
1613   {
1614     GNUNET_TESTBED_controller_disconnect (controller);
1615     return NULL;
1616   }
1617   if (NULL == host)
1618   {
1619     host = GNUNET_TESTBED_host_create_by_id_ (0);
1620     if (NULL == host)           /* If the above host create fails */
1621     {
1622       LOG (GNUNET_ERROR_TYPE_WARNING,
1623            "Treating NULL host as localhost. Multiple references to localhost "
1624            "may break when localhost freed before calling disconnect \n");
1625       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
1626     }
1627     else
1628     {
1629       controller->aux_host = GNUNET_YES;
1630     }
1631   }
1632   GNUNET_assert (NULL != host);
1633   GNUNET_TESTBED_mark_host_registered_at_ (host, controller);
1634   controller->host = host;
1635   controller->opq_parallel_operations =
1636       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1637                                               max_parallel_operations);
1638   controller->opq_parallel_service_connections =
1639       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1640                                               max_parallel_service_connections);
1641   controller->opq_parallel_topology_config_operations=
1642       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1643                                               max_parallel_topology_config_operations);
1644   controller->opq_parallel_overlay_connect_operations=
1645       GNUNET_TESTBED_operation_queue_create_ ((unsigned int)
1646                                               max_parallel_overlay_connect_operations);
1647   controller_hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1648   if (NULL == controller_hostname)
1649     controller_hostname = "127.0.0.1";
1650   msg =
1651       GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage) +
1652                      strlen (controller_hostname) + 1);
1653   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
1654   msg->header.size =
1655       htons (sizeof (struct GNUNET_TESTBED_InitMessage) +
1656              strlen (controller_hostname) + 1);
1657   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1658   msg->event_mask = GNUNET_htonll (controller->event_mask);
1659   strcpy ((char *) &msg[1], controller_hostname);
1660   GNUNET_TESTBED_queue_message_ (controller,
1661                                  (struct GNUNET_MessageHeader *) msg);
1662   return controller;
1663 }
1664
1665
1666 /**
1667  * Configure shared services at a controller.  Using this function,
1668  * you can specify that certain services (such as "resolver")
1669  * should not be run for each peer but instead be shared
1670  * across N peers on the specified host.  This function
1671  * must be called before any peers are created at the host.
1672  *
1673  * @param controller controller to configure
1674  * @param service_name name of the service to share
1675  * @param num_peers number of peers that should share one instance
1676  *        of the specified service (1 for no sharing is the default),
1677  *        use 0 to disable the service
1678  */
1679 void
1680 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller
1681                                              *controller,
1682                                              const char *service_name,
1683                                              uint32_t num_peers)
1684 {
1685   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1686   uint16_t service_name_size;
1687   uint16_t msg_size;
1688
1689   service_name_size = strlen (service_name) + 1;
1690   msg_size =
1691       sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage) +
1692       service_name_size;
1693   msg = GNUNET_malloc (msg_size);
1694   msg->header.size = htons (msg_size);
1695   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
1696   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
1697   msg->num_peers = htonl (num_peers);
1698   memcpy (&msg[1], service_name, service_name_size);
1699   GNUNET_TESTBED_queue_message_ (controller,
1700                                  (struct GNUNET_MessageHeader *) msg);
1701   GNUNET_break (0);             /* This function is not yet implemented on the
1702                                    testbed service */
1703 }
1704
1705
1706 /**
1707  * disconnects from the controller.
1708  *
1709  * @param controller handle to controller to stop
1710  */
1711 void
1712 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller
1713                                       *controller)
1714 {
1715   struct MessageQueue *mq_entry;
1716
1717   if (NULL != controller->th)
1718     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
1719   /* Clear the message queue */
1720   while (NULL != (mq_entry = controller->mq_head))
1721   {
1722     GNUNET_CONTAINER_DLL_remove (controller->mq_head, controller->mq_tail,
1723                                  mq_entry);
1724     GNUNET_free (mq_entry->msg);
1725     GNUNET_free (mq_entry);
1726   }
1727   if (NULL != controller->client)
1728     GNUNET_CLIENT_disconnect (controller->client);
1729   GNUNET_CONFIGURATION_destroy (controller->cfg);
1730   if (GNUNET_YES == controller->aux_host)
1731     GNUNET_TESTBED_host_destroy (controller->host);
1732   GNUNET_TESTBED_operation_queue_destroy_ (controller->opq_parallel_operations);
1733   GNUNET_TESTBED_operation_queue_destroy_
1734       (controller->opq_parallel_service_connections);
1735   GNUNET_TESTBED_operation_queue_destroy_
1736       (controller->opq_parallel_topology_config_operations);
1737   GNUNET_TESTBED_operation_queue_destroy_
1738       (controller->opq_parallel_overlay_connect_operations);
1739   GNUNET_free (controller);
1740 }
1741
1742
1743 /**
1744  * Register a host with the controller
1745  *
1746  * @param controller the controller handle
1747  * @param host the host to register
1748  * @param cc the completion callback to call to inform the status of
1749  *          registration. After calling this callback the registration handle
1750  *          will be invalid. Cannot be NULL.
1751  * @param cc_cls the closure for the cc
1752  * @return handle to the host registration which can be used to cancel the
1753  *           registration
1754  */
1755 struct GNUNET_TESTBED_HostRegistrationHandle *
1756 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
1757                               struct GNUNET_TESTBED_Host *host,
1758                               GNUNET_TESTBED_HostRegistrationCompletion cc,
1759                               void *cc_cls)
1760 {
1761   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
1762   struct GNUNET_TESTBED_AddHostMessage *msg;
1763   const char *username;
1764   const char *hostname;
1765   uint16_t msg_size;
1766   uint16_t user_name_length;
1767
1768   if (NULL != controller->rh)
1769     return NULL;
1770   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
1771   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
1772   {
1773     LOG (GNUNET_ERROR_TYPE_WARNING, "Host hostname: %s already registered\n",
1774          (NULL == hostname) ? "localhost" : hostname);
1775     return NULL;
1776   }
1777   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
1778   rh->host = host;
1779   rh->c = controller;
1780   GNUNET_assert (NULL != cc);
1781   rh->cc = cc;
1782   rh->cc_cls = cc_cls;
1783   controller->rh = rh;
1784   username = GNUNET_TESTBED_host_get_username_ (host);
1785   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
1786   user_name_length = 0;
1787   if (NULL != username)
1788   {
1789     user_name_length = strlen (username) + 1;
1790     msg_size += user_name_length;
1791   }
1792   /* FIXME: what happens when hostname is NULL? localhost */
1793   GNUNET_assert (NULL != hostname);
1794   msg_size += strlen (hostname) + 1;
1795   msg = GNUNET_malloc (msg_size);
1796   msg->header.size = htons (msg_size);
1797   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
1798   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1799   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
1800   if (NULL != username)
1801   {
1802     msg->user_name_length = htons (user_name_length - 1);
1803     memcpy (&msg[1], username, user_name_length);
1804   }
1805   else
1806     msg->user_name_length = htons (user_name_length);
1807   strcpy (((void *) &msg[1]) + user_name_length, hostname);
1808   GNUNET_TESTBED_queue_message_ (controller,
1809                                  (struct GNUNET_MessageHeader *) msg);
1810   return rh;
1811 }
1812
1813
1814 /**
1815  * Cancel the pending registration. Note that if the registration message is
1816  * already sent to the service the cancellation has only the effect that the
1817  * registration completion callback for the registration is never called.
1818  *
1819  * @param handle the registration handle to cancel
1820  */
1821 void
1822 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
1823                                     *handle)
1824 {
1825   if (handle != handle->c->rh)
1826   {
1827     GNUNET_break (0);
1828     return;
1829   }
1830   handle->c->rh = NULL;
1831   GNUNET_free (handle);
1832 }
1833
1834
1835 /**
1836  * Same as the GNUNET_TESTBED_controller_link_2, but with ids for delegated host
1837  * and slave host
1838  *
1839  * @param op_cls the operation closure for the event which is generated to
1840  *          signal success or failure of this operation
1841  * @param master handle to the master controller who creates the association
1842  * @param delegated_host_id id of the host to which requests should be delegated
1843  * @param slave_host_id id of the host which is used to run the slave controller
1844  * @param sxcfg serialized and compressed configuration
1845  * @param sxcfg_size the size sxcfg
1846  * @param scfg_size the size of uncompressed serialized configuration
1847  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1848  *          be started by the slave controller; GNUNET_NO if the slave
1849  *          controller has to connect to the already started delegated
1850  *          controller via TCP/IP
1851  * @return the operation handle
1852  */
1853 struct GNUNET_TESTBED_Operation *
1854 GNUNET_TESTBED_controller_link_2_ (void *op_cls,
1855                                    struct GNUNET_TESTBED_Controller *master,
1856                                    uint32_t delegated_host_id,
1857                                    uint32_t slave_host_id,
1858                                    const char *sxcfg, size_t sxcfg_size,
1859                                    size_t scfg_size, int is_subordinate)
1860 {
1861   struct OperationContext *opc;
1862   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1863   struct ControllerLinkData *data;
1864   uint16_t msg_size;
1865
1866   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1867   msg = GNUNET_malloc (msg_size);
1868   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);
1869   msg->header.size = htons (msg_size);
1870   msg->delegated_host_id = htonl (delegated_host_id);
1871   msg->slave_host_id = htonl (slave_host_id);
1872   msg->config_size = htons ((uint16_t) scfg_size);
1873   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
1874   memcpy (&msg[1], sxcfg, sxcfg_size);
1875   data = GNUNET_malloc (sizeof (struct ControllerLinkData));
1876   data->msg = msg;
1877   opc = GNUNET_malloc (sizeof (struct OperationContext));
1878   opc->c = master;
1879   opc->data = data;
1880   opc->type = OP_LINK_CONTROLLERS;
1881   opc->id = GNUNET_TESTBED_get_next_op_id (opc->c);
1882   opc->state = OPC_STATE_INIT;
1883   opc->op_cls = op_cls;
1884   msg->operation_id = GNUNET_htonll (opc->id);
1885   opc->op =
1886       GNUNET_TESTBED_operation_create_ (opc, &opstart_link_controllers,
1887                                         &oprelease_link_controllers);
1888   GNUNET_TESTBED_operation_queue_insert_ (master->opq_parallel_operations,
1889                                           opc->op);
1890   GNUNET_TESTBED_operation_begin_wait_ (opc->op);
1891   return opc->op;
1892 }
1893
1894
1895 /**
1896  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
1897  * serialized and compressed
1898  *
1899  * @param op_cls the operation closure for the event which is generated to
1900  *          signal success or failure of this operation
1901  * @param master handle to the master controller who creates the association
1902  * @param delegated_host requests to which host should be delegated; cannot be NULL
1903  * @param slave_host which host is used to run the slave controller; use NULL to
1904  *          make the master controller connect to the delegated host
1905  * @param sxcfg serialized and compressed configuration
1906  * @param sxcfg_size the size sxcfg
1907  * @param scfg_size the size of uncompressed serialized configuration
1908  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1909  *          be started by the slave controller; GNUNET_NO if the slave
1910  *          controller has to connect to the already started delegated
1911  *          controller via TCP/IP
1912  * @return the operation handle
1913  */
1914 struct GNUNET_TESTBED_Operation *
1915 GNUNET_TESTBED_controller_link_2 (void *op_cls,
1916                                   struct GNUNET_TESTBED_Controller *master,
1917                                   struct GNUNET_TESTBED_Host *delegated_host,
1918                                   struct GNUNET_TESTBED_Host *slave_host,
1919                                   const char *sxcfg, size_t sxcfg_size,
1920                                   size_t scfg_size, int is_subordinate)
1921
1922   uint32_t delegated_host_id;
1923   uint32_t slave_host_id;
1924
1925   GNUNET_assert (GNUNET_YES ==
1926                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1927   delegated_host_id = GNUNET_TESTBED_host_get_id_ (delegated_host);
1928   slave_host_id = 
1929       GNUNET_TESTBED_host_get_id_ ((NULL != slave_host)
1930                                    ? slave_host : master->host);
1931   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1932     GNUNET_assert (GNUNET_YES ==
1933                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1934   
1935   return GNUNET_TESTBED_controller_link_2_ (op_cls,
1936                                             master,
1937                                             delegated_host_id,
1938                                             slave_host_id,
1939                                             sxcfg, sxcfg_size,
1940                                             scfg_size, is_subordinate);
1941 }
1942
1943
1944 /**
1945  * Compresses given configuration using zlib compress
1946  *
1947  * @param config the serialized configuration
1948  * @param size the size of config
1949  * @param xconfig will be set to the compressed configuration (memory is fresly
1950  *          allocated)
1951  * @return the size of the xconfig
1952  */
1953 size_t
1954 GNUNET_TESTBED_compress_config_ (const char *config, size_t size,
1955                                  char **xconfig)
1956 {
1957   size_t xsize;
1958
1959   xsize = compressBound ((uLong) size);
1960   *xconfig = GNUNET_malloc (xsize);
1961   GNUNET_assert (Z_OK ==
1962                  compress2 ((Bytef *) * xconfig, (uLongf *) & xsize,
1963                             (const Bytef *) config, (uLongf) size,
1964                             Z_BEST_SPEED));
1965   return xsize;
1966 }
1967
1968
1969 /**
1970  * Same as the GNUNET_TESTBED_controller_link, but with ids for delegated host
1971  * and slave host
1972  *
1973  * @param op_cls the operation closure for the event which is generated to
1974  *          signal success or failure of this operation
1975  * @param master handle to the master controller who creates the association
1976  * @param delegated_host_id id of the host to which requests should be
1977  *          delegated; cannot be NULL
1978  * @param slave_host_id id of the host which should connect to controller
1979  *          running on delegated host ; use NULL to make the master controller
1980  *          connect to the delegated host
1981  * @param slave_cfg configuration to use for the slave controller
1982  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1983  *          be started by the slave controller; GNUNET_NO if the slave
1984  *          controller has to connect to the already started delegated
1985  *          controller via TCP/IP
1986  * @return the operation handle
1987  */
1988 struct GNUNET_TESTBED_Operation *
1989 GNUNET_TESTBED_controller_link_ (void *op_cls,
1990                                 struct GNUNET_TESTBED_Controller *master,
1991                                 uint32_t delegated_host_id,
1992                                 uint32_t slave_host_id,
1993                                 const struct GNUNET_CONFIGURATION_Handle
1994                                 *slave_cfg,
1995                                 int is_subordinate)
1996 {
1997   struct GNUNET_TESTBED_Operation *op;
1998   char *config;
1999   char *cconfig;
2000   size_t cc_size;
2001   size_t config_size;
2002
2003   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
2004   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
2005   GNUNET_free (config);
2006   /* Configuration doesn't fit in 1 message */
2007   GNUNET_assert ((UINT16_MAX - 
2008                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage)) >=
2009                  cc_size);
2010   op = GNUNET_TESTBED_controller_link_2_ (op_cls, master, delegated_host_id,
2011                                           slave_host_id, (const char *) cconfig,
2012                                           cc_size, config_size, is_subordinate);
2013   GNUNET_free (cconfig);
2014   return op;
2015 }
2016
2017
2018 /**
2019  * Create a link from slave controller to delegated controller. Whenever the
2020  * master controller is asked to start a peer at the delegated controller the
2021  * request will be routed towards slave controller (if a route exists). The
2022  * slave controller will then route it to the delegated controller. The
2023  * configuration of the delegated controller is given and is used to either
2024  * create the delegated controller or to connect to an existing controller. Note
2025  * that while starting the delegated controller the configuration will be
2026  * modified to accommodate available free ports.  the 'is_subordinate' specifies
2027  * if the given delegated controller should be started and managed by the slave
2028  * controller, or if the delegated controller already has a master and the slave
2029  * controller connects to it as a non master controller. The success or failure
2030  * of this operation will be signalled through the
2031  * GNUNET_TESTBED_ControllerCallback() with an event of type
2032  * GNUNET_TESTBED_ET_OPERATION_FINISHED
2033  *
2034  * @param op_cls the operation closure for the event which is generated to
2035  *          signal success or failure of this operation
2036  * @param master handle to the master controller who creates the association
2037  * @param delegated_host requests to which host should be delegated; cannot be NULL
2038  * @param slave_host which host is used to run the slave controller; use NULL to
2039  *          make the master controller connect to the delegated host
2040  * @param slave_cfg configuration to use for the slave controller
2041  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
2042  *          be started by the slave controller; GNUNET_NO if the slave
2043  *          controller has to connect to the already started delegated
2044  *          controller via TCP/IP
2045  * @return the operation handle
2046  */
2047 struct GNUNET_TESTBED_Operation *
2048 GNUNET_TESTBED_controller_link (void *op_cls,
2049                                 struct GNUNET_TESTBED_Controller *master,
2050                                 struct GNUNET_TESTBED_Host *delegated_host,
2051                                 struct GNUNET_TESTBED_Host *slave_host,
2052                                 const struct GNUNET_CONFIGURATION_Handle
2053                                 *slave_cfg, int is_subordinate)
2054 {
2055   uint32_t slave_host_id;
2056   uint32_t delegated_host_id;
2057
2058   GNUNET_assert (GNUNET_YES ==
2059                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
2060   slave_host_id = 
2061       GNUNET_TESTBED_host_get_id_ ((NULL != slave_host)
2062                                    ? slave_host : master->host);
2063   delegated_host_id = GNUNET_TESTBED_host_get_id_ (delegated_host);
2064   if ((NULL != slave_host) && (0 != slave_host_id))
2065     GNUNET_assert (GNUNET_YES ==
2066                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
2067   return GNUNET_TESTBED_controller_link_ (op_cls, master,
2068                                           delegated_host_id,
2069                                           slave_host_id,
2070                                           slave_cfg,
2071                                           is_subordinate);
2072                                           
2073 }
2074
2075
2076 /**
2077  * Like GNUNET_TESTBED_get_slave_config(), however without the host registration
2078  * check. Another difference is that this function takes the id of the slave
2079  * host.
2080  *
2081  * @param op_cls the closure for the operation
2082  * @param master the handle to master controller
2083  * @param slave_host_id id of the host where the slave controller is running to
2084  *          the slave_host should remain valid until this operation is cancelled
2085  *          or marked as finished
2086  * @return the operation handle;
2087  */
2088 struct GNUNET_TESTBED_Operation *
2089 GNUNET_TESTBED_get_slave_config_ (void *op_cls,
2090                                   struct GNUNET_TESTBED_Controller *master,
2091                                   uint32_t slave_host_id)
2092 {  
2093   struct OperationContext *opc;
2094   struct GetSlaveConfigData *data;
2095
2096   data = GNUNET_malloc (sizeof (struct GetSlaveConfigData));
2097   data->slave_id = slave_host_id;
2098   opc = GNUNET_malloc (sizeof (struct OperationContext));
2099   opc->state = OPC_STATE_INIT;
2100   opc->c = master;
2101   opc->id = GNUNET_TESTBED_get_next_op_id (master);
2102   opc->type = OP_GET_SLAVE_CONFIG;
2103   opc->data = data;
2104   opc->op_cls = op_cls;
2105   opc->op =
2106       GNUNET_TESTBED_operation_create_ (opc, &opstart_get_slave_config,
2107                                         &oprelease_get_slave_config);
2108   GNUNET_TESTBED_operation_queue_insert_ (master->opq_parallel_operations,
2109                                           opc->op); 
2110   GNUNET_TESTBED_operation_begin_wait_ (opc->op);
2111   return opc->op;
2112 }
2113
2114
2115 /**
2116  * Function to acquire the configuration of a running slave controller. The
2117  * completion of the operation is signalled through the controller_cb from
2118  * GNUNET_TESTBED_controller_connect(). If the operation is successful the
2119  * handle to the configuration is available in the generic pointer of
2120  * operation_finished field of struct GNUNET_TESTBED_EventInformation.
2121  *
2122  * @param op_cls the closure for the operation
2123  * @param master the handle to master controller
2124  * @param slave_host the host where the slave controller is running; the handle
2125  *          to the slave_host should remain valid until this operation is
2126  *          cancelled or marked as finished
2127  * @return the operation handle; NULL if the slave_host is not registered at
2128  *           master
2129  */
2130 struct GNUNET_TESTBED_Operation *
2131 GNUNET_TESTBED_get_slave_config (void *op_cls,
2132                                  struct GNUNET_TESTBED_Controller *master,
2133                                  struct GNUNET_TESTBED_Host *slave_host)
2134 {
2135   if (GNUNET_NO == GNUNET_TESTBED_is_host_registered_ (slave_host, master))
2136     return NULL;
2137   return GNUNET_TESTBED_get_slave_config_ (op_cls, master,
2138                                            GNUNET_TESTBED_host_get_id_ (slave_host));
2139 }
2140
2141
2142 /**
2143  * Ask the testbed controller to write the current overlay topology to
2144  * a file.  Naturally, the file will only contain a snapshot as the
2145  * topology may evolve all the time.
2146  *
2147  * @param controller overlay controller to inspect
2148  * @param filename name of the file the topology should
2149  *        be written to.
2150  */
2151 void
2152 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller
2153                                                *controller,
2154                                                const char *filename)
2155 {
2156   GNUNET_break (0);
2157 }
2158
2159
2160 /**
2161  * Creates a helper initialization message. This function is here because we
2162  * want to use this in testing
2163  *
2164  * @param cname the ip address of the controlling host
2165  * @param hostname the hostname of the destination this message is intended for
2166  * @param cfg the configuration that has to used to start the testbed service
2167  *          thru helper
2168  * @return the initialization message
2169  */
2170 struct GNUNET_TESTBED_HelperInit *
2171 GNUNET_TESTBED_create_helper_init_msg_ (const char *cname,
2172                                         const char *hostname,
2173                                         const struct GNUNET_CONFIGURATION_Handle
2174                                         *cfg)
2175 {
2176   struct GNUNET_TESTBED_HelperInit *msg;
2177   char *config;
2178   char *xconfig;
2179   size_t config_size;
2180   size_t xconfig_size;
2181   uint16_t cname_len;
2182   uint16_t hostname_len;
2183   uint16_t msg_size;
2184
2185   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
2186   GNUNET_assert (NULL != config);
2187   xconfig_size =
2188       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
2189   GNUNET_free (config);
2190   cname_len = strlen (cname);
2191   hostname_len = (NULL == hostname) ? 0 : strlen (hostname);
2192   msg_size =
2193       xconfig_size + cname_len + 1 + sizeof (struct GNUNET_TESTBED_HelperInit);
2194   msg_size += hostname_len;
2195   msg = GNUNET_realloc (xconfig, msg_size);
2196   (void) memmove (((void *) &msg[1]) + cname_len + 1 + hostname_len,
2197                   msg,
2198                   xconfig_size);
2199   msg->header.size = htons (msg_size);
2200   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
2201   msg->cname_size = htons (cname_len);
2202   msg->hostname_size = htons (hostname_len);
2203   msg->config_size = htons (config_size);
2204   (void) strcpy ((char *) &msg[1], cname);
2205   if (0 != hostname_len)
2206     (void) strncpy (((char *) &msg[1]) + cname_len + 1, hostname, hostname_len);
2207   return msg;
2208 }
2209
2210
2211 /**
2212  * Cancel a pending operation.  Releases all resources
2213  * of the operation and will ensure that no event
2214  * is generated for the operation.  Does NOT guarantee
2215  * that the operation will be fully undone (or that
2216  * nothing ever happened).
2217  *
2218  * @param operation operation to cancel
2219  */
2220 void
2221 GNUNET_TESTBED_operation_cancel (struct GNUNET_TESTBED_Operation *operation)
2222 {
2223   GNUNET_TESTBED_operation_done (operation);
2224 }
2225
2226
2227 /**
2228  * Signal that the information from an operation has been fully
2229  * processed.  This function MUST be called for each event
2230  * of type 'operation_finished' to fully remove the operation
2231  * from the operation queue.  After calling this function, the
2232  * 'op_result' becomes invalid (!).
2233  *
2234  * @param operation operation to signal completion for
2235  */
2236 void
2237 GNUNET_TESTBED_operation_done (struct GNUNET_TESTBED_Operation *operation)
2238 {
2239     GNUNET_TESTBED_operation_release_ (operation);
2240 }
2241
2242
2243 /**
2244  * Generates configuration by uncompressing configuration in given message. The
2245  * given message should be of the following types:
2246  * GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG,
2247  * GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG
2248  *
2249  * @param msg the message containing compressed configuration
2250  * @return handle to the parsed configuration
2251  */
2252 struct GNUNET_CONFIGURATION_Handle *
2253 GNUNET_TESTBED_extract_config_ (const struct GNUNET_MessageHeader *msg)
2254 {  
2255   struct GNUNET_CONFIGURATION_Handle *cfg;
2256   Bytef *data;
2257   const Bytef *xdata;
2258   uLong data_len;
2259   uLong xdata_len;
2260   int ret;
2261
2262   switch (ntohs (msg->type))
2263   {
2264   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG:
2265     {
2266       const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *imsg;
2267
2268       imsg = (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *)
2269           msg;
2270       data_len = (uLong) ntohs (imsg->config_size);
2271       xdata_len = ntohs (imsg->header.size)
2272           - sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
2273       xdata = (const Bytef *) &imsg[1];
2274     }
2275     break;
2276   case GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG:
2277     {
2278       const struct GNUNET_TESTBED_SlaveConfiguration *imsg;
2279
2280       imsg = (const struct GNUNET_TESTBED_SlaveConfiguration *) msg;
2281       data_len = (uLong) ntohs (imsg->config_size);
2282       xdata_len =  ntohs (imsg->header.size) 
2283           - sizeof (struct GNUNET_TESTBED_SlaveConfiguration);
2284       xdata = (const Bytef *) &imsg[1];
2285     }
2286     break;
2287   default:
2288     GNUNET_assert (0);
2289   }  
2290   data = GNUNET_malloc (data_len);
2291   if (Z_OK !=
2292       (ret =
2293        uncompress (data, &data_len, xdata, xdata_len)))
2294     GNUNET_assert (0);
2295   cfg = GNUNET_CONFIGURATION_create ();
2296   GNUNET_assert (GNUNET_OK ==
2297                  GNUNET_CONFIGURATION_deserialize (cfg, (const char *) data,
2298                                                    (size_t) data_len,
2299                                                    GNUNET_NO));
2300   GNUNET_free (data);
2301   return cfg;
2302 }
2303
2304
2305 /**
2306  * Checks the integrity of the OperationFailureEventMessage and if good returns
2307  * the error message it contains.
2308  *
2309  * @param msg the OperationFailureEventMessage
2310  * @return the error message
2311  */
2312 const char *
2313 GNUNET_TESTBED_parse_error_string_ (const struct
2314                                     GNUNET_TESTBED_OperationFailureEventMessage
2315                                     *msg)
2316 {
2317   uint16_t msize;
2318   const char *emsg;
2319   
2320   msize = ntohs (msg->header.size);
2321   if (sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage) >= msize)
2322     return NULL;
2323   msize -= sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
2324   emsg = (const char *) &msg[1];
2325   if ('\0' != emsg[msize - 1])
2326   {
2327     GNUNET_break (0);
2328     return NULL;
2329   }
2330   return emsg;
2331 }
2332
2333
2334 /**
2335  * Function to return the operation id for a controller. The operation id is
2336  * created from the controllers host id and its internal operation counter.
2337  *
2338  * @param controller the handle to the controller whose operation id has to be incremented
2339  * @return the incremented operation id.
2340  */
2341 uint64_t
2342 GNUNET_TESTBED_get_next_op_id (struct GNUNET_TESTBED_Controller *controller)
2343 {
2344   uint64_t op_id;  
2345
2346   op_id = (uint64_t) GNUNET_TESTBED_host_get_id_ (controller->host);
2347   op_id = op_id <<  32;
2348   op_id |= (uint64_t) controller->operation_counter++;
2349   return op_id;
2350 }
2351
2352 /* end of testbed_api.c */