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