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