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