- minor changes, TODO, debug message
[oweals/gnunet.git] / src / testbed / testbed_api.c
1 /*
2       This file is part of GNUnet
3       Copyright (C) 2008--2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18       Boston, MA 02110-1301, 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 #include "platform.h"
30 #include "gnunet_testbed_service.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_hello_lib.h"
35 #include <zlib.h>
36
37 #include "testbed.h"
38 #include "testbed_api.h"
39 #include "testbed_api_hosts.h"
40 #include "testbed_api_peers.h"
41 #include "testbed_api_operations.h"
42 #include "testbed_api_sd.h"
43
44 /**
45  * Generic logging shorthand
46  */
47 #define LOG(kind, ...)                          \
48   GNUNET_log_from (kind, "testbed-api", __VA_ARGS__)
49
50 /**
51  * Debug logging
52  */
53 #define LOG_DEBUG(...)                          \
54   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
55
56 /**
57  * Relative time seconds shorthand
58  */
59 #define TIME_REL_SECS(sec) \
60   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, sec)
61
62
63 /**
64  * Default server message sending retry timeout
65  */
66 #define TIMEOUT_REL TIME_REL_SECS(1)
67
68
69 /**
70  * Context data for forwarded Operation
71  */
72 struct ForwardedOperationData
73 {
74
75   /**
76    * The callback to call when reply is available
77    */
78   GNUNET_MQ_MessageCallback cc;
79
80   /**
81    * The closure for the above callback
82    */
83   void *cc_cls;
84
85 };
86
87
88 /**
89  * Context data for get slave config operations
90  */
91 struct GetSlaveConfigData
92 {
93   /**
94    * The id of the slave controller
95    */
96   uint32_t slave_id;
97
98 };
99
100
101 /**
102  * Context data for controller link operations
103  */
104 struct ControllerLinkData
105 {
106   /**
107    * The controller link message
108    */
109   struct GNUNET_TESTBED_ControllerLinkRequest *msg;
110
111   /**
112    * The id of the host which is hosting the controller to be linked
113    */
114   uint32_t host_id;
115
116 };
117
118
119 /**
120  * Date context for OP_SHUTDOWN_PEERS operations
121  */
122 struct ShutdownPeersData
123 {
124   /**
125    * The operation completion callback to call
126    */
127   GNUNET_TESTBED_OperationCompletionCallback cb;
128
129   /**
130    * The closure for the above callback
131    */
132   void *cb_cls;
133 };
134
135
136 /**
137  * An entry in the stack for keeping operations which are about to expire
138  */
139 struct ExpireOperationEntry
140 {
141   /**
142    * DLL head; new entries are to be inserted here
143    */
144   struct ExpireOperationEntry *next;
145
146   /**
147    * DLL tail; entries are deleted from here
148    */
149   struct ExpireOperationEntry *prev;
150
151   /**
152    * The operation.  This will be a dangling pointer when the operation is freed
153    */
154   const struct GNUNET_TESTBED_Operation *op;
155 };
156
157
158 /**
159  * DLL head for list of operations marked for expiry
160  */
161 static struct ExpireOperationEntry *exop_head;
162
163 /**
164  * DLL tail for list of operation marked for expiry
165  */
166 static struct ExpireOperationEntry *exop_tail;
167
168
169 /**
170  * Inserts an operation into the list of operations marked for expiry
171  *
172  * @param op the operation to insert
173  */
174 static void
175 exop_insert (struct GNUNET_TESTBED_Operation *op)
176 {
177   struct ExpireOperationEntry *entry;
178
179   entry = GNUNET_new (struct ExpireOperationEntry);
180   entry->op = op;
181   GNUNET_CONTAINER_DLL_insert_tail (exop_head, exop_tail, entry);
182 }
183
184
185 /**
186  * Checks if an operation is present in the list of operations marked for
187  * expiry.  If the operation is found, it and the tail of operations after it
188  * are removed from the list.
189  *
190  * @param op the operation to check
191  * @return GNUNET_NO if the operation is not present in the list; GNUNET_YES if
192  *           the operation is found in the list (the operation is then removed
193  *           from the list -- calling this function again with the same
194  *           paramenter will return GNUNET_NO)
195  */
196 static int
197 exop_check (const struct GNUNET_TESTBED_Operation *const op)
198 {
199   struct ExpireOperationEntry *entry;
200   struct ExpireOperationEntry *entry2;
201   int found;
202
203   found = GNUNET_NO;
204   entry = exop_head;
205   while (NULL != entry)
206   {
207     if (op == entry->op)
208     {
209       found = GNUNET_YES;
210       break;
211     }
212     entry = entry->next;
213   }
214   if (GNUNET_NO == found)
215     return GNUNET_NO;
216   /* Truncate the tail */
217   while (NULL != entry)
218   {
219     entry2 = entry->next;
220     GNUNET_CONTAINER_DLL_remove (exop_head,
221                                  exop_tail,
222                                  entry);
223     GNUNET_free (entry);
224     entry = entry2;
225   }
226   return GNUNET_YES;
227 }
228
229
230 /**
231  * Context information to be used while searching for operation contexts
232  */
233 struct SearchContext
234 {
235   /**
236    * The result of the search
237    */
238   struct OperationContext *opc;
239
240   /**
241    * The id of the operation context we are searching for
242    */
243   uint64_t id;
244 };
245
246
247 /**
248  * Search iterator for searching an operation context
249  *
250  * @param cls the serach context
251  * @param key current key code
252  * @param value value in the hash map
253  * @return #GNUNET_YES if we should continue to iterate,
254  *         #GNUNET_NO if not.
255  */
256 static int
257 opc_search_iterator (void *cls,
258                      uint32_t key,
259                      void *value)
260 {
261   struct SearchContext *sc = cls;
262   struct OperationContext *opc = value;
263
264   GNUNET_assert (NULL != opc);
265   GNUNET_assert (NULL == sc->opc);
266   if (opc->id != sc->id)
267     return GNUNET_YES;
268   sc->opc = opc;
269   return GNUNET_NO;
270 }
271
272
273 /**
274  * Returns the operation context with the given id if found in the Operation
275  * context queues of the controller
276  *
277  * @param c the controller whose operation context map is searched
278  * @param id the id which has to be checked
279  * @return the matching operation context; NULL if no match found
280  */
281 static struct OperationContext *
282 find_opc (const struct GNUNET_TESTBED_Controller *c, const uint64_t id)
283 {
284   struct SearchContext sc;
285
286   sc.id = id;
287   sc.opc = NULL;
288   GNUNET_assert (NULL != c->opc_map);
289   if (GNUNET_SYSERR !=
290       GNUNET_CONTAINER_multihashmap32_get_multiple (c->opc_map, (uint32_t) id,
291                                                     &opc_search_iterator, &sc))
292     return NULL;
293   return sc.opc;
294 }
295
296
297 /**
298  * Inserts the given operation context into the operation context map of the
299  * given controller.  Creates the operation context map if one does not exist
300  * for the controller
301  *
302  * @param c the controller
303  * @param opc the operation context to be inserted
304  */
305 void
306 GNUNET_TESTBED_insert_opc_ (struct GNUNET_TESTBED_Controller *c,
307                             struct OperationContext *opc)
308 {
309   if (NULL == c->opc_map)
310     c->opc_map = GNUNET_CONTAINER_multihashmap32_create (256);
311   GNUNET_assert (GNUNET_OK ==
312                  GNUNET_CONTAINER_multihashmap32_put (c->opc_map,
313                                                       (uint32_t) opc->id, opc,
314                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
315 }
316
317
318 /**
319  * Removes the given operation context from the operation context map of the
320  * given controller
321  *
322  * @param c the controller
323  * @param opc the operation context to remove
324  */
325 void
326 GNUNET_TESTBED_remove_opc_ (const struct GNUNET_TESTBED_Controller *c,
327                             struct OperationContext *opc)
328 {
329   GNUNET_assert (NULL != c->opc_map);
330   GNUNET_assert (GNUNET_YES ==
331                  GNUNET_CONTAINER_multihashmap32_remove (c->opc_map,
332                                                          (uint32_t) opc->id,
333                                                          opc));
334   if ( (0 == GNUNET_CONTAINER_multihashmap32_size (c->opc_map))
335        && (NULL != c->opcq_empty_cb) )
336     c->opcq_empty_cb (c->opcq_empty_cls);
337 }
338
339
340
341 /**
342  * Check #GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message is well-formed.
343  *
344  * @param cls the controller handler
345  * @param msg message received
346  * @return #GNUNET_OK if message is well-formed
347  */
348 static int
349 check_add_host_confirm (void *cls,
350                         const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
351 {
352   const char *emsg;
353   uint16_t msg_size;
354
355   msg_size = ntohs (msg->header.size) - sizeof (*msg);
356   if (0 == msg_size)
357     return GNUNET_OK;
358   /* We have an error message */
359   emsg = (const char *) &msg[1];
360   if ('\0' != emsg[msg_size - 1])
361   {
362     GNUNET_break (0);
363     return GNUNET_SYSERR;
364   }
365   return GNUNET_OK;
366 }
367
368
369 /**
370  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
371  * controller (testbed service)
372  *
373  * @param cls the controller handler
374  * @param msg message received
375  */
376 static void
377 handle_add_host_confirm (void *cls,
378                          const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
379 {
380   struct GNUNET_TESTBED_Controller *c = cls;
381   struct GNUNET_TESTBED_HostRegistrationHandle *rh = c->rh;
382   const char *emsg;
383   uint16_t msg_size;
384
385   if (NULL == rh)
386     return;
387   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
388   {
389     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
390                GNUNET_TESTBED_host_get_id_ (rh->host),
391                ntohl (msg->host_id));
392     return;
393   }
394   c->rh = NULL;
395   msg_size = ntohs (msg->header.size) - sizeof (*msg);
396   if (0 == msg_size)
397   {
398     LOG_DEBUG ("Host %u successfully registered\n",
399                ntohl (msg->host_id));
400     GNUNET_TESTBED_mark_host_registered_at_ (rh->host,
401                                              c);
402     rh->cc (rh->cc_cls,
403             NULL);
404     GNUNET_free (rh);
405     return;
406   }
407   /* We have an error message */
408   emsg = (const char *) &msg[1];
409   LOG (GNUNET_ERROR_TYPE_ERROR,
410        _("Adding host %u failed with error: %s\n"),
411        ntohl (msg->host_id),
412        emsg);
413   rh->cc (rh->cc_cls,
414           emsg);
415   GNUNET_free (rh);
416 }
417
418
419 /**
420  * Handler for forwarded operations
421  *
422  * @param c the controller handle
423  * @param opc the opearation context
424  * @param msg the message
425  */
426 static void
427 handle_forwarded_operation_msg (void *cls,
428                                 struct OperationContext *opc,
429                                 const struct GNUNET_MessageHeader *msg)
430 {
431   struct GNUNET_TESTBED_Controller *c = cls;
432   struct ForwardedOperationData *fo_data;
433
434   fo_data = opc->data;
435   if (NULL != fo_data->cc)
436     fo_data->cc (fo_data->cc_cls, msg);
437   GNUNET_TESTBED_remove_opc_ (c, opc);
438   GNUNET_free (fo_data);
439   GNUNET_free (opc);
440 }
441
442
443 /**
444  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST_SUCCESS message from
445  * controller (testbed service)
446  *
447  * @param c the controller handler
448  * @param msg message received
449  */
450 static void
451 handle_opsuccess (void *cls,
452                   const struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg)
453 {
454   struct GNUNET_TESTBED_Controller *c = cls;
455   struct OperationContext *opc;
456   GNUNET_TESTBED_OperationCompletionCallback op_comp_cb;
457   void *op_comp_cb_cls;
458   struct GNUNET_TESTBED_EventInformation event;
459   uint64_t op_id;
460
461   op_id = GNUNET_ntohll (msg->operation_id);
462   LOG_DEBUG ("Operation %lu successful\n", op_id);
463   if (NULL == (opc = find_opc (c, op_id)))
464   {
465     LOG_DEBUG ("Operation not found\n");
466     return;
467   }
468   event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
469   event.op = opc->op;
470   event.op_cls = opc->op_cls;
471   event.details.operation_finished.emsg = NULL;
472   event.details.operation_finished.generic = NULL;
473   op_comp_cb = NULL;
474   op_comp_cb_cls = NULL;
475   switch (opc->type)
476   {
477   case OP_FORWARDED:
478     {
479       handle_forwarded_operation_msg (c, opc,
480                                       (const struct GNUNET_MessageHeader *) msg);
481       return;
482     }
483     break;
484   case OP_PEER_DESTROY:
485   {
486     struct GNUNET_TESTBED_Peer *peer;
487
488     peer = opc->data;
489     GNUNET_TESTBED_peer_deregister_ (peer);
490     GNUNET_free (peer);
491     opc->data = NULL;
492     //PEERDESTROYDATA
493   }
494     break;
495   case OP_SHUTDOWN_PEERS:
496   {
497     struct ShutdownPeersData *data;
498
499     data = opc->data;
500     op_comp_cb = data->cb;
501     op_comp_cb_cls = data->cb_cls;
502     GNUNET_free (data);
503     opc->data = NULL;
504     GNUNET_TESTBED_cleanup_peers_ ();
505   }
506     break;
507   case OP_MANAGE_SERVICE:
508   {
509     struct ManageServiceData *data;
510
511     GNUNET_assert (NULL != (data = opc->data));
512     op_comp_cb = data->cb;
513     op_comp_cb_cls = data->cb_cls;
514     GNUNET_free (data);
515     opc->data = NULL;
516   }
517     break;
518   case OP_PEER_RECONFIGURE:
519     break;
520   default:
521     GNUNET_assert (0);
522   }
523   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
524   opc->state = OPC_STATE_FINISHED;
525   exop_insert (event.op);
526   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
527   {
528     if (NULL != c->cc)
529       c->cc (c->cc_cls, &event);
530     if (GNUNET_NO == exop_check (event.op))
531       return;
532   }
533   else
534     LOG_DEBUG ("Not calling callback\n");
535   if (NULL != op_comp_cb)
536     op_comp_cb (op_comp_cb_cls, event.op, NULL);
537    /* You could have marked the operation as done by now */
538   GNUNET_break (GNUNET_NO == exop_check (event.op));
539 }
540
541
542 /**
543  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_CREATE_PEER_SUCCESS message from
544  * controller (testbed service)
545  *
546  * @param c the controller handle
547  * @param msg message received
548  */
549 static void
550 handle_peer_create_success (void *cls,
551                             const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *msg)
552 {
553   struct GNUNET_TESTBED_Controller *c = cls;
554   struct OperationContext *opc;
555   struct PeerCreateData *data;
556   struct GNUNET_TESTBED_Peer *peer;
557   struct GNUNET_TESTBED_Operation *op;
558   GNUNET_TESTBED_PeerCreateCallback cb;
559   void *cb_cls;
560   uint64_t op_id;
561
562   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage) ==
563                  ntohs (msg->header.size));
564   op_id = GNUNET_ntohll (msg->operation_id);
565   if (NULL == (opc = find_opc (c, op_id)))
566   {
567     LOG_DEBUG ("Operation context for PeerCreateSuccessEvent not found\n");
568     return;
569   }
570   if (OP_FORWARDED == opc->type)
571   {
572     handle_forwarded_operation_msg (c, opc,
573                                     (const struct GNUNET_MessageHeader *) msg);
574     return;
575   }
576   GNUNET_assert (OP_PEER_CREATE == opc->type);
577   GNUNET_assert (NULL != opc->data);
578   data = opc->data;
579   GNUNET_assert (NULL != data->peer);
580   peer = data->peer;
581   GNUNET_assert (peer->unique_id == ntohl (msg->peer_id));
582   peer->state = TESTBED_PS_CREATED;
583   GNUNET_TESTBED_peer_register_ (peer);
584   cb = data->cb;
585   cb_cls = data->cls;
586   op = opc->op;
587   GNUNET_free (opc->data);
588   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
589   opc->state = OPC_STATE_FINISHED;
590   exop_insert (op);
591   if (NULL != cb)
592     cb (cb_cls, peer, NULL);
593    /* You could have marked the operation as done by now */
594   GNUNET_break (GNUNET_NO == exop_check (op));
595 }
596
597
598 /**
599  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_PEER_EVENT message from
600  * controller (testbed service)
601  *
602  * @param c the controller handler
603  * @param msg message received
604  */
605 static void
606 handle_peer_event (void *cls,
607                    const struct GNUNET_TESTBED_PeerEventMessage *msg)
608 {
609   struct GNUNET_TESTBED_Controller *c = cls;
610   struct OperationContext *opc;
611   struct GNUNET_TESTBED_Peer *peer;
612   struct PeerEventData *data;
613   GNUNET_TESTBED_PeerChurnCallback pcc;
614   void *pcc_cls;
615   struct GNUNET_TESTBED_EventInformation event;
616   uint64_t op_id;
617   uint64_t mask;
618
619   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerEventMessage) ==
620                  ntohs (msg->header.size));
621   op_id = GNUNET_ntohll (msg->operation_id);
622   if (NULL == (opc = find_opc (c, op_id)))
623   {
624     LOG_DEBUG ("Operation not found\n");
625     return;
626   }
627   if (OP_FORWARDED == opc->type)
628   {
629     handle_forwarded_operation_msg (c, opc,
630                                     (const struct GNUNET_MessageHeader *) msg);
631     return;
632   }
633   GNUNET_assert ((OP_PEER_START == opc->type) || (OP_PEER_STOP == opc->type));
634   data = opc->data;
635   GNUNET_assert (NULL != data);
636   peer = data->peer;
637   GNUNET_assert (NULL != peer);
638   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
639   event.op = opc->op;
640   event.op_cls = opc->op_cls;
641   switch (event.type)
642   {
643   case GNUNET_TESTBED_ET_PEER_START:
644     peer->state = TESTBED_PS_STARTED;
645     event.details.peer_start.host = peer->host;
646     event.details.peer_start.peer = peer;
647     break;
648   case GNUNET_TESTBED_ET_PEER_STOP:
649     peer->state = TESTBED_PS_STOPPED;
650     event.details.peer_stop.peer = peer;
651     break;
652   default:
653     GNUNET_assert (0);          /* We should never reach this state */
654   }
655   pcc = data->pcc;
656   pcc_cls = data->pcc_cls;
657   GNUNET_free (data);
658   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
659   opc->state = OPC_STATE_FINISHED;
660   exop_insert (event.op);
661   mask = 1LL << GNUNET_TESTBED_ET_PEER_START;
662   mask |= 1LL << GNUNET_TESTBED_ET_PEER_STOP;
663   if (0 != (mask & c->event_mask))
664   {
665     if (NULL != c->cc)
666       c->cc (c->cc_cls, &event);
667     if (GNUNET_NO == exop_check (event.op))
668       return;
669   }
670   if (NULL != pcc)
671     pcc (pcc_cls, NULL);
672    /* You could have marked the operation as done by now */
673   GNUNET_break (GNUNET_NO == exop_check (event.op));
674 }
675
676
677 /**
678  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_PEER_CONNECT_EVENT message from
679  * controller (testbed service)
680  *
681  * @param c the controller handler
682  * @param msg message received
683  */
684 static void
685 handle_peer_conevent (void *cls,
686                       const struct GNUNET_TESTBED_ConnectionEventMessage *msg)
687 {
688   struct GNUNET_TESTBED_Controller *c = cls;
689   struct OperationContext *opc;
690   struct OverlayConnectData *data;
691   GNUNET_TESTBED_OperationCompletionCallback cb;
692   void *cb_cls;
693   struct GNUNET_TESTBED_EventInformation event;
694   uint64_t op_id;
695   uint64_t mask;
696
697   op_id = GNUNET_ntohll (msg->operation_id);
698   if (NULL == (opc = find_opc (c, op_id)))
699   {
700     LOG_DEBUG ("Operation not found\n");
701     return;
702   }
703   if (OP_FORWARDED == opc->type)
704   {
705     handle_forwarded_operation_msg (c, opc,
706                                     (const struct GNUNET_MessageHeader *) msg);
707     return;
708   }
709   GNUNET_assert (OP_OVERLAY_CONNECT == opc->type);
710   GNUNET_assert (NULL != (data = opc->data));
711   GNUNET_assert ((ntohl (msg->peer1) == data->p1->unique_id) &&
712                  (ntohl (msg->peer2) == data->p2->unique_id));
713   event.type = (enum GNUNET_TESTBED_EventType) ntohl (msg->event_type);
714   event.op = opc->op;
715   event.op_cls = opc->op_cls;
716   switch (event.type)
717   {
718   case GNUNET_TESTBED_ET_CONNECT:
719     event.details.peer_connect.peer1 = data->p1;
720     event.details.peer_connect.peer2 = data->p2;
721     break;
722   case GNUNET_TESTBED_ET_DISCONNECT:
723     GNUNET_assert (0);          /* FIXME: implement */
724     break;
725   default:
726     GNUNET_assert (0);          /* Should never reach here */
727     break;
728   }
729   cb = data->cb;
730   cb_cls = data->cb_cls;
731   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
732   opc->state = OPC_STATE_FINISHED;
733   exop_insert (event.op);
734   mask = 1LL << GNUNET_TESTBED_ET_CONNECT;
735   mask |= 1LL << GNUNET_TESTBED_ET_DISCONNECT;
736   if (0 != (mask & c->event_mask))
737   {
738     if (NULL != c->cc)
739       c->cc (c->cc_cls, &event);
740     if (GNUNET_NO == exop_check (event.op))
741       return;
742   }
743   if (NULL != cb)
744     cb (cb_cls, opc->op, NULL);
745    /* You could have marked the operation as done by now */
746   GNUNET_break (GNUNET_NO == exop_check (event.op));
747 }
748
749
750 /**
751  * Validate #GNUNET_MESSAGE_TYPE_TESTBED_PEER_INFORMATION message from
752  * controller (testbed service)
753  *
754  * @param c the controller handler
755  * @param msg message received
756  */
757 static int
758 check_peer_config (void *cls,
759                    const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *msg)
760 {
761   /* anything goes? */
762   return GNUNET_OK;
763 }
764
765
766 /**
767  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_PEER_INFORMATION message from
768  * controller (testbed service)
769  *
770  * @param c the controller handler
771  * @param msg message received
772  */
773 static void
774 handle_peer_config (void *cls,
775                     const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *msg)
776 {
777   struct GNUNET_TESTBED_Controller *c = cls;
778   struct OperationContext *opc;
779   struct GNUNET_TESTBED_Peer *peer;
780   struct PeerInfoData *data;
781   struct GNUNET_TESTBED_PeerInformation *pinfo;
782   GNUNET_TESTBED_PeerInfoCallback cb;
783   void *cb_cls;
784   uint64_t op_id;
785
786   op_id = GNUNET_ntohll (msg->operation_id);
787   if (NULL == (opc = find_opc (c, op_id)))
788   {
789     LOG_DEBUG ("Operation not found\n");
790     return;
791   }
792   if (OP_FORWARDED == opc->type)
793   {
794     handle_forwarded_operation_msg (c,
795                                     opc,
796                                     &msg->header);
797     return;
798   }
799   data = opc->data;
800   GNUNET_assert (NULL != data);
801   peer = data->peer;
802   GNUNET_assert (NULL != peer);
803   GNUNET_assert (ntohl (msg->peer_id) == peer->unique_id);
804   pinfo = GNUNET_new (struct GNUNET_TESTBED_PeerInformation);
805   pinfo->pit = data->pit;
806   cb = data->cb;
807   cb_cls = data->cb_cls;
808   GNUNET_assert (NULL != cb);
809   GNUNET_free (data);
810   opc->data = NULL;
811   switch (pinfo->pit)
812   {
813   case GNUNET_TESTBED_PIT_IDENTITY:
814     pinfo->result.id = GNUNET_new (struct GNUNET_PeerIdentity);
815     GNUNET_memcpy (pinfo->result.id,
816                    &msg->peer_identity,
817                    sizeof (struct GNUNET_PeerIdentity));
818     break;
819   case GNUNET_TESTBED_PIT_CONFIGURATION:
820     pinfo->result.cfg =         /* Freed in oprelease_peer_getinfo */
821         GNUNET_TESTBED_extract_config_ (&msg->header);
822     break;
823   case GNUNET_TESTBED_PIT_GENERIC:
824     GNUNET_assert (0);          /* never reach here */
825     break;
826   }
827   opc->data = pinfo;
828   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
829   opc->state = OPC_STATE_FINISHED;
830   cb (cb_cls, opc->op, pinfo, NULL);
831   /* We dont check whether the operation is marked as done here as the
832      operation contains data (cfg/identify) which will be freed at a later point
833   */
834 }
835
836
837 /**
838  * Validate #GNUNET_MESSAGE_TYPE_TESTBED_OPERATION_FAIL_EVENT message from
839  * controller (testbed service)
840  *
841  * @param c the controller handler
842  * @param msg message received
843  * @return #GNUNET_OK if message is well-formed
844  */
845 static int
846 check_op_fail_event (void *cls,
847                      const struct GNUNET_TESTBED_OperationFailureEventMessage *msg)
848 {
849   /* we accept anything as a valid error message */
850   return GNUNET_OK;
851 }
852
853
854 /**
855  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_OPERATION_FAIL_EVENT message from
856  * controller (testbed service)
857  *
858  * @param c the controller handler
859  * @param msg message received
860  */
861 static void
862 handle_op_fail_event (void *cls,
863                       const struct GNUNET_TESTBED_OperationFailureEventMessage *msg)
864 {
865   struct GNUNET_TESTBED_Controller *c = cls;
866   struct OperationContext *opc;
867   const char *emsg;
868   uint64_t op_id;
869   uint64_t mask;
870   struct GNUNET_TESTBED_EventInformation event;
871
872   op_id = GNUNET_ntohll (msg->operation_id);
873   if (NULL == (opc = find_opc (c, op_id)))
874   {
875     LOG_DEBUG ("Operation not found\n");
876     return;
877   }
878   if (OP_FORWARDED == opc->type)
879   {
880     handle_forwarded_operation_msg (c, opc,
881                                     (const struct GNUNET_MessageHeader *) msg);
882     return;
883   }
884   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
885   opc->state = OPC_STATE_FINISHED;
886   emsg = GNUNET_TESTBED_parse_error_string_ (msg);
887   if (NULL == emsg)
888     emsg = "Unknown error";
889   if (OP_PEER_INFO == opc->type)
890   {
891     struct PeerInfoData *data;
892
893     data = opc->data;
894     if (NULL != data->cb)
895       data->cb (data->cb_cls, opc->op, NULL, emsg);
896     GNUNET_free (data);
897     return;          /* We do not call controller callback for peer info */
898   }
899   event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
900   event.op = opc->op;
901   event.op_cls = opc->op_cls;
902   event.details.operation_finished.emsg = emsg;
903   event.details.operation_finished.generic = NULL;
904   mask = (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
905   if ((0 != (mask & c->event_mask)) && (NULL != c->cc))
906   {
907     exop_insert (event.op);
908     c->cc (c->cc_cls, &event);
909     if (GNUNET_NO == exop_check (event.op))
910       return;
911   }
912   switch (opc->type)
913   {
914   case OP_PEER_CREATE:
915     {
916       struct PeerCreateData *data;
917
918       data = opc->data;
919       GNUNET_free (data->peer);
920       if (NULL != data->cb)
921         data->cb (data->cls, NULL, emsg);
922       GNUNET_free (data);
923     }
924     break;
925   case OP_PEER_START:
926   case OP_PEER_STOP:
927     {
928       struct PeerEventData *data;
929
930       data = opc->data;
931       if (NULL != data->pcc)
932         data->pcc (data->pcc_cls, emsg);
933       GNUNET_free (data);
934     }
935     break;
936   case OP_PEER_DESTROY:
937     break;
938   case OP_PEER_INFO:
939     GNUNET_assert (0);
940   case OP_OVERLAY_CONNECT:
941     {
942       struct OverlayConnectData *data;
943
944       data = opc->data;
945       GNUNET_TESTBED_operation_mark_failed (opc->op);
946       if (NULL != data->cb)
947         data->cb (data->cb_cls, opc->op, emsg);
948     }
949     break;
950   case OP_FORWARDED:
951     GNUNET_assert (0);
952   case OP_LINK_CONTROLLERS:    /* No secondary callback */
953     break;
954   case OP_SHUTDOWN_PEERS:
955     {
956       struct ShutdownPeersData *data;
957
958       data = opc->data;
959       GNUNET_free (data);         /* FIXME: Decide whether we call data->op_cb */
960       opc->data = NULL;
961     }
962     break;
963   case OP_MANAGE_SERVICE:
964     {
965       struct ManageServiceData *data = opc->data;
966       GNUNET_TESTBED_OperationCompletionCallback cb;
967       void *cb_cls;
968
969       GNUNET_assert (NULL != data);
970       cb = data->cb;
971       cb_cls = data->cb_cls;
972       GNUNET_free (data);
973       opc->data = NULL;
974       exop_insert (event.op);
975       if (NULL != cb)
976         cb (cb_cls, opc->op, emsg);
977       /* You could have marked the operation as done by now */
978       GNUNET_break (GNUNET_NO == exop_check (event.op));
979     }
980     break;
981   default:
982     GNUNET_break (0);
983   }
984 }
985
986
987 /**
988  * Function to build GET_SLAVE_CONFIG message
989  *
990  * @param op_id the id this message should contain in its operation id field
991  * @param slave_id the id this message should contain in its slave id field
992  * @return newly allocated SlaveGetConfigurationMessage
993  */
994 static struct GNUNET_TESTBED_SlaveGetConfigurationMessage *
995 GNUNET_TESTBED_generate_slavegetconfig_msg_ (uint64_t op_id, uint32_t slave_id)
996 {
997   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
998   uint16_t msize;
999
1000   msize = sizeof (struct GNUNET_TESTBED_SlaveGetConfigurationMessage);
1001   msg = GNUNET_malloc (msize);
1002   msg->header.size = htons (msize);
1003   msg->header.type =
1004       htons (GNUNET_MESSAGE_TYPE_TESTBED_GET_SLAVE_CONFIGURATION);
1005   msg->operation_id = GNUNET_htonll (op_id);
1006   msg->slave_id = htonl (slave_id);
1007   return msg;
1008 }
1009
1010
1011
1012 /**
1013  * Validate #GNUNET_MESSAGE_TYPE_TESTBED_SLAVE_INFORMATION message from
1014  * controller (testbed service)
1015  *
1016  * @param c the controller handler
1017  * @param msg message received
1018  */
1019 static int
1020 check_slave_config (void *cls,
1021                     const struct GNUNET_TESTBED_SlaveConfiguration *msg)
1022 {
1023   /* anything goes? */
1024   return GNUNET_OK;
1025 }
1026
1027
1028 /**
1029  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_SLAVE_CONFIGURATION message from controller
1030  * (testbed service)
1031  *
1032  * @param c the controller handler
1033  * @param msg message received
1034  */
1035 static void
1036 handle_slave_config (void *cls,
1037                      const struct GNUNET_TESTBED_SlaveConfiguration *msg)
1038 {
1039   struct GNUNET_TESTBED_Controller *c = cls;
1040   struct OperationContext *opc;
1041   uint64_t op_id;
1042   uint64_t mask;
1043   struct GNUNET_TESTBED_EventInformation event;
1044
1045   op_id = GNUNET_ntohll (msg->operation_id);
1046   if (NULL == (opc = find_opc (c, op_id)))
1047   {
1048     LOG_DEBUG ("Operation not found\n");
1049     return;
1050   }
1051   if (OP_GET_SLAVE_CONFIG != opc->type)
1052   {
1053     GNUNET_break (0);
1054     return;
1055   }
1056   opc->state = OPC_STATE_FINISHED;
1057   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
1058   mask = 1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED;
1059   if ((0 != (mask & c->event_mask)) &&
1060       (NULL != c->cc))
1061   {
1062     opc->data = GNUNET_TESTBED_extract_config_ (&msg->header);
1063     event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
1064     event.op = opc->op;
1065     event.op_cls = opc->op_cls;
1066     event.details.operation_finished.generic = opc->data;
1067     event.details.operation_finished.emsg = NULL;
1068     c->cc (c->cc_cls, &event);
1069   }
1070 }
1071
1072
1073 /**
1074  * Check #GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS_RESULT message from controller
1075  * (testbed service)
1076  *
1077  * @param c the controller handler
1078  * @param msg message received
1079  * @return #GNUNET_OK if @a msg is well-formed
1080  */
1081 static int
1082 check_link_controllers_result (void *cls,
1083                                 const struct GNUNET_TESTBED_ControllerLinkResponse *msg)
1084 {
1085   /* actual check to be implemented */
1086   return GNUNET_OK;
1087 }
1088
1089
1090 /**
1091  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS_RESULT message from controller
1092  * (testbed service)
1093  *
1094  * @param c the controller handler
1095  * @param msg message received
1096  */
1097 static void
1098 handle_link_controllers_result (void *cls,
1099                                 const struct GNUNET_TESTBED_ControllerLinkResponse *msg)
1100 {
1101   struct GNUNET_TESTBED_Controller *c = cls;
1102   struct OperationContext *opc;
1103   struct ControllerLinkData *data;
1104   struct GNUNET_CONFIGURATION_Handle *cfg;
1105   struct GNUNET_TESTBED_Host *host;
1106   char *emsg;
1107   uint64_t op_id;
1108   struct GNUNET_TESTBED_EventInformation event;
1109
1110   op_id = GNUNET_ntohll (msg->operation_id);
1111   if (NULL == (opc = find_opc (c, op_id)))
1112   {
1113     LOG_DEBUG ("Operation not found\n");
1114     return;
1115   }
1116   if (OP_FORWARDED == opc->type)
1117   {
1118     handle_forwarded_operation_msg (c, opc,
1119                                     (const struct GNUNET_MessageHeader *) msg);
1120     return;
1121   }
1122   if (OP_LINK_CONTROLLERS != opc->type)
1123   {
1124     GNUNET_break (0);
1125     return;
1126   }
1127   GNUNET_assert (NULL != (data = opc->data));
1128   host = GNUNET_TESTBED_host_lookup_by_id_ (data->host_id);
1129   GNUNET_assert (NULL != host);
1130   GNUNET_free (data);
1131   opc->data = NULL;
1132   opc->state = OPC_STATE_FINISHED;
1133   GNUNET_TESTBED_remove_opc_ (opc->c, opc);
1134   event.type = GNUNET_TESTBED_ET_OPERATION_FINISHED;
1135   event.op = opc->op;
1136   event.op_cls = opc->op_cls;
1137   event.details.operation_finished.emsg = NULL;
1138   event.details.operation_finished.generic = NULL;
1139   emsg = NULL;
1140   cfg = NULL;
1141   if (GNUNET_NO == ntohs (msg->success))
1142   {
1143     emsg = GNUNET_malloc (ntohs (msg->header.size)
1144                           - sizeof (struct
1145                                     GNUNET_TESTBED_ControllerLinkResponse) + 1);
1146     GNUNET_memcpy (emsg,
1147                    &msg[1],
1148                    ntohs (msg->header.size)- sizeof (struct GNUNET_TESTBED_ControllerLinkResponse));
1149     event.details.operation_finished.emsg = emsg;
1150   }
1151   else
1152   {
1153     if (0 != ntohs (msg->config_size))
1154     {
1155       cfg = GNUNET_TESTBED_extract_config_ ((const struct GNUNET_MessageHeader *) msg);
1156       GNUNET_assert (NULL != cfg);
1157       GNUNET_TESTBED_host_replace_cfg_ (host, cfg);
1158     }
1159   }
1160   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
1161   {
1162     if (NULL != c->cc)
1163       c->cc (c->cc_cls, &event);
1164   }
1165   else
1166     LOG_DEBUG ("Not calling callback\n");
1167   if (NULL != cfg)
1168     GNUNET_CONFIGURATION_destroy (cfg);
1169   GNUNET_free_non_null (emsg);
1170 }
1171
1172
1173 /**
1174  * Validate #GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS message.
1175  *
1176  * @param cls the controller handle to determine the connection this message
1177  *   belongs to
1178  * @param msg the barrier status message
1179  * @return #GNUNET_OK if the message is valid; #GNUNET_SYSERR to tear it
1180  *   down signalling an error (message malformed)
1181  */
1182 static int
1183 check_barrier_status (void *cls,
1184                       const struct GNUNET_TESTBED_BarrierStatusMsg *msg)
1185 {
1186   uint16_t msize;
1187   uint16_t name_len;
1188   int status;
1189   const char *name;
1190   size_t emsg_len;
1191
1192   msize = ntohs (msg->header.size);
1193   name = msg->data;
1194   name_len = ntohs (msg->name_len);
1195
1196   if (sizeof (struct GNUNET_TESTBED_BarrierStatusMsg) + name_len + 1 > msize)
1197   {
1198     GNUNET_break_op (0);
1199     return GNUNET_SYSERR;
1200   }
1201   if ('\0' != name[name_len])
1202   {
1203     GNUNET_break_op (0);
1204     return GNUNET_SYSERR;
1205   }
1206   status = ntohs (msg->status);
1207   if (GNUNET_TESTBED_BARRIERSTATUS_ERROR == status)
1208   {
1209     emsg_len = msize - (sizeof (struct GNUNET_TESTBED_BarrierStatusMsg) + name_len
1210                         + 1); /* +1!? */
1211     if (0 == emsg_len)
1212     {
1213       GNUNET_break_op (0);
1214       return GNUNET_SYSERR;
1215     }
1216   }
1217   return GNUNET_OK;
1218 }
1219
1220
1221 /**
1222  * Handler for #GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS messages
1223  *
1224  * @param cls the controller handle to determine the connection this message
1225  *   belongs to
1226  * @param msg the barrier status message
1227  */
1228 static void
1229 handle_barrier_status (void *cls,
1230                        const struct GNUNET_TESTBED_BarrierStatusMsg *msg)
1231 {
1232   struct GNUNET_TESTBED_Controller *c = cls;
1233   struct GNUNET_TESTBED_Barrier *barrier;
1234   char *emsg;
1235   const char *name;
1236   struct GNUNET_HashCode key;
1237   size_t emsg_len;
1238   int status;
1239   uint16_t msize;
1240   uint16_t name_len;
1241
1242   emsg = NULL;
1243   barrier = NULL;
1244   msize = ntohs (msg->header.size);
1245   if (msize <= sizeof (struct GNUNET_TESTBED_BarrierStatusMsg))
1246   {
1247     GNUNET_break_op (0);
1248     goto cleanup;
1249   }
1250   name = msg->data;
1251   name_len = ntohs (msg->name_len);
1252   if (name_len >=  //name_len is strlen(barrier_name)
1253       (msize - ((sizeof msg->header) + sizeof (msg->status)) )   )
1254   {
1255     GNUNET_break_op (0);
1256     goto cleanup;
1257   }
1258   if ('\0' != name[name_len])
1259   {
1260     GNUNET_break_op (0);
1261     goto cleanup;
1262   }
1263   LOG_DEBUG ("Received BARRIER_STATUS msg\n");
1264   status = ntohs (msg->status);
1265   if (GNUNET_TESTBED_BARRIERSTATUS_ERROR == status)
1266   {
1267     status = -1;
1268     //unlike name_len, emsg_len includes the trailing zero
1269     emsg_len = msize - (sizeof (struct GNUNET_TESTBED_BarrierStatusMsg)
1270                         + (name_len + 1));
1271     if (0 == emsg_len)
1272     {
1273       GNUNET_break_op (0);
1274       goto cleanup;
1275     }
1276     if ('\0' != (msg->data[(name_len + 1) + (emsg_len - 1)]))
1277     {
1278       GNUNET_break_op (0);
1279       goto cleanup;
1280     }
1281     emsg = GNUNET_malloc (emsg_len);
1282     GNUNET_memcpy (emsg,
1283                    msg->data + name_len + 1,
1284                    emsg_len);
1285   }
1286   if (NULL == c->barrier_map)
1287   {
1288     GNUNET_break_op (0);
1289     goto cleanup;
1290   }
1291   GNUNET_CRYPTO_hash (name, name_len, &key);
1292   barrier = GNUNET_CONTAINER_multihashmap_get (c->barrier_map, &key);
1293   if (NULL == barrier)
1294   {
1295     GNUNET_break_op (0);
1296     goto cleanup;
1297   }
1298   GNUNET_assert (NULL != barrier->cb);
1299   if ((GNUNET_YES == barrier->echo) &&
1300       (GNUNET_TESTBED_BARRIERSTATUS_CROSSED == status))
1301     GNUNET_TESTBED_queue_message_ (c,
1302                                    GNUNET_copy_message (&msg->header));
1303   barrier->cb (barrier->cls,
1304                name,
1305                barrier,
1306                status,
1307                emsg);
1308   if (GNUNET_TESTBED_BARRIERSTATUS_INITIALISED == status)
1309     return;           /* just initialised; skip cleanup */
1310
1311  cleanup:
1312   GNUNET_free_non_null (emsg);
1313   if (NULL != barrier)
1314     GNUNET_TESTBED_barrier_remove_ (barrier);
1315 }
1316
1317
1318 /**
1319  * Queues a message in send queue for sending to the service
1320  *
1321  * @param controller the handle to the controller
1322  * @param msg the message to queue
1323  */
1324 void
1325 GNUNET_TESTBED_queue_message_ (struct GNUNET_TESTBED_Controller *controller,
1326                                struct GNUNET_MessageHeader *msg)
1327 {
1328   struct GNUNET_MQ_Envelope *env;
1329   struct GNUNET_MessageHeader *m2;
1330   uint16_t type;
1331   uint16_t size;
1332
1333   type = ntohs (msg->type);
1334   size = ntohs (msg->size);
1335   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
1336                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));
1337   env = GNUNET_MQ_msg_extra (m2,
1338                              size - sizeof (*m2),
1339                              type);
1340   GNUNET_memcpy (m2, msg, size);
1341   GNUNET_free (msg);
1342   GNUNET_MQ_send (controller->mq,
1343                   env);
1344 }
1345
1346
1347 /**
1348  * Sends the given message as an operation. The given callback is called when a
1349  * reply for the operation is available.  Call
1350  * GNUNET_TESTBED_forward_operation_msg_cancel_() to cleanup the returned
1351  * operation context if the cc hasn't been called
1352  *
1353  * @param controller the controller to which the message has to be sent
1354  * @param operation_id the operation id of the message
1355  * @param msg the message to send
1356  * @param cc the callback to call when reply is available
1357  * @param cc_cls the closure for the above callback
1358  * @return the operation context which can be used to cancel the forwarded
1359  *           operation
1360  */
1361 struct OperationContext *
1362 GNUNET_TESTBED_forward_operation_msg_ (struct GNUNET_TESTBED_Controller *controller,
1363                                        uint64_t operation_id,
1364                                        const struct GNUNET_MessageHeader *msg,
1365                                        GNUNET_MQ_MessageCallback cc,
1366                                        void *cc_cls)
1367 {
1368   struct OperationContext *opc;
1369   struct ForwardedOperationData *data;
1370   struct GNUNET_MQ_Envelope *env;
1371   struct GNUNET_MessageHeader *m2;
1372   uint16_t type = ntohs (msg->type);
1373   uint16_t size = ntohs (msg->size);
1374
1375   env = GNUNET_MQ_msg_extra (m2,
1376                              size - sizeof (*m2),
1377                              type);
1378   GNUNET_memcpy (m2,
1379                  msg,
1380                  size);
1381   GNUNET_MQ_send (controller->mq,
1382                   env);
1383   data = GNUNET_new (struct ForwardedOperationData);
1384   data->cc = cc;
1385   data->cc_cls = cc_cls;
1386   opc = GNUNET_new (struct OperationContext);
1387   opc->c = controller;
1388   opc->type = OP_FORWARDED;
1389   opc->data = data;
1390   opc->id = operation_id;
1391   GNUNET_TESTBED_insert_opc_ (controller,
1392                               opc);
1393   return opc;
1394 }
1395
1396
1397 /**
1398  * Function to cancel an operation created by simply forwarding an operation
1399  * message.
1400  *
1401  * @param opc the operation context from GNUNET_TESTBED_forward_operation_msg_()
1402  */
1403 void
1404 GNUNET_TESTBED_forward_operation_msg_cancel_ (struct OperationContext *opc)
1405 {
1406   GNUNET_TESTBED_remove_opc_ (opc->c,
1407                               opc);
1408   GNUNET_free (opc->data);
1409   GNUNET_free (opc);
1410 }
1411
1412
1413 /**
1414  * Function to call to start a link-controllers type operation once all queues
1415  * the operation is part of declare that the operation can be activated.
1416  *
1417  * @param cls the closure from GNUNET_TESTBED_operation_create_()
1418  */
1419 static void
1420 opstart_link_controllers (void *cls)
1421 {
1422   struct OperationContext *opc = cls;
1423   struct ControllerLinkData *data;
1424   struct GNUNET_TESTBED_ControllerLinkRequest *msg;
1425
1426   GNUNET_assert (NULL != opc->data);
1427   data = opc->data;
1428   msg = data->msg;
1429   data->msg = NULL;
1430   opc->state = OPC_STATE_STARTED;
1431   GNUNET_TESTBED_insert_opc_ (opc->c, opc);
1432   GNUNET_TESTBED_queue_message_ (opc->c, &msg->header);
1433 }
1434
1435
1436 /**
1437  * Callback which will be called when link-controllers type operation is released
1438  *
1439  * @param cls the closure from GNUNET_TESTBED_operation_create_()
1440  */
1441 static void
1442 oprelease_link_controllers (void *cls)
1443 {
1444   struct OperationContext *opc = cls;
1445   struct ControllerLinkData *data;
1446
1447   data = opc->data;
1448   switch (opc->state)
1449   {
1450   case OPC_STATE_INIT:
1451     GNUNET_free (data->msg);
1452     break;
1453   case OPC_STATE_STARTED:
1454     GNUNET_TESTBED_remove_opc_ (opc->c, opc);
1455     break;
1456   case OPC_STATE_FINISHED:
1457     break;
1458   }
1459   GNUNET_free_non_null (data);
1460   GNUNET_free (opc);
1461 }
1462
1463
1464 /**
1465  * Function to be called when get slave config operation is ready
1466  *
1467  * @param cls the OperationContext of type OP_GET_SLAVE_CONFIG
1468  */
1469 static void
1470 opstart_get_slave_config (void *cls)
1471 {
1472   struct OperationContext *opc = cls;
1473   struct GetSlaveConfigData *data = opc->data;
1474   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
1475
1476   GNUNET_assert (NULL != data);
1477   msg = GNUNET_TESTBED_generate_slavegetconfig_msg_ (opc->id, data->slave_id);
1478   GNUNET_free (opc->data);
1479   data = NULL;
1480   opc->data = NULL;
1481   GNUNET_TESTBED_insert_opc_ (opc->c, opc);
1482   GNUNET_TESTBED_queue_message_ (opc->c, &msg->header);
1483   opc->state = OPC_STATE_STARTED;
1484 }
1485
1486
1487 /**
1488  * Function to be called when get slave config operation is cancelled or finished
1489  *
1490  * @param cls the OperationContext of type OP_GET_SLAVE_CONFIG
1491  */
1492 static void
1493 oprelease_get_slave_config (void *cls)
1494 {
1495   struct OperationContext *opc = cls;
1496
1497   switch (opc->state)
1498   {
1499   case OPC_STATE_INIT:
1500     GNUNET_free (opc->data);
1501     break;
1502   case OPC_STATE_STARTED:
1503     GNUNET_TESTBED_remove_opc_ (opc->c, opc);
1504     break;
1505   case OPC_STATE_FINISHED:
1506     if (NULL != opc->data)
1507       GNUNET_CONFIGURATION_destroy (opc->data);
1508     break;
1509   }
1510   GNUNET_free (opc);
1511 }
1512
1513
1514 /**
1515  * Generic error handler, called with the appropriate error code and
1516  * the same closure specified at the creation of the message queue.
1517  * Not every message queue implementation supports an error handler.
1518  *
1519  * @param cls closure, a `struct GNUNET_TESTBED_Controller *`
1520  * @param error error code
1521  */
1522 static void
1523 mq_error_handler (void *cls,
1524                   enum GNUNET_MQ_Error error)
1525 {
1526   /* struct GNUNET_TESTBED_Controller *c = cls; */
1527
1528   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1529               "Encountered MQ error: %d\n",
1530               error);
1531   /* now what? */
1532   GNUNET_SCHEDULER_shutdown (); /* seems most reasonable */
1533 }
1534
1535
1536 /**
1537  * Start a controller process using the given configuration at the
1538  * given host.
1539  *
1540  * @param host host to run the controller on; This should be the same host if
1541  *          the controller was previously started with
1542  *          GNUNET_TESTBED_controller_start()
1543  * @param event_mask bit mask with set of events to call 'cc' for;
1544  *                   or-ed values of "1LL" shifted by the
1545  *                   respective 'enum GNUNET_TESTBED_EventType'
1546  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
1547  * @param cc controller callback to invoke on events
1548  * @param cc_cls closure for cc
1549  * @return handle to the controller
1550  */
1551 struct GNUNET_TESTBED_Controller *
1552 GNUNET_TESTBED_controller_connect (struct GNUNET_TESTBED_Host *host,
1553                                    uint64_t event_mask,
1554                                    GNUNET_TESTBED_ControllerCallback cc,
1555                                    void *cc_cls)
1556 {
1557   struct GNUNET_TESTBED_Controller *controller
1558     = GNUNET_new (struct GNUNET_TESTBED_Controller);
1559   struct GNUNET_MQ_MessageHandler handlers[] = {
1560     GNUNET_MQ_hd_var_size (add_host_confirm,
1561                            GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST_SUCCESS,
1562                            struct GNUNET_TESTBED_HostConfirmedMessage,
1563                            controller),
1564     GNUNET_MQ_hd_fixed_size (peer_conevent,
1565                              GNUNET_MESSAGE_TYPE_TESTBED_PEER_CONNECT_EVENT,
1566                              struct GNUNET_TESTBED_ConnectionEventMessage,
1567                              controller),
1568     GNUNET_MQ_hd_fixed_size (opsuccess,
1569                              GNUNET_MESSAGE_TYPE_TESTBED_GENERIC_OPERATION_SUCCESS,
1570                              struct GNUNET_TESTBED_GenericOperationSuccessEventMessage,
1571                              controller),
1572     GNUNET_MQ_hd_var_size (op_fail_event,
1573                            GNUNET_MESSAGE_TYPE_TESTBED_OPERATION_FAIL_EVENT,
1574                            struct GNUNET_TESTBED_OperationFailureEventMessage,
1575                            controller),
1576     GNUNET_MQ_hd_fixed_size (peer_create_success,
1577                              GNUNET_MESSAGE_TYPE_TESTBED_CREATE_PEER_SUCCESS,
1578                              struct GNUNET_TESTBED_PeerCreateSuccessEventMessage,
1579                              controller),
1580     GNUNET_MQ_hd_fixed_size (peer_event,
1581                              GNUNET_MESSAGE_TYPE_TESTBED_PEER_EVENT,
1582                              struct GNUNET_TESTBED_PeerEventMessage,
1583                              controller),
1584     GNUNET_MQ_hd_var_size (peer_config,
1585                            GNUNET_MESSAGE_TYPE_TESTBED_PEER_INFORMATION,
1586                            struct GNUNET_TESTBED_PeerConfigurationInformationMessage,
1587                            controller),
1588     GNUNET_MQ_hd_var_size (slave_config,
1589                            GNUNET_MESSAGE_TYPE_TESTBED_SLAVE_CONFIGURATION,
1590                            struct GNUNET_TESTBED_SlaveConfiguration,
1591                            controller),
1592     GNUNET_MQ_hd_var_size (link_controllers_result,
1593                            GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS_RESULT,
1594                            struct GNUNET_TESTBED_ControllerLinkResponse,
1595                            controller),
1596     GNUNET_MQ_hd_var_size (barrier_status,
1597                            GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS,
1598                            const struct GNUNET_TESTBED_BarrierStatusMsg,
1599                            controller),
1600     GNUNET_MQ_handler_end ()
1601   };
1602   struct GNUNET_TESTBED_InitMessage *msg;
1603   struct GNUNET_MQ_Envelope *env;
1604   const struct GNUNET_CONFIGURATION_Handle *cfg;
1605   const char *controller_hostname;
1606   unsigned long long max_parallel_operations;
1607   unsigned long long max_parallel_service_connections;
1608   unsigned long long max_parallel_topology_config_operations;
1609   size_t slen;
1610
1611   GNUNET_assert (NULL != (cfg = GNUNET_TESTBED_host_get_cfg_ (host)));
1612   if (GNUNET_OK !=
1613       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1614                                              "MAX_PARALLEL_OPERATIONS",
1615                                              &max_parallel_operations))
1616   {
1617     GNUNET_break (0);
1618     GNUNET_free (controller);
1619     return NULL;
1620   }
1621   if (GNUNET_OK !=
1622       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1623                                              "MAX_PARALLEL_SERVICE_CONNECTIONS",
1624                                              &max_parallel_service_connections))
1625   {
1626     GNUNET_break (0);
1627     GNUNET_free (controller);
1628     return NULL;
1629   }
1630   if (GNUNET_OK !=
1631       GNUNET_CONFIGURATION_get_value_number (cfg, "testbed",
1632                                              "MAX_PARALLEL_TOPOLOGY_CONFIG_OPERATIONS",
1633                                              &max_parallel_topology_config_operations))
1634   {
1635     GNUNET_break (0);
1636     GNUNET_free (controller);
1637     return NULL;
1638   }
1639   controller->cc = cc;
1640   controller->cc_cls = cc_cls;
1641   controller->event_mask = event_mask;
1642   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
1643   controller->mq = GNUNET_CLIENT_connecT (controller->cfg,
1644                                           "testbed",
1645                                           handlers,
1646                                           &mq_error_handler,
1647                                           controller);
1648   if (NULL == controller->mq)
1649   {
1650     GNUNET_break (0);
1651     GNUNET_TESTBED_controller_disconnect (controller);
1652     return NULL;
1653   }
1654   GNUNET_TESTBED_mark_host_registered_at_ (host, controller);
1655   controller->host = host;
1656   controller->opq_parallel_operations =
1657       GNUNET_TESTBED_operation_queue_create_ (OPERATION_QUEUE_TYPE_FIXED,
1658                                               (unsigned int) max_parallel_operations);
1659   controller->opq_parallel_service_connections =
1660       GNUNET_TESTBED_operation_queue_create_ (OPERATION_QUEUE_TYPE_FIXED,
1661                                               (unsigned int)
1662                                               max_parallel_service_connections);
1663   controller->opq_parallel_topology_config_operations =
1664       GNUNET_TESTBED_operation_queue_create_ (OPERATION_QUEUE_TYPE_FIXED,
1665                                               (unsigned int)
1666                                               max_parallel_topology_config_operations);
1667   controller_hostname = GNUNET_TESTBED_host_get_hostname (host);
1668   if (NULL == controller_hostname)
1669     controller_hostname = "127.0.0.1";
1670   slen = strlen (controller_hostname) + 1;
1671   env = GNUNET_MQ_msg_extra (msg,
1672                              slen,
1673                              GNUNET_MESSAGE_TYPE_TESTBED_INIT);
1674   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
1675   msg->event_mask = GNUNET_htonll (controller->event_mask);
1676   GNUNET_memcpy (&msg[1],
1677                  controller_hostname,
1678                  slen);
1679   GNUNET_MQ_send (controller->mq,
1680                   env);
1681   return controller;
1682 }
1683
1684
1685 /**
1686  * Iterator to free opc map entries
1687  *
1688  * @param cls closure
1689  * @param key current key code
1690  * @param value value in the hash map
1691  * @return #GNUNET_YES if we should continue to iterate,
1692  *         #GNUNET_NO if not.
1693  */
1694 static int
1695 opc_free_iterator (void *cls, uint32_t key, void *value)
1696 {
1697   struct GNUNET_CONTAINER_MultiHashMap32 *map = cls;
1698   struct OperationContext *opc = value;
1699
1700   GNUNET_assert (NULL != opc);
1701   GNUNET_break (0);
1702   GNUNET_assert (GNUNET_YES ==
1703                  GNUNET_CONTAINER_multihashmap32_remove (map, key, value));
1704   GNUNET_free (opc);
1705   return GNUNET_YES;
1706 }
1707
1708
1709 /**
1710  * Stop the given controller (also will terminate all peers and
1711  * controllers dependent on this controller).  This function
1712  * blocks until the testbed has been fully terminated (!).
1713  *
1714  * @param c handle to controller to stop
1715  */
1716 void
1717 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *c)
1718 {
1719   if (NULL != c->mq)
1720   {
1721     GNUNET_MQ_destroy (c->mq);
1722     c->mq = NULL;
1723   }
1724   if (NULL != c->host)
1725     GNUNET_TESTBED_deregister_host_at_ (c->host, c);
1726   GNUNET_CONFIGURATION_destroy (c->cfg);
1727   GNUNET_TESTBED_operation_queue_destroy_ (c->opq_parallel_operations);
1728   GNUNET_TESTBED_operation_queue_destroy_
1729       (c->opq_parallel_service_connections);
1730   GNUNET_TESTBED_operation_queue_destroy_
1731       (c->opq_parallel_topology_config_operations);
1732   if (NULL != c->opc_map)
1733   {
1734     GNUNET_assert (GNUNET_SYSERR !=
1735                    GNUNET_CONTAINER_multihashmap32_iterate (c->opc_map,
1736                                                             &opc_free_iterator,
1737                                                             c->opc_map));
1738     GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (c->opc_map));
1739     GNUNET_CONTAINER_multihashmap32_destroy (c->opc_map);
1740   }
1741   GNUNET_free (c);
1742 }
1743
1744
1745 /**
1746  * Compresses given configuration using zlib compress
1747  *
1748  * @param config the serialized configuration
1749  * @param size the size of config
1750  * @param xconfig will be set to the compressed configuration (memory is fresly
1751  *          allocated)
1752  * @return the size of the xconfig
1753  */
1754 size_t
1755 GNUNET_TESTBED_compress_config_ (const char *config,
1756                                  size_t size,
1757                                  char **xconfig)
1758 {
1759   size_t xsize;
1760
1761   xsize = compressBound ((uLong) size);
1762   *xconfig = GNUNET_malloc (xsize);
1763   GNUNET_assert (Z_OK ==
1764                  compress2 ((Bytef *) * xconfig, (uLongf *) & xsize,
1765                             (const Bytef *) config, (uLongf) size,
1766                             Z_BEST_SPEED));
1767   return xsize;
1768 }
1769
1770
1771 /**
1772  * Function to serialize and compress using zlib a configuration through a
1773  * configuration handle
1774  *
1775  * @param cfg the configuration
1776  * @param size the size of configuration when serialize.  Will be set on success.
1777  * @param xsize the sizeo of the compressed configuration.  Will be set on success.
1778  * @return the serialized and compressed configuration
1779  */
1780 char *
1781 GNUNET_TESTBED_compress_cfg_ (const struct GNUNET_CONFIGURATION_Handle *cfg,
1782                               size_t *size, size_t *xsize)
1783 {
1784   char *config;
1785   char *xconfig;
1786   size_t size_;
1787   size_t xsize_;
1788
1789   config = GNUNET_CONFIGURATION_serialize (cfg, &size_);
1790   xsize_ = GNUNET_TESTBED_compress_config_ (config, size_, &xconfig);
1791   GNUNET_free (config);
1792   *size = size_;
1793   *xsize = xsize_;
1794   return xconfig;
1795 }
1796
1797
1798 /**
1799  * Create a link from slave controller to delegated controller. Whenever the
1800  * master controller is asked to start a peer at the delegated controller the
1801  * request will be routed towards slave controller (if a route exists). The
1802  * slave controller will then route it to the delegated controller. The
1803  * configuration of the delegated controller is given and is used to either
1804  * create the delegated controller or to connect to an existing controller. Note
1805  * that while starting the delegated controller the configuration will be
1806  * modified to accommodate available free ports.  the 'is_subordinate' specifies
1807  * if the given delegated controller should be started and managed by the slave
1808  * controller, or if the delegated controller already has a master and the slave
1809  * controller connects to it as a non master controller. The success or failure
1810  * of this operation will be signalled through the
1811  * GNUNET_TESTBED_ControllerCallback() with an event of type
1812  * GNUNET_TESTBED_ET_OPERATION_FINISHED
1813  *
1814  * @param op_cls the operation closure for the event which is generated to
1815  *          signal success or failure of this operation
1816  * @param master handle to the master controller who creates the association
1817  * @param delegated_host requests to which host should be delegated; cannot be NULL
1818  * @param slave_host which host is used to run the slave controller; use NULL to
1819  *          make the master controller connect to the delegated host
1820  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
1821  *          be started by the slave controller; GNUNET_NO if the slave
1822  *          controller has to connect to the already started delegated
1823  *          controller via TCP/IP
1824  * @return the operation handle
1825  */
1826 struct GNUNET_TESTBED_Operation *
1827 GNUNET_TESTBED_controller_link (void *op_cls,
1828                                 struct GNUNET_TESTBED_Controller *master,
1829                                 struct GNUNET_TESTBED_Host *delegated_host,
1830                                 struct GNUNET_TESTBED_Host *slave_host,
1831                                 int is_subordinate)
1832 {
1833   struct OperationContext *opc;
1834   struct GNUNET_TESTBED_ControllerLinkRequest *msg;
1835   struct ControllerLinkData *data;
1836   uint32_t slave_host_id;
1837   uint32_t delegated_host_id;
1838   uint16_t msg_size;
1839
1840   GNUNET_assert (GNUNET_YES ==
1841                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1842   slave_host_id =
1843       GNUNET_TESTBED_host_get_id_ ((NULL !=
1844                                     slave_host) ? slave_host : master->host);
1845   delegated_host_id = GNUNET_TESTBED_host_get_id_ (delegated_host);
1846   if ((NULL != slave_host) && (0 != slave_host_id))
1847     GNUNET_assert (GNUNET_YES ==
1848                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1849   msg_size = sizeof (struct GNUNET_TESTBED_ControllerLinkRequest);
1850   msg = GNUNET_malloc (msg_size);
1851   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS);
1852   msg->header.size = htons (msg_size);
1853   msg->delegated_host_id = htonl (delegated_host_id);
1854   msg->slave_host_id = htonl (slave_host_id);
1855   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
1856   data = GNUNET_new (struct ControllerLinkData);
1857   data->msg = msg;
1858   data->host_id = delegated_host_id;
1859   opc = GNUNET_new (struct OperationContext);
1860   opc->c = master;
1861   opc->data = data;
1862   opc->type = OP_LINK_CONTROLLERS;
1863   opc->id = GNUNET_TESTBED_get_next_op_id (opc->c);
1864   opc->state = OPC_STATE_INIT;
1865   opc->op_cls = op_cls;
1866   msg->operation_id = GNUNET_htonll (opc->id);
1867   opc->op =
1868       GNUNET_TESTBED_operation_create_ (opc, &opstart_link_controllers,
1869                                         &oprelease_link_controllers);
1870   GNUNET_TESTBED_operation_queue_insert_ (master->opq_parallel_operations,
1871                                           opc->op);
1872   GNUNET_TESTBED_operation_begin_wait_ (opc->op);
1873   return opc->op;
1874 }
1875
1876
1877 /**
1878  * Like GNUNET_TESTBED_get_slave_config(), however without the host registration
1879  * check. Another difference is that this function takes the id of the slave
1880  * host.
1881  *
1882  * @param op_cls the closure for the operation
1883  * @param master the handle to master controller
1884  * @param slave_host_id id of the host where the slave controller is running to
1885  *          the slave_host should remain valid until this operation is cancelled
1886  *          or marked as finished
1887  * @return the operation handle;
1888  */
1889 struct GNUNET_TESTBED_Operation *
1890 GNUNET_TESTBED_get_slave_config_ (void *op_cls,
1891                                   struct GNUNET_TESTBED_Controller *master,
1892                                   uint32_t slave_host_id)
1893 {
1894   struct OperationContext *opc;
1895   struct GetSlaveConfigData *data;
1896
1897   data = GNUNET_new (struct GetSlaveConfigData);
1898   data->slave_id = slave_host_id;
1899   opc = GNUNET_new (struct OperationContext);
1900   opc->state = OPC_STATE_INIT;
1901   opc->c = master;
1902   opc->id = GNUNET_TESTBED_get_next_op_id (master);
1903   opc->type = OP_GET_SLAVE_CONFIG;
1904   opc->data = data;
1905   opc->op_cls = op_cls;
1906   opc->op =
1907       GNUNET_TESTBED_operation_create_ (opc, &opstart_get_slave_config,
1908                                         &oprelease_get_slave_config);
1909   GNUNET_TESTBED_operation_queue_insert_ (master->opq_parallel_operations,
1910                                           opc->op);
1911   GNUNET_TESTBED_operation_begin_wait_ (opc->op);
1912   return opc->op;
1913 }
1914
1915
1916 /**
1917  * Function to acquire the configuration of a running slave controller. The
1918  * completion of the operation is signalled through the controller_cb from
1919  * GNUNET_TESTBED_controller_connect(). If the operation is successful the
1920  * handle to the configuration is available in the generic pointer of
1921  * operation_finished field of struct GNUNET_TESTBED_EventInformation.
1922  *
1923  * @param op_cls the closure for the operation
1924  * @param master the handle to master controller
1925  * @param slave_host the host where the slave controller is running; the handle
1926  *          to the slave_host should remain valid until this operation is
1927  *          cancelled or marked as finished
1928  * @return the operation handle; NULL if the slave_host is not registered at
1929  *           master
1930  */
1931 struct GNUNET_TESTBED_Operation *
1932 GNUNET_TESTBED_get_slave_config (void *op_cls,
1933                                  struct GNUNET_TESTBED_Controller *master,
1934                                  struct GNUNET_TESTBED_Host *slave_host)
1935 {
1936   if (GNUNET_NO == GNUNET_TESTBED_is_host_registered_ (slave_host, master))
1937     return NULL;
1938   return GNUNET_TESTBED_get_slave_config_ (op_cls, master,
1939                                            GNUNET_TESTBED_host_get_id_
1940                                            (slave_host));
1941 }
1942
1943
1944 /**
1945  * Ask the testbed controller to write the current overlay topology to
1946  * a file.  Naturally, the file will only contain a snapshot as the
1947  * topology may evolve all the time.
1948  *
1949  * @param controller overlay controller to inspect
1950  * @param filename name of the file the topology should
1951  *        be written to.
1952  */
1953 void
1954 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller
1955                                                *controller,
1956                                                const char *filename)
1957 {
1958   GNUNET_break (0);
1959 }
1960
1961
1962 /**
1963  * Creates a helper initialization message. This function is here because we
1964  * want to use this in testing
1965  *
1966  * @param trusted_ip the ip address of the controller which will be set as TRUSTED
1967  *          HOST(all connections form this ip are permitted by the testbed) when
1968  *          starting testbed controller at host. This can either be a single ip
1969  *          address or a network address in CIDR notation.
1970  * @param hostname the hostname of the destination this message is intended for
1971  * @param cfg the configuration that has to used to start the testbed service
1972  *          thru helper
1973  * @return the initialization message
1974  */
1975 struct GNUNET_TESTBED_HelperInit *
1976 GNUNET_TESTBED_create_helper_init_msg_ (const char *trusted_ip,
1977                                         const char *hostname,
1978                                         const struct GNUNET_CONFIGURATION_Handle
1979                                         *cfg)
1980 {
1981   struct GNUNET_TESTBED_HelperInit *msg;
1982   char *config;
1983   char *xconfig;
1984   size_t config_size;
1985   size_t xconfig_size;
1986   uint16_t trusted_ip_len;
1987   uint16_t hostname_len;
1988   uint16_t msg_size;
1989
1990   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
1991   GNUNET_assert (NULL != config);
1992   xconfig_size =
1993       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
1994   GNUNET_free (config);
1995   trusted_ip_len = strlen (trusted_ip);
1996   hostname_len = (NULL == hostname) ? 0 : strlen (hostname);
1997   msg_size =
1998       xconfig_size + trusted_ip_len + 1 +
1999       sizeof (struct GNUNET_TESTBED_HelperInit);
2000   msg_size += hostname_len;
2001   msg = GNUNET_realloc (xconfig, msg_size);
2002   (void) memmove (((void *) &msg[1]) + trusted_ip_len + 1 + hostname_len, msg,
2003                   xconfig_size);
2004   msg->header.size = htons (msg_size);
2005   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
2006   msg->trusted_ip_size = htons (trusted_ip_len);
2007   msg->hostname_size = htons (hostname_len);
2008   msg->config_size = htons (config_size);
2009   (void) strcpy ((char *) &msg[1], trusted_ip);
2010   if (0 != hostname_len)
2011     (void) strncpy (((char *) &msg[1]) + trusted_ip_len + 1, hostname,
2012                     hostname_len);
2013   return msg;
2014 }
2015
2016
2017 /**
2018  * This function is used to signal that the event information (struct
2019  * GNUNET_TESTBED_EventInformation) from an operation has been fully processed
2020  * i.e. if the event callback is ever called for this operation. If the event
2021  * callback for this operation has not yet been called, calling this function
2022  * cancels the operation, frees its resources and ensures the no event is
2023  * generated with respect to this operation. Note that however cancelling an
2024  * operation does NOT guarantee that the operation will be fully undone (or that
2025  * nothing ever happened).
2026  *
2027  * This function MUST be called for every operation to fully remove the
2028  * operation from the operation queue.  After calling this function, if
2029  * operation is completed and its event information is of type
2030  * GNUNET_TESTBED_ET_OPERATION_FINISHED, the 'op_result' becomes invalid (!).
2031
2032  * If the operation is generated from GNUNET_TESTBED_service_connect() then
2033  * calling this function on such as operation calls the disconnect adapter if
2034  * the connect adapter was ever called.
2035  *
2036  * @param operation operation to signal completion or cancellation
2037  */
2038 void
2039 GNUNET_TESTBED_operation_done (struct GNUNET_TESTBED_Operation *operation)
2040 {
2041   (void) exop_check (operation);
2042   GNUNET_TESTBED_operation_release_ (operation);
2043 }
2044
2045
2046 /**
2047  * Generates configuration by uncompressing configuration in given message. The
2048  * given message should be of the following types:
2049  * #GNUNET_MESSAGE_TYPE_TESTBED_PEER_INFORMATION,
2050  * #GNUNET_MESSAGE_TYPE_TESTBED_SLAVE_CONFIGURATION,
2051  * #GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST,
2052  * #GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS,
2053  * #GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS_RESULT,
2054  *
2055  * FIXME: This API is incredibly ugly.
2056  *
2057  * @param msg the message containing compressed configuration
2058  * @return handle to the parsed configuration; NULL upon error while parsing the message
2059  */
2060 struct GNUNET_CONFIGURATION_Handle *
2061 GNUNET_TESTBED_extract_config_ (const struct GNUNET_MessageHeader *msg)
2062 {
2063   struct GNUNET_CONFIGURATION_Handle *cfg;
2064   Bytef *data;
2065   const Bytef *xdata;
2066   uLong data_len;
2067   uLong xdata_len;
2068   int ret;
2069
2070   switch (ntohs (msg->type))
2071   {
2072   case GNUNET_MESSAGE_TYPE_TESTBED_PEER_INFORMATION:
2073   {
2074     const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *imsg;
2075
2076     imsg =
2077         (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *) msg;
2078     data_len = (uLong) ntohs (imsg->config_size);
2079     xdata_len =
2080         ntohs (imsg->header.size) -
2081         sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
2082     xdata = (const Bytef *) &imsg[1];
2083   }
2084     break;
2085   case GNUNET_MESSAGE_TYPE_TESTBED_SLAVE_CONFIGURATION:
2086   {
2087     const struct GNUNET_TESTBED_SlaveConfiguration *imsg;
2088
2089     imsg = (const struct GNUNET_TESTBED_SlaveConfiguration *) msg;
2090     data_len = (uLong) ntohs (imsg->config_size);
2091     xdata_len =
2092         ntohs (imsg->header.size) -
2093         sizeof (struct GNUNET_TESTBED_SlaveConfiguration);
2094     xdata = (const Bytef *) &imsg[1];
2095   }
2096   break;
2097   case GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST:
2098     {
2099       const struct GNUNET_TESTBED_AddHostMessage *imsg;
2100       uint16_t osize;
2101
2102       imsg = (const struct GNUNET_TESTBED_AddHostMessage *) msg;
2103       data_len = (uLong) ntohs (imsg->config_size);
2104       osize = sizeof (struct GNUNET_TESTBED_AddHostMessage) +
2105           ntohs (imsg->username_length) + ntohs (imsg->hostname_length);
2106       xdata_len = ntohs (imsg->header.size) - osize;
2107       xdata = (const Bytef *) ((const void *) imsg + osize);
2108     }
2109     break;
2110   case GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS_RESULT:
2111     {
2112       const struct GNUNET_TESTBED_ControllerLinkResponse *imsg;
2113
2114       imsg = (const struct GNUNET_TESTBED_ControllerLinkResponse *) msg;
2115       data_len = ntohs (imsg->config_size);
2116       xdata_len = ntohs (imsg->header.size) -
2117           sizeof (const struct GNUNET_TESTBED_ControllerLinkResponse);
2118       xdata = (const Bytef *) &imsg[1];
2119     }
2120     break;
2121   case GNUNET_MESSAGE_TYPE_TESTBED_CREATE_PEER:
2122     {
2123       const struct GNUNET_TESTBED_PeerCreateMessage *imsg;
2124
2125       imsg = (const struct GNUNET_TESTBED_PeerCreateMessage *) msg;
2126       data_len = ntohs (imsg->config_size);
2127       xdata_len = ntohs (imsg->header.size) -
2128           sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
2129       xdata = (const Bytef *) &imsg[1];
2130     }
2131     break;
2132   case GNUNET_MESSAGE_TYPE_TESTBED_RECONFIGURE_PEER:
2133     {
2134       const struct GNUNET_TESTBED_PeerReconfigureMessage *imsg;
2135
2136       imsg = (const struct GNUNET_TESTBED_PeerReconfigureMessage *) msg;
2137       data_len =  ntohs (imsg->config_size);
2138       xdata_len = ntohs (imsg->header.size) -
2139           sizeof (struct GNUNET_TESTBED_PeerReconfigureMessage);
2140       xdata = (const Bytef *) &imsg[1];
2141     }
2142     break;
2143   default:
2144     GNUNET_assert (0);
2145   }
2146   data = GNUNET_malloc (data_len);
2147   if (Z_OK != (ret = uncompress (data, &data_len, xdata, xdata_len)))
2148   {
2149     GNUNET_free (data);
2150     GNUNET_break_op (0);        /* Un-compression failure */
2151     return NULL;
2152   }
2153   cfg = GNUNET_CONFIGURATION_create ();
2154   if (GNUNET_OK !=
2155       GNUNET_CONFIGURATION_deserialize (cfg, (const char *) data,
2156                                         (size_t) data_len,
2157                                         GNUNET_NO))
2158   {
2159     GNUNET_free (data);
2160     GNUNET_break_op (0);        /* De-serialization failure */
2161     return NULL;
2162   }
2163   GNUNET_free (data);
2164   return cfg;
2165 }
2166
2167
2168 /**
2169  * Checks the integrity of the OperationFailureEventMessage and if good returns
2170  * the error message it contains.
2171  *
2172  * @param msg the OperationFailureEventMessage
2173  * @return the error message
2174  */
2175 const char *
2176 GNUNET_TESTBED_parse_error_string_ (const struct
2177                                     GNUNET_TESTBED_OperationFailureEventMessage
2178                                     *msg)
2179 {
2180   uint16_t msize;
2181   const char *emsg;
2182
2183   msize = ntohs (msg->header.size);
2184   if (sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage) >= msize)
2185     return NULL;
2186   msize -= sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
2187   emsg = (const char *) &msg[1];
2188   if ('\0' != emsg[msize - 1])
2189   {
2190     GNUNET_break (0);
2191     return NULL;
2192   }
2193   return emsg;
2194 }
2195
2196
2197 /**
2198  * Function to return the operation id for a controller. The operation id is
2199  * created from the controllers host id and its internal operation counter.
2200  *
2201  * @param controller the handle to the controller whose operation id has to be incremented
2202  * @return the incremented operation id.
2203  */
2204 uint64_t
2205 GNUNET_TESTBED_get_next_op_id (struct GNUNET_TESTBED_Controller * controller)
2206 {
2207   uint64_t op_id;
2208
2209   op_id = (uint64_t) GNUNET_TESTBED_host_get_id_ (controller->host);
2210   op_id = op_id << 32;
2211   op_id |= (uint64_t) controller->operation_counter++;
2212   return op_id;
2213 }
2214
2215
2216 /**
2217  * Function called when a shutdown peers operation is ready
2218  *
2219  * @param cls the closure from GNUNET_TESTBED_operation_create_()
2220  */
2221 static void
2222 opstart_shutdown_peers (void *cls)
2223 {
2224   struct OperationContext *opc = cls;
2225   struct GNUNET_MQ_Envelope *env;
2226   struct GNUNET_TESTBED_ShutdownPeersMessage *msg;
2227
2228   opc->state = OPC_STATE_STARTED;
2229   env = GNUNET_MQ_msg (msg,
2230                        GNUNET_MESSAGE_TYPE_TESTBED_SHUTDOWN_PEERS);
2231   msg->operation_id = GNUNET_htonll (opc->id);
2232   GNUNET_TESTBED_insert_opc_ (opc->c,
2233                               opc);
2234   GNUNET_MQ_send (opc->c->mq,
2235                   env);
2236 }
2237
2238
2239 /**
2240  * Callback which will be called when shutdown peers operation is released
2241  *
2242  * @param cls the closure from GNUNET_TESTBED_operation_create_()
2243  */
2244 static void
2245 oprelease_shutdown_peers (void *cls)
2246 {
2247   struct OperationContext *opc = cls;
2248
2249   switch (opc->state)
2250   {
2251   case OPC_STATE_STARTED:
2252     GNUNET_TESTBED_remove_opc_ (opc->c, opc);
2253     /* no break; continue */
2254   case OPC_STATE_INIT:
2255     GNUNET_free (opc->data);
2256     break;
2257   case OPC_STATE_FINISHED:
2258     break;
2259   }
2260   GNUNET_free (opc);
2261 }
2262
2263
2264 /**
2265  * Stops and destroys all peers.  Is equivalent of calling
2266  * GNUNET_TESTBED_peer_stop() and GNUNET_TESTBED_peer_destroy() on all peers,
2267  * except that the peer stop event and operation finished event corresponding to
2268  * the respective functions are not generated.  This function should be called
2269  * when there are no other pending operations.  If there are pending operations,
2270  * it will return NULL
2271  *
2272  * @param c the controller to send this message to
2273  * @param op_cls closure for the operation
2274  * @param cb the callback to call when all peers are stopped and destroyed
2275  * @param cb_cls the closure for the callback
2276  * @return operation handle on success; NULL if any pending operations are
2277  *           present
2278  */
2279 struct GNUNET_TESTBED_Operation *
2280 GNUNET_TESTBED_shutdown_peers (struct GNUNET_TESTBED_Controller *c,
2281                                void *op_cls,
2282                                GNUNET_TESTBED_OperationCompletionCallback cb,
2283                                void *cb_cls)
2284 {
2285   struct OperationContext *opc;
2286   struct ShutdownPeersData *data;
2287
2288   if (0 != GNUNET_CONTAINER_multihashmap32_size (c->opc_map))
2289     return NULL;
2290   data = GNUNET_new (struct ShutdownPeersData);
2291   data->cb = cb;
2292   data->cb_cls = cb_cls;
2293   opc = GNUNET_new (struct OperationContext);
2294   opc->c = c;
2295   opc->op_cls = op_cls;
2296   opc->data = data;
2297   opc->id =  GNUNET_TESTBED_get_next_op_id (c);
2298   opc->type = OP_SHUTDOWN_PEERS;
2299   opc->state = OPC_STATE_INIT;
2300   opc->op = GNUNET_TESTBED_operation_create_ (opc, &opstart_shutdown_peers,
2301                                               &oprelease_shutdown_peers);
2302   GNUNET_TESTBED_operation_queue_insert_ (opc->c->opq_parallel_operations,
2303                                         opc->op);
2304   GNUNET_TESTBED_operation_begin_wait_ (opc->op);
2305   return opc->op;
2306 }
2307
2308
2309 /**
2310  * Return the index of the peer inside of the total peer array,
2311  * aka. the peer's "unique ID".
2312  *
2313  * @param peer Peer handle.
2314  *
2315  * @return The peer's unique ID.
2316  */
2317 uint32_t
2318 GNUNET_TESTBED_get_index (const struct GNUNET_TESTBED_Peer *peer)
2319 {
2320   return peer->unique_id;
2321 }
2322
2323
2324 /**
2325  * Remove a barrier and it was the last one in the barrier hash map, destroy the
2326  * hash map
2327  *
2328  * @param barrier the barrier to remove
2329  */
2330 void
2331 GNUNET_TESTBED_barrier_remove_ (struct GNUNET_TESTBED_Barrier *barrier)
2332 {
2333   struct GNUNET_TESTBED_Controller *c = barrier->c;
2334
2335   GNUNET_assert (NULL != c->barrier_map); /* No barriers present */
2336   GNUNET_assert (GNUNET_OK ==
2337                  GNUNET_CONTAINER_multihashmap_remove (c->barrier_map,
2338                                                        &barrier->key,
2339                                                        barrier));
2340   GNUNET_free (barrier->name);
2341   GNUNET_free (barrier);
2342   if (0 == GNUNET_CONTAINER_multihashmap_size (c->barrier_map))
2343   {
2344     GNUNET_CONTAINER_multihashmap_destroy (c->barrier_map);
2345     c->barrier_map = NULL;
2346   }
2347 }
2348
2349
2350 /**
2351  * Initialise a barrier and call the given callback when the required percentage
2352  * of peers (quorum) reach the barrier OR upon error.
2353  *
2354  * @param controller the handle to the controller
2355  * @param name identification name of the barrier
2356  * @param quorum the percentage of peers that is required to reach the barrier.
2357  *   Peers signal reaching a barrier by calling
2358  *   GNUNET_TESTBED_barrier_reached().
2359  * @param cb the callback to call when the barrier is reached or upon error.
2360  *   Cannot be NULL.
2361  * @param cls closure for the above callback
2362  * @param echo GNUNET_YES to echo the barrier crossed status message back to the
2363  *   controller
2364  * @return barrier handle; NULL upon error
2365  */
2366 struct GNUNET_TESTBED_Barrier *
2367 GNUNET_TESTBED_barrier_init_ (struct GNUNET_TESTBED_Controller *controller,
2368                               const char *name,
2369                               unsigned int quorum,
2370                               GNUNET_TESTBED_barrier_status_cb cb, void *cls,
2371                               int echo)
2372 {
2373   struct GNUNET_TESTBED_BarrierInit *msg;
2374   struct GNUNET_MQ_Envelope *env;
2375   struct GNUNET_TESTBED_Barrier *barrier;
2376   struct GNUNET_HashCode key;
2377   size_t name_len;
2378
2379   GNUNET_assert (quorum <= 100);
2380   GNUNET_assert (NULL != cb);
2381   name_len = strlen (name);
2382   GNUNET_assert (0 < name_len);
2383   GNUNET_CRYPTO_hash (name, name_len, &key);
2384   if (NULL == controller->barrier_map)
2385     controller->barrier_map = GNUNET_CONTAINER_multihashmap_create (3, GNUNET_YES);
2386   if (GNUNET_YES ==
2387       GNUNET_CONTAINER_multihashmap_contains (controller->barrier_map,
2388                                               &key))
2389   {
2390     GNUNET_break (0);
2391     return NULL;
2392   }
2393   LOG_DEBUG ("Initialising barrier `%s'\n", name);
2394   barrier = GNUNET_new (struct GNUNET_TESTBED_Barrier);
2395   barrier->c = controller;
2396   barrier->name = GNUNET_strdup (name);
2397   barrier->cb = cb;
2398   barrier->cls = cls;
2399   barrier->echo = echo;
2400   GNUNET_memcpy (&barrier->key, &key, sizeof (struct GNUNET_HashCode));
2401   GNUNET_assert (GNUNET_OK ==
2402                  GNUNET_CONTAINER_multihashmap_put (controller->barrier_map,
2403                                                     &barrier->key,
2404                                                     barrier,
2405                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2406
2407   env = GNUNET_MQ_msg_extra (msg,
2408                              name_len,
2409                              GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_INIT);
2410   msg->quorum = (uint8_t) quorum;
2411   GNUNET_memcpy (msg->name,
2412                  barrier->name,
2413                  name_len);
2414   GNUNET_MQ_send (barrier->c->mq,
2415                   env);
2416   return barrier;
2417 }
2418
2419
2420 /**
2421  * Initialise a barrier and call the given callback when the required percentage
2422  * of peers (quorum) reach the barrier OR upon error.
2423  *
2424  * @param controller the handle to the controller
2425  * @param name identification name of the barrier
2426  * @param quorum the percentage of peers that is required to reach the barrier.
2427  *   Peers signal reaching a barrier by calling
2428  *   GNUNET_TESTBED_barrier_reached().
2429  * @param cb the callback to call when the barrier is reached or upon error.
2430  *   Cannot be NULL.
2431  * @param cls closure for the above callback
2432  * @return barrier handle; NULL upon error
2433  */
2434 struct GNUNET_TESTBED_Barrier *
2435 GNUNET_TESTBED_barrier_init (struct GNUNET_TESTBED_Controller *controller,
2436                              const char *name,
2437                              unsigned int quorum,
2438                              GNUNET_TESTBED_barrier_status_cb cb, void *cls)
2439 {
2440   return GNUNET_TESTBED_barrier_init_ (controller,
2441                                        name, quorum, cb, cls, GNUNET_YES);
2442 }
2443
2444
2445 /**
2446  * Cancel a barrier.
2447  *
2448  * @param barrier the barrier handle
2449  */
2450 void
2451 GNUNET_TESTBED_barrier_cancel (struct GNUNET_TESTBED_Barrier *barrier)
2452 {
2453   struct GNUNET_MQ_Envelope *env;
2454   struct GNUNET_TESTBED_BarrierCancel *msg;
2455   size_t slen;
2456
2457   slen = strlen (barrier->name);
2458   env = GNUNET_MQ_msg_extra (msg,
2459                              slen,
2460                              GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_CANCEL);
2461   GNUNET_memcpy (msg->name,
2462                  barrier->name,
2463                  slen);
2464   GNUNET_MQ_send (barrier->c->mq,
2465                   env);
2466   GNUNET_TESTBED_barrier_remove_ (barrier);
2467 }
2468
2469
2470 /* end of testbed_api.c */