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