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