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