implemented peer create operation forwarding
[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 LOG_DEBUG ("-------username: NULL\n");
1112   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1113   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1114                                              ntohs (msg->ssh_port));
1115   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1116   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1117   if (GNUNET_OK != host_list_add (host))
1118   {    
1119     /* We are unable to add a host */  
1120     emsg = "A host exists with given host-id";
1121     LOG_DEBUG ("%s: %u", emsg, host_id);
1122     GNUNET_TESTBED_host_destroy (host);
1123     reply_size += strlen (emsg) + 1;
1124     reply = GNUNET_malloc (reply_size);
1125     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1126   }
1127   else
1128     reply = GNUNET_malloc (reply_size);  
1129   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
1130   reply->header.size = htons (reply_size);
1131   reply->host_id = htonl (host_id);  
1132   queue_message (client, &reply->header);
1133 }
1134
1135
1136 /**
1137  * Iterator over hash map entries.
1138  *
1139  * @param cls closure
1140  * @param key current key code
1141  * @param value value in the hash map
1142  * @return GNUNET_YES if we should continue to
1143  *         iterate,
1144  *         GNUNET_NO if not.
1145  */
1146 int ss_exists_iterator (void *cls,
1147                         const struct GNUNET_HashCode * key,
1148                         void *value)
1149 {
1150   struct SharedService *queried_ss = cls;
1151   struct SharedService *ss = value;
1152
1153   if (0 == strcmp (ss->name, queried_ss->name))
1154     return GNUNET_NO;
1155   else
1156     return GNUNET_YES;
1157 }
1158
1159
1160 /**
1161  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1162  *
1163  * @param cls NULL
1164  * @param client identification of the client
1165  * @param message the actual message
1166  */
1167 static void 
1168 handle_configure_shared_service (void *cls,
1169                                  struct GNUNET_SERVER_Client *client,
1170                                  const struct GNUNET_MessageHeader *message)
1171 {
1172   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1173   struct SharedService *ss;
1174   char *service_name;
1175   struct GNUNET_HashCode hash;
1176   uint16_t msg_size;
1177   uint16_t service_name_size;
1178     
1179   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1180   msg_size = ntohs (message->size);
1181   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1182   {
1183     GNUNET_break (0);
1184     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1185     return;
1186   }
1187   service_name_size = msg_size - 
1188     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
1189   service_name = (char *) &msg[1];
1190   if ('\0' != service_name[service_name_size - 1])
1191   {
1192     GNUNET_break (0);
1193     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1194     return;
1195   }
1196   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
1197              service_name, ntohl (msg->num_peers));
1198   if (ntohl (msg->host_id) != master_context->host_id)
1199   {
1200     route_message (ntohl (msg->host_id), message);
1201     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1202     return;
1203   }
1204   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1205   ss = GNUNET_malloc (sizeof (struct SharedService));
1206   ss->name = strdup (service_name);
1207   ss->num_shared = ntohl (msg->num_peers);
1208   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1209   if (GNUNET_SYSERR == 
1210       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1211                                                   &ss_exists_iterator, ss))
1212   {
1213     LOG (GNUNET_ERROR_TYPE_WARNING,
1214          "Service %s already configured as a shared service. "
1215          "Ignoring service sharing request \n", ss->name);
1216     GNUNET_free (ss->name);
1217     GNUNET_free (ss);
1218     return;
1219   }
1220   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1221                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
1222 }
1223
1224
1225 /**
1226  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1227  *
1228  * @param cls NULL
1229  * @param client identification of the client
1230  * @param message the actual message
1231  */
1232 static void 
1233 handle_link_controllers (void *cls,
1234                          struct GNUNET_SERVER_Client *client,
1235                          const struct GNUNET_MessageHeader *message)
1236 {
1237   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1238   struct GNUNET_CONFIGURATION_Handle *cfg;
1239   struct LCFContextQueue *lcfq;
1240   struct Route *route;
1241   struct Route *new_route;
1242   char *config;  
1243   uLongf dest_size;
1244   size_t config_size;
1245   uint32_t delegated_host_id;
1246   uint32_t slave_host_id;
1247   uint16_t msize;
1248    
1249   if (NULL == master_context)
1250   {
1251     GNUNET_break (0);
1252     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1253     return;
1254   }
1255   msize = ntohs (message->size);
1256   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1257   {
1258     GNUNET_break (0);
1259     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1260     return;
1261   }
1262   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1263   delegated_host_id = ntohl (msg->delegated_host_id);
1264   if (delegated_host_id == master_context->host_id)
1265   {
1266     GNUNET_break (0);
1267     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1268     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1269     return;
1270   }
1271   if ((delegated_host_id >= host_list_size) || 
1272       (NULL == host_list[delegated_host_id]))
1273   {
1274     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
1275     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1276     return;
1277   }
1278   slave_host_id = ntohl (msg->slave_host_id);
1279   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1280   {
1281     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
1282     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1283     return;
1284   }
1285   if (slave_host_id == delegated_host_id)
1286   {
1287     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1288     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1289     return;
1290   }
1291   msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1292   config_size = ntohs (msg->config_size);
1293   
1294   if (slave_host_id == master_context->host_id) /* Link from us */
1295   {
1296     struct Slave *slave;
1297
1298     if ((delegated_host_id < slave_list_size) && 
1299         (NULL != slave_list[delegated_host_id])) /* We have already added */
1300     {
1301       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1302            delegated_host_id);
1303       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1304       return;
1305     }    
1306     config = GNUNET_malloc (config_size);
1307     dest_size = (uLongf) config_size;    
1308     if (Z_OK != uncompress ((Bytef *) config, &dest_size,
1309                             (const Bytef *) &msg[1], (uLong) msize))
1310     {
1311       GNUNET_break (0);           /* Compression error */
1312       GNUNET_free (config);
1313       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1314       return;
1315     }
1316     if (config_size == dest_size)
1317     {
1318       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1319       GNUNET_free (config);
1320       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1321       return;
1322     }
1323     cfg = GNUNET_CONFIGURATION_create (); /* Free here or in lcfcontext */
1324     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1325                                                        GNUNET_NO))
1326     {
1327       GNUNET_break (0);           /* Configuration parsing error */
1328       GNUNET_free (config);
1329       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1330       return;
1331     }
1332     GNUNET_free (config);
1333     if ((delegated_host_id < slave_list_size) &&
1334         (NULL != slave_list[delegated_host_id]))
1335     {
1336       GNUNET_break (0);           /* Configuration parsing error */
1337       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1338       return;
1339     }
1340     slave = GNUNET_malloc (sizeof (struct Slave));
1341     slave->host_id = delegated_host_id;    
1342     slave_list_add (slave);    
1343     if (1 == msg->is_subordinate)
1344     {
1345       slave->controller_proc =
1346         GNUNET_TESTBED_controller_start (master_context->master_ip,
1347                                          host_list[slave->host_id],
1348                                          cfg, &slave_status_callback,
1349                                          slave);
1350     }
1351     else {
1352       slave->controller = 
1353         GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1354                                            master_context->event_mask,
1355                                            &slave_event_callback, slave);
1356     }
1357     GNUNET_CONFIGURATION_destroy (cfg);
1358     new_route = GNUNET_malloc (sizeof (struct Route));
1359     new_route->dest = delegated_host_id;
1360     new_route->thru = master_context->host_id;
1361     route_list_add (new_route);
1362     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1363     return;
1364   }
1365
1366   /* Route the request */
1367   if (slave_host_id >= route_list_size)
1368   {
1369     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1370     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1371     return;
1372   }
1373   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1374   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1375   lcfq->lcf->delegated_host_id = delegated_host_id;
1376   lcfq->lcf->slave_host_id = slave_host_id;
1377   route = find_dest_route (slave_host_id);
1378   GNUNET_assert (NULL != route); /* because we add routes carefully */
1379   GNUNET_assert (route->dest < slave_list_size);
1380   GNUNET_assert (NULL != slave_list[route->dest]);  
1381   lcfq->lcf->is_subordinate =
1382     (1 == msg->is_subordinate) ? GNUNET_YES : GNUNET_NO;
1383   lcfq->lcf->state = INIT;
1384   lcfq->lcf->gateway = slave_list[route->dest];
1385   lcfq->lcf->sxcfg_size = msize;
1386   lcfq->lcf->sxcfg = GNUNET_malloc (msize);
1387   lcfq->lcf->scfg_size = config_size;
1388   (void) memcpy (lcfq->lcf->sxcfg, &msg[1], msize);
1389   if (NULL == lcfq_head)
1390   {
1391     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1392     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1393     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq);
1394   }
1395   else
1396     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1397   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1398   new_route = GNUNET_malloc (sizeof (struct Route));
1399   new_route->dest = delegated_host_id;
1400   new_route->thru = route->dest;
1401   route_list_add (new_route);
1402 }
1403
1404
1405 /**
1406  * The task to be executed if the forwarded peer create operation has been
1407  * timed out
1408  *
1409  * @param cls the FowardedOperationContext
1410  * @param tc the TaskContext from the scheduler
1411  */
1412 static void
1413 peer_create_forward_timeout (void *cls,
1414                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1415 {
1416   struct ForwardedOperationContext *fo_ctxt = cls;
1417   
1418   /* send error msg to client */
1419   send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id,
1420                            "Timedout");  
1421   GNUNET_SERVER_client_drop (fo_ctxt->client);
1422   GNUNET_TESTBED_forward_operation_msg_cancel_ (fo_ctxt->opc);
1423   GNUNET_free (fo_ctxt);  
1424 }
1425
1426
1427 /**
1428  * Callback to be called when forwarded peer create operation is
1429  * successfull. We have to relay the reply msg back to the client
1430  *
1431  * @param cls ForwardedOperationContext
1432  * @param msg the peer create success message
1433  */
1434 static void
1435 peer_create_success_cb (void *cls,
1436                         const struct GNUNET_MessageHeader *msg)
1437 {
1438   struct ForwardedOperationContext *fo_ctxt = cls;
1439   struct GNUNET_MessageHeader *dup_msg;  
1440   uint16_t msize;
1441   
1442   GNUNET_SCHEDULER_cancel (fo_ctxt->timeout_task);  
1443   GNUNET_assert (ntohs (msg->type) == 
1444                  GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1445   msize = ntohs (msg->size);  
1446   dup_msg = GNUNET_malloc (msize);
1447   (void) memcpy (dup_msg, msg, msize);  
1448   queue_message (fo_ctxt->client, dup_msg);
1449   GNUNET_SERVER_client_drop (fo_ctxt->client);
1450   GNUNET_free (fo_ctxt);  
1451 }
1452
1453
1454
1455 /**
1456  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1457  *
1458  * @param cls NULL
1459  * @param client identification of the client
1460  * @param message the actual message
1461  */
1462 static void 
1463 handle_peer_create (void *cls,
1464                     struct GNUNET_SERVER_Client *client,
1465                     const struct GNUNET_MessageHeader *message)
1466 {
1467   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1468   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1469   struct GNUNET_CONFIGURATION_Handle *cfg;
1470   struct ForwardedOperationContext *fo_ctxt;
1471   struct Route *route;
1472   struct Peer *peer;
1473   char *config;
1474   size_t dest_size;
1475   int ret;
1476   uint32_t config_size;
1477   uint32_t host_id;
1478   uint16_t msize;
1479   
1480
1481   msize = ntohs (message->size);
1482   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1483   {
1484     GNUNET_break (0);           /* We need configuration */
1485     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1486     return;
1487   }
1488   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1489   host_id = ntohl (msg->host_id);
1490   if (host_id == master_context->host_id)
1491   {
1492     char *emsg;
1493     
1494     /* We are responsible for this peer */
1495     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1496     config_size = ntohl (msg->config_size);    
1497     config = GNUNET_malloc (config_size);
1498     dest_size = config_size;
1499     if (Z_OK != (ret = uncompress ((Bytef *) config, (uLongf *) &dest_size,
1500                                    (const Bytef *) &msg[1], (uLong) msize)))
1501     {
1502       GNUNET_break (0);           /* uncompression error */
1503       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1504       return;
1505     }
1506     if (config_size != dest_size)
1507     {
1508       GNUNET_break (0);/* Uncompressed config size mismatch */
1509       GNUNET_free (config);
1510       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1511       return;
1512     }
1513     cfg = GNUNET_CONFIGURATION_create ();
1514     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1515                                                        GNUNET_NO))
1516     {
1517       GNUNET_break (0);           /* Configuration parsing error */
1518       GNUNET_free (config);
1519       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1520       return;
1521     }
1522     GNUNET_free (config);
1523     peer = GNUNET_malloc (sizeof (struct Peer));
1524     peer->is_remote = GNUNET_NO;
1525     peer->details.local.cfg = cfg;
1526     peer->id = ntohl (msg->peer_id);
1527     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1528     peer->details.local.peer = 
1529       GNUNET_TESTING_peer_configure (master_context->system,
1530                                      peer->details.local.cfg, peer->id,
1531                                      NULL /* Peer id */,
1532                                      &emsg);
1533     if (NULL == peer->details.local.peer)
1534     {
1535       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1536       GNUNET_free (emsg);
1537       GNUNET_free (peer);
1538       GNUNET_break (0);
1539       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1540       return;
1541     }
1542     peer_list_add (peer);
1543     reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1544     reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1545     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1546     reply->peer_id = msg->peer_id;
1547     reply->operation_id = msg->operation_id;
1548     queue_message (client, &reply->header);
1549     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1550     return;
1551   }
1552   
1553   /* Forward peer create request */
1554   route = find_dest_route (host_id);
1555   if (NULL == route)
1556   {
1557     GNUNET_break (0);
1558     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1559     return;
1560   }
1561   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1562   GNUNET_SERVER_client_keep (client);
1563   fo_ctxt->client = client;
1564   fo_ctxt->peer_id = ntohl (msg->peer_id);
1565   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);  
1566   fo_ctxt->opc = 
1567     GNUNET_TESTBED_forward_operation_msg_ (slave_list[route->dest]->controller,
1568                                            fo_ctxt->operation_id,
1569                                            &msg->header,
1570                                            peer_create_success_cb, fo_ctxt);
1571   fo_ctxt->timeout_task = 
1572     GNUNET_SCHEDULER_add_delayed (TIMEOUT,
1573                                   &peer_create_forward_timeout, fo_ctxt);
1574                                   
1575   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1576 }
1577
1578
1579 /**
1580  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1581  *
1582  * @param cls NULL
1583  * @param client identification of the client
1584  * @param message the actual message
1585  */
1586 static void 
1587 handle_peer_destroy (void *cls,
1588                      struct GNUNET_SERVER_Client *client,
1589                      const struct GNUNET_MessageHeader *message)
1590 {
1591   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1592   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *reply;
1593   struct Peer *peer;
1594   uint32_t peer_id;
1595   uint16_t reply_size;
1596   
1597   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1598   peer_id = ntohl (msg->peer_id);
1599   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1600              peer_id, GNUNET_ntohll (msg->operation_id));  
1601   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1602   {
1603     GNUNET_break (0);
1604     /* FIXME: Reply with failure event message or forward to slave controller */
1605     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1606     return;
1607   }
1608   peer = peer_list[peer_id];
1609   if (GNUNET_YES == peer->is_remote)
1610   {
1611     /* Forward the destory message to sub controller */
1612     GNUNET_break (0);
1613     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1614     return;
1615   }
1616   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
1617   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
1618   peer_list_remove (peer);
1619   GNUNET_free (peer);
1620   reply_size = 
1621     sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1622   reply = GNUNET_malloc (reply_size);
1623   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1624   reply->header.size = htons (reply_size);
1625   reply->operation_id = msg->operation_id;
1626   reply->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1627   queue_message (client, &reply->header);
1628   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1629 }
1630
1631
1632 /**
1633  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1634  *
1635  * @param cls NULL
1636  * @param client identification of the client
1637  * @param message the actual message
1638  */
1639 static void 
1640 handle_peer_start (void *cls,
1641                    struct GNUNET_SERVER_Client *client,
1642                    const struct GNUNET_MessageHeader *message)
1643 {
1644   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1645   struct GNUNET_TESTBED_PeerEventMessage *reply;
1646   uint32_t peer_id;
1647
1648   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1649   peer_id = ntohl (msg->peer_id);
1650   if ((peer_id >= peer_list_size) 
1651       || (NULL == peer_list[peer_id]))
1652   {
1653     GNUNET_break (0);
1654     /* FIXME: reply with failure message or forward to slave controller */
1655     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1656     return;
1657   }
1658   if (GNUNET_OK != 
1659       GNUNET_TESTING_peer_start (peer_list[peer_id]->details.local.peer))
1660   {
1661     /* FIXME: return FAILURE message */
1662     GNUNET_break (0);
1663     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1664     return;
1665   }
1666   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1667   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1668   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1669   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1670   reply->host_id = htonl (master_context->host_id);
1671   reply->peer_id = msg->peer_id;
1672   reply->operation_id = msg->operation_id;
1673   queue_message (client, &reply->header);
1674   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1675 }
1676
1677
1678 /**
1679  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1680  *
1681  * @param cls NULL
1682  * @param client identification of the client
1683  * @param message the actual message
1684  */
1685 static void 
1686 handle_peer_stop (void *cls,
1687                   struct GNUNET_SERVER_Client *client,
1688                   const struct GNUNET_MessageHeader *message)
1689 {
1690   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1691   struct GNUNET_TESTBED_PeerEventMessage *reply;
1692   uint32_t peer_id;
1693
1694   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1695   peer_id = ntohl (msg->peer_id);
1696   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1697   {
1698     GNUNET_break (0);           /* FIXME: route to slave? */
1699     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1700     return;
1701   }
1702   if (GNUNET_OK != 
1703       GNUNET_TESTING_peer_stop (peer_list[peer_id]->details.local.peer))
1704   {
1705     /* FIXME: return FAILURE message */
1706     GNUNET_break (0);
1707     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1708     return;
1709   }
1710   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1711   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1712   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1713   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1714   reply->host_id = htonl (master_context->host_id);
1715   reply->peer_id = msg->peer_id;
1716   reply->operation_id = msg->operation_id;
1717   queue_message (client, &reply->header);
1718   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1719 }
1720
1721
1722 /**
1723  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1724  *
1725  * @param cls NULL
1726  * @param client identification of the client
1727  * @param message the actual message
1728  */
1729 static void 
1730 handle_peer_get_config (void *cls,
1731                         struct GNUNET_SERVER_Client *client,
1732                         const struct GNUNET_MessageHeader *message)
1733 {
1734   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1735   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1736   struct Peer *peer;
1737   char *config;
1738   char *xconfig;
1739   size_t c_size;
1740   size_t xc_size;  
1741   uint32_t peer_id;
1742   uint16_t msize;
1743   
1744   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1745   peer_id = ntohl (msg->peer_id);
1746   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1747   {
1748     /* FIXME: return FAILURE message */
1749     GNUNET_break (0);
1750     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1751     return;
1752   }
1753   peer = peer_list[peer_id];
1754   if (GNUNET_YES == peer->is_remote)
1755   {
1756     /* FIXME: forward to sub controller */
1757     GNUNET_break (0);
1758     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1759     return;
1760   }
1761   config =
1762     GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
1763                                     &c_size);
1764   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1765   GNUNET_free (config);
1766   msize = xc_size + sizeof (struct
1767                             GNUNET_TESTBED_PeerConfigurationInformationMessage);
1768   reply = GNUNET_realloc (xconfig, msize);
1769   (void) memmove (&reply[1], reply, xc_size);
1770   reply->header.size = htons (msize);
1771   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
1772   reply->peer_id = msg->peer_id;
1773   reply->operation_id = msg->operation_id;
1774   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
1775                                     &reply->peer_identity);
1776   reply->config_size = htons ((uint16_t) c_size);
1777   queue_message (client, &reply->header);
1778   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1779 }
1780
1781
1782 /**
1783  * Task for cleaing up overlay connect context structure
1784  *
1785  * @param cls the overlay connect context
1786  * @param tc the task context
1787  */
1788 static void
1789 occ_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1790 {
1791   struct OverlayConnectContext *occ = cls;
1792
1793   GNUNET_free_non_null (occ->emsg);
1794   GNUNET_free_non_null (occ->hello);
1795   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1796     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1797   if (NULL != occ->ch)
1798     GNUNET_CORE_disconnect (occ->ch);
1799   if (NULL != occ->ghh)
1800     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1801   if (NULL != occ->p1th)
1802     GNUNET_TRANSPORT_disconnect (occ->p1th);
1803   if (NULL != occ->p2th)
1804     GNUNET_TRANSPORT_disconnect (occ->p2th);
1805   GNUNET_free (occ);
1806 }
1807
1808
1809 /**
1810  * Task which will be run when overlay connect request has been timed out
1811  *
1812  * @param 
1813  * @return 
1814  */
1815 static void
1816 timeout_overlay_connect (void *cls,
1817                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1818 {
1819   struct OverlayConnectContext *occ = cls;
1820
1821   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1822   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
1823   GNUNET_SERVER_client_drop (occ->client);
1824   occ_cleanup (occ, tc);
1825 }
1826
1827
1828
1829 /**
1830  * Function called to notify transport users that another
1831  * peer connected to us.
1832  *
1833  * @param cls closure
1834  * @param new_peer the peer that connected
1835  * @param ats performance data
1836  * @param ats_count number of entries in ats (excluding 0-termination)
1837  */
1838 static void 
1839 overlay_connect_notify (void *cls,
1840                         const struct GNUNET_PeerIdentity * new_peer,
1841                         const struct GNUNET_ATS_Information * ats,
1842                         unsigned int ats_count)
1843 {
1844   struct OverlayConnectContext *occ = cls;
1845   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
1846   char *new_peer_str;
1847   char *other_peer_str;
1848
1849   LOG_DEBUG ("Overlay connect notify\n");
1850   if (0 == memcmp (new_peer, &occ->peer_identity, 
1851                    sizeof (struct GNUNET_PeerIdentity)))
1852     return;
1853   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
1854   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
1855   if (0 != memcmp (new_peer, &occ->other_peer_identity,
1856                    sizeof (struct GNUNET_PeerIdentity)))
1857   {
1858     LOG_DEBUG ("Unexpected peer %4s connected to peer %4s\n",
1859                new_peer_str, other_peer_str);
1860     GNUNET_free (new_peer_str);
1861     GNUNET_free (other_peer_str);
1862     return;
1863   }
1864   LOG_DEBUG ("Peer %4s connected to peer %4s\n", new_peer_str, other_peer_str);
1865   GNUNET_free (new_peer_str);
1866   GNUNET_free (other_peer_str);
1867   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1868   {
1869     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1870     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
1871   }
1872   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
1873   GNUNET_SCHEDULER_cancel (occ->timeout_task);
1874   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1875   GNUNET_free_non_null (occ->emsg);
1876   occ->emsg = NULL;
1877   GNUNET_TRANSPORT_disconnect (occ->p1th);
1878   occ->p1th = NULL;
1879   /* Peer 1 has connected connect to peer2 - now send overlay connect success message */
1880   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
1881   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
1882   msg->header.size = htons (sizeof (struct
1883                                     GNUNET_TESTBED_ConnectionEventMessage));
1884   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
1885   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
1886   msg->peer1 = htonl (occ->peer->id);
1887   msg->peer2 = htonl (occ->other_peer->id);
1888   msg->operation_id = GNUNET_htonll (occ->op_id);
1889   queue_message (occ->client, &msg->header);
1890   GNUNET_SERVER_client_drop (occ->client);
1891   GNUNET_SCHEDULER_add_now (&occ_cleanup, occ);
1892 }
1893
1894
1895 static void
1896 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1897 {
1898   struct OverlayConnectContext *occ = cls;
1899   char *other_peer_str;
1900
1901   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
1902   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1903     return;
1904   GNUNET_assert (NULL != occ->hello);
1905   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
1906   LOG_DEBUG ("Offering HELLO of %s to %s\n", other_peer_str, GNUNET_i2s (&occ->peer_identity));
1907   GNUNET_free (other_peer_str);
1908   GNUNET_TRANSPORT_offer_hello (occ->p1th, occ->hello, NULL, NULL);
1909   GNUNET_TRANSPORT_try_connect (occ->p1th, &occ->other_peer_identity);
1910   occ->send_hello_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1911                                                        &send_hello, occ);
1912 }
1913
1914 /**
1915  * Test for checking whether HELLO message is empty
1916  *
1917  * @param cls empty flag to set
1918  * @param address the HELLO
1919  * @param expiration expiration of the HELLO
1920  * @return 
1921  */
1922 static int
1923 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
1924               struct GNUNET_TIME_Absolute expiration)
1925 {
1926   int *empty = cls;
1927
1928   *empty = GNUNET_NO;
1929   return GNUNET_OK;
1930 }
1931
1932
1933 /**
1934  * Function called whenever there is an update to the
1935  * HELLO of peers in the OverlayConnectClosure
1936  *
1937  * @param cls closure
1938  * @param hello our updated HELLO
1939  */
1940 static void 
1941 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
1942 {
1943   struct OverlayConnectContext *occ = cls;
1944   int empty;
1945   uint16_t msize;
1946   
1947   msize = ntohs (hello->size);
1948   if (msize < 0)
1949   {
1950     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1951                 "HELLO message of peer %s is of size 0\n",
1952                 &occ->other_peer_identity);
1953     return;
1954   }
1955   empty = GNUNET_YES;
1956   (void) 
1957     GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *) hello,
1958                                     GNUNET_NO, &test_address, &empty);
1959   if (GNUNET_YES == empty)
1960   {
1961     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->other_peer_identity));
1962     return;
1963   }
1964   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->other_peer_identity));
1965   occ->hello = GNUNET_malloc (msize);
1966   memcpy (occ->hello, hello, msize);
1967   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1968   occ->ghh = NULL;
1969   GNUNET_TRANSPORT_disconnect (occ->p2th);
1970   occ->p2th = NULL;
1971   GNUNET_free_non_null (occ->emsg);  
1972   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
1973   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
1974 }
1975
1976
1977 /**
1978  * Function called after GNUNET_CORE_connect has succeeded (or failed
1979  * for good).  Note that the private key of the peer is intentionally
1980  * not exposed here; if you need it, your process should try to read
1981  * the private key file directly (which should work if you are
1982  * authorized...).
1983  *
1984  * @param cls closure
1985  * @param server handle to the server, NULL if we failed
1986  * @param my_identity ID of this peer, NULL if we failed
1987  */
1988 static void 
1989 core_startup_cb (void *cls, struct GNUNET_CORE_Handle * server,
1990                  const struct GNUNET_PeerIdentity *my_identity)
1991 {
1992   struct OverlayConnectContext *occ = cls;
1993
1994   GNUNET_free_non_null (occ->emsg);
1995   occ->emsg = NULL;
1996   memcpy (&occ->peer_identity, my_identity, sizeof (struct GNUNET_PeerIdentity));
1997   occ->p1th =
1998     GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg, 
1999                               &occ->peer_identity, NULL, NULL, NULL, NULL);
2000   /* Connect to the transport of 2nd peer and get its HELLO message */
2001   GNUNET_TESTING_peer_get_identity (occ->other_peer->details.local.peer,
2002                                     &occ->other_peer_identity);
2003   occ->p2th = 
2004     GNUNET_TRANSPORT_connect (occ->other_peer->details.local.cfg,
2005                               &occ->other_peer_identity,
2006                               NULL, NULL, NULL, NULL);
2007   if ((NULL == occ->p1th) || (NULL == occ->p2th))
2008   {
2009     occ->emsg = GNUNET_strdup ("Cannot connect to TRANSPORTs of peers");
2010     goto send_failure;
2011   }
2012   LOG_DEBUG ("Acquiring HELLO of peer %s\n", GNUNET_i2s
2013              (&occ->other_peer_identity));
2014   occ->emsg = GNUNET_strdup ("Timeout while acquiring HELLO message");
2015   occ->ghh = GNUNET_TRANSPORT_get_hello (occ->p2th, &hello_update_cb, occ);
2016   return;
2017
2018  send_failure:
2019   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2020   occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);  
2021 }
2022
2023
2024 /**
2025  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
2026  *
2027  * @param cls NULL
2028  * @param client identification of the client
2029  * @param message the actual message
2030  */
2031 static void 
2032 handle_overlay_connect (void *cls,
2033                         struct GNUNET_SERVER_Client *client,
2034                         const struct GNUNET_MessageHeader *message)
2035 {
2036   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
2037   struct OverlayConnectContext *occ;
2038   struct GNUNET_CORE_MessageHandler no_handlers[] = {
2039     {NULL, 0, 0}
2040   };
2041   uint32_t p1;
2042   uint32_t p2;
2043
2044   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
2045   p1 = ntohl (msg->peer1);
2046   p2 = ntohl (msg->peer2);
2047   GNUNET_assert (p1 < peer_list_size);
2048   GNUNET_assert (NULL != peer_list[p1]);
2049   GNUNET_assert (p2 < peer_list_size);
2050   GNUNET_assert (NULL != peer_list[p2]);
2051   /* FIXME: Add cases where we have to forward overlay connect message to sub
2052      controllers */
2053   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
2054   GNUNET_SERVER_client_keep (client);
2055   occ->client = client;
2056   occ->state = OCC_STATE_INIT;
2057   occ->peer = peer_list[p1];
2058   occ->other_peer = peer_list[p2];
2059   occ->op_id = GNUNET_ntohll (msg->operation_id);
2060   occ->timeout_task =
2061     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2062                                   (GNUNET_TIME_UNIT_SECONDS, 30),
2063                                   &timeout_overlay_connect, occ);   
2064   /* Connect to the core of 1st peer and wait for the 2nd peer to connect */
2065   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
2066   occ->ch = 
2067     GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
2068                          &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
2069                          GNUNET_NO, no_handlers);
2070   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2071 }
2072
2073
2074 /**
2075  * Iterator over hash map entries.
2076  *
2077  * @param cls closure
2078  * @param key current key code
2079  * @param value value in the hash map
2080  * @return GNUNET_YES if we should continue to
2081  *         iterate,
2082  *         GNUNET_NO if not.
2083  */
2084 static int 
2085 ss_map_free_iterator (void *cls,
2086                       const struct GNUNET_HashCode * key, void *value)
2087 {
2088   struct SharedService *ss = value;
2089
2090   GNUNET_assert (GNUNET_YES ==
2091                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
2092   GNUNET_free (ss->name);
2093   GNUNET_free (ss);
2094   return GNUNET_YES;
2095 }
2096
2097
2098 /**
2099  * Task to clean up and shutdown nicely
2100  *
2101  * @param cls NULL
2102  * @param tc the TaskContext from scheduler
2103  */
2104 static void
2105 shutdown_task (void *cls,
2106                const struct GNUNET_SCHEDULER_TaskContext *tc)
2107 {
2108   struct LCFContextQueue *lcfq;
2109   uint32_t id;
2110
2111   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
2112   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
2113   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
2114                                                 NULL);
2115   GNUNET_CONTAINER_multihashmap_destroy (ss_map);  
2116   if (NULL != lcfq_head)
2117   {
2118     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
2119     {
2120       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
2121       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
2122     }
2123     if (NULL != lcfq_head->lcf->rhandle)
2124       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
2125   }
2126   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2127   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
2128   {
2129     GNUNET_free (lcfq->lcf->sxcfg);
2130     GNUNET_free (lcfq->lcf);
2131     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
2132     GNUNET_free (lcfq);
2133   }
2134   /* Clear peer list */
2135   for (id = 0; id < peer_list_size; id++)
2136     if (NULL != peer_list[id])
2137     {
2138       GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
2139       GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
2140       GNUNET_free (peer_list[id]);
2141     }
2142   GNUNET_free_non_null (peer_list);
2143   /* Clear host list */
2144   for (id = 0; id < host_list_size; id++)
2145     if (NULL != host_list[id])
2146       GNUNET_TESTBED_host_destroy (host_list[id]);
2147   GNUNET_free_non_null (host_list);
2148   /* Clear route list */
2149   for (id = 0; id < route_list_size; id++)
2150     if (NULL != route_list[id])
2151       GNUNET_free (route_list[id]);
2152   GNUNET_free_non_null (route_list);
2153   /* Clear slave_list */
2154   for (id = 0; id < slave_list_size; id++)
2155     if (NULL != slave_list[id])
2156     {
2157       GNUNET_assert (NULL != slave_list[id]->controller);
2158       GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
2159       if (NULL != slave_list[id]->controller_proc)
2160         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
2161     }
2162   if (NULL != master_context)
2163   {  
2164     GNUNET_free_non_null (master_context->master_ip);
2165     if (NULL != master_context->system)
2166       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
2167     GNUNET_free (master_context);
2168     master_context = NULL;
2169   }
2170 }
2171
2172
2173 /**
2174  * Callback for client disconnect
2175  *
2176  * @param cls NULL
2177  * @param client the client which has disconnected
2178  */
2179 static void
2180 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
2181 {
2182   if (NULL == master_context)
2183     return;
2184   if (client == master_context->client)
2185   {
2186     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
2187     GNUNET_SERVER_client_drop (client);
2188     /* should not be needed as we're terminated by failure to read
2189        from stdin, but if stdin fails for some reason, this shouldn't 
2190        hurt for now --- might need to revise this later if we ever
2191        decide that master connections might be temporarily down 
2192        for some reason */
2193     //GNUNET_SCHEDULER_shutdown ();
2194   }
2195 }
2196
2197
2198 /**
2199  * Testbed setup
2200  *
2201  * @param cls closure
2202  * @param server the initialized server
2203  * @param cfg configuration to use
2204  */
2205 static void 
2206 testbed_run (void *cls,
2207              struct GNUNET_SERVER_Handle *server,
2208              const struct GNUNET_CONFIGURATION_Handle *cfg)
2209 {
2210   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
2211     {
2212       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
2213       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
2214       {&handle_configure_shared_service, NULL,
2215        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
2216       {&handle_link_controllers, NULL,
2217        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
2218       {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
2219       {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
2220        sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
2221       {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
2222        sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
2223       {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
2224        sizeof (struct GNUNET_TESTBED_PeerStopMessage)},      
2225       {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
2226        sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
2227       {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
2228        sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
2229       {NULL}
2230     };
2231
2232   GNUNET_SERVER_add_handlers (server,
2233                               message_handlers);
2234   GNUNET_SERVER_disconnect_notify (server,
2235                                    &client_disconnect_cb,
2236                                    NULL);
2237   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
2238   shutdown_task_id = 
2239     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2240                                   &shutdown_task,
2241                                   NULL);
2242   LOG_DEBUG ("Testbed startup complete\n");
2243 }
2244
2245
2246 /**
2247  * The starting point of execution
2248  */
2249 int main (int argc, char *const *argv)
2250 {
2251   //sleep (30);                 /* Debugging */
2252   return
2253     (GNUNET_OK ==
2254      GNUNET_SERVICE_run (argc,
2255                          argv,
2256                          "testbed",
2257                          GNUNET_SERVICE_OPTION_NONE,
2258                          &testbed_run,
2259                          NULL)) ? 0 : 1;
2260 }