Local and remote peers
[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 "gnunet_transport_service.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_hello_lib.h"
33 #include <zlib.h>
34
35 #include "gnunet_testbed_service.h"
36 #include "testbed.h"
37 #include "testbed_api.h"
38 #include "testbed_api_hosts.h"
39 #include "gnunet_testing_lib-new.h"
40
41 /**
42  * Generic logging
43  */
44 #define LOG(kind,...)                           \
45   GNUNET_log (kind, __VA_ARGS__)
46
47 /**
48  * Debug logging
49  */
50 #define LOG_DEBUG(...)                          \
51   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
52
53
54 #define LIST_GROW_STEP 10
55
56 struct Context
57 {
58   /**
59    * The client handle associated with this context
60    */
61   struct GNUNET_SERVER_Client *client;
62
63   /**
64    * The network address of the master controller
65    */
66   char *master_ip;
67
68   /**
69    * The TESTING system handle for starting peers locally
70    */
71   struct GNUNET_TESTING_System *system;
72   
73   /**
74    * Event mask of event to be responded in this context
75    */
76   uint64_t event_mask;
77
78   /**
79    * Our host id according to this context
80    */
81   uint32_t host_id;
82 };
83
84
85 /**
86  * The message queue for sending messages to clients
87  */
88 struct MessageQueue
89 {
90   /**
91    * The message to be sent
92    */
93   struct GNUNET_MessageHeader *msg;
94
95   /**
96    * The client to send the message to
97    */
98   struct GNUNET_SERVER_Client *client;
99   
100   /**
101    * next pointer for DLL
102    */
103   struct MessageQueue *next;
104   
105   /**
106    * prev pointer for DLL
107    */
108   struct MessageQueue *prev;
109 };
110
111
112 /**
113  * The structure for identifying a shared service
114  */
115 struct SharedService
116 {
117   /**
118    * The name of the shared service
119    */
120   char *name;
121
122   /**
123    * Number of shared peers per instance of the shared service
124    */
125   uint32_t num_shared;
126
127   /**
128    * Number of peers currently sharing the service
129    */
130   uint32_t num_sharing;
131 };
132
133
134 /**
135  * A routing entry
136  */
137 struct Route
138 {
139   /**
140    * destination host
141    */
142   uint32_t dest;
143
144   /**
145    * The host destination is reachable thru
146    */
147   uint32_t thru;
148 };
149
150
151 /**
152  * Structure representing a connected(directly-linked) controller
153  */
154 struct Slave
155 {
156   /**
157    * The controller process handle if we had started the controller
158    */
159   struct GNUNET_TESTBED_ControllerProc *controller_proc;
160
161   /**
162    * The controller handle
163    */
164   struct GNUNET_TESTBED_Controller *controller;
165
166   /**
167    * The id of the host this controller is running on
168    */
169   uint32_t host_id;
170 };
171
172
173 /**
174  * States of LCFContext
175  */
176 enum LCFContextState
177   {
178     /**
179      * The Context has been initialized; Nothing has been done on it
180      */
181     INIT,
182
183     /**
184      * Delegated host has been registered at the forwarding controller
185      */
186     DELEGATED_HOST_REGISTERED,
187     
188     /**
189      * The slave host has been registred at the forwarding controller
190      */
191     SLAVE_HOST_REGISTERED,
192
193     /**
194      * The context has been finished (may have error)
195      */
196     FINISHED
197
198   };
199
200
201 /**
202  * Link controllers request forwarding context
203  */
204 struct LCFContext
205 {
206   /**
207    * The serialized and compressed configuration
208    */
209   char *sxcfg;
210
211   /**
212    * The gateway which will pass the link message to delegated host
213    */
214   struct Slave *gateway;
215
216   /**
217    * The host registration handle while registered hosts in this context
218    */
219   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
220
221   /**
222    * The size of the compressed serialized configuration
223    */
224   size_t sxcfg_size;
225
226   /**
227    * The size of the uncompressed configuration
228    */
229   size_t scfg_size;
230
231   /**
232    * Should the delegated host be started by the slave host?
233    */
234   int is_subordinate;
235
236   /**
237    * The state of this context
238    */
239   enum LCFContextState state;
240
241   /**
242    * The delegated host
243    */
244   uint32_t delegated_host_id;
245
246   /**
247    * The slave host
248    */
249   uint32_t slave_host_id;
250
251 };
252
253
254 /**
255  * Structure of a queue entry in LCFContext request queue
256  */
257 struct LCFContextQueue
258 {
259   /**
260    * The LCFContext
261    */
262   struct LCFContext *lcf;
263
264   /**
265    * Head prt for DLL
266    */
267   struct LCFContextQueue *next;
268
269   /**
270    * Tail ptr for DLL
271    */
272   struct LCFContextQueue *prev;
273 };
274
275
276 /**
277  * A locally started peer
278  */
279 struct Peer
280 {
281   union
282   {
283     struct 
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
292        * peer is configured with
293        */
294       struct GNUNET_CONFIGURATION_Handle *cfg;
295
296     } local;
297
298     struct
299     {
300       /**
301        * The controller this peer is started through
302        */
303       struct GNUNET_TESTBED_Controller *controller;
304
305     } remote;
306     
307   } details;
308
309   /**
310    * Our local reference id for this peer
311    */
312   uint32_t id;
313
314   /**
315    * Is this peer local created?
316    */
317   uint32_t is_remote;
318
319 };
320
321
322 /**
323  * State information for overlay connect context
324  */
325 enum OCCState
326   {
327     /**
328      * Initial state
329      */
330     OCC_STATE_INIT,
331
332     /**
333      * Peer 1 has connected to peer0
334      */
335     OCC_STATE_PEER0_SUCCESS,
336
337     /**
338      * Peer 2 has connected to peer1
339      */
340     OCC_STATE_PEER1_SUCCESS,
341
342   };
343
344
345 /**
346  * Context information for connecting 2 peers in overlay
347  */
348 struct OverlayConnectContext
349 {
350   /**
351    * The client which has requested for overlay connection
352    */
353   struct GNUNET_SERVER_Client *client;
354
355   /**
356    * the peer which has to connect to the other peer
357    */
358   struct Peer *peer;
359
360   /**
361    * The other peer
362    */
363   struct Peer *other_peer;
364   
365   /**
366    * Transport handle of the first peer to offer second peer's HELLO
367    */
368   struct GNUNET_TRANSPORT_Handle *p1th;
369
370   /**
371    * Transport handle of other peer to get its HELLO
372    */
373   struct GNUNET_TRANSPORT_Handle *p2th;
374
375   /**
376    * Core handles of the peer which has to connect to other peer
377    */
378   struct GNUNET_CORE_Handle *ch;
379
380   /**
381    * HELLO of the other peer
382    */
383   struct GNUNET_MessageHeader *hello;
384   
385   /**
386    * Get hello handle for the other peer
387    */
388   struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
389
390   /**
391    * The error message we send if this overlay connect operation has timed out
392    */
393   char *emsg;
394   
395   /**
396    * The peer identity of the first peer
397    */
398   struct GNUNET_PeerIdentity peer_identity;
399
400   /**
401    * The peer identity of the other peer
402    */
403   struct GNUNET_PeerIdentity other_peer_identity;
404
405   /**
406    * The id of the operation responsible for creating this context
407    */
408   uint64_t op_id;
409
410   /**
411    * The id of the task for sending HELLO of peer 2 to peer 1 and ask peer 1 to
412    * connect to peer 2
413    */
414   GNUNET_SCHEDULER_TaskIdentifier send_hello_task;
415   
416   /**
417    * The id of the overlay connect timeout task
418    */
419   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
420
421   /**
422    * State information for determining whose HELLOs have been successfully
423    * exchanged
424    */
425   enum OCCState state;
426
427 };
428
429
430 /**
431  * Context data to be used when forwarding peer create messages
432  */
433 struct PeerCreateContext
434 {
435   /**
436    * The operation handle to peer create
437    */
438   struct GNUNET_TESTBED_operation *operation;
439
440   /**
441    * The ID of the operation which created this context
442    */
443   uint64_t operation_id;
444
445   /**
446    * The peer create timeout task id
447    */
448   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
449
450 };
451
452
453 /**
454  * The master context; generated with the first INIT message
455  */
456 static struct Context *master_context;
457
458 /***********/
459 /* Handles */
460 /***********/
461
462 /**
463  * Current Transmit Handle; NULL if no notify transmit exists currently
464  */
465 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
466
467 /****************/
468 /* Lists & Maps */
469 /****************/
470
471 /**
472  * The head for the LCF queue
473  */
474 static struct LCFContextQueue *lcfq_head;
475
476 /**
477  * The tail for the LCF queue
478  */
479 static struct LCFContextQueue *lcfq_tail;
480
481 /**
482  * The message queue head
483  */
484 static struct MessageQueue *mq_head;
485
486 /**
487  * The message queue tail
488  */
489 static struct MessageQueue *mq_tail;
490
491 /**
492  * Array of host list
493  */
494 static struct GNUNET_TESTBED_Host **host_list;
495
496 /**
497  * A list of routes
498  */
499 static struct Route **route_list;
500
501 /**
502  * A list of directly linked neighbours
503  */
504 static struct Slave **slave_list;
505
506 /**
507  * A list of peers we own locally
508  */
509 static struct Peer **peer_list;
510
511 /**
512  * The hashmap of shared services
513  */
514 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
515
516 /**
517  * The size of the host list
518  */
519 static uint32_t host_list_size;
520
521 /**
522  * The size of the route list
523  */
524 static uint32_t route_list_size;
525
526 /**
527  * The size of directly linked neighbours list
528  */
529 static uint32_t slave_list_size;
530
531 /**
532  * The size of the peer list
533  */
534 static uint32_t peer_list_size;
535
536 /*********/
537 /* Tasks */
538 /*********/
539
540 /**
541  * The lcf_task handle
542  */
543 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
544
545 /**
546  * The shutdown task handle
547  */
548 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
549
550
551 /**
552  * Function called to notify a client about the connection begin ready to queue
553  * more data.  "buf" will be NULL and "size" zero if the connection was closed
554  * for writing in the meantime.
555  *
556  * @param cls NULL
557  * @param size number of bytes available in buf
558  * @param buf where the callee should write the message
559  * @return number of bytes written to buf
560  */
561 static size_t
562 transmit_ready_notify (void *cls, size_t size, void *buf)
563 {
564   struct MessageQueue *mq_entry;
565
566   transmit_handle = NULL;
567   mq_entry = mq_head;
568   GNUNET_assert (NULL != mq_entry);
569   if (0 == size)
570     return 0;
571   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
572   size = ntohs (mq_entry->msg->size);
573   memcpy (buf, mq_entry->msg, size);
574   GNUNET_free (mq_entry->msg);
575   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
576   GNUNET_free (mq_entry);
577   mq_entry = mq_head;
578   if (NULL != mq_entry)
579     transmit_handle = 
580       GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
581                                            ntohs (mq_entry->msg->size),
582                                            GNUNET_TIME_UNIT_FOREVER_REL,
583                                            &transmit_ready_notify, NULL);
584   return size;
585 }
586
587
588 /**
589  * Queues a message in send queue for sending to the service
590  *
591  * @param client the client to whom the queued message has to be sent
592  * @param msg the message to queue
593  */
594 static void
595 queue_message (struct GNUNET_SERVER_Client *client,
596                struct GNUNET_MessageHeader *msg)
597 {
598   struct MessageQueue *mq_entry;
599   uint16_t type;
600   uint16_t size;
601
602   type = ntohs (msg->type);
603   size = ntohs (msg->size);
604   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
605                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
606   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
607   mq_entry->msg = msg;
608   mq_entry->client = client;
609   LOG_DEBUG ( "Queueing message of type %u, size %u for sending\n", type,
610               ntohs (msg->size));
611   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
612   if (NULL == transmit_handle)
613     transmit_handle = 
614       GNUNET_SERVER_notify_transmit_ready (client, size,
615                                            GNUNET_TIME_UNIT_FOREVER_REL,
616                                            &transmit_ready_notify, NULL);
617 }
618
619
620 /**
621  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
622  *
623  * @param ptr the memory block to realloc
624  * @param size the size of ptr
625  * @param new_size the size to which ptr has to be realloc'ed
626  * @return the newly reallocated memory block
627  */
628 static void *
629 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
630 {
631   ptr = GNUNET_realloc (ptr, new_size);
632   if (new_size > size)
633     ptr = memset (ptr + size, 0, new_size - size);
634   return ptr;
635 }
636
637
638 /**
639  * Function to add a host to the current list of known hosts
640  *
641  * @param host the host to add 
642  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
643  *           already in use
644  */
645 static int
646 host_list_add (struct GNUNET_TESTBED_Host *host)
647 {
648   uint32_t host_id;
649
650   host_id = GNUNET_TESTBED_host_get_id_ (host);
651   if (host_list_size <= host_id)
652   {
653     host_list = 
654       TESTBED_realloc (host_list, 
655                        sizeof (struct GNUNET_TESTBED_Host *) * host_list_size,
656                        sizeof (struct GNUNET_TESTBED_Host *) *
657                        (host_list_size + LIST_GROW_STEP));
658     host_list_size += LIST_GROW_STEP;
659   }
660   if (NULL != host_list[host_id])
661   {
662     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
663     return GNUNET_SYSERR;
664   }
665   host_list[host_id] = host;
666   return GNUNET_OK;
667 }
668
669
670 /**
671  * Adds a route to the route list
672  *
673  * @param route the route to add
674  */
675 static void
676 route_list_add (struct Route *route)
677 {
678   if (route->dest >= route_list_size)
679   {
680     route_list = 
681       TESTBED_realloc (route_list, 
682                        sizeof (struct Route *) * route_list_size,
683                        sizeof (struct Route *) * 
684                        (route_list_size + LIST_GROW_STEP));
685     route_list_size += LIST_GROW_STEP;
686   }
687   GNUNET_assert (NULL == route_list[route->dest]);
688   route_list[route->dest] = route;
689 }
690
691
692 /**
693  * Adds a slave to the slave array
694  *
695  * @param slave the slave controller to add
696  */
697 static void
698 slave_list_add (struct Slave *slave)
699 {
700   if (slave->host_id  >= slave_list_size)
701   {
702     slave_list = TESTBED_realloc (slave_list, 
703                                   sizeof (struct Slave *) *slave_list_size,
704                                   sizeof (struct Slave *) *
705                                   (slave_list_size + LIST_GROW_STEP));
706     slave_list_size += LIST_GROW_STEP;
707   }
708   GNUNET_assert (NULL == slave_list[slave->host_id]);
709   slave_list[slave->host_id] = slave;
710 }
711
712
713 /**
714  * Adds a peer to the peer array
715  *
716  * @param peer the peer to add
717  */
718 static void
719 peer_list_add (struct Peer *peer)
720 {
721   if (peer->id  >= peer_list_size)
722   {
723     peer_list = TESTBED_realloc (peer_list, 
724                                  sizeof (struct Peer *) * peer_list_size,
725                                  sizeof (struct Peer *) *
726                                  (peer_list_size + LIST_GROW_STEP));
727     peer_list_size += LIST_GROW_STEP;
728   }
729   GNUNET_assert (NULL == peer_list[peer->id]);
730   peer_list[peer->id] = peer;
731 }
732
733
734 /**
735  * Removes a the give peer from the peer array
736  *
737  * @param peer the peer to be removed
738  */
739 static void
740 peer_list_remove (struct Peer *peer)
741 {
742   uint32_t id;
743
744   peer_list[peer->id] = NULL;
745   while (peer_list_size >= LIST_GROW_STEP)
746   {
747     for (id = peer_list_size - 1;
748          id > peer_list_size - LIST_GROW_STEP; id--)
749       if (NULL != peer_list[id])
750         break;
751     if (id != peer_list_size - LIST_GROW_STEP)
752       break;
753     peer_list_size -= LIST_GROW_STEP;
754   }
755   peer_list = GNUNET_realloc (peer_list, sizeof (struct GNUNET_TESTBED_Peer*)
756                               * peer_list_size);
757 }
758
759
760 /**
761  * Finds the route with directly connected host as destination through which
762  * the destination host can be reached
763  *
764  * @param host_id the id of the destination host
765  * @return the route with directly connected destination host; NULL if no route
766  *           is found
767  */
768 static struct Route *
769 find_dest_route (uint32_t host_id)
770 {
771   struct Route *route;
772   
773   while(NULL != (route = route_list[host_id]))
774   {
775     if (route->thru == master_context->host_id)
776       break;
777     host_id = route->thru;
778   }
779   return route;
780 }
781
782
783 /**
784  * Routes message to a host given its host_id
785  *
786  * @param host_id the id of the destination host
787  * @param msg the message to be routed
788  */
789 static void
790 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
791 {
792   GNUNET_break (0);
793 }
794
795
796 /**
797  * Send operation failure message to client
798  *
799  * @param client the client to which the failure message has to be sent to
800  * @param operation_id the id of the failed operation
801  * @param emsg the error message; can be NULL
802  */
803 static void
804 send_operation_fail_msg (struct GNUNET_SERVER_Client *client,
805                          uint64_t operation_id,
806                          const char *emsg)
807 {
808   struct GNUNET_TESTBED_OperationFailureEventMessage *msg;
809   uint16_t msize;
810   uint16_t emsg_len;
811   
812   msize = sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);  
813   emsg_len = (NULL == emsg) ? 0 : strlen (emsg) + 1;
814   msize += emsg_len;
815   msg = GNUNET_malloc (msize);
816   msg->header.size = htons (msize);
817   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONEVENT);
818   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
819   msg->operation_id = GNUNET_htonll (operation_id);
820   if (0 != emsg_len)
821     memcpy (&msg[1], emsg, emsg_len);
822   queue_message (client, &msg->header);
823 }
824
825
826 /**
827  * The  Link Controller forwarding task
828  *
829  * @param cls the LCFContext
830  * @param tc the Task context from scheduler
831  */
832 static void
833 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
834
835
836 /**
837  * Completion callback for host registrations while forwarding Link Controller messages
838  *
839  * @param cls the LCFContext
840  * @param emsg the error message; NULL if host registration is successful
841  */
842 static void
843 lcf_proc_cc (void *cls, const char *emsg)
844 {
845   struct LCFContext *lcf = cls;
846
847   lcf->rhandle = NULL;
848   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
849   switch (lcf->state)
850   {
851   case INIT:
852     if (NULL != emsg)
853       goto registration_error;
854     lcf->state = DELEGATED_HOST_REGISTERED;
855     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
856     break;
857   case DELEGATED_HOST_REGISTERED:
858      if (NULL != emsg)
859       goto registration_error;
860      lcf->state = SLAVE_HOST_REGISTERED;
861      lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
862      break;
863   default:
864     GNUNET_assert (0);          /* Shouldn't reach here */
865   }  
866   return;
867
868  registration_error:
869   LOG (GNUNET_ERROR_TYPE_WARNING, 
870        "Host registration failed with message: %s\n", emsg);
871   lcf->state = FINISHED;
872   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
873 }
874
875
876 /**
877  * The  Link Controller forwarding task
878  *
879  * @param cls the LCFContext
880  * @param tc the Task context from scheduler
881  */
882 static void
883 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
884 {
885   struct LCFContext *lcf = cls;
886   struct LCFContextQueue *lcfq;
887
888   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
889   switch (lcf->state)
890   {
891   case INIT:
892     if (GNUNET_NO ==
893         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
894                                             lcf->gateway->controller))
895     {
896       lcf->rhandle =
897         GNUNET_TESTBED_register_host (lcf->gateway->controller,
898                                       host_list[lcf->delegated_host_id],
899                                       lcf_proc_cc, lcf);
900     }
901     else
902     {
903       lcf->state = DELEGATED_HOST_REGISTERED;
904       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
905     }
906     break;
907   case DELEGATED_HOST_REGISTERED:
908     if (GNUNET_NO ==
909         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
910                                             lcf->gateway->controller))
911     {
912       lcf->rhandle =
913         GNUNET_TESTBED_register_host (lcf->gateway->controller,
914                                       host_list[lcf->slave_host_id],
915                                       lcf_proc_cc, lcf);
916     }
917     else
918     {
919       lcf->state = SLAVE_HOST_REGISTERED;
920       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
921     }
922     break;
923   case SLAVE_HOST_REGISTERED:
924     GNUNET_TESTBED_controller_link_2 (lcf->gateway->controller,
925                                       host_list[lcf->delegated_host_id],
926                                       host_list[lcf->slave_host_id],
927                                       lcf->sxcfg, lcf->sxcfg_size,
928                                       lcf->scfg_size,
929                                       lcf->is_subordinate);
930     lcf->state = FINISHED;
931     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
932     break;
933   case FINISHED:
934     lcfq = lcfq_head;
935     GNUNET_assert (lcfq->lcf == lcf);
936     GNUNET_free (lcf->sxcfg);
937     GNUNET_free (lcf);
938     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
939     GNUNET_free (lcfq);
940     if (NULL != lcfq_head)
941       lcf_proc_task_id = 
942         GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
943   }
944 }
945
946
947 /**
948  * Callback for event from slave controllers
949  *
950  * @param cls struct Slave *
951  * @param event information about the event
952  */
953 static void 
954 slave_event_callback(void *cls,
955                      const struct GNUNET_TESTBED_EventInformation *event)
956 {
957   GNUNET_break (0);
958 }
959
960
961 /**
962  * Callback to signal successfull startup of the controller process
963  *
964  * @param cls the closure from GNUNET_TESTBED_controller_start()
965  * @param cfg the configuration with which the controller has been started;
966  *          NULL if status is not GNUNET_OK
967  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
968  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
969  */
970 static void 
971 slave_status_callback (void *cls, 
972                        const struct GNUNET_CONFIGURATION_Handle *cfg,
973                        int status)
974 {
975   struct Slave *slave = cls;
976
977   if (GNUNET_SYSERR == status)
978   {
979     slave->controller_proc = NULL;
980     LOG (GNUNET_ERROR_TYPE_WARNING,
981          "Unexpected slave shutdown\n");
982     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
983     return;
984   }
985   slave->controller =
986     GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
987                                        master_context->event_mask,
988                                        &slave_event_callback, slave);
989 }
990
991
992 /**
993  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
994  *
995  * @param cls NULL
996  * @param client identification of the client
997  * @param message the actual message
998  */
999 static void 
1000 handle_init (void *cls,
1001              struct GNUNET_SERVER_Client *client,
1002              const struct GNUNET_MessageHeader *message)
1003 {
1004   const struct GNUNET_TESTBED_InitMessage *msg;
1005   struct GNUNET_TESTBED_Host *host;
1006   const char *controller_hostname;
1007   uint16_t msize;
1008
1009   if (NULL != master_context)
1010   {
1011     GNUNET_break (0);
1012     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1013     return;
1014   }
1015   msg = (const struct GNUNET_TESTBED_InitMessage *) message;
1016   msize = ntohs (message->size);
1017   if (msize <= sizeof (struct GNUNET_TESTBED_InitMessage))
1018   {
1019     GNUNET_break (0);
1020     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1021     return;
1022   }
1023   msize -= sizeof (struct GNUNET_TESTBED_InitMessage);  
1024   controller_hostname = (const char *) &msg[1];
1025   if ('\0' != controller_hostname[msize - 1])
1026   {
1027     GNUNET_break (0);
1028     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1029     return;
1030   }    
1031   master_context = GNUNET_malloc (sizeof (struct Context));
1032   master_context->client = client;
1033   master_context->host_id = ntohl (msg->host_id);
1034   master_context->master_ip = GNUNET_strdup (controller_hostname);  
1035   LOG_DEBUG ("Master Controller IP: %s\n", master_context->master_ip);
1036   master_context->system = 
1037     GNUNET_TESTING_system_create ("testbed", master_context->master_ip);
1038   host = GNUNET_TESTBED_host_create_with_id (master_context->host_id,
1039                                              NULL, NULL, 0);
1040   host_list_add (host);
1041   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
1042   GNUNET_SERVER_client_keep (client);
1043   LOG_DEBUG ("Created master context with host ID: %u\n",
1044              master_context->host_id);
1045   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1046 }
1047
1048
1049 /**
1050  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1051  *
1052  * @param cls NULL
1053  * @param client identification of the client
1054  * @param message the actual message
1055  */
1056 static void 
1057 handle_add_host (void *cls,
1058                  struct GNUNET_SERVER_Client *client,
1059                  const struct GNUNET_MessageHeader *message)
1060 {
1061   struct GNUNET_TESTBED_Host *host;
1062   const struct GNUNET_TESTBED_AddHostMessage *msg;
1063   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
1064   char *username;
1065   char *hostname;
1066   char *emsg;
1067   uint32_t host_id;
1068   uint16_t username_length;
1069   uint16_t hostname_length;
1070   uint16_t reply_size;
1071   uint16_t msize;
1072   
1073   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
1074   msize = ntohs (msg->header.size);
1075   username = (char *) &(msg[1]);
1076   username_length = ntohs (msg->user_name_length);
1077   GNUNET_assert (msize > (sizeof (struct GNUNET_TESTBED_AddHostMessage)
1078                           + username_length + 1)); /* msg must contain hostname */
1079   if (0 != username_length)
1080     GNUNET_assert ('\0' == username[username_length]);
1081   username_length = (0 == username_length) ? 0 : username_length + 1;              
1082   hostname = username + username_length;
1083   hostname_length = msize - (sizeof (struct GNUNET_TESTBED_AddHostMessage)
1084                              + username_length);
1085   GNUNET_assert ('\0' == hostname[hostname_length - 1]);
1086   GNUNET_assert (strlen (hostname) == hostname_length - 1);
1087   host_id = ntohl (msg->host_id);
1088   LOG_DEBUG ("Received ADDHOST message\n");
1089   LOG_DEBUG ("-------host id: %u\n", host_id);
1090   if (NULL != hostname) LOG_DEBUG ("-------hostname: %s\n", hostname);
1091   if (0 != username_length) LOG_DEBUG ("-------username: %s\n", username);
1092   else LOG_DEBUG ("-------username: NULL\n");
1093   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1094   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1095                                              ntohs (msg->ssh_port));
1096   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1097   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1098   if (GNUNET_OK != host_list_add (host))
1099   {    
1100     /* We are unable to add a host */  
1101     emsg = "A host exists with given host-id";
1102     LOG_DEBUG ("%s: %u", emsg, host_id);
1103     GNUNET_TESTBED_host_destroy (host);
1104     reply_size += strlen (emsg) + 1;
1105     reply = GNUNET_malloc (reply_size);
1106     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1107   }
1108   else
1109     reply = GNUNET_malloc (reply_size);  
1110   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
1111   reply->header.size = htons (reply_size);
1112   reply->host_id = htonl (host_id);  
1113   queue_message (client, &reply->header);
1114 }
1115
1116
1117 /**
1118  * Iterator over hash map entries.
1119  *
1120  * @param cls closure
1121  * @param key current key code
1122  * @param value value in the hash map
1123  * @return GNUNET_YES if we should continue to
1124  *         iterate,
1125  *         GNUNET_NO if not.
1126  */
1127 int ss_exists_iterator (void *cls,
1128                         const struct GNUNET_HashCode * key,
1129                         void *value)
1130 {
1131   struct SharedService *queried_ss = cls;
1132   struct SharedService *ss = value;
1133
1134   if (0 == strcmp (ss->name, queried_ss->name))
1135     return GNUNET_NO;
1136   else
1137     return GNUNET_YES;
1138 }
1139
1140
1141 /**
1142  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1143  *
1144  * @param cls NULL
1145  * @param client identification of the client
1146  * @param message the actual message
1147  */
1148 static void 
1149 handle_configure_shared_service (void *cls,
1150                                  struct GNUNET_SERVER_Client *client,
1151                                  const struct GNUNET_MessageHeader *message)
1152 {
1153   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1154   struct SharedService *ss;
1155   char *service_name;
1156   struct GNUNET_HashCode hash;
1157   uint16_t msg_size;
1158   uint16_t service_name_size;
1159     
1160   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1161   msg_size = ntohs (message->size);
1162   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1163   {
1164     GNUNET_break (0);
1165     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1166     return;
1167   }
1168   service_name_size = msg_size - 
1169     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
1170   service_name = (char *) &msg[1];
1171   if ('\0' != service_name[service_name_size - 1])
1172   {
1173     GNUNET_break (0);
1174     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1175     return;
1176   }
1177   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
1178              service_name, ntohl (msg->num_peers));
1179   if (ntohl (msg->host_id) != master_context->host_id)
1180   {
1181     route_message (ntohl (msg->host_id), message);
1182     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1183     return;
1184   }
1185   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1186   ss = GNUNET_malloc (sizeof (struct SharedService));
1187   ss->name = strdup (service_name);
1188   ss->num_shared = ntohl (msg->num_peers);
1189   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1190   if (GNUNET_SYSERR == 
1191       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1192                                                   &ss_exists_iterator, ss))
1193   {
1194     LOG (GNUNET_ERROR_TYPE_WARNING,
1195          "Service %s already configured as a shared service. "
1196          "Ignoring service sharing request \n", ss->name);
1197     GNUNET_free (ss->name);
1198     GNUNET_free (ss);
1199     return;
1200   }
1201   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1202                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
1203 }
1204
1205
1206 /**
1207  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1208  *
1209  * @param cls NULL
1210  * @param client identification of the client
1211  * @param message the actual message
1212  */
1213 static void 
1214 handle_link_controllers (void *cls,
1215                          struct GNUNET_SERVER_Client *client,
1216                          const struct GNUNET_MessageHeader *message)
1217 {
1218   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1219   struct GNUNET_CONFIGURATION_Handle *cfg;
1220   struct LCFContextQueue *lcfq;
1221   struct Route *route;
1222   struct Route *new_route;
1223   char *config;  
1224   uLongf dest_size;
1225   size_t config_size;
1226   uint32_t delegated_host_id;
1227   uint32_t slave_host_id;
1228   uint16_t msize;
1229    
1230   if (NULL == master_context)
1231   {
1232     GNUNET_break (0);
1233     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1234     return;
1235   }
1236   msize = ntohs (message->size);
1237   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1238   {
1239     GNUNET_break (0);
1240     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1241     return;
1242   }
1243   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1244   delegated_host_id = ntohl (msg->delegated_host_id);
1245   if (delegated_host_id == master_context->host_id)
1246   {
1247     GNUNET_break (0);
1248     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1249     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1250     return;
1251   }
1252   if ((delegated_host_id >= host_list_size) || 
1253       (NULL == host_list[delegated_host_id]))
1254   {
1255     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
1256     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1257     return;
1258   }
1259   slave_host_id = ntohl (msg->slave_host_id);
1260   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1261   {
1262     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
1263     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1264     return;
1265   }
1266   if (slave_host_id == delegated_host_id)
1267   {
1268     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1269     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1270     return;
1271   }
1272   msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1273   config_size = ntohs (msg->config_size);
1274   
1275   if (slave_host_id == master_context->host_id) /* Link from us */
1276   {
1277     struct Slave *slave;
1278
1279     if ((delegated_host_id < slave_list_size) && 
1280         (NULL != slave_list[delegated_host_id])) /* We have already added */
1281     {
1282       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1283            delegated_host_id);
1284       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1285       return;
1286     }    
1287     config = GNUNET_malloc (config_size);
1288     dest_size = (uLongf) config_size;    
1289     if (Z_OK != uncompress ((Bytef *) config, &dest_size,
1290                             (const Bytef *) &msg[1], (uLong) msize))
1291     {
1292       GNUNET_break (0);           /* Compression error */
1293       GNUNET_free (config);
1294       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1295       return;
1296     }
1297     if (config_size == dest_size)
1298     {
1299       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1300       GNUNET_free (config);
1301       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1302       return;
1303     }
1304     cfg = GNUNET_CONFIGURATION_create (); /* Free here or in lcfcontext */
1305     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1306                                                        GNUNET_NO))
1307     {
1308       GNUNET_break (0);           /* Configuration parsing error */
1309       GNUNET_free (config);
1310       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1311       return;
1312     }
1313     GNUNET_free (config);
1314     if ((delegated_host_id < slave_list_size) &&
1315         (NULL != slave_list[delegated_host_id]))
1316     {
1317       GNUNET_break (0);           /* Configuration parsing error */
1318       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1319       return;
1320     }
1321     slave = GNUNET_malloc (sizeof (struct Slave));
1322     slave->host_id = delegated_host_id;    
1323     slave_list_add (slave);    
1324     if (1 == msg->is_subordinate)
1325     {
1326       slave->controller_proc =
1327         GNUNET_TESTBED_controller_start (master_context->master_ip,
1328                                          host_list[slave->host_id],
1329                                          cfg, &slave_status_callback,
1330                                          slave);
1331     }
1332     else {
1333       slave->controller = 
1334         GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1335                                            master_context->event_mask,
1336                                            &slave_event_callback, slave);
1337     }
1338     GNUNET_CONFIGURATION_destroy (cfg);
1339     new_route = GNUNET_malloc (sizeof (struct Route));
1340     new_route->dest = delegated_host_id;
1341     new_route->thru = master_context->host_id;
1342     route_list_add (new_route);
1343     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1344     return;
1345   }
1346
1347   /* Route the request */
1348   if (slave_host_id >= route_list_size)
1349   {
1350     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1351     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1352     return;
1353   }
1354   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1355   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1356   lcfq->lcf->delegated_host_id = delegated_host_id;
1357   lcfq->lcf->slave_host_id = slave_host_id;
1358   route = find_dest_route (slave_host_id);
1359   GNUNET_assert (NULL != route); /* because we add routes carefully */
1360   GNUNET_assert (route->dest < slave_list_size);
1361   GNUNET_assert (NULL != slave_list[route->dest]);  
1362   lcfq->lcf->is_subordinate =
1363     (1 == msg->is_subordinate) ? GNUNET_YES : GNUNET_NO;
1364   lcfq->lcf->state = INIT;
1365   lcfq->lcf->gateway = slave_list[route->dest];
1366   lcfq->lcf->sxcfg_size = msize;
1367   lcfq->lcf->sxcfg = GNUNET_malloc (msize);
1368   lcfq->lcf->scfg_size = config_size;
1369   (void) memcpy (lcfq->lcf->sxcfg, &msg[1], msize);
1370   if (NULL == lcfq_head)
1371   {
1372     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1373     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1374     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq);
1375   }
1376   else
1377     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1378   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1379   new_route = GNUNET_malloc (sizeof (struct Route));
1380   new_route->dest = delegated_host_id;
1381   new_route->thru = route->dest;
1382   route_list_add (new_route);
1383 }
1384
1385
1386 /**
1387  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1388  *
1389  * @param cls NULL
1390  * @param client identification of the client
1391  * @param message the actual message
1392  */
1393 static void 
1394 handle_peer_create (void *cls,
1395                     struct GNUNET_SERVER_Client *client,
1396                     const struct GNUNET_MessageHeader *message)
1397 {
1398   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1399   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1400   struct GNUNET_CONFIGURATION_Handle *cfg;
1401   struct PeerCreateContext *pc_ctxt;
1402   struct Route *route;
1403   char *config;
1404   size_t dest_size;
1405   int ret;
1406   uint32_t config_size;
1407   uint32_t host_id;
1408   uint16_t msize;
1409   
1410
1411   msize = ntohs (message->size);
1412   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1413   {
1414     GNUNET_break (0);           /* We need configuration */
1415     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1416     return;
1417   }
1418   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1419   host_id = ntohl (msg->host_id);
1420   if (host_id == master_context->host_id)
1421   {
1422     struct Peer *peer;
1423     char *emsg;
1424     
1425     /* We are responsible for this peer */
1426     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1427     config_size = ntohl (msg->config_size);    
1428     config = GNUNET_malloc (config_size);
1429     dest_size = config_size;
1430     if (Z_OK != (ret = uncompress ((Bytef *) config, (uLongf *) &dest_size,
1431                                    (const Bytef *) &msg[1], (uLong) msize)))
1432     {
1433       GNUNET_break (0);           /* uncompression error */
1434       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1435       return;
1436     }
1437     if (config_size != dest_size)
1438     {
1439       GNUNET_break (0);/* Uncompressed config size mismatch */
1440       GNUNET_free (config);
1441       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1442       return;
1443     }
1444     cfg = GNUNET_CONFIGURATION_create ();
1445     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1446                                                        GNUNET_NO))
1447     {
1448       GNUNET_break (0);           /* Configuration parsing error */
1449       GNUNET_free (config);
1450       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1451       return;
1452     }
1453     GNUNET_free (config);
1454     peer = GNUNET_malloc (sizeof (struct Peer));
1455     peer->is_remote = GNUNET_NO;
1456     peer->details.local.cfg = cfg;
1457     peer->id = ntohl (msg->peer_id);
1458     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1459     peer->details.local.peer = 
1460       GNUNET_TESTING_peer_configure (master_context->system,
1461                                      peer->details.local.cfg, peer->id,
1462                                      NULL /* Peer id */,
1463                                      &emsg);
1464     if (NULL == peer->details.local.peer)
1465     {
1466       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1467       GNUNET_free (emsg);
1468       GNUNET_free (peer);
1469       GNUNET_break (0);
1470       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1471       return;
1472     }
1473     peer_list_add (peer);
1474     reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1475     reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1476     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1477     reply->peer_id = msg->peer_id;
1478     reply->operation_id = msg->operation_id;
1479     queue_message (client, &reply->header);
1480     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1481     return;
1482   }
1483   
1484   /* Forward peer create request */
1485   route = find_dest_route (host_id);
1486   if (NULL == route)
1487   {
1488     GNUNET_break (0);
1489     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1490     return;
1491   }
1492   pc_ctxt = GNUNET_malloc (sizeof (struct PeerCreateContext));
1493   pc_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);
1494   /* To be continued .. :) */
1495 }
1496
1497
1498 /**
1499  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1500  *
1501  * @param cls NULL
1502  * @param client identification of the client
1503  * @param message the actual message
1504  */
1505 static void 
1506 handle_peer_destroy (void *cls,
1507                      struct GNUNET_SERVER_Client *client,
1508                      const struct GNUNET_MessageHeader *message)
1509 {
1510   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1511   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *reply;
1512   struct Peer *peer;
1513   uint32_t peer_id;
1514   uint16_t reply_size;
1515   
1516   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1517   peer_id = ntohl (msg->peer_id);
1518   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1519              peer_id, GNUNET_ntohll (msg->operation_id));  
1520   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1521   {
1522     GNUNET_break (0);
1523     /* FIXME: Reply with failure event message or forward to slave controller */
1524     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1525     return;
1526   }
1527   peer = peer_list[peer_id];
1528   if (GNUNET_YES == peer->is_remote)
1529   {
1530     /* Forward the destory message to sub controller */
1531     GNUNET_break (0);
1532     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1533     return;
1534   }
1535   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
1536   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
1537   peer_list_remove (peer);
1538   GNUNET_free (peer);
1539   reply_size = 
1540     sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1541   reply = GNUNET_malloc (reply_size);
1542   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1543   reply->header.size = htons (reply_size);
1544   reply->operation_id = msg->operation_id;
1545   reply->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1546   queue_message (client, &reply->header);
1547   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1548 }
1549
1550
1551 /**
1552  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1553  *
1554  * @param cls NULL
1555  * @param client identification of the client
1556  * @param message the actual message
1557  */
1558 static void 
1559 handle_peer_start (void *cls,
1560                    struct GNUNET_SERVER_Client *client,
1561                    const struct GNUNET_MessageHeader *message)
1562 {
1563   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1564   struct GNUNET_TESTBED_PeerEventMessage *reply;
1565   uint32_t peer_id;
1566
1567   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1568   peer_id = ntohl (msg->peer_id);
1569   if ((peer_id >= peer_list_size) 
1570       || (NULL == peer_list[peer_id]))
1571   {
1572     GNUNET_break (0);
1573     /* FIXME: reply with failure message or forward to slave controller */
1574     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1575     return;
1576   }
1577   if (GNUNET_OK != 
1578       GNUNET_TESTING_peer_start (peer_list[peer_id]->details.local.peer))
1579   {
1580     /* FIXME: return FAILURE message */
1581     GNUNET_break (0);
1582     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1583     return;
1584   }
1585   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1586   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1587   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1588   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1589   reply->host_id = htonl (master_context->host_id);
1590   reply->peer_id = msg->peer_id;
1591   reply->operation_id = msg->operation_id;
1592   queue_message (client, &reply->header);
1593   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1594 }
1595
1596
1597 /**
1598  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1599  *
1600  * @param cls NULL
1601  * @param client identification of the client
1602  * @param message the actual message
1603  */
1604 static void 
1605 handle_peer_stop (void *cls,
1606                   struct GNUNET_SERVER_Client *client,
1607                   const struct GNUNET_MessageHeader *message)
1608 {
1609   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1610   struct GNUNET_TESTBED_PeerEventMessage *reply;
1611   uint32_t peer_id;
1612
1613   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1614   peer_id = ntohl (msg->peer_id);
1615   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1616   {
1617     GNUNET_break (0);           /* FIXME: route to slave? */
1618     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1619     return;
1620   }
1621   if (GNUNET_OK != 
1622       GNUNET_TESTING_peer_stop (peer_list[peer_id]->details.local.peer))
1623   {
1624     /* FIXME: return FAILURE message */
1625     GNUNET_break (0);
1626     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1627     return;
1628   }
1629   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1630   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1631   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1632   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1633   reply->host_id = htonl (master_context->host_id);
1634   reply->peer_id = msg->peer_id;
1635   reply->operation_id = msg->operation_id;
1636   queue_message (client, &reply->header);
1637   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1638 }
1639
1640
1641 /**
1642  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1643  *
1644  * @param cls NULL
1645  * @param client identification of the client
1646  * @param message the actual message
1647  */
1648 static void 
1649 handle_peer_get_config (void *cls,
1650                         struct GNUNET_SERVER_Client *client,
1651                         const struct GNUNET_MessageHeader *message)
1652 {
1653   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1654   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1655   struct Peer *peer;
1656   char *config;
1657   char *xconfig;
1658   size_t c_size;
1659   size_t xc_size;  
1660   uint32_t peer_id;
1661   uint16_t msize;
1662   
1663   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1664   peer_id = ntohl (msg->peer_id);
1665   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1666   {
1667     /* FIXME: return FAILURE message */
1668     GNUNET_break (0);
1669     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1670     return;
1671   }
1672   peer = peer_list[peer_id];
1673   if (GNUNET_YES == peer->is_remote)
1674   {
1675     /* FIXME: forward to sub controller */
1676     GNUNET_break (0);
1677     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1678     return;
1679   }
1680   config =
1681     GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
1682                                     &c_size);
1683   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1684   GNUNET_free (config);
1685   msize = xc_size + sizeof (struct
1686                             GNUNET_TESTBED_PeerConfigurationInformationMessage);
1687   reply = GNUNET_realloc (xconfig, msize);
1688   (void) memmove (&reply[1], reply, xc_size);
1689   reply->header.size = htons (msize);
1690   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
1691   reply->peer_id = msg->peer_id;
1692   reply->operation_id = msg->operation_id;
1693   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
1694                                     &reply->peer_identity);
1695   reply->config_size = htons ((uint16_t) c_size);
1696   queue_message (client, &reply->header);
1697   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1698 }
1699
1700
1701 /**
1702  * Task for cleaing up overlay connect context structure
1703  *
1704  * @param cls the overlay connect context
1705  * @param tc the task context
1706  */
1707 static void
1708 occ_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1709 {
1710   struct OverlayConnectContext *occ = cls;
1711
1712   GNUNET_free_non_null (occ->emsg);
1713   GNUNET_free_non_null (occ->hello);
1714   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1715     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1716   if (NULL != occ->ch)
1717     GNUNET_CORE_disconnect (occ->ch);
1718   if (NULL != occ->ghh)
1719     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1720   if (NULL != occ->p1th)
1721     GNUNET_TRANSPORT_disconnect (occ->p1th);
1722   if (NULL != occ->p2th)
1723     GNUNET_TRANSPORT_disconnect (occ->p2th);
1724   GNUNET_free (occ);
1725 }
1726
1727
1728 /**
1729  * Task which will be run when overlay connect request has been timed out
1730  *
1731  * @param 
1732  * @return 
1733  */
1734 static void
1735 timeout_overlay_connect (void *cls,
1736                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1737 {
1738   struct OverlayConnectContext *occ = cls;
1739
1740   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1741   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
1742   GNUNET_SERVER_client_drop (occ->client);
1743   occ_cleanup (occ, tc);
1744 }
1745
1746
1747
1748 /**
1749  * Function called to notify transport users that another
1750  * peer connected to us.
1751  *
1752  * @param cls closure
1753  * @param new_peer the peer that connected
1754  * @param ats performance data
1755  * @param ats_count number of entries in ats (excluding 0-termination)
1756  */
1757 static void 
1758 overlay_connect_notify (void *cls,
1759                         const struct GNUNET_PeerIdentity * new_peer,
1760                         const struct GNUNET_ATS_Information * ats,
1761                         unsigned int ats_count)
1762 {
1763   struct OverlayConnectContext *occ = cls;
1764   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
1765   char *new_peer_str;
1766   char *other_peer_str;
1767
1768   LOG_DEBUG ("Overlay connect notify\n");
1769   if (0 == memcmp (new_peer, &occ->peer_identity, 
1770                    sizeof (struct GNUNET_PeerIdentity)))
1771     return;
1772   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
1773   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
1774   if (0 != memcmp (new_peer, &occ->other_peer_identity,
1775                    sizeof (struct GNUNET_PeerIdentity)))
1776   {
1777     LOG_DEBUG ("Unexpected peer %4s connected to peer %4s\n",
1778                new_peer_str, other_peer_str);
1779     GNUNET_free (new_peer_str);
1780     GNUNET_free (other_peer_str);
1781     return;
1782   }
1783   LOG_DEBUG ("Peer %4s connected to peer %4s\n", new_peer_str, other_peer_str);
1784   GNUNET_free (new_peer_str);
1785   GNUNET_free (other_peer_str);
1786   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1787   {
1788     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1789     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
1790   }
1791   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
1792   GNUNET_SCHEDULER_cancel (occ->timeout_task);
1793   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1794   GNUNET_free_non_null (occ->emsg);
1795   occ->emsg = NULL;
1796   GNUNET_TRANSPORT_disconnect (occ->p1th);
1797   occ->p1th = NULL;
1798   /* Peer 1 has connected connect to peer2 - now send overlay connect success message */
1799   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
1800   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
1801   msg->header.size = htons (sizeof (struct
1802                                     GNUNET_TESTBED_ConnectionEventMessage));
1803   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
1804   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
1805   msg->peer1 = htonl (occ->peer->id);
1806   msg->peer2 = htonl (occ->other_peer->id);
1807   msg->operation_id = GNUNET_htonll (occ->op_id);
1808   queue_message (occ->client, &msg->header);
1809   GNUNET_SERVER_client_drop (occ->client);
1810   GNUNET_SCHEDULER_add_now (&occ_cleanup, occ);
1811 }
1812
1813
1814 static void
1815 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1816 {
1817   struct OverlayConnectContext *occ = cls;
1818   char *other_peer_str;
1819
1820   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
1821   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1822     return;
1823   GNUNET_assert (NULL != occ->hello);
1824   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
1825   LOG_DEBUG ("Offering HELLO of %s to %s\n", other_peer_str, GNUNET_i2s (&occ->peer_identity));
1826   GNUNET_free (other_peer_str);
1827   GNUNET_TRANSPORT_offer_hello (occ->p1th, occ->hello, NULL, NULL);
1828   GNUNET_TRANSPORT_try_connect (occ->p1th, &occ->other_peer_identity);
1829   occ->send_hello_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1830                                                        &send_hello, occ);
1831 }
1832
1833 /**
1834  * Test for checking whether HELLO message is empty
1835  *
1836  * @param cls empty flag to set
1837  * @param address the HELLO
1838  * @param expiration expiration of the HELLO
1839  * @return 
1840  */
1841 static int
1842 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
1843               struct GNUNET_TIME_Absolute expiration)
1844 {
1845   int *empty = cls;
1846
1847   *empty = GNUNET_NO;
1848   return GNUNET_OK;
1849 }
1850
1851
1852 /**
1853  * Function called whenever there is an update to the
1854  * HELLO of peers in the OverlayConnectClosure
1855  *
1856  * @param cls closure
1857  * @param hello our updated HELLO
1858  */
1859 static void 
1860 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
1861 {
1862   struct OverlayConnectContext *occ = cls;
1863   int empty;
1864   uint16_t msize;
1865   
1866   msize = ntohs (hello->size);
1867   if (msize < 0)
1868   {
1869     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1870                 "HELLO message of peer %s is of size 0\n",
1871                 &occ->other_peer_identity);
1872     return;
1873   }
1874   empty = GNUNET_YES;
1875   (void) 
1876     GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *) hello,
1877                                     GNUNET_NO, &test_address, &empty);
1878   if (GNUNET_YES == empty)
1879   {
1880     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->other_peer_identity));
1881     return;
1882   }
1883   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->other_peer_identity));
1884   occ->hello = GNUNET_malloc (msize);
1885   memcpy (occ->hello, hello, msize);
1886   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1887   occ->ghh = NULL;
1888   GNUNET_TRANSPORT_disconnect (occ->p2th);
1889   occ->p2th = NULL;
1890   GNUNET_free_non_null (occ->emsg);  
1891   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
1892   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
1893 }
1894
1895
1896 /**
1897  * Function called after GNUNET_CORE_connect has succeeded (or failed
1898  * for good).  Note that the private key of the peer is intentionally
1899  * not exposed here; if you need it, your process should try to read
1900  * the private key file directly (which should work if you are
1901  * authorized...).
1902  *
1903  * @param cls closure
1904  * @param server handle to the server, NULL if we failed
1905  * @param my_identity ID of this peer, NULL if we failed
1906  */
1907 static void 
1908 core_startup_cb (void *cls, struct GNUNET_CORE_Handle * server,
1909                  const struct GNUNET_PeerIdentity *my_identity)
1910 {
1911   struct OverlayConnectContext *occ = cls;
1912
1913   GNUNET_free_non_null (occ->emsg);
1914   occ->emsg = NULL;
1915   memcpy (&occ->peer_identity, my_identity, sizeof (struct GNUNET_PeerIdentity));
1916   occ->p1th =
1917     GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg, 
1918                               &occ->peer_identity, NULL, NULL, NULL, NULL);
1919   /* Connect to the transport of 2nd peer and get its HELLO message */
1920   GNUNET_TESTING_peer_get_identity (occ->other_peer->details.local.peer,
1921                                     &occ->other_peer_identity);
1922   occ->p2th = 
1923     GNUNET_TRANSPORT_connect (occ->other_peer->details.local.cfg,
1924                               &occ->other_peer_identity,
1925                               NULL, NULL, NULL, NULL);
1926   if ((NULL == occ->p1th) || (NULL == occ->p2th))
1927   {
1928     occ->emsg = GNUNET_strdup ("Cannot connect to TRANSPORTs of peers");
1929     goto send_failure;
1930   }
1931   LOG_DEBUG ("Acquiring HELLO of peer %s\n", GNUNET_i2s
1932              (&occ->other_peer_identity));
1933   occ->emsg = GNUNET_strdup ("Timeout while acquiring HELLO message");
1934   occ->ghh = GNUNET_TRANSPORT_get_hello (occ->p2th, &hello_update_cb, occ);
1935   return;
1936
1937  send_failure:
1938   GNUNET_SCHEDULER_cancel (occ->timeout_task);
1939   occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);  
1940 }
1941
1942
1943 /**
1944  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
1945  *
1946  * @param cls NULL
1947  * @param client identification of the client
1948  * @param message the actual message
1949  */
1950 static void 
1951 handle_overlay_connect (void *cls,
1952                         struct GNUNET_SERVER_Client *client,
1953                         const struct GNUNET_MessageHeader *message)
1954 {
1955   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
1956   struct OverlayConnectContext *occ;
1957   struct GNUNET_CORE_MessageHandler no_handlers[] = {
1958     {NULL, 0, 0}
1959   };
1960   uint32_t p1;
1961   uint32_t p2;
1962
1963   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
1964   p1 = ntohl (msg->peer1);
1965   p2 = ntohl (msg->peer2);
1966   GNUNET_assert (p1 < peer_list_size);
1967   GNUNET_assert (NULL != peer_list[p1]);
1968   GNUNET_assert (p2 < peer_list_size);
1969   GNUNET_assert (NULL != peer_list[p2]);
1970   /* FIXME: Add cases where we have to forward overlay connect message to sub
1971      controllers */
1972   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
1973   GNUNET_SERVER_client_keep (client);
1974   occ->client = client;
1975   occ->state = OCC_STATE_INIT;
1976   occ->peer = peer_list[p1];
1977   occ->other_peer = peer_list[p2];
1978   occ->op_id = GNUNET_ntohll (msg->operation_id);
1979   occ->timeout_task =
1980     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1981                                   (GNUNET_TIME_UNIT_SECONDS, 30),
1982                                   &timeout_overlay_connect, occ);   
1983   /* Connect to the core of 1st peer and wait for the 2nd peer to connect */
1984   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
1985   occ->ch = 
1986     GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
1987                          &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
1988                          GNUNET_NO, no_handlers);
1989   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1990 }
1991
1992
1993 /**
1994  * Iterator over hash map entries.
1995  *
1996  * @param cls closure
1997  * @param key current key code
1998  * @param value value in the hash map
1999  * @return GNUNET_YES if we should continue to
2000  *         iterate,
2001  *         GNUNET_NO if not.
2002  */
2003 static int 
2004 ss_map_free_iterator (void *cls,
2005                       const struct GNUNET_HashCode * key, void *value)
2006 {
2007   struct SharedService *ss = value;
2008
2009   GNUNET_assert (GNUNET_YES ==
2010                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
2011   GNUNET_free (ss->name);
2012   GNUNET_free (ss);
2013   return GNUNET_YES;
2014 }
2015
2016
2017 /**
2018  * Task to clean up and shutdown nicely
2019  *
2020  * @param cls NULL
2021  * @param tc the TaskContext from scheduler
2022  */
2023 static void
2024 shutdown_task (void *cls,
2025                const struct GNUNET_SCHEDULER_TaskContext *tc)
2026 {
2027   struct LCFContextQueue *lcfq;
2028   uint32_t id;
2029
2030   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
2031   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
2032   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
2033                                                 NULL);
2034   GNUNET_CONTAINER_multihashmap_destroy (ss_map);  
2035   if (NULL != lcfq_head)
2036   {
2037     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
2038     {
2039       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
2040       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
2041     }
2042     if (NULL != lcfq_head->lcf->rhandle)
2043       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
2044   }
2045   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2046   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
2047   {
2048     GNUNET_free (lcfq->lcf->sxcfg);
2049     GNUNET_free (lcfq->lcf);
2050     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
2051     GNUNET_free (lcfq);
2052   }
2053   /* Clear peer list */
2054   for (id = 0; id < peer_list_size; id++)
2055     if (NULL != peer_list[id])
2056     {
2057       GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
2058       GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
2059       GNUNET_free (peer_list[id]);
2060     }
2061   GNUNET_free_non_null (peer_list);
2062   /* Clear host list */
2063   for (id = 0; id < host_list_size; id++)
2064     if (NULL != host_list[id])
2065       GNUNET_TESTBED_host_destroy (host_list[id]);
2066   GNUNET_free_non_null (host_list);
2067   /* Clear route list */
2068   for (id = 0; id < route_list_size; id++)
2069     if (NULL != route_list[id])
2070       GNUNET_free (route_list[id]);
2071   GNUNET_free_non_null (route_list);
2072   /* Clear slave_list */
2073   for (id = 0; id < slave_list_size; id++)
2074     if (NULL != slave_list[id])
2075     {
2076       GNUNET_assert (NULL != slave_list[id]->controller);
2077       GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
2078       if (NULL != slave_list[id]->controller_proc)
2079         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
2080     }
2081   if (NULL != master_context)
2082   {  
2083     GNUNET_free_non_null (master_context->master_ip);
2084     if (NULL != master_context->system)
2085       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
2086     GNUNET_free (master_context);
2087     master_context = NULL;
2088   }
2089 }
2090
2091
2092 /**
2093  * Callback for client disconnect
2094  *
2095  * @param cls NULL
2096  * @param client the client which has disconnected
2097  */
2098 static void
2099 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
2100 {
2101   if (NULL == master_context)
2102     return;
2103   if (client == master_context->client)
2104   {
2105     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
2106     GNUNET_SERVER_client_drop (client);
2107     /* should not be needed as we're terminated by failure to read
2108        from stdin, but if stdin fails for some reason, this shouldn't 
2109        hurt for now --- might need to revise this later if we ever
2110        decide that master connections might be temporarily down 
2111        for some reason */
2112     //GNUNET_SCHEDULER_shutdown ();
2113   }
2114 }
2115
2116
2117 /**
2118  * Testbed setup
2119  *
2120  * @param cls closure
2121  * @param server the initialized server
2122  * @param cfg configuration to use
2123  */
2124 static void 
2125 testbed_run (void *cls,
2126              struct GNUNET_SERVER_Handle *server,
2127              const struct GNUNET_CONFIGURATION_Handle *cfg)
2128 {
2129   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
2130     {
2131       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
2132       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
2133       {&handle_configure_shared_service, NULL,
2134        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
2135       {&handle_link_controllers, NULL,
2136        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
2137       {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
2138       {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
2139        sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
2140       {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
2141        sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
2142       {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
2143        sizeof (struct GNUNET_TESTBED_PeerStopMessage)},      
2144       {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
2145        sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
2146       {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
2147        sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
2148       {NULL}
2149     };
2150
2151   GNUNET_SERVER_add_handlers (server,
2152                               message_handlers);
2153   GNUNET_SERVER_disconnect_notify (server,
2154                                    &client_disconnect_cb,
2155                                    NULL);
2156   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
2157   shutdown_task_id = 
2158     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2159                                   &shutdown_task,
2160                                   NULL);
2161   LOG_DEBUG ("Testbed startup complete\n");
2162 }
2163
2164
2165 /**
2166  * The starting point of execution
2167  */
2168 int main (int argc, char *const *argv)
2169 {
2170   //sleep (30);                 /* Debugging */
2171   return
2172     (GNUNET_OK ==
2173      GNUNET_SERVICE_run (argc,
2174                          argv,
2175                          "testbed",
2176                          GNUNET_SERVICE_OPTION_NONE,
2177                          &testbed_run,
2178                          NULL)) ? 0 : 1;
2179 }