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