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