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