fix mem leak
[oweals/gnunet.git] / src / testbed / gnunet-service-testbed.c
1 /*
2   This file is part of GNUnet.
3   (C) 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 2, 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/gnunet-service-testbed.c
23  * @brief implementation of the TESTBED service
24  * @author Sree Harsha Totakura
25  */
26
27 #include "platform.h"
28 #include "gnunet_service_lib.h"
29 #include "gnunet_server_lib.h"
30 #include <zlib.h>
31
32 #include "testbed.h"
33 #include "gnunet_testbed_service.h"
34 #include "testbed_api_hosts.h"
35 #include "gnunet_testing_lib-new.h"
36
37 /**
38  * Generic logging
39  */
40 #define LOG(kind,...)                           \
41   GNUNET_log (kind, __VA_ARGS__)
42
43 /**
44  * Debug logging
45  */
46 #define LOG_DEBUG(...)                          \
47   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
48
49
50 #define LIST_GROW_STEP 10
51
52 struct Context
53 {
54   /**
55    * The client handle associated with this context
56    */
57   struct GNUNET_SERVER_Client *client;
58
59   /**
60    * The network address of the master controller
61    */
62   char *master_ip;
63
64   /**
65    * The TESTING system handle for starting peers locally
66    */
67   struct GNUNET_TESTING_System *system;
68   
69   /**
70    * Event mask of event to be responded in this context
71    */
72   uint64_t event_mask;
73
74   /**
75    * Our host id according to this context
76    */
77   uint32_t host_id;
78 };
79
80
81 /**
82  * The message queue for sending messages to clients
83  */
84 struct MessageQueue
85 {
86   /**
87    * The message to be sent
88    */
89   struct GNUNET_MessageHeader *msg;
90
91   /**
92    * The client to send the message to
93    */
94   struct GNUNET_SERVER_Client *client;
95   
96   /**
97    * next pointer for DLL
98    */
99   struct MessageQueue *next;
100   
101   /**
102    * prev pointer for DLL
103    */
104   struct MessageQueue *prev;
105 };
106
107
108 /**
109  * The structure for identifying a shared service
110  */
111 struct SharedService
112 {
113   /**
114    * The name of the shared service
115    */
116   char *name;
117
118   /**
119    * Number of shared peers per instance of the shared service
120    */
121   uint32_t num_shared;
122
123   /**
124    * Number of peers currently sharing the service
125    */
126   uint32_t num_sharing;
127 };
128
129
130 /**
131  * A routing entry
132  */
133 struct Route
134 {
135   /**
136    * destination host
137    */
138   uint32_t dest;
139
140   /**
141    * The host destination is reachable thru
142    */
143   uint32_t thru;
144 };
145
146
147 /**
148  * Structure representing a connected(directly-linked) controller
149  */
150 struct Slave
151 {
152   /**
153    * The controller process handle if we had started the controller
154    */
155   struct GNUNET_TESTBED_ControllerProc *controller_proc;
156
157   /**
158    * The controller handle
159    */
160   struct GNUNET_TESTBED_Controller *controller;
161
162   /**
163    * The id of the host this controller is running on
164    */
165   uint32_t host_id;
166 };
167
168
169 /**
170  * Slave startup context
171  */
172 struct SlaveContext
173 {
174   /**
175    * The slave corresponding to this context
176    */
177   struct Slave *slave;
178
179   /**
180    * The configuration used as a template while startup
181    */
182   struct GNUNET_CONFIGURATION_Handle *cfg;
183 };
184
185
186 /**
187  * States of LCFContext
188  */
189 enum LCFContextState
190   {
191     /**
192      * The Context has been initialized; Nothing has been done on it
193      */
194     INIT,
195
196     /**
197      * Delegated host has been registered at the forwarding controller
198      */
199     DELEGATED_HOST_REGISTERED,
200     
201     /**
202      * The context has been finished (may have error)
203      */
204     FINISHED
205
206   };
207
208
209 /**
210  * Link controllers request forwarding context
211  */
212 struct LCFContext
213 {
214   /**
215    * The serialized and compressed configuration
216    */
217   char *sxcfg;
218
219   /**
220    * The gateway which will pass the link message to delegated host
221    */
222   struct Slave *gateway;
223
224   /**
225    * The host registration handle while registered hosts in this context
226    */
227   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
228
229   /**
230    * The size of the compressed serialized configuration
231    */
232   size_t sxcfg_size;
233
234   /**
235    * The size of the uncompressed configuration
236    */
237   size_t scfg_size;
238
239   /**
240    * Should the delegated host be started by the slave host?
241    */
242   int is_subordinate;
243
244   /**
245    * The state of this context
246    */
247   enum LCFContextState state;
248
249   /**
250    * The delegated host
251    */
252   uint32_t delegated_host_id;
253   
254
255 };
256
257
258 /**
259  * Structure of a queue entry in LCFContext request queue
260  */
261 struct LCFContextQueue
262 {
263   /**
264    * The LCFContext
265    */
266   struct LCFContext *lcf;
267
268   /**
269    * Head prt for DLL
270    */
271   struct LCFContextQueue *next;
272
273   /**
274    * Tail ptr for DLL
275    */
276   struct LCFContextQueue *prev;
277 };
278
279
280 /**
281  * A locally started peer
282  */
283 struct Peer
284 {
285   /**
286    * The peer handle from testing API
287    */
288   struct GNUNET_TESTING_Peer *peer;
289
290   /**
291    * The modified (by GNUNET_TESTING_peer_configure) configuration this peer is
292    * configured with
293    */
294   struct GNUNET_CONFIGURATION_Handle *cfg;
295
296   /**
297    * Our local reference id for this peer
298    */
299   uint32_t id;
300
301 };
302
303
304 /**
305  * The master context; generated with the first INIT message
306  */
307 static struct Context *master_context;
308
309 /***********/
310 /* Handles */
311 /***********/
312
313 /**
314  * Wrapped stdin.
315  */
316 static struct GNUNET_DISK_FileHandle *fh;
317
318 /**
319  * Current Transmit Handle; NULL if no notify transmit exists currently
320  */
321 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
322
323 /****************/
324 /* Lists & Maps */
325 /****************/
326
327 /**
328  * The head for the LCF queue
329  */
330 static struct LCFContextQueue *lcfq_head;
331
332 /**
333  * The tail for the LCF queue
334  */
335 static struct LCFContextQueue *lcfq_tail;
336
337 /**
338  * The message queue head
339  */
340 static struct MessageQueue *mq_head;
341
342 /**
343  * The message queue tail
344  */
345 static struct MessageQueue *mq_tail;
346
347 /**
348  * Array of host list
349  */
350 static struct GNUNET_TESTBED_Host **host_list;
351
352 /**
353  * A list of routes
354  */
355 static struct Route **route_list;
356
357 /**
358  * A list of directly linked neighbours
359  */
360 static struct Slave **slave_list;
361
362 /**
363  * A list of peers we own locally
364  */
365 static struct Peer **peer_list;
366
367 /**
368  * The hashmap of shared services
369  */
370 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
371
372 /**
373  * The size of the host list
374  */
375 static uint32_t host_list_size;
376
377 /**
378  * The size of the route list
379  */
380 static uint32_t route_list_size;
381
382 /**
383  * The size of directly linked neighbours list
384  */
385 static uint32_t slave_list_size;
386
387 /**
388  * The size of the peer list
389  */
390 static uint32_t peer_list_size;
391
392 /*********/
393 /* Tasks */
394 /*********/
395
396 /**
397  * The lcf_task handle
398  */
399 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
400
401 /**
402  * The shutdown task handle
403  */
404 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
405
406 /******************/
407 /* Testing System */
408 /******************/
409
410 /**
411  * Our configuration; we also use this as template for starting other controllers
412  */
413 static struct GNUNET_CONFIGURATION_Handle *config;
414
415
416 /**
417  * Function called to notify a client about the connection begin ready to queue
418  * more data.  "buf" will be NULL and "size" zero if the connection was closed
419  * for writing in the meantime.
420  *
421  * @param cls NULL
422  * @param size number of bytes available in buf
423  * @param buf where the callee should write the message
424  * @return number of bytes written to buf
425  */
426 static size_t
427 transmit_ready_notify (void *cls, size_t size, void *buf)
428 {
429   struct MessageQueue *mq_entry;
430
431   transmit_handle = NULL;
432   mq_entry = mq_head;
433   GNUNET_assert (NULL != mq_entry);
434   if (0 == size)
435     return 0;
436   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
437   size = ntohs (mq_entry->msg->size);
438   memcpy (buf, mq_entry->msg, size);
439   GNUNET_free (mq_entry->msg);
440   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
441   GNUNET_free (mq_entry);
442   mq_entry = mq_head;
443   if (NULL != mq_entry)
444     transmit_handle = 
445       GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
446                                            ntohs (mq_entry->msg->size),
447                                            GNUNET_TIME_UNIT_FOREVER_REL,
448                                            &transmit_ready_notify, NULL);
449   return size;
450 }
451
452
453 /**
454  * Queues a message in send queue for sending to the service
455  *
456  * @param client the client to whom the queued message has to be sent
457  * @param msg the message to queue
458  */
459 static void
460 queue_message (struct GNUNET_SERVER_Client *client,
461                struct GNUNET_MessageHeader *msg)
462 {
463   struct MessageQueue *mq_entry;
464   uint16_t type;
465   uint16_t size;
466
467   type = ntohs (msg->type);
468   size = ntohs (msg->size);
469   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
470                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
471   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
472   mq_entry->msg = msg;
473   mq_entry->client = client;
474   LOG_DEBUG ( "Queueing message of type %u, size %u for sending\n", type,
475               ntohs (msg->size));
476   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
477   if (NULL == transmit_handle)
478     transmit_handle = 
479       GNUNET_SERVER_notify_transmit_ready (client, size,
480                                            GNUNET_TIME_UNIT_FOREVER_REL,
481                                            &transmit_ready_notify, NULL);
482 }
483
484
485 /**
486  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
487  *
488  * @param ptr the memory block to realloc
489  * @param size the size of ptr
490  * @param new_size the size to which ptr has to be realloc'ed
491  * @return the newly reallocated memory block
492  */
493 static void *
494 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
495 {
496   ptr = GNUNET_realloc (ptr, new_size);
497   if (new_size > size)
498     ptr = memset (ptr + size, 0, new_size - size);
499   return ptr;
500 }
501
502
503 /**
504  * Function to add a host to the current list of known hosts
505  *
506  * @param host the host to add 
507  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
508  *           already in use
509  */
510 static int
511 host_list_add (struct GNUNET_TESTBED_Host *host)
512 {
513   uint32_t host_id;
514
515   host_id = GNUNET_TESTBED_host_get_id_ (host);
516   if (host_list_size <= host_id)
517   {
518     host_list = 
519       TESTBED_realloc (host_list, 
520                        sizeof (struct GNUNET_TESTBED_Host *) * host_list_size,
521                        sizeof (struct GNUNET_TESTBED_Host *) *
522                        (host_list_size + LIST_GROW_STEP));
523     host_list_size += LIST_GROW_STEP;
524   }
525   if (NULL != host_list[host_id])
526   {
527     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
528     return GNUNET_SYSERR;
529   }
530   host_list[host_id] = host;
531   return GNUNET_OK;
532 }
533
534
535 /**
536  * Adds a route to the route list
537  *
538  * @param route the route to add
539  */
540 static void
541 route_list_add (struct Route *route)
542 {
543   if (route->dest >= route_list_size)
544   {
545     route_list = 
546       TESTBED_realloc (route_list, 
547                        sizeof (struct Route *) * route_list_size,
548                        sizeof (struct Route *) * 
549                        (route_list_size + LIST_GROW_STEP));
550     route_list_size += LIST_GROW_STEP;
551   }
552   GNUNET_assert (NULL == route_list[route->dest]);
553   route_list[route->dest] = route;
554 }
555
556
557 /**
558  * Adds a slave to the slave array
559  *
560  * @param route the route to add
561  */
562 static void
563 slave_list_add (struct Slave *slave)
564 {
565   if (slave->host_id  >= slave_list_size)
566   {
567     slave_list = TESTBED_realloc (slave_list, 
568                                   sizeof (struct Slave *) *slave_list_size,
569                                   sizeof (struct Slave *) *
570                                   (slave_list_size + LIST_GROW_STEP));
571     slave_list_size += LIST_GROW_STEP;
572   }
573   GNUNET_assert (NULL == slave_list[slave->host_id]);
574   slave_list[slave->host_id] = slave;
575 }
576
577
578 /**
579  * Adds a peer to the peer array
580  *
581  * @param route the route to add
582  */
583 static void
584 peer_list_add (struct Peer *peer)
585 {
586   if (peer->id  >= peer_list_size)
587   {
588     peer_list = TESTBED_realloc (peer_list, 
589                                  sizeof (struct Peer *) * peer_list_size,
590                                  sizeof (struct Peer *) *
591                                  (peer_list_size + LIST_GROW_STEP));
592     peer_list_size += LIST_GROW_STEP;
593   }
594   GNUNET_assert (NULL == peer_list[peer->id]);
595   peer_list[peer->id] = peer;
596 }
597
598
599 /**
600  * Routes message to a host given its host_id
601  *
602  * @param host_id the id of the destination host
603  * @param msg the message to be routed
604  */
605 static void
606 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
607 {
608   GNUNET_break (0);
609 }
610
611
612 /**
613  * The  Link Controller forwarding task
614  *
615  * @param cls the LCFContext
616  * @param tc the Task context from scheduler
617  */
618 static void
619 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
620
621
622 /**
623  * Completion callback for host registrations while forwarding Link Controller messages
624  *
625  * @param cls the LCFContext
626  * @param emsg the error message; NULL if host registration is successful
627  */
628 static void
629 lcf_proc_cc (void *cls, const char *emsg)
630 {
631   struct LCFContext *lcf = cls;
632
633   lcf->rhandle = NULL;
634   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
635   switch (lcf->state)
636   {
637   case INIT:
638     if (NULL != emsg)
639     {
640       LOG (GNUNET_ERROR_TYPE_WARNING, 
641            "Host registration failed with message: %s\n", emsg);
642       lcf->state = FINISHED;
643       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
644       return;
645     }
646     lcf->state = DELEGATED_HOST_REGISTERED;
647     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
648     break;
649   default:
650     GNUNET_assert (0);          /* Shouldn't reach here */
651   }  
652 }
653
654
655 /**
656  * The  Link Controller forwarding task
657  *
658  * @param cls the LCFContext
659  * @param tc the Task context from scheduler
660  */
661 static void
662 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
663 {
664   struct LCFContext *lcf = cls;
665   struct LCFContextQueue *lcfq;
666
667   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
668   switch (lcf->state)
669   {
670   case INIT:
671     if (GNUNET_NO ==
672         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
673                                             lcf->gateway->controller))
674     {
675       lcf->rhandle =
676         GNUNET_TESTBED_register_host (lcf->gateway->controller,
677                                       host_list[lcf->delegated_host_id],
678                                       lcf_proc_cc, lcf);                                                   
679     }
680     else
681     {
682       lcf->state = DELEGATED_HOST_REGISTERED;
683       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
684     }
685     break;
686   case DELEGATED_HOST_REGISTERED:
687     GNUNET_TESTBED_controller_link_2 (lcf->gateway->controller,
688                                       host_list[lcf->delegated_host_id],
689                                       host_list[lcf->gateway->host_id],
690                                       lcf->sxcfg, lcf->sxcfg_size,
691                                       lcf->scfg_size,
692                                       lcf->is_subordinate);
693     lcf->state = FINISHED;
694   case FINISHED:   
695     lcfq = lcfq_head;
696     GNUNET_assert (lcfq->lcf == lcf);
697     GNUNET_free (lcf->sxcfg);
698     GNUNET_free (lcf);
699     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
700     GNUNET_free (lcfq);
701     if (NULL != lcfq_head)
702       lcf_proc_task_id = 
703         GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
704   }
705 }
706
707
708 /**
709  * Callback for event from slave controllers
710  *
711  * @param cls struct Slave *
712  * @param event information about the event
713  */
714 static void 
715 slave_event_callback(void *cls,
716                      const struct GNUNET_TESTBED_EventInformation *event)
717 {
718   GNUNET_break (0);
719 }
720
721
722 /**
723  * Callback to signal successfull startup of the controller process
724  *
725  * @param cls the closure from GNUNET_TESTBED_controller_start()
726  * @param cfg the configuration with which the controller has been started;
727  *          NULL if status is not GNUNET_OK
728  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
729  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
730  */
731 static void 
732 slave_status_callback (void *cls, 
733                        const struct GNUNET_CONFIGURATION_Handle *cfg,
734                        int status)
735 {
736   struct SlaveContext *sc = cls;
737
738   if (GNUNET_SYSERR == status)
739   {
740     sc->slave->controller_proc = NULL;
741     LOG (GNUNET_ERROR_TYPE_WARNING,
742          "Unexpected slave shutdown\n");
743     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
744     return;
745   }
746   GNUNET_CONFIGURATION_destroy (sc->cfg);
747   sc->slave->controller =
748     GNUNET_TESTBED_controller_connect (cfg, host_list[sc->slave->host_id],
749                                        master_context->event_mask,
750                                        &slave_event_callback, sc->slave);
751   GNUNET_free (sc);
752 }
753
754
755 /**
756  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
757  *
758  * @param cls NULL
759  * @param client identification of the client
760  * @param message the actual message
761  */
762 static void 
763 handle_init (void *cls,
764              struct GNUNET_SERVER_Client *client,
765              const struct GNUNET_MessageHeader *message)
766 {
767   const struct GNUNET_TESTBED_InitMessage *msg;
768   struct GNUNET_TESTBED_Host *host;
769   void *addr;
770   size_t addrlen;
771
772   if (NULL != master_context)
773   {
774     GNUNET_break (0);
775     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
776     return;
777   }
778   msg = (const struct GNUNET_TESTBED_InitMessage *) message;  
779   master_context = GNUNET_malloc (sizeof (struct Context));
780   master_context->client = client;
781   master_context->host_id = ntohl (msg->host_id);
782   GNUNET_assert (GNUNET_OK == 
783                  GNUNET_SERVER_client_get_address (client, &addr, &addrlen));
784   master_context->master_ip = GNUNET_malloc (NI_MAXHOST);
785   if (0 != getnameinfo (addr, addrlen, master_context->master_ip, NI_MAXHOST,
786                         NULL, 0, NI_NUMERICHOST))
787   {
788     LOG (GNUNET_ERROR_TYPE_WARNING,
789          "Cannot determine the ip of master controller: %s\n", STRERROR (errno));
790     GNUNET_free (addr);
791     GNUNET_assert (0);
792   }
793   GNUNET_free (addr);
794   LOG_DEBUG ("Master Controller IP: %s\n", master_context->master_ip);
795   master_context->system = 
796     GNUNET_TESTING_system_create ("testbed", master_context->master_ip);
797   host = GNUNET_TESTBED_host_create_with_id (master_context->host_id,
798                                              NULL, NULL, 0);
799   host_list_add (host);
800   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
801   GNUNET_SERVER_client_keep (client);
802   LOG_DEBUG ("Created master context with host ID: %u\n",
803              master_context->host_id);
804   GNUNET_SERVER_receive_done (client, GNUNET_OK);
805 }
806
807
808 /**
809  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
810  *
811  * @param cls NULL
812  * @param client identification of the client
813  * @param message the actual message
814  */
815 static void 
816 handle_add_host (void *cls,
817                  struct GNUNET_SERVER_Client *client,
818                  const struct GNUNET_MessageHeader *message)
819 {
820   struct GNUNET_TESTBED_Host *host;
821   const struct GNUNET_TESTBED_AddHostMessage *msg;
822   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
823   char *username;
824   char *hostname;
825   char *emsg;
826   uint32_t host_id;
827   uint16_t username_length;
828   uint16_t hostname_length;
829   uint16_t reply_size;
830   
831   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
832   username_length = ntohs (msg->user_name_length);
833   username_length = (0 == username_length) ? 0 : username_length + 1;
834   username = (char *) &(msg[1]);
835   hostname = username + username_length;
836   if (ntohs (message->size) <=
837       (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length))
838   {
839     GNUNET_break (0);
840     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
841     return;
842   }
843   hostname_length = ntohs (message->size)
844     - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
845   if (strlen (hostname) != hostname_length - 1)
846   {
847     GNUNET_break (0);
848     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
849     return;
850   }
851   host_id = ntohl (msg->host_id);
852   LOG_DEBUG ("Received ADDHOST message\n");
853   LOG_DEBUG ("-------host id: %u\n", host_id);
854   if (NULL != hostname) LOG_DEBUG ("-------hostname: %s\n", hostname);
855   if (0 != username_length) LOG_DEBUG ("-------username: %s\n", username);
856   else LOG_DEBUG ("-------username: NULL\n");
857   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
858   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
859                                              ntohs (msg->ssh_port));
860   GNUNET_SERVER_receive_done (client, GNUNET_OK);
861   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
862   if (GNUNET_OK != host_list_add (host))
863   {    
864     /* We are unable to add a host */  
865     emsg = "A host exists with given host-id";
866     LOG_DEBUG ("%s: %u", emsg, host_id);
867     GNUNET_TESTBED_host_destroy (host);
868     reply_size += strlen (emsg) + 1;
869     reply = GNUNET_malloc (reply_size);
870     memcpy (&reply[1], emsg, strlen (emsg) + 1);
871   }
872   else
873     reply = GNUNET_malloc (reply_size);  
874   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
875   reply->header.size = htons (reply_size);
876   reply->host_id = htonl (host_id);  
877   queue_message (client, (struct GNUNET_MessageHeader *) reply);
878 }
879
880
881 /**
882  * Iterator over hash map entries.
883  *
884  * @param cls closure
885  * @param key current key code
886  * @param value value in the hash map
887  * @return GNUNET_YES if we should continue to
888  *         iterate,
889  *         GNUNET_NO if not.
890  */
891 int ss_exists_iterator (void *cls,
892                         const struct GNUNET_HashCode * key,
893                         void *value)
894 {
895   struct SharedService *queried_ss = cls;
896   struct SharedService *ss = value;
897
898   if (0 == strcmp (ss->name, queried_ss->name))
899     return GNUNET_NO;
900   else
901     return GNUNET_YES;
902 }
903
904
905 /**
906  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
907  *
908  * @param cls NULL
909  * @param client identification of the client
910  * @param message the actual message
911  */
912 static void 
913 handle_configure_shared_service (void *cls,
914                                  struct GNUNET_SERVER_Client *client,
915                                  const struct GNUNET_MessageHeader *message)
916 {
917   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
918   struct SharedService *ss;
919   char *service_name;
920   struct GNUNET_HashCode hash;
921   uint16_t msg_size;
922   uint16_t service_name_size;
923     
924   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
925   msg_size = ntohs (message->size);
926   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
927   {
928     GNUNET_break (0);
929     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
930     return;
931   }
932   service_name_size = msg_size - 
933     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
934   service_name = (char *) &msg[1];
935   if ('\0' != service_name[service_name_size - 1])
936   {
937     GNUNET_break (0);
938     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
939     return;
940   }
941   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
942              service_name, ntohl (msg->num_peers));
943   if (ntohl (msg->host_id) != master_context->host_id)
944   {
945     route_message (ntohl (msg->host_id), message);
946     GNUNET_SERVER_receive_done (client, GNUNET_OK);
947     return;
948   }
949   GNUNET_SERVER_receive_done (client, GNUNET_OK);
950   ss = GNUNET_malloc (sizeof (struct SharedService));
951   ss->name = strdup (service_name);
952   ss->num_shared = ntohl (msg->num_peers);
953   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
954   if (GNUNET_SYSERR == 
955       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
956                                                   &ss_exists_iterator, ss))
957   {
958     LOG (GNUNET_ERROR_TYPE_WARNING,
959          "Service %s already configured as a shared service. "
960          "Ignoring service sharing request \n", ss->name);
961     GNUNET_free (ss->name);
962     GNUNET_free (ss);
963     return;
964   }
965   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
966                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
967 }
968
969
970 /**
971  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
972  *
973  * @param cls NULL
974  * @param client identification of the client
975  * @param message the actual message
976  */
977 static void 
978 handle_link_controllers (void *cls,
979                          struct GNUNET_SERVER_Client *client,
980                          const struct GNUNET_MessageHeader *message)
981 {
982   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
983   struct GNUNET_CONFIGURATION_Handle *cfg;
984   struct SlaveContext *sc;
985   struct LCFContextQueue *lcfq;
986   struct Route *route;
987   struct Route *new_route;
988   char *config;  
989   uLongf dest_size;
990   size_t config_size;
991   uint32_t delegated_host_id;
992   uint32_t slave_host_id;
993   uint16_t msize;
994    
995   if (NULL == master_context)
996   {
997     GNUNET_break (0);
998     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
999     return;
1000   }
1001   msize = ntohs (message->size);
1002   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1003   {
1004     GNUNET_break (0);
1005     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1006     return;
1007   }
1008   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1009   delegated_host_id = ntohl (msg->delegated_host_id);
1010   if (delegated_host_id == master_context->host_id)
1011   {
1012     GNUNET_break (0);
1013     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1014     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1015     return;
1016   }
1017   if ((delegated_host_id >= host_list_size) || 
1018       (NULL == host_list[delegated_host_id]))
1019   {
1020     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
1021     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1022     return;
1023   }
1024   slave_host_id = ntohl (msg->slave_host_id);
1025   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1026   {
1027     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
1028     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1029     return;
1030   }
1031   if (slave_host_id == delegated_host_id)
1032   {
1033     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1034     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1035     return;
1036   }
1037   msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1038   config_size = ntohs (msg->config_size);
1039   
1040   if (slave_host_id == master_context->host_id) /* Link from us */
1041   {
1042     struct Slave *slave;
1043
1044     if ((delegated_host_id < slave_list_size) && 
1045         (NULL != slave_list[delegated_host_id])) /* We have already added */
1046     {
1047       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1048            delegated_host_id);
1049       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1050       return;
1051     }    
1052     config = GNUNET_malloc (config_size);
1053     dest_size = (uLongf) config_size;    
1054     if (Z_OK != uncompress ((Bytef *) config, &dest_size,
1055                             (const Bytef *) &msg[1], (uLong) msize))
1056     {
1057       GNUNET_break (0);           /* Compression error */
1058       GNUNET_free (config);
1059       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1060       return;
1061     }
1062     if (config_size == dest_size)
1063     {
1064       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1065       GNUNET_free (config);
1066       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1067     }
1068     cfg = GNUNET_CONFIGURATION_create (); /* Free here or in lcfcontext */
1069     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1070                                                        GNUNET_NO))
1071     {
1072       GNUNET_break (0);           /* Configuration parsing error */
1073       GNUNET_free (config);
1074       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1075       return;
1076     }
1077     GNUNET_free (config);
1078     if ((delegated_host_id < slave_list_size) &&
1079         (NULL != slave_list[delegated_host_id]))
1080     {
1081       GNUNET_break (0);           /* Configuration parsing error */
1082       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1083       return;
1084     }
1085     slave = GNUNET_malloc (sizeof (struct Slave));
1086     slave->host_id = delegated_host_id;
1087     slave_list_add (slave);
1088     sc = GNUNET_malloc (sizeof (struct SlaveContext));
1089     sc->slave = slave;
1090     sc->cfg = cfg;
1091     if (1 == msg->is_subordinate)
1092     {
1093       slave->controller_proc =
1094         GNUNET_TESTBED_controller_start (master_context->master_ip,
1095                                          host_list[slave->host_id],
1096                                          cfg, &slave_status_callback,
1097                                          sc);
1098     }    
1099     new_route = GNUNET_malloc (sizeof (struct Route));
1100     new_route->dest = delegated_host_id;
1101     new_route->thru = master_context->host_id;
1102     route_list_add (new_route);
1103     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1104     return;
1105   }
1106
1107   /* Route the request */
1108   if (slave_host_id >= route_list_size)
1109   {
1110     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1111     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1112     return;
1113   }
1114   while (NULL != (route = route_list[slave_host_id]))
1115   {
1116     if (route->thru == master_context->host_id)
1117       break;
1118     slave_host_id = route->thru;
1119   }
1120   GNUNET_assert (NULL != route); /* because we add routes carefully */
1121   GNUNET_assert (route->dest < slave_list_size);
1122   GNUNET_assert (NULL != slave_list[route->dest]);  
1123   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1124   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1125   lcfq->lcf->delegated_host_id = delegated_host_id;
1126   lcfq->lcf->is_subordinate =
1127     (1 == msg->is_subordinate) ? GNUNET_YES : GNUNET_NO;
1128   lcfq->lcf->state = INIT;
1129   lcfq->lcf->gateway = slave_list[route->dest];
1130   lcfq->lcf->sxcfg_size = msize;
1131   lcfq->lcf->sxcfg = GNUNET_malloc (msize);
1132   lcfq->lcf->scfg_size = config_size;
1133   (void) memcpy (lcfq->lcf->sxcfg, &msg[1], msize);
1134   if (NULL == lcfq_head)
1135   {
1136     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1137     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1138     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq);
1139   }
1140   else
1141     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1142   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1143   new_route = GNUNET_malloc (sizeof (struct Route));
1144   new_route->dest = delegated_host_id;
1145   new_route->thru = route->dest;
1146   route_list_add (new_route);
1147 }
1148
1149
1150 /**
1151  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1152  *
1153  * @param cls NULL
1154  * @param client identification of the client
1155  * @param message the actual message
1156  */
1157 static void 
1158 handle_peer_create (void *cls,
1159                     struct GNUNET_SERVER_Client *client,
1160                     const struct GNUNET_MessageHeader *message)
1161 {
1162   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1163   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1164   struct GNUNET_CONFIGURATION_Handle *cfg;
1165   char *config;
1166   size_t dest_size;
1167   int ret;
1168   uint32_t config_size;
1169   uint16_t msize;
1170   
1171
1172   msize = ntohs (message->size);
1173   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1174   {
1175     GNUNET_break (0);           /* We need configuration */
1176     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1177     return;
1178   }
1179   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1180   if (ntohl (msg->host_id) == master_context->host_id)
1181   {
1182     struct Peer *peer;
1183     char *emsg;
1184     
1185     /* We are responsible for this peer */
1186     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1187     config_size = ntohl (msg->config_size);    
1188     config = GNUNET_malloc (config_size);
1189     dest_size = config_size;
1190     if (Z_OK != (ret = uncompress ((Bytef *) config, (uLongf *) &dest_size,
1191                                    (const Bytef *) &msg[1], (uLong) msize)))
1192     {
1193       GNUNET_break (0);           /* uncompression error */
1194       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1195       return;
1196     }
1197     if (config_size != dest_size)
1198     {
1199       GNUNET_break (0);/* Uncompressed config size mismatch */
1200       GNUNET_free (config);
1201       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1202       return;
1203     }
1204     cfg = GNUNET_CONFIGURATION_create ();
1205     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1206                                                        GNUNET_NO))
1207     {
1208       GNUNET_break (0);           /* Configuration parsing error */
1209       GNUNET_free (config);
1210       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1211       return;
1212     }
1213     GNUNET_free (config);
1214     peer = GNUNET_malloc (sizeof (struct Peer));
1215     peer->cfg = cfg;
1216     peer->id = ntohl (msg->peer_id);
1217     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1218     peer->peer = GNUNET_TESTING_peer_configure (master_context->system, peer->cfg,
1219                                                 peer->id,
1220                                                 NULL /* Peer id */,
1221                                                 &emsg);
1222     if (NULL == peer->peer)
1223     {
1224       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1225       GNUNET_free (emsg);
1226       GNUNET_break (0);
1227       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1228       return;
1229     }
1230     peer_list_add (peer);
1231     reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1232     reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1233     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1234     reply->peer_id = msg->peer_id;
1235     reply->operation_id = msg->operation_id;
1236     queue_message (client, &reply->header);
1237     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1238     return;
1239   }
1240
1241   /* FIXME: Forward the peer to other host */
1242   GNUNET_break (0);
1243   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1244 }
1245
1246
1247 /**
1248  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1249  *
1250  * @param cls NULL
1251  * @param client identification of the client
1252  * @param message the actual message
1253  */
1254 static void 
1255 handle_peer_destroy (void *cls,
1256                      struct GNUNET_SERVER_Client *client,
1257                      const struct GNUNET_MessageHeader *message)
1258 {
1259   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1260   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *reply;
1261   uint32_t peer_id;
1262   uint32_t id;
1263   uint16_t reply_size;
1264   
1265   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1266   peer_id = ntohl (msg->peer_id);
1267   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1268              peer_id, GNUNET_ntohll (msg->operation_id));
1269   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1270   {
1271     GNUNET_break (0);
1272     /* FIXME: Reply with failure event message or forward to slave controller */
1273     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1274     return;
1275   }  
1276   GNUNET_TESTING_peer_destroy (peer_list[peer_id]->peer);
1277   GNUNET_CONFIGURATION_destroy (peer_list[peer_id]->cfg);
1278   GNUNET_free (peer_list[peer_id]);
1279   peer_list[peer_id] = NULL;
1280   for (id = 0; id < LIST_GROW_STEP; id++)
1281   {
1282     if (((peer_id + id >= peer_list_size) ||
1283          (NULL != peer_list[peer_id])))
1284       break;
1285   }
1286   if (LIST_GROW_STEP == id)
1287   {
1288     peer_list_size -= LIST_GROW_STEP;
1289     peer_list = GNUNET_realloc (peer_list, peer_list_size);
1290   }
1291   reply_size = 
1292     sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1293   reply = GNUNET_malloc (reply_size);
1294   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1295   reply->header.size = htons (reply_size);
1296   reply->operation_id = msg->operation_id;
1297   reply->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1298   queue_message (client, &reply->header);
1299   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1300 }
1301
1302
1303 /**
1304  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1305  *
1306  * @param cls NULL
1307  * @param client identification of the client
1308  * @param message the actual message
1309  */
1310 static void 
1311 handle_peer_start (void *cls,
1312                    struct GNUNET_SERVER_Client *client,
1313                    const struct GNUNET_MessageHeader *message)
1314 {
1315   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1316   struct GNUNET_TESTBED_PeerEventMessage *reply;
1317   uint32_t peer_id;
1318
1319   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1320   peer_id = ntohl (msg->peer_id);
1321   if ((peer_id >= peer_list_size) 
1322       || (NULL == peer_list[peer_id]))
1323   {
1324     GNUNET_break (0);
1325     /* FIXME: reply with failure message or forward to slave controller */
1326     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1327     return;
1328   }
1329   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer_list[peer_id]->peer))
1330   {
1331     /* FIXME: return FAILURE message */
1332     GNUNET_break (0);
1333     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1334     return;
1335   }
1336   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1337   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1338   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1339   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1340   reply->host_id = htonl (master_context->host_id);
1341   reply->peer_id = msg->peer_id;
1342   reply->operation_id = msg->operation_id;
1343   queue_message (client, &reply->header);
1344   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1345 }
1346
1347
1348 /**
1349  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1350  *
1351  * @param cls NULL
1352  * @param client identification of the client
1353  * @param message the actual message
1354  */
1355 static void 
1356 handle_peer_stop (void *cls,
1357                   struct GNUNET_SERVER_Client *client,
1358                   const struct GNUNET_MessageHeader *message)
1359 {
1360   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1361   struct GNUNET_TESTBED_PeerEventMessage *reply;
1362   uint32_t peer_id;
1363
1364   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1365   peer_id = ntohl (msg->peer_id);
1366   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1367   {
1368     GNUNET_break (0);           /* FIXME: route to slave? */
1369     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1370     return;
1371   }
1372   if (GNUNET_OK != GNUNET_TESTING_peer_stop (peer_list[peer_id]->peer))
1373   {
1374     /* FIXME: return FAILURE message */
1375     GNUNET_break (0);
1376     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1377     return;
1378   }
1379   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1380   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1381   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1382   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1383   reply->host_id = htonl (master_context->host_id);
1384   reply->peer_id = msg->peer_id;
1385   reply->operation_id = msg->operation_id;
1386   queue_message (client, &reply->header);
1387   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1388 }
1389
1390
1391 /**
1392  * Iterator over hash map entries.
1393  *
1394  * @param cls closure
1395  * @param key current key code
1396  * @param value value in the hash map
1397  * @return GNUNET_YES if we should continue to
1398  *         iterate,
1399  *         GNUNET_NO if not.
1400  */
1401 static int 
1402 ss_map_free_iterator (void *cls,
1403                       const struct GNUNET_HashCode * key, void *value)
1404 {
1405   struct SharedService *ss = value;
1406
1407   GNUNET_assert (GNUNET_YES ==
1408                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
1409   GNUNET_free (ss->name);
1410   GNUNET_free (ss);
1411   return GNUNET_YES;
1412 }
1413
1414
1415 /**
1416  * Task to clean up and shutdown nicely
1417  *
1418  * @param cls NULL
1419  * @param tc the TaskContext from scheduler
1420  */
1421 static void
1422 shutdown_task (void *cls,
1423                const struct GNUNET_SCHEDULER_TaskContext *tc)
1424 {
1425   struct LCFContextQueue *lcfq;
1426   uint32_t id;
1427
1428   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
1429   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
1430   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
1431                                                 NULL);
1432   GNUNET_CONTAINER_multihashmap_destroy (ss_map);  
1433   if (NULL != fh)
1434   {
1435     GNUNET_DISK_file_close (fh);
1436     fh = NULL;
1437   }
1438   if (NULL != lcfq_head)
1439   {
1440     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
1441     {
1442       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
1443       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
1444     }
1445     if (NULL != lcfq_head->lcf->rhandle)
1446       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
1447   }
1448   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1449   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
1450   {
1451     GNUNET_free (lcfq->lcf->sxcfg);
1452     GNUNET_free (lcfq->lcf);
1453     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1454     GNUNET_free (lcfq);
1455   }
1456   /* Clear peer list */
1457   for (id = 0; id < peer_list_size; id++)
1458     if (NULL != peer_list[id])
1459     {
1460       GNUNET_TESTING_peer_destroy (peer_list[id]->peer);
1461       GNUNET_CONFIGURATION_destroy (peer_list[id]->cfg);
1462       GNUNET_free (peer_list[id]);
1463     }
1464   GNUNET_free_non_null (peer_list);
1465   /* Clear host list */
1466   for (id = 0; id < host_list_size; id++)
1467     if (NULL != host_list[id])
1468       GNUNET_TESTBED_host_destroy (host_list[id]);
1469   GNUNET_free_non_null (host_list);
1470   /* Clear route list */
1471   for (id = 0; id < route_list_size; id++)
1472     if (NULL != route_list[id])
1473       GNUNET_free (route_list[id]);
1474   GNUNET_free_non_null (route_list);
1475   /* Clear slave_list */
1476   for (id = 0; id < slave_list_size; id++)
1477     if (NULL != slave_list[id])
1478     {
1479       GNUNET_assert (NULL != slave_list[id]->controller);
1480       GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
1481       if (NULL != slave_list[id]->controller_proc)
1482         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
1483     }
1484   GNUNET_free_non_null (master_context->master_ip);
1485   if (NULL != master_context->system)
1486     GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
1487   GNUNET_free_non_null (master_context);
1488 }
1489
1490
1491 /**
1492  * Debug shutdown task in case of stdin getting closed
1493  *
1494  * @param cls NULL
1495  * @param tc the TaskContext from scheduler
1496  */
1497 static void
1498 shutdown_task_ (void *cls,
1499                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1500 {
1501   LOG (GNUNET_ERROR_TYPE_DEBUG, "STDIN closed ...\n");
1502   shutdown_task (cls, tc);
1503 }
1504
1505
1506 /**
1507  * Callback for client disconnect
1508  *
1509  * @param cls NULL
1510  * @param client the client which has disconnected
1511  */
1512 static void
1513 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
1514 {
1515   if (NULL == master_context)
1516     return;
1517   if (client == master_context->client)
1518   {
1519     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
1520     GNUNET_SERVER_client_drop (client);
1521     /* should not be needed as we're terminated by failure to read
1522        from stdin, but if stdin fails for some reason, this shouldn't 
1523        hurt for now --- might need to revise this later if we ever
1524        decide that master connections might be temporarily down 
1525        for some reason */
1526     GNUNET_SCHEDULER_shutdown ();
1527   }
1528 }
1529
1530
1531 /**
1532  * Testbed setup
1533  *
1534  * @param cls closure
1535  * @param server the initialized server
1536  * @param cfg configuration to use
1537  */
1538 static void 
1539 testbed_run (void *cls,
1540              struct GNUNET_SERVER_Handle *server,
1541              const struct GNUNET_CONFIGURATION_Handle *cfg)
1542 {
1543   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
1544     {
1545       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT,
1546        sizeof (struct GNUNET_TESTBED_InitMessage)},
1547       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
1548       {&handle_configure_shared_service, NULL,
1549        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
1550       {&handle_link_controllers, NULL,
1551        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
1552       {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
1553       {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
1554        sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
1555       {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
1556        sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
1557       {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
1558        sizeof (struct GNUNET_TESTBED_PeerStopMessage)},
1559       {NULL}
1560     };
1561
1562   config = GNUNET_CONFIGURATION_dup (cfg);
1563   GNUNET_SERVER_add_handlers (server,
1564                               message_handlers);
1565   GNUNET_SERVER_disconnect_notify (server,
1566                                    &client_disconnect_cb,
1567                                    NULL);
1568   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
1569   fh = GNUNET_DISK_get_handle_from_native (stdin);
1570   if (NULL == fh)
1571     shutdown_task_id = 
1572       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1573                                     &shutdown_task,
1574                                     NULL);
1575   else
1576     shutdown_task_id = 
1577       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1578                                       fh,
1579                                       &shutdown_task_,
1580                                       NULL);
1581   LOG_DEBUG ("Testbed startup complete\n");
1582 }
1583
1584
1585 /**
1586  * The starting point of execution
1587  */
1588 int main (int argc, char *const *argv)
1589 {
1590   return
1591     (GNUNET_OK ==
1592      GNUNET_SERVICE_run (argc,
1593                          argv,
1594                          "testbed",
1595                          GNUNET_SERVICE_OPTION_NONE,
1596                          &testbed_run,
1597                          NULL)) ? 0 : 1;
1598 }