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