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