peer create callback
[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
44 /**
45  * Generic logging shorthand
46  */
47 #define LOG(kind, ...)                          \
48   GNUNET_log_from (kind, "testbed-api", __VA_ARGS__);
49
50 /**
51  * Debug logging
52  */
53 #define LOG_DEBUG(...)                          \
54   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__);
55
56 /**
57  * Relative time seconds shorthand
58  */
59 #define TIME_REL_SECS(sec) \
60   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, sec)
61
62
63 /**
64  * Default server message sending retry timeout
65  */
66 #define TIMEOUT_REL TIME_REL_SECS(1)
67
68
69 /**
70  * The message queue for sending messages to the controller service
71  */
72 struct MessageQueue
73 {
74   /**
75    * The message to be sent
76    */
77   struct GNUNET_MessageHeader *msg;
78
79   /**
80    * next pointer for DLL
81    */
82   struct MessageQueue *next;
83   
84   /**
85    * prev pointer for DLL
86    */
87   struct MessageQueue *prev;
88 };
89
90
91 /**
92  * Structure for a controller link
93  */
94 struct ControllerLink
95 {
96   /**
97    * The next ptr for DLL
98    */
99   struct ControllerLink *next;
100
101   /**
102    * The prev ptr for DLL
103    */
104   struct ControllerLink *prev;
105
106   /**
107    * The host which will be referred in the peer start request. This is the
108    * host where the peer should be started
109    */
110   struct GNUNET_TESTBED_Host *delegated_host;
111
112   /**
113    * The host which will contacted to delegate the peer start request
114    */
115   struct GNUNET_TESTBED_Host *slave_host;
116
117   /**
118    * The configuration to be used to connect to slave host
119    */
120   const struct GNUNET_CONFIGURATION_Handle *slave_cfg;
121
122   /**
123    * GNUNET_YES if the slave should be started (and stopped) by us; GNUNET_NO
124    * if we are just allowed to use the slave via TCP/IP
125    */
126   int is_subordinate;
127 };
128
129
130 /**
131  * handle for host registration
132  */
133 struct GNUNET_TESTBED_HostRegistrationHandle
134 {
135   /**
136    * The host being registered
137    */
138   struct GNUNET_TESTBED_Host *host;
139
140   /**
141    * The controller at which this host is being registered
142    */
143   struct GNUNET_TESTBED_Controller *c;
144
145   /**
146    * The Registartion completion callback
147    */
148   GNUNET_TESTBED_HostRegistrationCompletion cc;
149
150   /**
151    * The closure for above callback
152    */
153   void *cc_cls;
154 };
155
156
157 /**
158  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
159  * controller (testbed service)
160  *
161  * @param c the controller handler
162  * @param msg message received
163  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
164  *           not
165  */
166 static int
167 handle_addhostconfirm (struct GNUNET_TESTBED_Controller *c,
168                        const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
169 {
170   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
171   char *emsg;
172   uint16_t msg_size;
173
174   rh = c->rh;
175   if (NULL == rh)
176   {  
177     return GNUNET_OK;    
178   }
179   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
180   {
181     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
182                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
183     return GNUNET_OK;
184   }
185   c->rh = NULL;
186   msg_size = ntohs (msg->header.size);
187   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
188   {
189     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
190     GNUNET_TESTBED_mark_host_registered_at_  (rh->host, c);
191     rh->cc (rh->cc_cls, NULL);
192     GNUNET_free (rh);
193     return GNUNET_OK;
194   } 
195   /* We have an error message */
196   emsg = (char *) &msg[1];
197   if ('\0' != emsg[msg_size - 
198                    sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
199   {
200     GNUNET_break (0);
201     GNUNET_free (rh);
202     return GNUNET_NO;
203   }  
204   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
205        ntohl (msg->host_id), emsg);
206   rh->cc (rh->cc_cls, emsg);
207   GNUNET_free (rh);
208   return GNUNET_OK;
209 }
210
211
212 /**
213  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
214  * controller (testbed service)
215  *
216  * @param c the controller handler
217  * @param msg message received
218  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
219  *           not
220  */
221 static int
222 handle_opsuccess (struct GNUNET_TESTBED_Controller *c,
223                   const struct
224                   GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg)
225 {
226   struct GNUNET_TESTBED_Operation *op;
227   struct GNUNET_TESTBED_EventInformation *event;
228   uint64_t op_id;
229   
230   op_id = GNUNET_ntohll (msg->operation_id);
231   LOG_DEBUG ("Operation %ul successful\n", op_id);
232   for (op = c->op_head; NULL != op; op = op->next)
233   {
234     if (op->operation_id == op_id)
235       break;
236   }
237   if (NULL == op)
238   {
239     LOG_DEBUG ("Operation not found\n");
240     return GNUNET_YES;
241   }
242   event = NULL;
243   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
244     event = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_EventInformation));
245   if (NULL != event)
246     event->type = GNUNET_TESTBED_ET_OPERATION_FINISHED; 
247   switch (op->type)
248   {
249   case OP_PEER_DESTROY:
250     {
251       struct PeerDestroyData *data;
252       
253       if (NULL != event)
254       {
255         event->details.operation_finished.operation = op;
256         event->details.operation_finished.op_cls = NULL;
257         event->details.operation_finished.emsg = NULL;
258         event->details.operation_finished.pit = GNUNET_TESTBED_PIT_GENERIC;
259         event->details.operation_finished.op_result.generic = NULL;
260       }
261       data = (struct PeerDestroyData *) op->data;
262       if (NULL != data->peer->details)
263       {
264         if (NULL != data->peer->details->cfg)
265           GNUNET_CONFIGURATION_destroy (data->peer->details->cfg);
266         //PEER_DETAILS
267       }
268       GNUNET_free (data->peer);
269       GNUNET_free (data);
270       //PEERDESTROYDATA
271     }
272     break;
273   default:
274     GNUNET_break (0);
275   }
276   if (NULL != event)
277   {
278     if (NULL != c->cc)
279       c->cc (c->cc_cls, event);
280     GNUNET_free (event);
281   }
282   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
283   GNUNET_free (op);
284   return GNUNET_YES;  
285 }
286
287
288 /**
289  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS message from
290  * controller (testbed service)
291  *
292  * @param c the controller handler
293  * @param msg message received
294  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
295  *           not
296  */
297 static int
298 handle_peer_create_success (struct GNUNET_TESTBED_Controller *c,
299                             const struct
300                             GNUNET_TESTBED_PeerCreateSuccessEventMessage *msg)
301 {
302   struct GNUNET_TESTBED_Operation *op;
303   struct PeerCreateData *data;
304   struct GNUNET_TESTBED_Peer *peer;
305   GNUNET_TESTBED_PeerCreateCallback cb;
306   void *cls;
307   uint64_t op_id;
308
309   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage)
310                  == ntohs (msg->header.size));
311   op_id = GNUNET_ntohll (msg->operation_id);
312   for (op = c->op_head; NULL != op; op = op->next)
313   {
314     if (op->operation_id == op_id)
315       break;
316   }
317   if (NULL == op)
318   {
319     LOG_DEBUG ("Operation not found\n");
320     return GNUNET_YES;
321   }
322   GNUNET_assert (OP_PEER_CREATE == op->type);
323   GNUNET_assert (NULL != op->data);
324   data = op->data;
325   GNUNET_assert (NULL != data->peer);
326   peer = data->peer;
327   GNUNET_assert (peer->unique_id == ntohl (msg->peer_id));
328   cb = data->cb;
329   cls = data->cls;
330   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
331   GNUNET_free (data);
332   GNUNET_free (op);
333   if (NULL != cb)
334     cb (cls, peer, NULL);
335   return GNUNET_YES;
336 }
337
338
339 /**
340  * Handler for messages from controller (testbed service)
341  *
342  * @param cls the controller handler
343  * @param msg message received, NULL on timeout or fatal error
344  */
345 static void 
346 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
347 {
348   struct GNUNET_TESTBED_Controller *c = cls;  
349   int status;
350
351   c->in_receive = GNUNET_NO;
352   /* FIXME: Add checks for message integrity */
353   if (NULL == msg)
354   {
355     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
356     return;
357   }
358   status = GNUNET_OK;
359   switch (ntohs (msg->type))
360   {
361   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
362     status =
363       handle_addhostconfirm (c, (const struct
364                                  GNUNET_TESTBED_HostConfirmedMessage *) msg);
365     break;
366   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
367     status =
368       handle_opsuccess (c, (const struct
369                             GNUNET_TESTBED_GenericOperationSuccessEventMessage
370                             *) msg);
371     break;
372   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS:
373     status =
374       handle_peer_create_success 
375       (c, (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *)msg);
376     break;
377   default:
378     GNUNET_break (0);
379   }
380   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
381   {
382     c->in_receive = GNUNET_YES;
383     GNUNET_CLIENT_receive (c->client, &message_handler, c,
384                            GNUNET_TIME_UNIT_FOREVER_REL);    
385   }
386 }
387
388
389 /**
390  * Function called to notify a client about the connection begin ready to queue
391  * more data.  "buf" will be NULL and "size" zero if the connection was closed
392  * for writing in the meantime.
393  *
394  * @param cls closure
395  * @param size number of bytes available in buf
396  * @param buf where the callee should write the message
397  * @return number of bytes written to buf
398  */
399 static size_t
400 transmit_ready_notify (void *cls, size_t size, void *buf)
401 {
402   struct GNUNET_TESTBED_Controller *c = cls;
403   struct MessageQueue *mq_entry;
404
405   c->th = NULL;
406   mq_entry = c->mq_head;
407   GNUNET_assert (NULL != mq_entry);
408   if ((0 == size) && (NULL == buf)) /* Timeout */
409   {
410     LOG_DEBUG ("Message sending timed out -- retrying\n");
411     c->th =
412       GNUNET_CLIENT_notify_transmit_ready (c->client,
413                                            ntohs (mq_entry->msg->size),
414                                            TIMEOUT_REL,
415                                            GNUNET_YES, &transmit_ready_notify,
416                                            c);
417     return 0;
418   }
419   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
420   size = ntohs (mq_entry->msg->size);  
421   memcpy (buf, mq_entry->msg, size);
422   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
423              ntohs (mq_entry->msg->type), size);
424   GNUNET_free (mq_entry->msg);
425   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
426   GNUNET_free (mq_entry);
427   mq_entry = c->mq_head;
428   if (NULL != mq_entry)
429     c->th = 
430       GNUNET_CLIENT_notify_transmit_ready (c->client,
431                                            ntohs (mq_entry->msg->size),
432                                            TIMEOUT_REL,
433                                            GNUNET_YES, &transmit_ready_notify,
434                                            c);
435   if (GNUNET_NO == c->in_receive)
436   {
437     c->in_receive = GNUNET_YES;
438     GNUNET_CLIENT_receive (c->client, &message_handler, c,
439                            GNUNET_TIME_UNIT_FOREVER_REL);
440   }
441   return size;
442 }
443
444
445 /**
446  * Queues a message in send queue for sending to the service
447  *
448  * @param controller the handle to the controller
449  * @param msg the message to queue
450  */
451 void
452 GNUNET_TESTBED_queue_message_ (struct GNUNET_TESTBED_Controller *controller,
453                                struct GNUNET_MessageHeader *msg)
454 {
455   struct MessageQueue *mq_entry;
456   uint16_t type;
457   uint16_t size;
458
459   type = ntohs (msg->type);
460   size = ntohs (msg->size);
461   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
462                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
463   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
464   mq_entry->msg = msg;
465   LOG (GNUNET_ERROR_TYPE_DEBUG,
466        "Queueing message of type %u, size %u for sending\n", type,
467        ntohs (msg->size));
468   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
469                                     mq_entry);
470   if (NULL == controller->th)
471     controller->th = 
472       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
473                                            TIMEOUT_REL,
474                                            GNUNET_YES, &transmit_ready_notify,
475                                            controller);
476 }
477
478
479 /**
480  * Handle for controller process
481  */
482 struct GNUNET_TESTBED_ControllerProc
483 {
484   /**
485    * The process handle
486    */
487   struct GNUNET_HELPER_Handle *helper;
488
489   /**
490    * The host where the helper is run
491    */
492   struct GNUNET_TESTBED_Host *host;
493
494   /**
495    * The controller error callback
496    */
497   GNUNET_TESTBED_ControllerStatusCallback cb;
498
499   /**
500    * The closure for the above callback
501    */
502   void *cls;
503
504   /**
505    * The send handle for the helper
506    */
507   struct GNUNET_HELPER_SendHandle *shandle;
508
509   /**
510    * The message corresponding to send handle
511    */
512   struct GNUNET_MessageHeader *msg;
513
514   /**
515    * The port number for ssh; used for helpers starting ssh
516    */
517   char *port;
518
519   /**
520    * The ssh destination string; used for helpers starting ssh
521    */
522   char *dst;
523
524   /**
525    * The configuration of the running testbed service
526    */
527   struct GNUNET_CONFIGURATION_Handle *cfg;
528
529 };
530
531
532 /**
533  * Functions with this signature are called whenever a
534  * complete message is received by the tokenizer.
535  *
536  * Do not call GNUNET_SERVER_mst_destroy in callback
537  *
538  * @param cls closure
539  * @param client identification of the client
540  * @param message the actual message
541  *
542  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
543  */
544 static int helper_mst (void *cls, void *client,
545                        const struct GNUNET_MessageHeader *message)
546 {
547   struct GNUNET_TESTBED_ControllerProc *cp = cls;
548   const struct GNUNET_TESTBED_HelperReply *msg;
549   const char *hostname;
550   char *config;
551   uLongf config_size;
552   uLongf xconfig_size;
553     
554   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
555   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) 
556                  < ntohs (msg->header.size));
557   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY 
558                  == ntohs (msg->header.type));
559   config_size = (uLongf) ntohs (msg->config_size);
560   xconfig_size = (uLongf) (ntohs (msg->header.size)
561                            - sizeof (struct GNUNET_TESTBED_HelperReply));
562   config = GNUNET_malloc (config_size);
563   GNUNET_assert (Z_OK == uncompress ((Bytef *) config, &config_size,
564                                      (const Bytef *) &msg[1], xconfig_size));
565   GNUNET_assert (NULL == cp->cfg);
566   cp->cfg = GNUNET_CONFIGURATION_create ();
567   GNUNET_assert (GNUNET_CONFIGURATION_deserialize (cp->cfg, config, 
568                                                    config_size, GNUNET_NO));
569   GNUNET_free (config);
570   if ((NULL == cp->host) || 
571       (NULL == (hostname = GNUNET_TESTBED_host_get_hostname_ (cp->host))))
572     hostname = "localhost";
573   /* Change the hostname so that we can connect to it */
574   GNUNET_CONFIGURATION_set_value_string (cp->cfg, "testbed", "hostname", 
575                                          hostname);
576   cp->cb (cp->cls, cp->cfg, GNUNET_OK);
577   return GNUNET_OK;
578 }
579
580
581 /**
582  * Continuation function from GNUNET_HELPER_send()
583  * 
584  * @param cls closure
585  * @param result GNUNET_OK on success,
586  *               GNUNET_NO if helper process died
587  *               GNUNET_SYSERR during GNUNET_HELPER_stop
588  */
589 static void 
590 clear_msg (void *cls, int result)
591 {
592   struct GNUNET_TESTBED_ControllerProc *cp = cls;
593   
594   GNUNET_assert (NULL != cp->shandle);
595   cp->shandle = NULL;
596   GNUNET_free (cp->msg);
597 }
598
599
600 /**
601  * Callback that will be called when the helper process dies. This is not called
602  * when the helper process is stoped using GNUNET_HELPER_stop()
603  *
604  * @param cls the closure from GNUNET_HELPER_start()
605  */
606 static void 
607 helper_exp_cb (void *cls)
608 {
609   struct GNUNET_TESTBED_ControllerProc *cp = cls;
610   GNUNET_TESTBED_ControllerStatusCallback cb;
611   void *cb_cls;
612
613   cb = cp->cb;
614   cb_cls = cp->cls;
615   GNUNET_TESTBED_controller_stop (cp);
616   if (NULL != cb)
617     cb (cb_cls, NULL, GNUNET_SYSERR);
618 }
619
620
621 /**
622  * Starts a controller process at the host. FIXME: add controller start callback
623  * with the configuration with which the controller is started
624  *
625  * @param controller_ip the ip address of the controller. Will be set as TRUSTED
626  *          host when starting testbed controller at host
627  * @param host the host where the controller has to be started; NULL for
628  *          localhost
629  * @param cfg template configuration to use for the remote controller; the
630  *          remote controller will be started with a slightly modified
631  *          configuration (port numbers, unix domain sockets and service home
632  *          values are changed as per TESTING library on the remote host)
633  * @param cb function called when the controller is successfully started or
634  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
635  *          called if cb is called with GNUNET_SYSERR as status. Will never be
636  *          called in the same task as 'GNUNET_TESTBED_controller_start'
637  *          (synchronous errors will be signalled by returning NULL). This
638  *          parameter cannot be NULL.
639  * @param cls closure for above callbacks
640  * @return the controller process handle, NULL on errors
641  */
642 struct GNUNET_TESTBED_ControllerProc *
643 GNUNET_TESTBED_controller_start (const char *controller_ip,
644                                  struct GNUNET_TESTBED_Host *host,
645                                  const struct GNUNET_CONFIGURATION_Handle *cfg,
646                                  GNUNET_TESTBED_ControllerStatusCallback cb,
647                                  void *cls)
648 {
649   struct GNUNET_TESTBED_ControllerProc *cp;
650   struct GNUNET_TESTBED_HelperInit *msg;
651   
652   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
653   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
654   {
655     char * const binary_argv[] = {
656       "gnunet-testbed-helper", NULL
657     };
658
659     cp->helper = GNUNET_HELPER_start ("gnunet-testbed-helper", binary_argv, 
660                                       &helper_mst, &helper_exp_cb, cp);
661   }
662   else
663   {
664     char *remote_args[6 + 1];
665     unsigned int argp;
666     const char *username;
667     const char *hostname;
668
669     username = GNUNET_TESTBED_host_get_username_ (host);
670     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
671     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
672     if (NULL == username)
673       GNUNET_asprintf (&cp->dst, "%s", hostname);
674     else 
675       GNUNET_asprintf (&cp->dst, "%s@%s", hostname, username);
676     argp = 0;
677     remote_args[argp++] = "ssh";
678     remote_args[argp++] = "-p";
679     remote_args[argp++] = cp->port;
680     remote_args[argp++] = "-q";
681     remote_args[argp++] = cp->dst;
682     remote_args[argp++] = "gnunet-testbed-helper";
683     remote_args[argp++] = NULL;
684     GNUNET_assert (argp == 6 + 1);
685     cp->helper = GNUNET_HELPER_start ("ssh", remote_args,
686                                       &helper_mst, &helper_exp_cb, cp);
687   }
688   if (NULL == cp->helper)
689   {
690     GNUNET_free_non_null (cp->port);
691     GNUNET_free_non_null (cp->dst);
692     GNUNET_free (cp);
693     return NULL;
694   }
695   cp->host = host;
696   cp->cb = cb;
697   cp->cls = cls;
698   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, cfg);
699   cp->msg = &msg->header;
700   cp->shandle = GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO,
701                                     &clear_msg, cp);
702   if (NULL == cp->shandle)
703   {
704     GNUNET_free (msg);
705     GNUNET_TESTBED_controller_stop (cp);
706     return NULL;
707   }
708   return cp;
709 }
710
711
712 /**
713  * Stop the controller process (also will terminate all peers and controllers
714  * dependent on this controller).  This function blocks until the testbed has
715  * been fully terminated (!).
716  *
717  * @param cproc the controller process handle
718  */
719 void
720 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cp)
721 {
722   if (NULL != cp->shandle)
723     GNUNET_HELPER_send_cancel (cp->shandle);
724   GNUNET_HELPER_stop (cp->helper);
725   if (NULL != cp->cfg)
726     GNUNET_CONFIGURATION_destroy (cp->cfg);
727   GNUNET_free_non_null (cp->port);
728   GNUNET_free_non_null (cp->dst);
729   GNUNET_free (cp);
730 }
731
732
733 /**
734  * Start a controller process using the given configuration at the
735  * given host.
736  *
737  * @param cfg configuration to use
738  * @param host host to run the controller on; This should be the same host if
739  *          the controller was previously started with
740  *          GNUNET_TESTBED_controller_start; NULL for localhost
741  * @param event_mask bit mask with set of events to call 'cc' for;
742  *                   or-ed values of "1LL" shifted by the
743  *                   respective 'enum GNUNET_TESTBED_EventType'
744  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
745  * @param cc controller callback to invoke on events
746  * @param cc_cls closure for cc
747  * @return handle to the controller
748  */
749 struct GNUNET_TESTBED_Controller *
750 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
751                                    struct GNUNET_TESTBED_Host *host,
752                                    uint64_t event_mask,
753                                    GNUNET_TESTBED_ControllerCallback cc,
754                                    void *cc_cls)
755 {
756   struct GNUNET_TESTBED_Controller *controller;
757   struct GNUNET_TESTBED_InitMessage *msg;
758
759   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
760   controller->cc = cc;
761   controller->cc_cls = cc_cls;
762   controller->event_mask = event_mask;
763   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
764   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);  
765   if (NULL == controller->client)
766   {
767     GNUNET_TESTBED_controller_disconnect (controller);
768     return NULL;
769   }
770   if (NULL == host)
771   {
772     host = GNUNET_TESTBED_host_create_by_id_ (0);
773     if (NULL == host)
774     {
775       LOG (GNUNET_ERROR_TYPE_WARNING,
776            "Treating NULL host as localhost. Multiple references to localhost. "
777            " May break when localhost freed before calling disconnect \n");
778       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
779     }
780     else
781     {
782       controller->aux_host = GNUNET_YES;
783     }
784   }
785   GNUNET_assert (NULL != host);
786   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage));
787   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
788   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage));
789   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
790   msg->event_mask = GNUNET_htonll (controller->event_mask);
791   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
792   return controller;
793 }
794
795
796 /**
797  * Configure shared services at a controller.  Using this function,
798  * you can specify that certain services (such as "resolver")
799  * should not be run for each peer but instead be shared
800  * across N peers on the specified host.  This function
801  * must be called before any peers are created at the host.
802  * 
803  * @param controller controller to configure
804  * @param service_name name of the service to share
805  * @param num_peers number of peers that should share one instance
806  *        of the specified service (1 for no sharing is the default),
807  *        use 0 to disable the service
808  */
809 void
810 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
811                                              const char *service_name,
812                                              uint32_t num_peers)
813 {
814   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
815   uint16_t service_name_size;
816   uint16_t msg_size;
817   
818   service_name_size = strlen (service_name) + 1;
819   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
820     + service_name_size;
821   msg = GNUNET_malloc (msg_size);
822   msg->header.size = htons (msg_size);
823   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
824   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
825   msg->num_peers = htonl (num_peers);
826   memcpy (&msg[1], service_name, service_name_size);
827   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
828 }
829
830
831 /**
832  * disconnects from the controller.
833  *
834  * @param controller handle to controller to stop
835  */
836 void
837 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *controller)
838 {
839   struct MessageQueue *mq_entry;
840
841   if (NULL != controller->th)
842     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
843  /* Clear the message queue */
844   while (NULL != (mq_entry = controller->mq_head))
845   {
846     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
847                                  controller->mq_tail,
848                                  mq_entry);
849     GNUNET_free (mq_entry->msg);
850     GNUNET_free (mq_entry);
851   }
852   if (NULL != controller->client)
853     GNUNET_CLIENT_disconnect (controller->client);
854   GNUNET_CONFIGURATION_destroy (controller->cfg);
855   if (GNUNET_YES == controller->aux_host)
856     GNUNET_TESTBED_host_destroy (controller->host);
857   GNUNET_free (controller);
858 }
859
860
861 /**
862  * Register a host with the controller
863  *
864  * @param controller the controller handle
865  * @param host the host to register
866  * @param cc the completion callback to call to inform the status of
867  *          registration. After calling this callback the registration handle
868  *          will be invalid. Cannot be NULL.
869  * @param cc_cls the closure for the cc
870  * @return handle to the host registration which can be used to cancel the
871  *           registration 
872  */
873 struct GNUNET_TESTBED_HostRegistrationHandle *
874 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
875                               struct GNUNET_TESTBED_Host *host,
876                               GNUNET_TESTBED_HostRegistrationCompletion cc,
877                               void *cc_cls)
878 {
879   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
880   struct GNUNET_TESTBED_AddHostMessage *msg;
881   const char *username;
882   const char *hostname;
883   uint16_t msg_size;
884   uint16_t user_name_length;
885
886   if (NULL != controller->rh)
887     return NULL;
888   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
889   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
890   {
891     LOG (GNUNET_ERROR_TYPE_WARNING,
892          "Host hostname: %s already registered\n",
893          (NULL == hostname) ? "localhost" : hostname);
894     return NULL;
895   }  
896   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
897   rh->host = host;
898   rh->c = controller;
899   GNUNET_assert (NULL != cc);
900   rh->cc = cc;
901   rh->cc_cls = cc_cls;
902   controller->rh = rh;
903   username = GNUNET_TESTBED_host_get_username_ (host);
904   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
905   user_name_length = 0;
906   if (NULL != username)
907   {
908     user_name_length = strlen (username) + 1;
909     msg_size += user_name_length;
910   }
911   /* FIXME: what happens when hostname is NULL? localhost */
912   GNUNET_assert (NULL != hostname);
913   msg_size += strlen (hostname) + 1;
914   msg = GNUNET_malloc (msg_size);
915   msg->header.size = htons (msg_size);
916   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
917   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
918   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
919   msg->user_name_length = htons (user_name_length);
920   if (NULL != username)
921     memcpy (&msg[1], username, user_name_length);
922   strcpy (((void *) &msg[1]) + user_name_length, hostname);
923   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
924   return rh;
925 }
926
927
928 /**
929  * Cancel the pending registration. Note that if the registration message is
930  * already sent to the service the cancellation has only the effect that the
931  * registration completion callback for the registration is never called.
932  *
933  * @param handle the registration handle to cancel
934  */
935 void
936 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
937                                     *handle)
938 {
939   if (handle != handle->c->rh)
940   {
941     GNUNET_break (0);
942     return;
943   }
944   handle->c->rh = NULL;
945   GNUNET_free (handle);  
946 }
947
948
949 /**
950  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
951  * serialized and compressed
952  *
953  * @param master handle to the master controller who creates the association
954  * @param delegated_host requests to which host should be delegated; cannot be NULL
955  * @param slave_host which host is used to run the slave controller; use NULL to
956  *          make the master controller connect to the delegated host
957  * @param sxcfg serialized and compressed configuration
958  * @param sxcfg_size the size scfg
959  * @param scfg_size the size of uncompressed serialized configuration
960  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
961  *          be started by the master controller; GNUNET_NO if we are just
962  *          allowed to use the slave via TCP/IP
963  */
964 void
965 GNUNET_TESTBED_controller_link_2 (struct GNUNET_TESTBED_Controller *master,
966                                   struct GNUNET_TESTBED_Host *delegated_host,
967                                   struct GNUNET_TESTBED_Host *slave_host,
968                                   const char *sxcfg,
969                                   size_t sxcfg_size,
970                                   size_t scfg_size,
971                                   int is_subordinate)
972 {
973   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
974   uint16_t msg_size;
975
976   GNUNET_assert (GNUNET_YES == 
977                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
978   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
979     GNUNET_assert (GNUNET_YES == 
980                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
981   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
982   msg = GNUNET_malloc (msg_size);
983   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);  
984   msg->header.size = htons (msg_size);
985   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
986   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ 
987                               ((NULL != slave_host) ? slave_host : master->host));
988   msg->config_size = htons ((uint16_t) scfg_size);
989   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
990   memcpy (&msg[1], sxcfg, sxcfg_size);
991   GNUNET_TESTBED_queue_message_ (master, (struct GNUNET_MessageHeader *) msg);
992 }
993
994
995 /**
996  * Compresses given configuration using zlib compress
997  *
998  * @param config the serialized configuration
999  * @param size the size of config
1000  * @param xconfig will be set to the compressed configuration (memory is fresly
1001  *          allocated) 
1002  * @return the size of the xconfig
1003  */
1004 size_t
1005 GNUNET_TESTBED_compress_config_ (const char *config, size_t size,
1006                                  char **xconfig)
1007 {
1008   size_t xsize;
1009   
1010   xsize = compressBound ((uLong) size);
1011   *xconfig = GNUNET_malloc (xsize);
1012   GNUNET_assert (Z_OK ==
1013                  compress2 ((Bytef *)* xconfig, (uLongf *) &xsize,
1014                             (const Bytef *) config, (uLongf) size, 
1015                             Z_BEST_SPEED));
1016   return xsize;
1017 }
1018                                 
1019
1020 /**
1021  * Create a link from slave controller to delegated controller. Whenever the
1022  * master controller is asked to start a peer at the delegated controller the
1023  * request will be routed towards slave controller (if a route exists). The
1024  * slave controller will then route it to the delegated controller. The
1025  * configuration of the slave controller is given and to be used to either
1026  * create the slave controller or to connect to an existing slave controller
1027  * process.  'is_subordinate' specifies if the given slave controller should be
1028  * started and managed by the master controller, or if the slave already has a
1029  * master and this is just a secondary master that is also allowed to use the
1030  * existing slave.
1031  *
1032  * @param master handle to the master controller who creates the association
1033  * @param delegated_host requests to which host should be delegated
1034  * @param slave_host which host is used to run the slave controller 
1035  * @param slave_cfg configuration to use for the slave controller
1036  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
1037  *                       by the master controller; GNUNET_NO if we are just
1038  *                       allowed to use the slave via TCP/IP
1039  */
1040 void
1041 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
1042                                 struct GNUNET_TESTBED_Host *delegated_host,
1043                                 struct GNUNET_TESTBED_Host *slave_host,
1044                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
1045                                 int is_subordinate)
1046 {
1047   char *config;
1048   char *cconfig;
1049   size_t cc_size;
1050   size_t config_size;  
1051   
1052   GNUNET_assert (GNUNET_YES == 
1053                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1054   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1055     GNUNET_assert (GNUNET_YES == 
1056                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1057   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
1058   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1059   GNUNET_free (config);
1060   GNUNET_assert ((UINT16_MAX -
1061                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
1062                   >= cc_size); /* Configuration doesn't fit in 1 message */
1063   GNUNET_TESTBED_controller_link_2 (master, delegated_host, slave_host,
1064                                     (const char *) cconfig,
1065                                     cc_size, config_size, is_subordinate);
1066   GNUNET_free (cconfig);
1067 }
1068
1069
1070 /**
1071  * Ask the testbed controller to write the current overlay topology to
1072  * a file.  Naturally, the file will only contain a snapshot as the
1073  * topology may evolve all the time.
1074  *
1075  * @param controller overlay controller to inspect
1076  * @param filename name of the file the topology should
1077  *        be written to.
1078  */
1079 void
1080 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
1081                                                const char *filename)
1082 {
1083   GNUNET_break (0);
1084 }
1085
1086
1087 /**
1088  * Creates a helper initialization message. Only for testing.
1089  *
1090  * @param cname the ip address of the controlling host
1091  * @param cfg the configuration that has to used to start the testbed service
1092  *          thru helper
1093  * @return the initialization message
1094  */
1095 struct GNUNET_TESTBED_HelperInit *
1096 GNUNET_TESTBED_create_helper_init_msg_ (const char *cname,
1097                                          const struct GNUNET_CONFIGURATION_Handle *cfg)
1098 {
1099   struct GNUNET_TESTBED_HelperInit *msg;
1100   char *config;
1101   char *xconfig;
1102   size_t config_size;
1103   size_t xconfig_size;
1104   uint16_t cname_len;
1105   uint16_t msg_size;
1106
1107   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
1108   GNUNET_assert (NULL != config);
1109   xconfig_size =
1110     GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
1111   GNUNET_free (config);
1112   cname_len = strlen (cname);
1113   msg_size = xconfig_size + cname_len + 1 + 
1114     sizeof (struct GNUNET_TESTBED_HelperInit);
1115   msg = GNUNET_realloc (xconfig, msg_size);
1116   (void) memmove ( ((void *) &msg[1]) + cname_len + 1, msg, xconfig_size);
1117   msg->header.size = htons (msg_size);
1118   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
1119   msg->cname_size = htons (cname_len);
1120   msg->config_size = htons (config_size);
1121   (void) strcpy ((char *) &msg[1], cname);
1122   return msg;
1123 }
1124
1125
1126 /* end of testbed_api.c */