stop peer before destroying it
[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, 60)
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    * Our host id according to this context
85    */
86   uint32_t host_id;
87 };
88
89
90 /**
91  * The message queue for sending messages to clients
92  */
93 struct MessageQueue
94 {
95   /**
96    * The message to be sent
97    */
98   struct GNUNET_MessageHeader *msg;
99
100   /**
101    * The client to send the message to
102    */
103   struct GNUNET_SERVER_Client *client;
104
105   /**
106    * next pointer for DLL
107    */
108   struct MessageQueue *next;
109
110   /**
111    * prev pointer for DLL
112    */
113   struct MessageQueue *prev;
114 };
115
116
117 /**
118  * The structure for identifying a shared service
119  */
120 struct SharedService
121 {
122   /**
123    * The name of the shared service
124    */
125   char *name;
126
127   /**
128    * Number of shared peers per instance of the shared service
129    */
130   uint32_t num_shared;
131
132   /**
133    * Number of peers currently sharing the service
134    */
135   uint32_t num_sharing;
136 };
137
138
139 /**
140  * A routing entry
141  */
142 struct Route
143 {
144   /**
145    * destination host
146    */
147   uint32_t dest;
148
149   /**
150    * The destination host is reachable thru
151    */
152   uint32_t thru;
153 };
154
155
156 /**
157  * Context information used while linking controllers
158  */
159 struct LinkControllersContext;
160
161
162 /**
163  * A DLL of host registrations to be made
164  */
165 struct HostRegistration
166 {
167   /**
168    * next registration in the DLL
169    */
170   struct HostRegistration *next;
171
172   /**
173    * previous registration in the DLL
174    */
175   struct HostRegistration *prev;
176
177   /**
178    * The callback to call after this registration's status is available
179    */
180   GNUNET_TESTBED_HostRegistrationCompletion cb;
181
182   /**
183    * The closure for the above callback
184    */
185   void *cb_cls;
186
187   /**
188    * The host that has to be registered
189    */
190   struct GNUNET_TESTBED_Host *host;
191 };
192
193
194 /**
195  * This context information will be created for each host that is registered at
196  * slave controllers during overlay connects.
197  */
198 struct RegisteredHostContext
199 {
200   /**
201    * The host which is being registered
202    */
203   struct GNUNET_TESTBED_Host *reg_host;
204
205   /**
206    * The host of the controller which has to connect to the above rhost
207    */
208   struct GNUNET_TESTBED_Host *host;
209
210   /**
211    * The gateway to which this operation is forwarded to
212    */
213   struct Slave *gateway;
214
215   /**
216    * The gateway through which peer2's controller can be reached
217    */
218   struct Slave *gateway2;
219
220   /**
221    * Handle for sub-operations
222    */
223   struct GNUNET_TESTBED_Operation *sub_op;
224
225   /**
226    * The client which initiated the link controller operation
227    */
228   struct GNUNET_SERVER_Client *client;
229
230   /**
231    * Head of the ForwardedOverlayConnectContext DLL
232    */
233   struct ForwardedOverlayConnectContext *focc_dll_head;
234
235   /**
236    * Tail of the ForwardedOverlayConnectContext DLL
237    */
238   struct ForwardedOverlayConnectContext *focc_dll_tail;
239   
240   /**
241    * Enumeration of states for this context
242    */
243   enum RHCState {
244
245     /**
246      * The initial state
247      */
248     RHC_INIT = 0,
249
250     /**
251      * State where we attempt to get peer2's controller configuration
252      */
253     RHC_GET_CFG,
254
255     /**
256      * State where we attempt to link the controller of peer 1 to the controller
257      * of peer2
258      */
259     RHC_LINK,
260
261     /**
262      * State where we attempt to do the overlay connection again
263      */
264     RHC_OL_CONNECT
265     
266   } state;
267
268 };
269
270
271 /**
272  * Function to generate the hashcode corresponding to a RegisteredHostContext
273  *
274  * @param reg_host the host which is being registered in RegisteredHostContext
275  * @param host the host of the controller which has to connect to the above rhost
276  * @return the hashcode
277  */
278 static struct GNUNET_HashCode
279 hash_hosts (struct GNUNET_TESTBED_Host *reg_host,
280             struct GNUNET_TESTBED_Host *host)
281 {
282   struct GNUNET_HashCode hash;
283   uint32_t host_ids[2];
284
285   host_ids[0] = GNUNET_TESTBED_host_get_id_ (reg_host);
286   host_ids[1] = GNUNET_TESTBED_host_get_id_ (host);
287   GNUNET_CRYPTO_hash (host_ids, sizeof (host_ids), &hash);
288   return hash;
289 }
290
291
292 /**
293  * Structure representing a connected(directly-linked) controller
294  */
295 struct Slave
296 {
297   /**
298    * The controller process handle if we had started the controller
299    */
300   struct GNUNET_TESTBED_ControllerProc *controller_proc;
301
302   /**
303    * The controller handle
304    */
305   struct GNUNET_TESTBED_Controller *controller;
306
307   /**
308    * The configuration of the slave. Cannot be NULL
309    */
310   struct GNUNET_CONFIGURATION_Handle *cfg;
311
312   /**
313    * handle to lcc which is associated with this slave startup. Should be set to
314    * NULL when the slave has successfully started up
315    */
316   struct LinkControllersContext *lcc;
317
318   /**
319    * Head of the host registration DLL
320    */
321   struct HostRegistration *hr_dll_head;
322
323   /**
324    * Tail of the host registration DLL
325    */
326   struct HostRegistration *hr_dll_tail;
327
328   /**
329    * The current host registration handle
330    */
331   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
332
333   /**
334    * Hashmap to hold Registered host contexts
335    */
336   struct GNUNET_CONTAINER_MultiHashMap *reghost_map;
337
338   /**
339    * The id of the host this controller is running on
340    */
341   uint32_t host_id;
342
343 };
344
345
346 /**
347  * States of LCFContext
348  */
349 enum LCFContextState
350 {
351   /**
352    * The Context has been initialized; Nothing has been done on it
353    */
354   INIT,
355
356   /**
357    * Delegated host has been registered at the forwarding controller
358    */
359   DELEGATED_HOST_REGISTERED,
360   
361   /**
362    * The slave host has been registred at the forwarding controller
363    */
364   SLAVE_HOST_REGISTERED,
365   
366   /**
367    * The context has been finished (may have error)
368    */
369   FINISHED
370 };
371
372
373 /**
374  * Link controllers request forwarding context
375  */
376 struct LCFContext
377 {
378   /**
379    * The gateway which will pass the link message to delegated host
380    */
381   struct Slave *gateway;
382
383   /**
384    * The controller link message that has to be forwarded to
385    */
386   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
387
388   /**
389    * The client which has asked to perform this operation
390    */
391   struct GNUNET_SERVER_Client *client;
392
393   /**
394    * The id of the operation which created this context
395    */
396   uint64_t operation_id;
397
398   /**
399    * The state of this context
400    */
401   enum LCFContextState state;
402
403   /**
404    * The delegated host
405    */
406   uint32_t delegated_host_id;
407
408   /**
409    * The slave host
410    */
411   uint32_t slave_host_id;
412
413 };
414
415
416 /**
417  * Structure of a queue entry in LCFContext request queue
418  */
419 struct LCFContextQueue
420 {
421   /**
422    * The LCFContext
423    */
424   struct LCFContext *lcf;
425
426   /**
427    * Head prt for DLL
428    */
429   struct LCFContextQueue *next;
430
431   /**
432    * Tail ptr for DLL
433    */
434   struct LCFContextQueue *prev;
435 };
436
437
438 /**
439  * A peer
440  */
441 struct Peer
442 {
443   union
444   {
445     struct
446     {
447       /**
448        * The peer handle from testing API
449        */
450       struct GNUNET_TESTING_Peer *peer;
451
452       /**
453        * The modified (by GNUNET_TESTING_peer_configure) configuration this
454        * peer is configured with
455        */
456       struct GNUNET_CONFIGURATION_Handle *cfg;
457       
458       /**
459        * Is the peer running
460        */
461       int is_running;
462
463     } local;
464
465     struct
466     {
467       /**
468        * The slave this peer is started through
469        */
470       struct Slave *slave;
471
472       /**
473        * The id of the remote host this peer is running on
474        */
475       uint32_t remote_host_id;
476
477     } remote;
478
479   } details;
480
481   /**
482    * Is this peer locally created?
483    */
484   int is_remote;
485
486   /**
487    * Our local reference id for this peer
488    */
489   uint32_t id;
490
491 };
492
493
494 /**
495  * Context information for connecting 2 peers in overlay
496  */
497 struct OverlayConnectContext
498 {
499   /**
500    * The client which has requested for overlay connection
501    */
502   struct GNUNET_SERVER_Client *client;
503
504   /**
505    * the peer which has to connect to the other peer
506    */
507   struct Peer *peer;
508
509   /**
510    * Transport handle of the first peer to get its HELLO
511    */
512   struct GNUNET_TRANSPORT_Handle *p1th;
513
514   /**
515    * Transport handle of other peer to offer first peer's HELLO
516    */
517   struct GNUNET_TRANSPORT_Handle *p2th;
518
519   /**
520    * Core handles of the first peer; used to notify when second peer connects to it
521    */
522   struct GNUNET_CORE_Handle *ch;
523
524   /**
525    * HELLO of the other peer
526    */
527   struct GNUNET_MessageHeader *hello;
528
529   /**
530    * Get hello handle to acquire HELLO of first peer
531    */
532   struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
533
534   /**
535    * The error message we send if this overlay connect operation has timed out
536    */
537   char *emsg;
538
539   /**
540    * Operation context for suboperations
541    */
542   struct OperationContext *opc;
543
544   /**
545    * Controller of peer 2; NULL if the peer is local
546    */
547   struct GNUNET_TESTBED_Controller *peer2_controller;
548
549   /**
550    * The peer identity of the first peer
551    */
552   struct GNUNET_PeerIdentity peer_identity;
553
554   /**
555    * The peer identity of the other peer
556    */
557   struct GNUNET_PeerIdentity other_peer_identity;
558
559   /**
560    * The id of the operation responsible for creating this context
561    */
562   uint64_t op_id;
563
564   /**
565    * The id of the task for sending HELLO of peer 2 to peer 1 and ask peer 1 to
566    * connect to peer 2
567    */
568   GNUNET_SCHEDULER_TaskIdentifier send_hello_task;
569
570   /**
571    * The id of the overlay connect timeout task
572    */
573   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
574
575   /**
576    * The id of peer A
577    */
578   uint32_t peer_id;
579
580   /**
581    * The id of peer B
582    */
583   uint32_t other_peer_id;
584
585   /**
586    * Number of times we tried to send hello; used to increase delay in offering
587    * hellos
588    */
589   uint16_t retries;
590 };
591
592
593 /**
594  * Context information for RequestOverlayConnect
595  * operations. RequestOverlayConnect is used when peers A, B reside on different
596  * hosts and the host controller for peer B is asked by the host controller of
597  * peer A to make peer B connect to peer A
598  */
599 struct RequestOverlayConnectContext
600 {
601   /**
602    * The transport handle of peer B
603    */
604   struct GNUNET_TRANSPORT_Handle *th;
605   
606   /**
607    * Peer A's HELLO
608    */
609   struct GNUNET_MessageHeader *hello;
610
611   /**
612    * The peer identity of peer A
613    */
614   struct GNUNET_PeerIdentity a_id;
615
616   /**
617    * Task for offering HELLO of A to B and doing try_connect
618    */
619   GNUNET_SCHEDULER_TaskIdentifier attempt_connect_task_id;
620   
621   /**
622    * Task to timeout RequestOverlayConnect
623    */
624   GNUNET_SCHEDULER_TaskIdentifier timeout_rocc_task_id;
625   
626   /**
627    * Number of times we tried to send hello; used to increase delay in offering
628    * hellos
629    */
630   uint16_t retries;
631   
632 };
633
634
635 /**
636  * Context information for operations forwarded to subcontrollers
637  */
638 struct ForwardedOperationContext
639 {
640   /**
641    * The generated operation context
642    */
643   struct OperationContext *opc;
644
645   /**
646    * The client to which we have to reply
647    */
648   struct GNUNET_SERVER_Client *client;
649
650   /**
651    * Closure pointer
652    */
653   void *cls;
654
655   /**
656    * Task ID for the timeout task
657    */
658   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
659
660   /**
661    * The id of the operation that has been forwarded
662    */
663   uint64_t operation_id;
664
665 };
666
667
668 /**
669  * Context information used while linking controllers
670  */
671 struct LinkControllersContext
672 {
673   /**
674    * The client which initiated the link controller operation
675    */
676   struct GNUNET_SERVER_Client *client;
677
678   /**
679    * The ID of the operation
680    */
681   uint64_t operation_id;
682
683 };
684
685
686 /**
687  * Context information to used during operations which forward the overlay
688  * connect message
689  */
690 struct ForwardedOverlayConnectContext
691 {
692   /**
693    * next ForwardedOverlayConnectContext in the DLL
694    */
695   struct ForwardedOverlayConnectContext *next;
696
697   /**
698    * previous ForwardedOverlayConnectContext in the DLL
699    */
700   struct ForwardedOverlayConnectContext *prev;
701
702   /**
703    * A copy of the original overlay connect message
704    */
705   struct GNUNET_MessageHeader *orig_msg;
706
707   /**
708    * The id of the operation which created this context information
709    */
710   uint64_t operation_id;
711
712   /**
713    * the id of peer 1
714    */
715   uint32_t peer1;
716   
717   /**
718    * The id of peer 2
719    */
720   uint32_t peer2;
721   
722   /**
723    * Id of the host where peer2 is running
724    */
725   uint32_t peer2_host_id;
726 };
727
728
729
730 /**
731  * The master context; generated with the first INIT message
732  */
733 static struct Context *master_context;
734
735 /**
736  * Our hostname; we give this to all the peers we start
737  */
738 static char *hostname;
739
740
741 /***********/
742 /* Handles */
743 /***********/
744
745 /**
746  * Our configuration
747  */
748 static struct GNUNET_CONFIGURATION_Handle *our_config;
749
750 /**
751  * Current Transmit Handle; NULL if no notify transmit exists currently
752  */
753 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
754
755 /****************/
756 /* Lists & Maps */
757 /****************/
758
759 /**
760  * The head for the LCF queue
761  */
762 static struct LCFContextQueue *lcfq_head;
763
764 /**
765  * The tail for the LCF queue
766  */
767 static struct LCFContextQueue *lcfq_tail;
768
769 /**
770  * The message queue head
771  */
772 static struct MessageQueue *mq_head;
773
774 /**
775  * The message queue tail
776  */
777 static struct MessageQueue *mq_tail;
778
779 /**
780  * Array of hosts
781  */
782 static struct GNUNET_TESTBED_Host **host_list;
783
784 /**
785  * A list of routes
786  */
787 static struct Route **route_list;
788
789 /**
790  * A list of directly linked neighbours
791  */
792 static struct Slave **slave_list;
793
794 /**
795  * A list of peers we know about
796  */
797 static struct Peer **peer_list;
798
799 /**
800  * The hashmap of shared services
801  */
802 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
803
804 /**
805  * The event mask for the events we listen from sub-controllers
806  */
807 static uint64_t event_mask;
808
809 /**
810  * The size of the host list
811  */
812 static uint32_t host_list_size;
813
814 /**
815  * The size of the route list
816  */
817 static uint32_t route_list_size;
818
819 /**
820  * The size of directly linked neighbours list
821  */
822 static uint32_t slave_list_size;
823
824 /**
825  * The size of the peer list
826  */
827 static uint32_t peer_list_size;
828
829 /*********/
830 /* Tasks */
831 /*********/
832
833 /**
834  * The lcf_task handle
835  */
836 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
837
838 /**
839  * The shutdown task handle
840  */
841 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
842
843
844 /**
845  * Function called to notify a client about the connection begin ready to queue
846  * more data.  "buf" will be NULL and "size" zero if the connection was closed
847  * for writing in the meantime.
848  *
849  * @param cls NULL
850  * @param size number of bytes available in buf
851  * @param buf where the callee should write the message
852  * @return number of bytes written to buf
853  */
854 static size_t
855 transmit_ready_notify (void *cls, size_t size, void *buf)
856 {
857   struct MessageQueue *mq_entry;
858
859   transmit_handle = NULL;
860   mq_entry = mq_head;
861   GNUNET_assert (NULL != mq_entry);
862   if (0 == size)
863     return 0;
864   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
865   size = ntohs (mq_entry->msg->size);
866   memcpy (buf, mq_entry->msg, size);
867   GNUNET_free (mq_entry->msg);
868   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
869   GNUNET_free (mq_entry);
870   mq_entry = mq_head;
871   if (NULL != mq_entry)
872     transmit_handle =
873         GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
874                                              ntohs (mq_entry->msg->size),
875                                              GNUNET_TIME_UNIT_FOREVER_REL,
876                                              &transmit_ready_notify, NULL);
877   return size;
878 }
879
880
881 /**
882  * Queues a message in send queue for sending to the service
883  *
884  * @param client the client to whom the queued message has to be sent
885  * @param msg the message to queue
886  */
887 static void
888 queue_message (struct GNUNET_SERVER_Client *client,
889                struct GNUNET_MessageHeader *msg)
890 {
891   struct MessageQueue *mq_entry;
892   uint16_t type;
893   uint16_t size;
894
895   type = ntohs (msg->type);
896   size = ntohs (msg->size);
897   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
898                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));
899   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
900   mq_entry->msg = msg;
901   mq_entry->client = client;
902   LOG_DEBUG ("Queueing message of type %u, size %u for sending\n", type,
903              ntohs (msg->size));
904   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
905   if (NULL == transmit_handle)
906     transmit_handle =
907         GNUNET_SERVER_notify_transmit_ready (client, size,
908                                              GNUNET_TIME_UNIT_FOREVER_REL,
909                                              &transmit_ready_notify, NULL);
910 }
911
912
913 /**
914  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
915  *
916  * @param ptr the memory block to realloc
917  * @param size the size of ptr
918  * @param new_size the size to which ptr has to be realloc'ed
919  * @return the newly reallocated memory block
920  */
921 static void *
922 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
923 {
924   ptr = GNUNET_realloc (ptr, new_size);
925   if (new_size > size)
926     (void) memset (ptr + size, 0, new_size - size);
927   return ptr;
928 }
929
930
931 /**
932  * Function to add a host to the current list of known hosts
933  *
934  * @param host the host to add
935  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
936  *           already in use
937  */
938 static int
939 host_list_add (struct GNUNET_TESTBED_Host *host)
940 {
941   uint32_t host_id;
942   uint32_t orig_size;
943
944   host_id = GNUNET_TESTBED_host_get_id_ (host);
945   orig_size = host_list_size;  
946   if (host_list_size <= host_id)
947   {
948     while (host_list_size <= host_id)
949       host_list_size += LIST_GROW_STEP;
950     host_list =
951         TESTBED_realloc (host_list,
952                          sizeof (struct GNUNET_TESTBED_Host *) * orig_size,
953                          sizeof (struct GNUNET_TESTBED_Host *)
954                          * host_list_size);
955   }
956   if (NULL != host_list[host_id])
957   {
958     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
959     return GNUNET_SYSERR;
960   }
961   host_list[host_id] = host;
962   return GNUNET_OK;
963 }
964
965
966 /**
967  * Adds a route to the route list
968  *
969  * @param route the route to add
970  */
971 static void
972 route_list_add (struct Route *route)
973 {
974   uint32_t orig_size;
975
976   orig_size = route_list_size;  
977   if (route->dest >= route_list_size)
978   {
979     while (route->dest >= route_list_size)
980       route_list_size += LIST_GROW_STEP;
981     route_list =
982         TESTBED_realloc (route_list,
983                          sizeof (struct Route *) * orig_size,
984                          sizeof (struct Route *) * route_list_size);
985   }
986   GNUNET_assert (NULL == route_list[route->dest]);
987   route_list[route->dest] = route;
988 }
989
990
991 /**
992  * Adds a slave to the slave array
993  *
994  * @param slave the slave controller to add
995  */
996 static void
997 slave_list_add (struct Slave *slave)
998 {
999   uint32_t orig_size;
1000
1001   orig_size = slave_list_size;  
1002   if (slave->host_id >= slave_list_size)
1003   {
1004     while (slave->host_id >= slave_list_size)
1005       slave_list_size += LIST_GROW_STEP;
1006     slave_list =
1007         TESTBED_realloc (slave_list, sizeof (struct Slave *) * orig_size,
1008                          sizeof (struct Slave *) * slave_list_size);
1009   }
1010   GNUNET_assert (NULL == slave_list[slave->host_id]);
1011   slave_list[slave->host_id] = slave;
1012 }
1013
1014
1015 /**
1016  * Adds a peer to the peer array
1017  *
1018  * @param peer the peer to add
1019  */
1020 static void
1021 peer_list_add (struct Peer *peer)
1022 {
1023   uint32_t orig_size;
1024
1025   orig_size = peer_list_size;
1026   if (peer->id >= peer_list_size)
1027   {
1028     while (peer->id >= peer_list_size)
1029       peer_list_size += LIST_GROW_STEP;
1030     peer_list =
1031         TESTBED_realloc (peer_list, sizeof (struct Peer *) * orig_size,
1032                          sizeof (struct Peer *) * peer_list_size);
1033   }  
1034   GNUNET_assert (NULL == peer_list[peer->id]);
1035   peer_list[peer->id] = peer;
1036 }
1037
1038
1039 /**
1040  * Removes a the give peer from the peer array
1041  *
1042  * @param peer the peer to be removed
1043  */
1044 static void
1045 peer_list_remove (struct Peer *peer)
1046 {
1047   uint32_t id;
1048   uint32_t orig_size;
1049
1050   peer_list[peer->id] = NULL;
1051   orig_size = peer_list_size;
1052   while (peer_list_size >= LIST_GROW_STEP)
1053   {
1054     for (id = peer_list_size - 1;
1055          (id >= peer_list_size - LIST_GROW_STEP) && (id != UINT32_MAX); id--)
1056       if (NULL != peer_list[id])
1057         break;
1058     if (id != ((peer_list_size - LIST_GROW_STEP) - 1))
1059       break;
1060     peer_list_size -= LIST_GROW_STEP;
1061   }
1062   if (orig_size == peer_list_size)
1063     return;
1064   peer_list =
1065       GNUNET_realloc (peer_list, sizeof (struct Peer *) * peer_list_size);
1066 }
1067
1068
1069 /**
1070  * Finds the route with directly connected host as destination through which
1071  * the destination host can be reached
1072  *
1073  * @param host_id the id of the destination host
1074  * @return the route with directly connected destination host; NULL if no route
1075  *           is found
1076  */
1077 static struct Route *
1078 find_dest_route (uint32_t host_id)
1079 {
1080   struct Route *route;
1081
1082   if (route_list_size <= host_id)
1083     return NULL;
1084   while (NULL != (route = route_list[host_id]))
1085   {
1086     if (route->thru == master_context->host_id)
1087       break;
1088     host_id = route->thru;
1089   }
1090   return route;
1091 }
1092
1093
1094 /**
1095  * Routes message to a host given its host_id
1096  *
1097  * @param host_id the id of the destination host
1098  * @param msg the message to be routed
1099  */
1100 static void
1101 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
1102 {
1103   GNUNET_break (0);
1104 }
1105
1106
1107 /**
1108  * Send operation failure message to client
1109  *
1110  * @param client the client to which the failure message has to be sent to
1111  * @param operation_id the id of the failed operation
1112  * @param emsg the error message; can be NULL
1113  */
1114 static void
1115 send_operation_fail_msg (struct GNUNET_SERVER_Client *client,
1116                          uint64_t operation_id, const char *emsg)
1117 {
1118   struct GNUNET_TESTBED_OperationFailureEventMessage *msg;
1119   uint16_t msize;
1120   uint16_t emsg_len;
1121
1122   msize = sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
1123   emsg_len = (NULL == emsg) ? 0 : strlen (emsg) + 1;
1124   msize += emsg_len;
1125   msg = GNUNET_malloc (msize);
1126   msg->header.size = htons (msize);
1127   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONFAILEVENT);
1128   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1129   msg->operation_id = GNUNET_htonll (operation_id);
1130   if (0 != emsg_len)
1131     memcpy (&msg[1], emsg, emsg_len);
1132   queue_message (client, &msg->header);
1133 }
1134
1135
1136 /**
1137  * Function to send generic operation success message to given client
1138  *
1139  * @param client the client to send the message to
1140  * @param operation_id the id of the operation which was successful
1141  */
1142 static void
1143 send_operation_success_msg (struct GNUNET_SERVER_Client *client,
1144                             uint64_t operation_id)
1145 {
1146   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg;
1147   uint16_t msize;
1148
1149   msize = sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1150   msg = GNUNET_malloc (msize);
1151   msg->header.size = htons (msize);
1152   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1153   msg->operation_id = GNUNET_htonll (operation_id);
1154   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1155   queue_message (client, &msg->header);
1156 }
1157
1158
1159 /**
1160  * Callback which will be called to after a host registration succeeded or failed
1161  *
1162  * @param cls the handle to the slave at which the registration is completed
1163  * @param emsg the error message; NULL if host registration is successful
1164  */
1165 static void 
1166 hr_completion (void *cls, const char *emsg);
1167
1168
1169 /**
1170  * Attempts to register the next host in the host registration queue
1171  *
1172  * @param slave the slave controller whose host registration queue is checked
1173  *          for host registrations
1174  */
1175 static void
1176 register_next_host (struct Slave *slave)
1177 {
1178   struct HostRegistration *hr;
1179   
1180   hr = slave->hr_dll_head;
1181   GNUNET_assert (NULL != hr);
1182   GNUNET_assert (NULL == slave->rhandle);
1183   LOG (GNUNET_ERROR_TYPE_DEBUG,
1184        "Registering host %u at %u\n",
1185        GNUNET_TESTBED_host_get_id_ (hr->host),
1186        GNUNET_TESTBED_host_get_id_ (host_list[slave->host_id]));
1187   slave->rhandle = GNUNET_TESTBED_register_host (slave->controller,
1188                                                  hr->host,
1189                                                  hr_completion,
1190                                                  slave);
1191 }
1192
1193
1194 /**
1195  * Callback which will be called to after a host registration succeeded or failed
1196  *
1197  * @param cls the handle to the slave at which the registration is completed
1198  * @param emsg the error message; NULL if host registration is successful
1199  */
1200 static void 
1201 hr_completion (void *cls, const char *emsg)
1202 {
1203   struct Slave *slave = cls;
1204   struct HostRegistration *hr;
1205
1206   slave->rhandle = NULL;
1207   hr = slave->hr_dll_head;
1208   GNUNET_assert (NULL != hr);
1209   LOG (GNUNET_ERROR_TYPE_DEBUG,
1210        "Registering host %u at %u successful\n",
1211        GNUNET_TESTBED_host_get_id_ (hr->host),
1212        GNUNET_TESTBED_host_get_id_ (host_list[slave->host_id]));
1213   GNUNET_CONTAINER_DLL_remove (slave->hr_dll_head,
1214                                slave->hr_dll_tail,
1215                                hr);
1216   if (NULL != hr->cb)
1217     hr->cb (hr->cb_cls, emsg);
1218   GNUNET_free (hr);
1219   if (NULL != slave->hr_dll_head)
1220     register_next_host (slave);
1221 }
1222
1223
1224 /**
1225  * Adds a host registration's request to a slave's registration queue
1226  *
1227  * @param slave the slave controller at which the given host has to be
1228  *          registered 
1229  * @param cb the host registration completion callback
1230  * @param cb_cls the closure for the host registration completion callback
1231  * @param host the host which has to be registered
1232  */
1233 static void
1234 queue_host_registration (struct Slave *slave,
1235                          GNUNET_TESTBED_HostRegistrationCompletion cb,
1236                          void *cb_cls,
1237                          struct GNUNET_TESTBED_Host *host)
1238 {
1239   struct HostRegistration *hr;
1240   int call_register;
1241
1242   LOG (GNUNET_ERROR_TYPE_DEBUG,
1243        "Queueing host registration for host %u at %u\n",
1244        GNUNET_TESTBED_host_get_id_ (host),
1245        GNUNET_TESTBED_host_get_id_ (host_list[slave->host_id]));
1246   hr = GNUNET_malloc (sizeof (struct HostRegistration));
1247   hr->cb = cb;
1248   hr->cb_cls = cb_cls;
1249   hr->host = host;
1250   call_register = (NULL == slave->hr_dll_head) ? GNUNET_YES : GNUNET_NO;
1251   GNUNET_CONTAINER_DLL_insert_tail (slave->hr_dll_head,
1252                                     slave->hr_dll_tail,
1253                                     hr);
1254   if (GNUNET_YES == call_register)
1255     register_next_host (slave);
1256 }
1257
1258
1259 /**
1260  * The  Link Controller forwarding task
1261  *
1262  * @param cls the LCFContext
1263  * @param tc the Task context from scheduler
1264  */
1265 static void
1266 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1267
1268
1269 /**
1270  * Completion callback for host registrations while forwarding Link Controller messages
1271  *
1272  * @param cls the LCFContext
1273  * @param emsg the error message; NULL if host registration is successful
1274  */
1275 static void
1276 lcf_proc_cc (void *cls, const char *emsg)
1277 {
1278   struct LCFContext *lcf = cls;
1279
1280   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1281   switch (lcf->state)
1282   {
1283   case INIT:
1284     if (NULL != emsg)
1285       goto registration_error;
1286     lcf->state = DELEGATED_HOST_REGISTERED;
1287     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1288     break;
1289   case DELEGATED_HOST_REGISTERED:
1290     if (NULL != emsg)
1291       goto registration_error;
1292     lcf->state = SLAVE_HOST_REGISTERED;
1293     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1294     break;
1295   default:
1296     GNUNET_assert (0);          /* Shouldn't reach here */
1297   }
1298   return;
1299
1300  registration_error:
1301   LOG (GNUNET_ERROR_TYPE_WARNING, "Host registration failed with message: %s\n",
1302        emsg);
1303   lcf->state = FINISHED;
1304   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1305 }
1306
1307
1308 /**
1309  * Callback to be called when forwarded link controllers operation is
1310  * successfull. We have to relay the reply msg back to the client
1311  *
1312  * @param cls ForwardedOperationContext
1313  * @param msg the peer create success message
1314  */
1315 static void
1316 forwarded_operation_reply_relay (void *cls,
1317                                  const struct GNUNET_MessageHeader *msg)
1318 {
1319   struct ForwardedOperationContext *fopc = cls;
1320   struct GNUNET_MessageHeader *dup_msg;
1321   uint16_t msize;
1322
1323   msize = ntohs (msg->size);
1324   LOG_DEBUG ("Relaying message with type: %u, size: %u\n", ntohs (msg->type),
1325              msize);
1326   dup_msg = GNUNET_malloc (msize);
1327   (void) memcpy (dup_msg, msg, msize);
1328   queue_message (fopc->client, dup_msg);
1329   GNUNET_SERVER_client_drop (fopc->client);
1330   GNUNET_SCHEDULER_cancel (fopc->timeout_task);
1331   GNUNET_free (fopc);
1332 }
1333
1334
1335 /**
1336  * Task to free resources when forwarded link controllers has been timedout
1337  *
1338  * @param cls the ForwardedOperationContext
1339  * @param tc the task context from scheduler
1340  */
1341 static void
1342 forwarded_operation_timeout (void *cls,
1343                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1344 {
1345   struct ForwardedOperationContext *fopc = cls;
1346
1347   GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
1348   LOG (GNUNET_ERROR_TYPE_WARNING, "A forwarded operation has timed out\n");
1349   send_operation_fail_msg (fopc->client, fopc->operation_id, "Timeout");
1350   GNUNET_SERVER_client_drop (fopc->client);
1351   GNUNET_free (fopc);
1352 }
1353
1354
1355 /**
1356  * The  Link Controller forwarding task
1357  *
1358  * @param cls the LCFContext
1359  * @param tc the Task context from scheduler
1360  */
1361 static void
1362 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1363 {
1364   struct LCFContext *lcf = cls;
1365   struct LCFContextQueue *lcfq;
1366   struct ForwardedOperationContext *fopc;
1367
1368   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
1369   switch (lcf->state)
1370   {
1371   case INIT:
1372     if (GNUNET_NO ==
1373         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
1374                                             lcf->gateway->controller))
1375     {
1376       queue_host_registration (lcf->gateway,
1377                                lcf_proc_cc, lcf,
1378                                host_list[lcf->delegated_host_id]);
1379     }
1380     else
1381     {
1382       lcf->state = DELEGATED_HOST_REGISTERED;
1383       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1384     }
1385     break;
1386   case DELEGATED_HOST_REGISTERED:
1387     if (GNUNET_NO ==
1388         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
1389                                             lcf->gateway->controller))
1390     {
1391       queue_host_registration (lcf->gateway,
1392                                lcf_proc_cc, lcf,
1393                                host_list[lcf->slave_host_id]);
1394     }
1395     else
1396     {
1397       lcf->state = SLAVE_HOST_REGISTERED;
1398       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1399     }
1400     break;
1401   case SLAVE_HOST_REGISTERED:
1402     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1403     fopc->client = lcf->client;
1404     fopc->operation_id = lcf->operation_id;
1405     fopc->opc =
1406         GNUNET_TESTBED_forward_operation_msg_ (lcf->gateway->controller,
1407                                                lcf->operation_id,
1408                                                &lcf->msg->header,
1409                                                &forwarded_operation_reply_relay,
1410                                                fopc);
1411     fopc->timeout_task =
1412         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1413                                       fopc);
1414     lcf->state = FINISHED;
1415     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1416     break;
1417   case FINISHED:
1418     lcfq = lcfq_head;
1419     GNUNET_assert (lcfq->lcf == lcf);
1420     GNUNET_free (lcf->msg);
1421     GNUNET_free (lcf);
1422     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1423     GNUNET_free (lcfq);
1424     if (NULL != lcfq_head)
1425       lcf_proc_task_id =
1426           GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
1427   }
1428 }
1429
1430
1431 /**
1432  * Cleans up ForwardedOverlayConnectContext
1433  *
1434  * @param focc the ForwardedOverlayConnectContext to cleanup
1435  */
1436 static void
1437 cleanup_focc (struct ForwardedOverlayConnectContext *focc)
1438 {
1439   GNUNET_free_non_null (focc->orig_msg);
1440   GNUNET_free (focc);
1441 }
1442
1443
1444 /**
1445  * Processes a forwarded overlay connect context in the queue of the given RegisteredHostContext
1446  *
1447  * @param rhc the RegisteredHostContext
1448  */
1449 static void
1450 process_next_focc (struct RegisteredHostContext *rhc);
1451
1452
1453 /**
1454  * Timeout task for cancelling a forwarded overlay connect connect
1455  *
1456  * @param cls the ForwardedOverlayConnectContext
1457  * @param tc the task context from the scheduler
1458  */
1459 static void
1460 forwarded_overlay_connect_timeout (void *cls,
1461                                    const struct GNUNET_SCHEDULER_TaskContext
1462                                    *tc)
1463 {
1464   struct ForwardedOperationContext *fopc = cls;
1465   struct RegisteredHostContext *rhc;
1466   struct ForwardedOverlayConnectContext *focc;
1467   
1468   rhc = fopc->cls;
1469   focc = rhc->focc_dll_head;
1470   GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head, rhc->focc_dll_tail, focc);
1471   cleanup_focc (focc);
1472   LOG_DEBUG ("Overlay linking between peers %u and %u failed\n",
1473              focc->peer1, focc->peer2);
1474   forwarded_operation_timeout (cls, tc);
1475   if (NULL != rhc->focc_dll_head)
1476     process_next_focc (rhc);
1477 }
1478
1479
1480 /**
1481  * Callback to be called when forwarded overlay connection operation has a reply
1482  * from the sub-controller successfull. We have to relay the reply msg back to
1483  * the client
1484  *
1485  * @param cls ForwardedOperationContext
1486  * @param msg the peer create success message
1487  */
1488 static void
1489 forwarded_overlay_connect_listener (void *cls,
1490                                     const struct GNUNET_MessageHeader *msg)
1491 {
1492   struct ForwardedOperationContext *fopc = cls;
1493   struct RegisteredHostContext *rhc;
1494   struct ForwardedOverlayConnectContext *focc;
1495   
1496   rhc = fopc->cls;
1497   forwarded_operation_reply_relay (cls, msg);
1498   focc = rhc->focc_dll_head;
1499   GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head, rhc->focc_dll_tail, focc);
1500   cleanup_focc (focc);
1501   if (NULL != rhc->focc_dll_head)
1502     process_next_focc (rhc);
1503 }
1504
1505
1506 /**
1507  * Processes a forwarded overlay connect context in the queue of the given RegisteredHostContext
1508  *
1509  * @param rhc the RegisteredHostContext
1510  */
1511 static void
1512 process_next_focc (struct RegisteredHostContext *rhc)
1513 {
1514   struct ForwardedOperationContext *fopc;
1515   struct ForwardedOverlayConnectContext *focc;
1516
1517   focc = rhc->focc_dll_head;
1518   GNUNET_assert (NULL != focc);
1519   GNUNET_assert (RHC_OL_CONNECT == rhc->state);
1520   fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1521   GNUNET_SERVER_client_keep (rhc->client);
1522   fopc->client = rhc->client;  
1523   fopc->operation_id = focc->operation_id;
1524   fopc->cls = rhc;
1525   fopc->opc =
1526         GNUNET_TESTBED_forward_operation_msg_ (rhc->gateway->controller,
1527                                                focc->operation_id, focc->orig_msg,
1528                                                &forwarded_overlay_connect_listener,
1529                                                fopc);
1530   GNUNET_free (focc->orig_msg);
1531   focc->orig_msg = NULL;
1532   fopc->timeout_task =
1533       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_overlay_connect_timeout,
1534                                     fopc);
1535 }
1536
1537
1538 /**
1539  * Callback for event from slave controllers
1540  *
1541  * @param cls struct Slave *
1542  * @param event information about the event
1543  */
1544 static void
1545 slave_event_callback (void *cls,
1546                       const struct GNUNET_TESTBED_EventInformation *event)
1547 {
1548   struct RegisteredHostContext *rhc;
1549   struct GNUNET_CONFIGURATION_Handle *cfg;
1550   struct GNUNET_TESTBED_Operation *old_op;
1551   
1552   /* We currently only get here when working on RegisteredHostContexts */
1553   GNUNET_assert (GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type);
1554   rhc = event->details.operation_finished.op_cls;
1555   GNUNET_assert (rhc->sub_op == event->details.operation_finished.operation);
1556   switch (rhc->state)
1557   {
1558   case RHC_GET_CFG:
1559     cfg = event->details.operation_finished.generic;
1560     old_op = rhc->sub_op;
1561     rhc->state = RHC_LINK;
1562     rhc->sub_op =
1563         GNUNET_TESTBED_controller_link (rhc,
1564                                         rhc->gateway->controller,
1565                                         rhc->reg_host,
1566                                         rhc->host,
1567                                         cfg,
1568                                         GNUNET_NO);
1569     GNUNET_TESTBED_operation_done (old_op);
1570     break;
1571   case RHC_LINK:
1572     LOG_DEBUG ("OL: Linking controllers successfull\n");
1573     GNUNET_TESTBED_operation_done (rhc->sub_op);
1574     rhc->sub_op = NULL;
1575     rhc->state = RHC_OL_CONNECT;
1576     process_next_focc (rhc);
1577     break;
1578   default:
1579     GNUNET_assert (0);
1580   }
1581 }
1582
1583
1584 /**
1585  * Callback to signal successfull startup of the controller process
1586  *
1587  * @param cls the handle to the slave whose status is to be found here
1588  * @param cfg the configuration with which the controller has been started;
1589  *          NULL if status is not GNUNET_OK
1590  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1591  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1592  */
1593 static void
1594 slave_status_callback (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
1595                        int status)
1596 {
1597   struct Slave *slave = cls;
1598   struct LinkControllersContext *lcc;
1599
1600   lcc = slave->lcc;
1601   if (GNUNET_SYSERR == status)
1602   {
1603     slave->controller_proc = NULL;
1604     slave_list[slave->host_id] = NULL;
1605     if (NULL != slave->cfg)
1606       GNUNET_CONFIGURATION_destroy (slave->cfg);
1607     GNUNET_free (slave);
1608     slave = NULL;
1609     LOG (GNUNET_ERROR_TYPE_WARNING, "Unexpected slave shutdown\n");
1610     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
1611     goto clean_lcc;
1612   }
1613   slave->controller =
1614       GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1615                                          event_mask,
1616                                          &slave_event_callback, slave);
1617   if (NULL != slave->controller)
1618   {
1619     send_operation_success_msg (lcc->client, lcc->operation_id);
1620     slave->cfg = GNUNET_CONFIGURATION_dup (cfg);
1621   }
1622   else
1623   {
1624     send_operation_fail_msg (lcc->client, lcc->operation_id,
1625                              "Could not connect to delegated controller");
1626     GNUNET_TESTBED_controller_stop (slave->controller_proc);
1627     slave_list[slave->host_id] = NULL;
1628     GNUNET_free (slave);
1629     slave = NULL;
1630   }
1631
1632  clean_lcc:
1633   if (NULL != lcc)
1634   {
1635     if (NULL != lcc->client)
1636     {
1637       GNUNET_SERVER_receive_done (lcc->client, GNUNET_OK);
1638       GNUNET_SERVER_client_drop (lcc->client);
1639       lcc->client = NULL;
1640     }
1641     GNUNET_free (lcc);
1642   }
1643   if (NULL != slave)
1644     slave->lcc = NULL;
1645 }
1646
1647
1648 /**
1649  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
1650  *
1651  * @param cls NULL
1652  * @param client identification of the client
1653  * @param message the actual message
1654  */
1655 static void
1656 handle_init (void *cls, struct GNUNET_SERVER_Client *client,
1657              const struct GNUNET_MessageHeader *message)
1658 {
1659   const struct GNUNET_TESTBED_InitMessage *msg;
1660   struct GNUNET_TESTBED_Host *host;
1661   const char *controller_hostname;
1662   uint16_t msize;
1663
1664   if (NULL != master_context)
1665   {
1666     LOG_DEBUG ("We are being connected to laterally\n");
1667     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1668     return;
1669   }
1670   msg = (const struct GNUNET_TESTBED_InitMessage *) message;
1671   msize = ntohs (message->size);
1672   if (msize <= sizeof (struct GNUNET_TESTBED_InitMessage))
1673   {
1674     GNUNET_break (0);
1675     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1676     return;
1677   }
1678   msize -= sizeof (struct GNUNET_TESTBED_InitMessage);
1679   controller_hostname = (const char *) &msg[1];
1680   if ('\0' != controller_hostname[msize - 1])
1681   {
1682     GNUNET_break (0);
1683     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1684     return;
1685   }
1686   master_context = GNUNET_malloc (sizeof (struct Context));
1687   master_context->client = client;
1688   master_context->host_id = ntohl (msg->host_id);
1689   master_context->master_ip = GNUNET_strdup (controller_hostname);
1690   LOG_DEBUG ("Master Controller IP: %s\n", master_context->master_ip);
1691   master_context->system =
1692       GNUNET_TESTING_system_create ("testbed", master_context->master_ip, hostname);
1693   host =
1694       GNUNET_TESTBED_host_create_with_id (master_context->host_id,
1695                                           master_context->master_ip,
1696                                           NULL,
1697                                           0);
1698   host_list_add (host);
1699   GNUNET_SERVER_client_keep (client);
1700   LOG_DEBUG ("Created master context with host ID: %u\n",
1701              master_context->host_id);
1702   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1703 }
1704
1705
1706 /**
1707  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1708  *
1709  * @param cls NULL
1710  * @param client identification of the client
1711  * @param message the actual message
1712  */
1713 static void
1714 handle_add_host (void *cls, struct GNUNET_SERVER_Client *client,
1715                  const struct GNUNET_MessageHeader *message)
1716 {
1717   struct GNUNET_TESTBED_Host *host;
1718   const struct GNUNET_TESTBED_AddHostMessage *msg;
1719   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
1720   char *username;
1721   char *hostname;
1722   char *emsg;
1723   uint32_t host_id;
1724   uint16_t username_length;
1725   uint16_t hostname_length;
1726   uint16_t reply_size;
1727   uint16_t msize;
1728
1729   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
1730   msize = ntohs (msg->header.size);
1731   username = (char *) &msg[1];
1732   username_length = ntohs (msg->user_name_length);
1733   if (0 != username_length)
1734     username_length++;
1735   /* msg must contain hostname */
1736   GNUNET_assert (msize > (sizeof (struct GNUNET_TESTBED_AddHostMessage) +
1737                           username_length + 1));
1738   if (0 != username_length)
1739     GNUNET_assert ('\0' == username[username_length - 1]);
1740   hostname = username + username_length;
1741   hostname_length =
1742       msize - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
1743   GNUNET_assert ('\0' == hostname[hostname_length - 1]);
1744   GNUNET_assert (strlen (hostname) == hostname_length - 1);
1745   host_id = ntohl (msg->host_id);
1746   LOG_DEBUG ("Received ADDHOST %u message\n", host_id);
1747   LOG_DEBUG ("-------host id: %u\n", host_id);
1748   LOG_DEBUG ("-------hostname: %s\n", hostname);
1749   if (0 != username_length)
1750     LOG_DEBUG ("-------username: %s\n", username);
1751   else
1752   {
1753     LOG_DEBUG ("-------username: NULL\n");
1754     username = NULL;
1755   }
1756   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1757   host =
1758       GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1759                                           ntohs (msg->ssh_port));
1760   GNUNET_assert (NULL != host);
1761   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1762   if (GNUNET_OK != host_list_add (host))
1763   {
1764     /* We are unable to add a host */
1765     emsg = "A host exists with given host-id";
1766     LOG_DEBUG ("%s: %u", emsg, host_id);
1767     GNUNET_TESTBED_host_destroy (host);
1768     reply_size += strlen (emsg) + 1;
1769     reply = GNUNET_malloc (reply_size);
1770     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1771   }
1772   else
1773   {
1774     LOG_DEBUG ("Added host %u at %u\n",
1775                host_id, master_context->host_id);
1776     reply = GNUNET_malloc (reply_size);
1777   }
1778   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
1779   reply->header.size = htons (reply_size);
1780   reply->host_id = htonl (host_id);
1781   queue_message (client, &reply->header);
1782   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1783 }
1784
1785
1786 /**
1787  * Iterator over hash map entries.
1788  *
1789  * @param cls closure
1790  * @param key current key code
1791  * @param value value in the hash map
1792  * @return GNUNET_YES if we should continue to
1793  *         iterate,
1794  *         GNUNET_NO if not.
1795  */
1796 int
1797 ss_exists_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
1798 {
1799   struct SharedService *queried_ss = cls;
1800   struct SharedService *ss = value;
1801
1802   if (0 == strcmp (ss->name, queried_ss->name))
1803     return GNUNET_NO;
1804   else
1805     return GNUNET_YES;
1806 }
1807
1808
1809 /**
1810  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1811  *
1812  * @param cls NULL
1813  * @param client identification of the client
1814  * @param message the actual message
1815  */
1816 static void
1817 handle_configure_shared_service (void *cls, struct GNUNET_SERVER_Client *client,
1818                                  const struct GNUNET_MessageHeader *message)
1819 {
1820   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1821   struct SharedService *ss;
1822   char *service_name;
1823   struct GNUNET_HashCode hash;
1824   uint16_t msg_size;
1825   uint16_t service_name_size;
1826
1827   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1828   msg_size = ntohs (message->size);
1829   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1830   {
1831     GNUNET_break (0);
1832     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1833     return;
1834   }
1835   service_name_size =
1836       msg_size - sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
1837   service_name = (char *) &msg[1];
1838   if ('\0' != service_name[service_name_size - 1])
1839   {
1840     GNUNET_break (0);
1841     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1842     return;
1843   }
1844   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
1845              service_name, ntohl (msg->num_peers));
1846   if (ntohl (msg->host_id) != master_context->host_id)
1847   {
1848     route_message (ntohl (msg->host_id), message);
1849     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1850     return;
1851   }
1852   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1853   ss = GNUNET_malloc (sizeof (struct SharedService));
1854   ss->name = strdup (service_name);
1855   ss->num_shared = ntohl (msg->num_peers);
1856   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1857   if (GNUNET_SYSERR ==
1858       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1859                                                   &ss_exists_iterator, ss))
1860   {
1861     LOG (GNUNET_ERROR_TYPE_WARNING,
1862          "Service %s already configured as a shared service. "
1863          "Ignoring service sharing request \n", ss->name);
1864     GNUNET_free (ss->name);
1865     GNUNET_free (ss);
1866     return;
1867   }
1868   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1869                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1870 }
1871
1872
1873 /**
1874  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1875  *
1876  * @param cls NULL
1877  * @param client identification of the client
1878  * @param message the actual message
1879  */
1880 static void
1881 handle_link_controllers (void *cls, struct GNUNET_SERVER_Client *client,
1882                          const struct GNUNET_MessageHeader *message)
1883 {
1884   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1885   struct GNUNET_CONFIGURATION_Handle *cfg;
1886   struct LCFContextQueue *lcfq;
1887   struct Route *route;
1888   struct Route *new_route;
1889   char *config;
1890   uLongf dest_size;
1891   size_t config_size;
1892   uint32_t delegated_host_id;
1893   uint32_t slave_host_id;
1894   uint16_t msize;
1895
1896   if (NULL == master_context)
1897   {
1898     GNUNET_break (0);
1899     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1900     return;
1901   }
1902   msize = ntohs (message->size);
1903   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1904   {
1905     GNUNET_break (0);
1906     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1907     return;
1908   }
1909   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1910   delegated_host_id = ntohl (msg->delegated_host_id);
1911   if (delegated_host_id == master_context->host_id)
1912   {
1913     GNUNET_break (0);
1914     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1915     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1916     return;
1917   }
1918   if ((delegated_host_id >= host_list_size) ||
1919       (NULL == host_list[delegated_host_id]))
1920   {
1921     LOG (GNUNET_ERROR_TYPE_WARNING,
1922          "Delegated host %u not registered with us\n", delegated_host_id);
1923     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1924     return;
1925   }
1926   slave_host_id = ntohl (msg->slave_host_id);
1927   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1928   {
1929     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host %u not registered with us\n",
1930          slave_host_id);
1931     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1932     return;
1933   }
1934   if (slave_host_id == delegated_host_id)
1935   {
1936     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1938     return;
1939   }
1940
1941   if (slave_host_id == master_context->host_id) /* Link from us */
1942   {
1943     struct Slave *slave;
1944     struct LinkControllersContext *lcc;
1945
1946     msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1947     config_size = ntohs (msg->config_size);
1948     if ((delegated_host_id < slave_list_size) && (NULL != slave_list[delegated_host_id]))       /* We have already added */
1949     {
1950       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1951            delegated_host_id);
1952       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1953       return;
1954     }
1955     config = GNUNET_malloc (config_size);
1956     dest_size = (uLongf) config_size;
1957     if (Z_OK !=
1958         uncompress ((Bytef *) config, &dest_size, (const Bytef *) &msg[1],
1959                     (uLong) msize))
1960     {
1961       GNUNET_break (0);         /* Compression error */
1962       GNUNET_free (config);
1963       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1964       return;
1965     }
1966     if (config_size != dest_size)
1967     {
1968       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1969       GNUNET_free (config);
1970       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1971       return;
1972     }
1973     cfg = GNUNET_CONFIGURATION_create ();       /* Free here or in lcfcontext */
1974     if (GNUNET_OK !=
1975         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
1976     {
1977       GNUNET_break (0);         /* Configuration parsing error */
1978       GNUNET_free (config);
1979       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1980       return;
1981     }
1982     GNUNET_free (config);
1983     if ((delegated_host_id < slave_list_size) &&
1984         (NULL != slave_list[delegated_host_id]))
1985     {
1986       GNUNET_break (0);         /* Configuration parsing error */
1987       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1988       return;
1989     }
1990     slave = GNUNET_malloc (sizeof (struct Slave));
1991     slave->host_id = delegated_host_id;
1992     slave->reghost_map = GNUNET_CONTAINER_multihashmap_create (100, GNUNET_NO);
1993     slave_list_add (slave);
1994     if (1 != msg->is_subordinate)
1995     {
1996       slave->controller =
1997           GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1998                                              event_mask,
1999                                              &slave_event_callback, slave);
2000       slave->cfg = cfg;
2001       if (NULL != slave->controller)
2002         send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
2003       else
2004         send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2005                                  "Could not connect to delegated controller");
2006       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2007       return;
2008     }
2009     lcc = GNUNET_malloc (sizeof (struct LinkControllersContext));
2010     lcc->operation_id = GNUNET_ntohll (msg->operation_id);
2011     GNUNET_SERVER_client_keep (client);
2012     lcc->client = client;
2013     slave->lcc = lcc;
2014     slave->controller_proc =
2015         GNUNET_TESTBED_controller_start (master_context->master_ip,
2016                                          host_list[slave->host_id], cfg,
2017                                          &slave_status_callback, slave);
2018     GNUNET_CONFIGURATION_destroy (cfg);
2019     new_route = GNUNET_malloc (sizeof (struct Route));
2020     new_route->dest = delegated_host_id;
2021     new_route->thru = master_context->host_id;
2022     route_list_add (new_route);
2023     return;
2024   }
2025
2026   /* Route the request */
2027   if (slave_host_id >= route_list_size)
2028   {
2029     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
2030     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2031     return;
2032   }
2033   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
2034   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
2035   lcfq->lcf->delegated_host_id = delegated_host_id;
2036   lcfq->lcf->slave_host_id = slave_host_id;
2037   route = find_dest_route (slave_host_id);
2038   GNUNET_assert (NULL != route);        /* because we add routes carefully */
2039   GNUNET_assert (route->dest < slave_list_size);
2040   GNUNET_assert (NULL != slave_list[route->dest]);
2041   lcfq->lcf->state = INIT;
2042   lcfq->lcf->operation_id = GNUNET_ntohll (msg->operation_id);
2043   lcfq->lcf->gateway = slave_list[route->dest];
2044   lcfq->lcf->msg = GNUNET_malloc (msize);
2045   (void) memcpy (lcfq->lcf->msg, msg, msize);
2046   GNUNET_SERVER_client_keep (client);
2047   lcfq->lcf->client = client;
2048   if (NULL == lcfq_head)
2049   {
2050     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2051     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
2052     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq->lcf);
2053   }
2054   else
2055     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
2056   /* FIXME: Adding a new route should happen after the controllers are linked
2057    * successfully */
2058   if (1 != msg->is_subordinate)
2059   {
2060     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2061     return;
2062   }
2063   if ((delegated_host_id < route_list_size)
2064       && (NULL != route_list[delegated_host_id]))
2065   {
2066     GNUNET_break_op (0);        /* Are you trying to link delegated host twice
2067                                    with is subordinate flag set to GNUNET_YES? */
2068     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2069     return;
2070   }
2071   new_route = GNUNET_malloc (sizeof (struct Route));
2072   new_route->dest = delegated_host_id;
2073   new_route->thru = route->dest;
2074   route_list_add (new_route);
2075   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2076 }
2077
2078
2079 /**
2080  * The task to be executed if the forwarded peer create operation has been
2081  * timed out
2082  *
2083  * @param cls the FowardedOperationContext
2084  * @param tc the TaskContext from the scheduler
2085  */
2086 static void
2087 peer_create_forward_timeout (void *cls,
2088                              const struct GNUNET_SCHEDULER_TaskContext *tc)
2089 {
2090   struct ForwardedOperationContext *fo_ctxt = cls;
2091
2092   /* send error msg to client */
2093   GNUNET_free (fo_ctxt->cls);
2094   send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id, "Timedout");
2095   GNUNET_SERVER_client_drop (fo_ctxt->client);
2096   GNUNET_TESTBED_forward_operation_msg_cancel_ (fo_ctxt->opc);
2097   GNUNET_free (fo_ctxt);
2098 }
2099
2100
2101 /**
2102  * Callback to be called when forwarded peer create operation is
2103  * successfull. We have to relay the reply msg back to the client
2104  *
2105  * @param cls ForwardedOperationContext
2106  * @param msg the peer create success message
2107  */
2108 static void
2109 peer_create_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
2110 {
2111   struct ForwardedOperationContext *fo_ctxt = cls;
2112   struct GNUNET_MessageHeader *dup_msg;
2113   struct Peer *remote_peer;
2114   uint16_t msize;
2115
2116   GNUNET_SCHEDULER_cancel (fo_ctxt->timeout_task);
2117   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS)
2118   {
2119     GNUNET_assert (NULL != fo_ctxt->cls);
2120     remote_peer = fo_ctxt->cls;
2121     peer_list_add (remote_peer);
2122   }
2123   msize = ntohs (msg->size);
2124   dup_msg = GNUNET_malloc (msize);
2125   (void) memcpy (dup_msg, msg, msize);
2126   queue_message (fo_ctxt->client, dup_msg);
2127   GNUNET_SERVER_client_drop (fo_ctxt->client);
2128   GNUNET_free (fo_ctxt);
2129 }
2130
2131
2132
2133 /**
2134  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
2135  *
2136  * @param cls NULL
2137  * @param client identification of the client
2138  * @param message the actual message
2139  */
2140 static void
2141 handle_peer_create (void *cls, struct GNUNET_SERVER_Client *client,
2142                     const struct GNUNET_MessageHeader *message)
2143 {
2144   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
2145   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
2146   struct GNUNET_CONFIGURATION_Handle *cfg;
2147   struct ForwardedOperationContext *fo_ctxt;
2148   struct Route *route;
2149   struct Peer *peer;
2150   char *config;
2151   size_t dest_size;
2152   int ret;
2153   uint32_t config_size;
2154   uint32_t host_id;
2155   uint32_t peer_id;
2156   uint16_t msize;
2157
2158
2159   msize = ntohs (message->size);
2160   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
2161   {
2162     GNUNET_break (0);           /* We need configuration */
2163     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2164     return;
2165   }
2166   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
2167   host_id = ntohl (msg->host_id);
2168   peer_id = ntohl (msg->peer_id);
2169   if (UINT32_MAX == peer_id)
2170   {
2171     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2172                              "Cannot create peer with given ID");
2173     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2174     return;
2175   }
2176   if (host_id == master_context->host_id)
2177   {
2178     char *emsg;
2179
2180     /* We are responsible for this peer */
2181     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
2182     config_size = ntohl (msg->config_size);
2183     config = GNUNET_malloc (config_size);
2184     dest_size = config_size;
2185     if (Z_OK !=
2186         (ret =
2187          uncompress ((Bytef *) config, (uLongf *) & dest_size,
2188                      (const Bytef *) &msg[1], (uLong) msize)))
2189     {
2190       GNUNET_break (0);         /* uncompression error */
2191       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2192       return;
2193     }
2194     if (config_size != dest_size)
2195     {
2196       GNUNET_break (0);         /* Uncompressed config size mismatch */
2197       GNUNET_free (config);
2198       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2199       return;
2200     }
2201     cfg = GNUNET_CONFIGURATION_create ();
2202     if (GNUNET_OK !=
2203         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
2204     {
2205       GNUNET_break (0);         /* Configuration parsing error */
2206       GNUNET_free (config);
2207       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2208       return;
2209     }
2210     GNUNET_free (config);
2211     peer = GNUNET_malloc (sizeof (struct Peer));
2212     peer->is_remote = GNUNET_NO;
2213     peer->details.local.cfg = cfg;
2214     peer->id = peer_id;
2215     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
2216     peer->details.local.peer =
2217         GNUNET_TESTING_peer_configure (master_context->system,
2218                                        peer->details.local.cfg, peer->id,
2219                                        NULL /* Peer id */ ,
2220                                        &emsg);
2221     if (NULL == peer->details.local.peer)
2222     {
2223       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
2224       GNUNET_free (emsg);
2225       GNUNET_free (peer);
2226       GNUNET_break (0);
2227       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2228       return;
2229     }
2230     peer->details.local.is_running = GNUNET_NO;
2231     peer_list_add (peer);
2232     reply =
2233         GNUNET_malloc (sizeof
2234                        (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
2235     reply->header.size =
2236         htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
2237     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
2238     reply->peer_id = msg->peer_id;
2239     reply->operation_id = msg->operation_id;
2240     queue_message (client, &reply->header);
2241     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2242     return;
2243   }
2244
2245   /* Forward peer create request */
2246   route = find_dest_route (host_id);
2247   if (NULL == route)
2248   {
2249     GNUNET_break (0);
2250     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2251     return;
2252   }
2253
2254   peer = GNUNET_malloc (sizeof (struct Peer));
2255   peer->is_remote = GNUNET_YES;
2256   peer->id = peer_id;
2257   peer->details.remote.slave = slave_list[route->dest];
2258   peer->details.remote.remote_host_id = host_id;
2259   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2260   GNUNET_SERVER_client_keep (client);
2261   fo_ctxt->client = client;
2262   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);
2263   fo_ctxt->cls = peer; //slave_list[route->dest]->controller;
2264   fo_ctxt->opc =
2265       GNUNET_TESTBED_forward_operation_msg_ (slave_list [route->dest]->controller,
2266                                              fo_ctxt->operation_id,
2267                                              &msg->header,
2268                                              peer_create_success_cb, fo_ctxt);
2269   fo_ctxt->timeout_task =
2270       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &peer_create_forward_timeout,
2271                                     fo_ctxt);
2272   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2273 }
2274
2275
2276 /**
2277  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
2278  *
2279  * @param cls NULL
2280  * @param client identification of the client
2281  * @param message the actual message
2282  */
2283 static void
2284 handle_peer_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2285                      const struct GNUNET_MessageHeader *message)
2286 {
2287   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
2288   struct ForwardedOperationContext *fopc;
2289   struct Peer *peer;
2290   uint32_t peer_id;
2291
2292   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
2293   peer_id = ntohl (msg->peer_id);
2294   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
2295              peer_id, GNUNET_ntohll (msg->operation_id));
2296   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
2297   {
2298     LOG (GNUNET_ERROR_TYPE_ERROR,
2299          "Asked to destroy a non existent peer with id: %u\n", peer_id);
2300     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2301                              "Peer doesn't exist");
2302     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2303     return;
2304   }
2305   peer = peer_list[peer_id];
2306   if (GNUNET_YES == peer->is_remote)
2307   {
2308     /* Forward the destory message to sub controller */
2309     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2310     GNUNET_SERVER_client_keep (client);
2311     fopc->client = client;
2312     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2313     fopc->opc = 
2314         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2315                                                fopc->operation_id, &msg->header,
2316                                                &forwarded_operation_reply_relay,
2317                                                fopc);
2318     fopc->timeout_task =
2319         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2320                                       fopc);
2321     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2322     return;
2323   }
2324   if (GNUNET_YES == peer->details.local.is_running)
2325   {
2326     GNUNET_TESTING_peer_stop (peer->details.local.peer);
2327     peer->details.local.is_running = GNUNET_NO;
2328   }
2329   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
2330   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
2331   peer_list_remove (peer);
2332   GNUNET_free (peer);
2333   send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
2334   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2335 }
2336
2337
2338 /**
2339  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
2340  *
2341  * @param cls NULL
2342  * @param client identification of the client
2343  * @param message the actual message
2344  */
2345 static void
2346 handle_peer_start (void *cls, struct GNUNET_SERVER_Client *client,
2347                    const struct GNUNET_MessageHeader *message)
2348 {
2349   const struct GNUNET_TESTBED_PeerStartMessage *msg;
2350   struct GNUNET_TESTBED_PeerEventMessage *reply;
2351   struct ForwardedOperationContext *fopc;
2352   struct Peer *peer;
2353   uint32_t peer_id;
2354
2355   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
2356   peer_id = ntohl (msg->peer_id);
2357   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
2358   {
2359     GNUNET_break (0);
2360     LOG (GNUNET_ERROR_TYPE_ERROR,
2361          "Asked to start a non existent peer with id: %u\n", peer_id);
2362     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2363     return;
2364   }
2365   peer = peer_list[peer_id];
2366   if (GNUNET_YES == peer->is_remote)
2367   {
2368     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2369     GNUNET_SERVER_client_keep (client);
2370     fopc->client = client;
2371     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2372     fopc->opc =
2373         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2374                                                fopc->operation_id, &msg->header,
2375                                                &forwarded_operation_reply_relay,
2376                                                fopc);
2377     fopc->timeout_task =
2378         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2379                                       fopc);
2380     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2381     return;
2382   }
2383   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer->details.local.peer))
2384   {
2385     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2386                              "Failed to start");
2387     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2388     return;
2389   }
2390   peer->details.local.is_running = GNUNET_YES;
2391   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2392   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
2393   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2394   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
2395   reply->host_id = htonl (master_context->host_id);
2396   reply->peer_id = msg->peer_id;
2397   reply->operation_id = msg->operation_id;
2398   queue_message (client, &reply->header);
2399   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2400 }
2401
2402
2403 /**
2404  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
2405  *
2406  * @param cls NULL
2407  * @param client identification of the client
2408  * @param message the actual message
2409  */
2410 static void
2411 handle_peer_stop (void *cls, struct GNUNET_SERVER_Client *client,
2412                   const struct GNUNET_MessageHeader *message)
2413 {
2414   const struct GNUNET_TESTBED_PeerStopMessage *msg;
2415   struct GNUNET_TESTBED_PeerEventMessage *reply;
2416   struct ForwardedOperationContext *fopc;
2417   struct Peer *peer;
2418   uint32_t peer_id;
2419
2420   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
2421   peer_id = ntohl (msg->peer_id);
2422   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
2423   {
2424     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2425                              "Peer not found");
2426     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2427     return;
2428   }
2429   peer = peer_list[peer_id];
2430   if (GNUNET_YES == peer->is_remote)
2431   {
2432     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2433     GNUNET_SERVER_client_keep (client);
2434     fopc->client = client;
2435     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2436     fopc->opc =
2437         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2438                                                fopc->operation_id, &msg->header,
2439                                                &forwarded_operation_reply_relay,
2440                                                fopc);
2441     fopc->timeout_task =
2442         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2443                                       fopc);
2444     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2445     return;
2446   }
2447   if (GNUNET_OK != GNUNET_TESTING_peer_stop (peer->details.local.peer))
2448   {
2449     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2450                              "Peer not running");
2451     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2452     return;
2453   }
2454   peer->details.local.is_running = GNUNET_NO;
2455   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2456   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
2457   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2458   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
2459   reply->host_id = htonl (master_context->host_id);
2460   reply->peer_id = msg->peer_id;
2461   reply->operation_id = msg->operation_id;
2462   queue_message (client, &reply->header);
2463   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2464 }
2465
2466
2467 /**
2468  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
2469  *
2470  * @param cls NULL
2471  * @param client identification of the client
2472  * @param message the actual message
2473  */
2474 static void
2475 handle_peer_get_config (void *cls, struct GNUNET_SERVER_Client *client,
2476                         const struct GNUNET_MessageHeader *message)
2477 {
2478   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
2479   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
2480   struct Peer *peer;
2481   char *config;
2482   char *xconfig;
2483   size_t c_size;
2484   size_t xc_size;
2485   uint32_t peer_id;
2486   uint16_t msize;
2487
2488   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
2489   peer_id = ntohl (msg->peer_id);
2490   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
2491   {
2492     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2493                              "Peer not found");
2494     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2495     return;
2496   }
2497   peer = peer_list[peer_id];
2498   if (GNUNET_YES == peer->is_remote)
2499   {
2500     struct ForwardedOperationContext *fopc;
2501     
2502     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2503     GNUNET_SERVER_client_keep (client);
2504     fopc->client = client;
2505     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2506     fopc->opc =
2507         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2508                                                fopc->operation_id, &msg->header,
2509                                                &forwarded_operation_reply_relay,
2510                                                fopc);
2511     fopc->timeout_task =
2512         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2513                                       fopc);    
2514     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2515     return;
2516   }
2517   config =
2518       GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
2519                                       &c_size);
2520   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
2521   GNUNET_free (config);
2522   msize =
2523       xc_size +
2524       sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
2525   reply = GNUNET_realloc (xconfig, msize);
2526   (void) memmove (&reply[1], reply, xc_size);
2527   reply->header.size = htons (msize);
2528   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
2529   reply->peer_id = msg->peer_id;
2530   reply->operation_id = msg->operation_id;
2531   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
2532                                     &reply->peer_identity);
2533   reply->config_size = htons ((uint16_t) c_size);
2534   queue_message (client, &reply->header);
2535   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2536 }
2537
2538
2539 /**
2540  * Task for cleaing up overlay connect context structure
2541  *
2542  * @param cls the overlay connect context
2543  * @param tc the task context
2544  */
2545 static void
2546 occ_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2547 {
2548   struct OverlayConnectContext *occ = cls;
2549
2550   LOG_DEBUG ("Cleaning up occ\n");
2551   GNUNET_free_non_null (occ->emsg);
2552   GNUNET_free_non_null (occ->hello);
2553   GNUNET_SERVER_client_drop (occ->client);
2554   if (NULL != occ->opc)
2555     GNUNET_TESTBED_forward_operation_msg_cancel_ (occ->opc);
2556   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
2557     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
2558   if (NULL != occ->ch)
2559     GNUNET_CORE_disconnect (occ->ch);
2560   if (NULL != occ->ghh)
2561     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
2562   if (NULL != occ->p1th)
2563     GNUNET_TRANSPORT_disconnect (occ->p1th);
2564   if (NULL != occ->p2th)
2565     GNUNET_TRANSPORT_disconnect (occ->p2th);
2566   GNUNET_free (occ);
2567 }
2568
2569
2570 /**
2571  * Task which will be run when overlay connect request has been timed out
2572  *
2573  * @param cls the OverlayConnectContext
2574  * @param tc the TaskContext
2575  */
2576 static void
2577 timeout_overlay_connect (void *cls,
2578                          const struct GNUNET_SCHEDULER_TaskContext *tc)
2579 {
2580   struct OverlayConnectContext *occ = cls;
2581
2582   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2583   LOG (GNUNET_ERROR_TYPE_WARNING,
2584        "Timeout while connecting peers %u and %u\n",
2585        occ->peer_id, occ->other_peer_id);
2586   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
2587   occ_cleanup (occ, tc);
2588 }
2589
2590
2591
2592 /**
2593  * Function called to notify transport users that another
2594  * peer connected to us.
2595  *
2596  * @param cls closure
2597  * @param new_peer the peer that connected
2598  * @param ats performance data
2599  * @param ats_count number of entries in ats (excluding 0-termination)
2600  */
2601 static void
2602 overlay_connect_notify (void *cls, const struct GNUNET_PeerIdentity *new_peer,
2603                         const struct GNUNET_ATS_Information *ats,
2604                         unsigned int ats_count)
2605 {
2606   struct OverlayConnectContext *occ = cls;
2607   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
2608   char *new_peer_str;
2609   char *other_peer_str;
2610
2611   LOG_DEBUG ("Overlay connect notify\n");
2612   if (0 ==
2613       memcmp (new_peer, &occ->peer_identity,
2614               sizeof (struct GNUNET_PeerIdentity)))
2615     return;
2616   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
2617   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2618   if (0 !=
2619       memcmp (new_peer, &occ->other_peer_identity,
2620               sizeof (struct GNUNET_PeerIdentity)))
2621   {
2622     LOG_DEBUG ("Unexpected peer %4s connected when expecting peer %4s\n",
2623                new_peer_str, other_peer_str);
2624     GNUNET_free (new_peer_str);
2625     GNUNET_free (other_peer_str);
2626     return;
2627   }
2628   GNUNET_free (new_peer_str);
2629   LOG_DEBUG ("Peer %4s connected to peer %4s\n", other_peer_str, 
2630              GNUNET_i2s (&occ->peer_identity));
2631   GNUNET_free (other_peer_str);
2632   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
2633   {
2634     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
2635     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2636   }
2637   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
2638   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2639   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2640   GNUNET_free_non_null (occ->emsg);
2641   occ->emsg = NULL;
2642   if (NULL != occ->p2th)
2643     GNUNET_TRANSPORT_disconnect (occ->p2th);
2644   occ->p2th = NULL;
2645   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
2646   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2647   msg->header.size =
2648       htons (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2649   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
2650   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
2651   msg->peer1 = htonl (occ->peer_id);
2652   msg->peer2 = htonl (occ->other_peer_id);
2653   msg->operation_id = GNUNET_htonll (occ->op_id);
2654   queue_message (occ->client, &msg->header);
2655   GNUNET_SCHEDULER_add_now (&occ_cleanup, occ);
2656 }
2657
2658
2659 /**
2660  * Task to offer HELLO of peer 1 to peer 2 and try to make peer 2 to connect to
2661  * peer 1.
2662  *
2663  * @param cls the OverlayConnectContext
2664  * @param tc the TaskContext from scheduler
2665  */
2666 static void
2667 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2668 {
2669   struct OverlayConnectContext *occ = cls;
2670   char *other_peer_str;
2671
2672   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2673   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2674     return;
2675   GNUNET_assert (NULL != occ->hello);
2676   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2677   if (NULL != occ->peer2_controller)
2678   {
2679     struct GNUNET_TESTBED_RequestConnectMessage *msg;
2680     uint16_t msize;
2681     uint16_t hello_size;
2682
2683     LOG_DEBUG ("Offering HELLO of %s to %s via Remote Overlay Request\n", 
2684                GNUNET_i2s (&occ->peer_identity), other_peer_str);
2685     hello_size = ntohs (occ->hello->size);
2686     msize = sizeof (struct GNUNET_TESTBED_RequestConnectMessage) + hello_size;
2687     msg = GNUNET_malloc (msize);
2688     msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT);
2689     msg->header.size = htons (msize);
2690     msg->peer = htonl (occ->other_peer_id);
2691     msg->operation_id = GNUNET_htonll (occ->op_id);
2692     (void) memcpy (&msg->peer_identity, &occ->peer_identity,
2693                    sizeof (struct GNUNET_PeerIdentity));
2694     memcpy (msg->hello, occ->hello, hello_size);
2695     GNUNET_TESTBED_queue_message_ (occ->peer2_controller, &msg->header);
2696   }
2697   else
2698   {
2699     LOG_DEBUG ("Offering HELLO of %s to %s\n", 
2700                GNUNET_i2s (&occ->peer_identity), other_peer_str);
2701     GNUNET_TRANSPORT_offer_hello (occ->p2th, occ->hello, NULL, NULL);
2702     GNUNET_TRANSPORT_try_connect (occ->p2th, &occ->peer_identity);
2703     occ->send_hello_task =
2704         GNUNET_SCHEDULER_add_delayed
2705         (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2706                                         100 * (pow (2, occ->retries++))),
2707          &send_hello, occ);
2708   }
2709   GNUNET_free (other_peer_str);  
2710 }
2711
2712 /**
2713  * Test for checking whether HELLO message is empty
2714  *
2715  * @param cls empty flag to set
2716  * @param address the HELLO
2717  * @param expiration expiration of the HELLO
2718  * @return
2719  */
2720 static int
2721 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
2722               struct GNUNET_TIME_Absolute expiration)
2723 {
2724   int *empty = cls;
2725
2726   *empty = GNUNET_NO;
2727   return GNUNET_OK;
2728 }
2729
2730
2731 /**
2732  * Function called whenever there is an update to the HELLO of peers in the
2733  * OverlayConnectClosure. If we have a valid HELLO, we connect to the peer 2's
2734  * transport and offer peer 1's HELLO and ask peer 2 to connect to peer 1
2735  *
2736  * @param cls closure
2737  * @param hello our updated HELLO
2738  */
2739 static void
2740 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
2741 {
2742   struct OverlayConnectContext *occ = cls;
2743   int empty;
2744   uint16_t msize;
2745
2746   msize = ntohs (hello->size);
2747   empty = GNUNET_YES;
2748   (void) GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *)
2749                                          hello, GNUNET_NO, &test_address,
2750                                          &empty);
2751   if (GNUNET_YES == empty)
2752   {
2753     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->peer_identity));
2754     return;
2755   }
2756   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->peer_identity));
2757   occ->hello = GNUNET_malloc (msize);
2758   memcpy (occ->hello, hello, msize);
2759   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
2760   occ->ghh = NULL;
2761   GNUNET_TRANSPORT_disconnect (occ->p1th);
2762   occ->p1th = NULL;
2763   GNUNET_free_non_null (occ->emsg);
2764   if (NULL == occ->peer2_controller)
2765   {   
2766     occ->p2th =
2767         GNUNET_TRANSPORT_connect (peer_list[occ->other_peer_id]->details.local.cfg,
2768                                   &occ->other_peer_identity, NULL, NULL, NULL,
2769                                   NULL);
2770     if (NULL == occ->p2th)
2771     {
2772       GNUNET_asprintf (&occ->emsg, "Cannot connect to TRANSPORT of %s\n",
2773                        GNUNET_i2s (&occ->other_peer_identity));
2774       GNUNET_SCHEDULER_cancel (occ->timeout_task);
2775       occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
2776       return;
2777     }
2778   }
2779   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
2780   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
2781 }
2782
2783
2784 /**
2785  * Function called after GNUNET_CORE_connect has succeeded (or failed
2786  * for good).  Note that the private key of the peer is intentionally
2787  * not exposed here; if you need it, your process should try to read
2788  * the private key file directly (which should work if you are
2789  * authorized...).
2790  *
2791  * @param cls closure
2792  * @param server handle to the server, NULL if we failed
2793  * @param my_identity ID of this peer, NULL if we failed
2794  */
2795 static void
2796 core_startup_cb (void *cls, struct GNUNET_CORE_Handle *server,
2797                  const struct GNUNET_PeerIdentity *my_identity)
2798 {
2799   struct OverlayConnectContext *occ = cls;
2800
2801   GNUNET_free_non_null (occ->emsg);
2802   occ->emsg = GNUNET_strdup ("Failed to connect to CORE\n");
2803   if ((NULL == server) || (NULL == my_identity))
2804     goto error_return;
2805   GNUNET_free (occ->emsg);
2806   occ->ch = server;
2807   occ->emsg = NULL;
2808   memcpy (&occ->peer_identity, my_identity,
2809           sizeof (struct GNUNET_PeerIdentity));
2810   occ->p1th =
2811       GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg,
2812                                 &occ->peer_identity, NULL, NULL, NULL, NULL);
2813   if (NULL == occ->p1th)
2814   {
2815     GNUNET_asprintf (&occ->emsg, "Cannot connect to TRANSPORT of peers %4s",
2816                     GNUNET_i2s (&occ->peer_identity));
2817     goto error_return;
2818   }
2819   LOG_DEBUG ("Acquiring HELLO of peer %s\n", GNUNET_i2s (&occ->peer_identity));
2820   occ->emsg = GNUNET_strdup ("Timeout while acquiring HELLO message");
2821   occ->ghh = GNUNET_TRANSPORT_get_hello (occ->p1th, &hello_update_cb, occ);
2822   return;
2823   
2824  error_return:
2825   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2826   occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
2827   return;
2828 }
2829
2830
2831 /**
2832  * Callback to be called when forwarded get peer config operation as part of
2833  * overlay connect is successfull. Connection to Peer 1's core is made and is
2834  * checked for new connection from peer 2
2835  *
2836  * @param cls ForwardedOperationContext
2837  * @param msg the peer create success message
2838  */
2839 static void
2840 overlay_connect_get_config (void *cls, const struct GNUNET_MessageHeader *msg)
2841 {
2842   struct OverlayConnectContext *occ = cls;
2843   const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *cmsg;
2844   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
2845     {NULL, 0, 0}
2846   };
2847
2848   occ->opc = NULL;
2849   if (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG != ntohs (msg->type))
2850     goto error_return;
2851   cmsg = (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *)
2852       msg;
2853   memcpy (&occ->other_peer_identity, &cmsg->peer_identity,
2854           sizeof (struct GNUNET_PeerIdentity));
2855   GNUNET_free_non_null (occ->emsg);
2856   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
2857   occ->ch =
2858       GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
2859                            &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
2860                            GNUNET_NO, no_handlers);
2861   if (NULL == occ->ch)
2862     goto error_return;
2863   return;
2864
2865  error_return:
2866   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2867   occ->timeout_task = 
2868       GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
2869 }
2870
2871
2872 /**
2873  * Callback which will be called to after a host registration succeeded or failed
2874  *
2875  * @param cls the RegisteredHostContext
2876  * @param emsg the error message; NULL if host registration is successful
2877  */
2878 static void 
2879 registeredhost_registration_completion (void *cls, const char *emsg)
2880 {
2881   struct RegisteredHostContext *rhc = cls;
2882   struct GNUNET_CONFIGURATION_Handle *cfg;
2883   uint32_t peer2_host_id;
2884
2885   /* if (NULL != rhc->focc_dll_head) */
2886   /*   process_next_focc (rhc); */
2887   peer2_host_id = GNUNET_TESTBED_host_get_id_ (rhc->reg_host);
2888   GNUNET_assert (RHC_INIT == rhc->state);
2889   GNUNET_assert (NULL == rhc->sub_op);
2890   if ((NULL == rhc->gateway2)
2891       || ((peer2_host_id < slave_list_size) /* Check if we have the needed config */
2892           && (NULL != slave_list[peer2_host_id])))
2893   {
2894     rhc->state = RHC_LINK;
2895     cfg = (NULL == rhc->gateway2) ? our_config : slave_list[peer2_host_id]->cfg;
2896     rhc->sub_op =
2897         GNUNET_TESTBED_controller_link (rhc,
2898                                         rhc->gateway->controller,
2899                                         rhc->reg_host,
2900                                         rhc->host,
2901                                         cfg,
2902                                         GNUNET_NO);
2903     return;
2904   }
2905   rhc->state = RHC_GET_CFG;
2906   rhc->sub_op =  GNUNET_TESTBED_get_slave_config (rhc,
2907                                                   rhc->gateway2->controller,
2908                                                   rhc->reg_host);
2909 }
2910
2911
2912 /**
2913  * Iterator to match a registered host context
2914  *
2915  * @param cls pointer 2 pointer of RegisteredHostContext
2916  * @param key current key code
2917  * @param value value in the hash map
2918  * @return GNUNET_YES if we should continue to
2919  *         iterate,
2920  *         GNUNET_NO if not.
2921  */
2922 static int 
2923 reghost_match_iterator (void *cls,
2924                         const struct GNUNET_HashCode * key,
2925                         void *value)
2926 {
2927   struct RegisteredHostContext **rh = cls;
2928   struct RegisteredHostContext *rh_val = value;
2929
2930   if ((rh_val->host == (*rh)->host) && (rh_val->reg_host == (*rh)->reg_host))
2931   {
2932     GNUNET_free (*rh);
2933     *rh = rh_val;
2934     return GNUNET_NO;
2935   }
2936   return GNUNET_YES;
2937 }
2938
2939
2940 /**
2941  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
2942  *
2943  * @param cls NULL
2944  * @param client identification of the client
2945  * @param message the actual message
2946  */
2947 static void
2948 handle_overlay_connect (void *cls, struct GNUNET_SERVER_Client *client,
2949                         const struct GNUNET_MessageHeader *message)
2950 {
2951   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
2952   struct OverlayConnectContext *occ;
2953   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
2954     {NULL, 0, 0}
2955   };
2956   struct Peer *peer;
2957   uint64_t operation_id;
2958   uint32_t p1;
2959   uint32_t p2; 
2960   uint32_t peer2_host_id;
2961
2962   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
2963   p1 = ntohl (msg->peer1);
2964   p2 = ntohl (msg->peer2);
2965   peer2_host_id = ntohl (msg->peer2_host_id);
2966   GNUNET_assert (p1 < peer_list_size);
2967   GNUNET_assert (NULL != peer_list[p1]);
2968   peer = peer_list[p1];
2969   operation_id = GNUNET_ntohll (msg->operation_id);  
2970   LOG_DEBUG ("Received overlay connect for peers %u and %u with op id: 0x%lx\n",
2971              p1, p2, operation_id);
2972   if (GNUNET_YES == peer->is_remote)
2973   {
2974     struct ForwardedOperationContext *fopc;
2975     struct Route *route_to_peer2_host;
2976     struct Route *route_to_peer1_host;
2977
2978     LOG_DEBUG ("Forwarding overlay connect\n");
2979     route_to_peer2_host = NULL;
2980     route_to_peer1_host = NULL;
2981     route_to_peer2_host = find_dest_route (peer2_host_id);
2982     if ((NULL != route_to_peer2_host) 
2983         || (peer2_host_id == master_context->host_id))
2984     {
2985       route_to_peer1_host = 
2986           find_dest_route (peer_list[p1]->details.remote.remote_host_id);
2987       GNUNET_assert (NULL != route_to_peer1_host);
2988       if ((peer2_host_id == master_context->host_id) 
2989           || (route_to_peer2_host->dest != route_to_peer1_host->dest))
2990       {
2991         struct GNUNET_HashCode hash;
2992         struct RegisteredHostContext *rhc;
2993         int skip_focc;
2994
2995         rhc = GNUNET_malloc (sizeof (struct RegisteredHostContext));
2996         if (NULL != route_to_peer2_host)
2997           rhc->reg_host = host_list[route_to_peer2_host->dest];
2998         else
2999           rhc->reg_host = host_list[master_context->host_id];
3000         rhc->host = host_list[route_to_peer1_host->dest];
3001         GNUNET_assert (NULL != rhc->reg_host);
3002         GNUNET_assert (NULL != rhc->host);
3003         rhc->gateway = peer->details.remote.slave;
3004         rhc->gateway2 = (NULL == route_to_peer2_host) ? NULL :
3005             slave_list[route_to_peer2_host->dest];
3006         rhc->state = RHC_INIT;
3007         GNUNET_SERVER_client_keep (client);
3008         rhc->client = client;
3009         hash = hash_hosts (rhc->reg_host, rhc->host);
3010         skip_focc = GNUNET_NO;
3011         if ((GNUNET_NO == 
3012              GNUNET_CONTAINER_multihashmap_contains
3013              (peer->details.remote.slave->reghost_map, &hash))
3014             || (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple
3015                 (peer->details.remote.slave->reghost_map, &hash,
3016                  reghost_match_iterator, &rhc)))
3017         {
3018           /* create and add a new registerd host context */
3019           /* add the focc to its queue */
3020           GNUNET_CONTAINER_multihashmap_put
3021               (peer->details.remote.slave->reghost_map,
3022                &hash, rhc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3023           GNUNET_assert (NULL != host_list[peer2_host_id]);
3024           queue_host_registration (peer->details.remote.slave,
3025                                    registeredhost_registration_completion, rhc,
3026                                    host_list[peer2_host_id]);
3027         }
3028         else {
3029           /* rhc is now set to the existing one from the hash map by
3030              reghost_match_iterator */
3031           /* if queue is empty then ignore creating focc and proceed with
3032              normal forwarding */
3033           if (NULL == rhc->focc_dll_head)
3034             skip_focc = GNUNET_YES;
3035         }
3036         if (GNUNET_NO == skip_focc)
3037         {
3038           struct ForwardedOverlayConnectContext *focc;
3039           uint16_t msize;
3040
3041           msize = sizeof (struct GNUNET_TESTBED_OverlayConnectMessage);
3042           focc = GNUNET_malloc (sizeof (struct ForwardedOverlayConnectContext));
3043           focc->peer1 = p1;
3044           focc->peer2 = p2;
3045           focc->peer2_host_id = peer2_host_id;
3046           focc->orig_msg = GNUNET_malloc (msize);
3047           (void) memcpy (focc->orig_msg, message, msize);
3048           focc->operation_id = operation_id;
3049           GNUNET_CONTAINER_DLL_insert_tail (rhc->focc_dll_head,
3050                                             rhc->focc_dll_tail,
3051                                             focc);
3052           GNUNET_SERVER_receive_done (client, GNUNET_OK);
3053           return;
3054         }
3055       }
3056     }
3057     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
3058     GNUNET_SERVER_client_keep (client);
3059     fopc->client = client;
3060     fopc->operation_id = operation_id;
3061     fopc->opc = 
3062         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
3063                                                operation_id, message,
3064                                                &forwarded_operation_reply_relay,
3065                                                fopc);
3066     fopc->timeout_task =
3067         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
3068                                       fopc);
3069     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3070     return;
3071   }
3072   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
3073   GNUNET_SERVER_client_keep (client);
3074   occ->client = client;
3075   occ->peer_id = p1;
3076   occ->other_peer_id = p2;
3077   occ->peer = peer_list[p1];
3078   occ->op_id = GNUNET_ntohll (msg->operation_id);  
3079   if ((p2 >= peer_list_size) || (NULL == peer_list[p2]))
3080   {   
3081     if ((peer2_host_id >= slave_list_size)
3082         || (NULL ==slave_list[peer2_host_id]))
3083     {
3084       struct GNUNET_TESTBED_NeedControllerConfig *reply;
3085
3086       LOG_DEBUG ("Need controller configuration for connecting peers %u and %u\n",
3087                  occ->peer_id, occ->other_peer_id);
3088       GNUNET_free (occ);
3089       reply = GNUNET_malloc (sizeof (struct
3090                                      GNUNET_TESTBED_NeedControllerConfig)); 
3091       reply->header.size = htons (sizeof (struct
3092                                           GNUNET_TESTBED_NeedControllerConfig));
3093       reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_NEEDCONTROLLERCONFIG);
3094       reply->controller_host_id = msg->peer2_host_id;
3095       reply->operation_id = msg->operation_id;
3096       queue_message (client, &reply->header);      
3097       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3098       return;
3099     }
3100     else
3101     {
3102       occ->peer2_controller = slave_list[peer2_host_id]->controller;
3103       if (NULL == occ->peer2_controller)
3104       {
3105         GNUNET_break (0);       /* What's going on? */
3106         GNUNET_SERVER_client_drop (client);
3107         GNUNET_free (occ);
3108         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3109         return;
3110       }
3111     }
3112   }
3113   else
3114   {
3115     if (GNUNET_YES == peer_list[occ->other_peer_id]->is_remote)
3116       occ->peer2_controller = peer_list[occ->other_peer_id]->details.remote.slave->controller;
3117   }
3118   /* Get the identity of the second peer */
3119   if (NULL != occ->peer2_controller)
3120   {
3121     struct GNUNET_TESTBED_PeerGetConfigurationMessage cmsg;
3122
3123     cmsg.header.size = 
3124         htons (sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage));
3125     cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG);
3126     cmsg.peer_id = msg->peer2;
3127     cmsg.operation_id = msg->operation_id;
3128     occ->opc = 
3129         GNUNET_TESTBED_forward_operation_msg_ (occ->peer2_controller,
3130                                                occ->op_id, &cmsg.header,
3131                                                &overlay_connect_get_config,
3132                                                occ);
3133     occ->emsg = 
3134         GNUNET_strdup ("Timeout while getting peer identity of peer B\n");
3135     occ->timeout_task =
3136         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3137                                       (GNUNET_TIME_UNIT_SECONDS, 30),
3138                                       &timeout_overlay_connect, occ);
3139     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3140     return;
3141   }
3142   GNUNET_TESTING_peer_get_identity (peer_list[occ->other_peer_id]->details.local.peer,
3143                                     &occ->other_peer_identity);
3144   /* Connect to the core of 1st peer and wait for the 2nd peer to connect */
3145   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
3146   occ->ch =
3147       GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
3148                            &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
3149                            GNUNET_NO, no_handlers);
3150   if (NULL == occ->ch)
3151     occ->timeout_task = 
3152         GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
3153   else
3154     occ->timeout_task =
3155         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3156                                       (GNUNET_TIME_UNIT_SECONDS, 30),
3157                                       &timeout_overlay_connect, occ);
3158   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3159 }
3160
3161
3162 /**
3163  * Function to cleanup RequestOverlayConnectContext and any associated tasks
3164  * with it
3165  *
3166  * @param rocc the RequestOverlayConnectContext
3167  */
3168 static void
3169 cleanup_rocc (struct RequestOverlayConnectContext *rocc)
3170 {
3171   if (GNUNET_SCHEDULER_NO_TASK != rocc->attempt_connect_task_id)
3172     GNUNET_SCHEDULER_cancel (rocc->attempt_connect_task_id);
3173   if (GNUNET_SCHEDULER_NO_TASK != rocc->timeout_rocc_task_id)
3174     GNUNET_SCHEDULER_cancel (rocc->timeout_rocc_task_id);
3175   GNUNET_TRANSPORT_disconnect (rocc->th);
3176   GNUNET_free_non_null (rocc->hello);
3177   GNUNET_free (rocc);
3178 }
3179
3180
3181 /**
3182  * Task to timeout rocc and cleanit up
3183  *
3184  * @param cls the RequestOverlayConnectContext
3185  * @param tc the TaskContext from scheduler
3186  */
3187 static void
3188 timeout_rocc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3189 {
3190   struct RequestOverlayConnectContext *rocc = cls;
3191   
3192   rocc->timeout_rocc_task_id = GNUNET_SCHEDULER_NO_TASK;
3193   cleanup_rocc (rocc);
3194 }
3195
3196
3197 /**
3198  * Function called to notify transport users that another
3199  * peer connected to us.
3200  *
3201  * @param cls closure
3202  * @param new_peer the peer that connected
3203  * @param ats performance data
3204  * @param ats_count number of entries in ats (excluding 0-termination)
3205  */
3206 static void 
3207 transport_connect_notify (void *cls, const struct GNUNET_PeerIdentity *new_peer,
3208                           const struct GNUNET_ATS_Information * ats,
3209                           uint32_t ats_count)
3210 {
3211   struct RequestOverlayConnectContext *rocc = cls;
3212
3213   LOG_DEBUG ("Request Overlay connect notify\n");
3214   if (0 != memcmp (new_peer, &rocc->a_id, sizeof (struct GNUNET_PeerIdentity)))
3215     return;
3216   LOG_DEBUG ("Peer %4s connected\n", GNUNET_i2s (&rocc->a_id));
3217   cleanup_rocc (rocc);
3218 }
3219
3220
3221 /**
3222  * Task to offer the HELLO message to the peer and ask it to connect to the peer
3223  * whose identity is in RequestOverlayConnectContext
3224  *
3225  * @param cls the RequestOverlayConnectContext
3226  * @param tc the TaskContext from scheduler
3227  */
3228 static void
3229 attempt_connect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3230 {
3231   struct RequestOverlayConnectContext *rocc = cls;
3232
3233   rocc->attempt_connect_task_id = GNUNET_SCHEDULER_NO_TASK;
3234   GNUNET_TRANSPORT_offer_hello (rocc->th, rocc->hello, NULL, NULL);
3235   GNUNET_TRANSPORT_try_connect (rocc->th, &rocc->a_id);
3236   rocc->attempt_connect_task_id = 
3237       GNUNET_SCHEDULER_add_delayed 
3238       (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3239                                       100 * (pow (2, rocc->retries++))),
3240        &attempt_connect_task, rocc);
3241 }
3242
3243
3244 /**
3245  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT messages
3246  *
3247  * @param cls NULL
3248  * @param client identification of the client
3249  * @param message the actual message
3250  */
3251 static void
3252 handle_overlay_request_connect (void *cls, struct GNUNET_SERVER_Client *client,
3253                                 const struct GNUNET_MessageHeader *message)
3254 {
3255   const struct GNUNET_TESTBED_RequestConnectMessage *msg;
3256   struct RequestOverlayConnectContext *rocc;
3257   struct Peer *peer;
3258   uint32_t peer_id;
3259   uint16_t msize;
3260   uint16_t hsize;
3261   
3262   msize = ntohs (message->size);
3263   if (sizeof (struct GNUNET_TESTBED_RequestConnectMessage) >= msize)
3264   {
3265     GNUNET_break (0);
3266     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3267     return;
3268   }  
3269   msg = (const struct GNUNET_TESTBED_RequestConnectMessage *) message;
3270   if ((NULL == msg->hello) || 
3271       (GNUNET_MESSAGE_TYPE_HELLO != ntohs (msg->hello->type)))
3272   {
3273     GNUNET_break (0);
3274     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3275     return;
3276   }
3277   hsize = ntohs (msg->hello->size);
3278   if ((sizeof (struct GNUNET_TESTBED_RequestConnectMessage) + hsize) != msize)
3279   {
3280     GNUNET_break (0);
3281     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3282     return;
3283   }
3284   peer_id = ntohl (msg->peer);
3285   if ((peer_id >= peer_list_size) || (NULL == (peer = peer_list[peer_id])))
3286   {
3287     GNUNET_break_op (0);
3288     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3289     return;
3290   }
3291   if (GNUNET_YES == peer->is_remote)
3292   {
3293     struct GNUNET_MessageHeader *msg2;
3294     
3295     msg2 = GNUNET_malloc (msize);
3296     (void) memcpy (msg2, message, msize);
3297     GNUNET_TESTBED_queue_message_ (peer->details.remote.slave->controller, msg2);
3298     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3299     return;
3300   }
3301   rocc = GNUNET_malloc (sizeof (struct RequestOverlayConnectContext));
3302   rocc->th = GNUNET_TRANSPORT_connect (peer->details.local.cfg, NULL, rocc, 
3303                                        NULL, &transport_connect_notify, NULL);
3304   if (NULL == rocc->th)
3305   {
3306     GNUNET_break (0);
3307     GNUNET_free (rocc);
3308     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3309     return;
3310   }
3311   memcpy (&rocc->a_id, &msg->peer_identity,
3312           sizeof (struct GNUNET_PeerIdentity));
3313   rocc->hello = GNUNET_malloc (hsize);
3314   memcpy (rocc->hello, msg->hello, hsize);
3315   rocc->attempt_connect_task_id =
3316       GNUNET_SCHEDULER_add_now (&attempt_connect_task, rocc);
3317   rocc->timeout_rocc_task_id =
3318       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &timeout_rocc_task, rocc);
3319   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3320 }
3321
3322
3323 /**
3324  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETSLAVECONFIG messages
3325  *
3326  * @param cls NULL
3327  * @param client identification of the client
3328  * @param message the actual message
3329  */
3330 static void
3331 handle_slave_get_config (void *cls, struct GNUNET_SERVER_Client *client,
3332                          const struct GNUNET_MessageHeader *message)
3333 {
3334   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
3335   struct Slave *slave;  
3336   struct GNUNET_TESTBED_SlaveConfiguration *reply;
3337   char *config;
3338   char *xconfig;
3339   size_t config_size;
3340   size_t xconfig_size;
3341   size_t reply_size;
3342   uint64_t op_id;
3343   uint32_t slave_id;
3344
3345   msg = (struct GNUNET_TESTBED_SlaveGetConfigurationMessage *) message;
3346   slave_id = ntohl (msg->slave_id);
3347   op_id = GNUNET_ntohll (msg->operation_id);
3348   if ((slave_list_size <= slave_id) || (NULL == slave_list[slave_id]))
3349   {
3350     send_operation_fail_msg (client, op_id, "Slave not found");
3351     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3352     return;
3353   }
3354   slave = slave_list[slave_id];
3355   if (NULL == slave->cfg)
3356   {
3357     send_operation_fail_msg (client, op_id,
3358                              "Configuration not found (slave not started by me)");
3359     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3360     return;
3361   }
3362   config = GNUNET_CONFIGURATION_serialize (slave->cfg, &config_size);
3363   xconfig_size = GNUNET_TESTBED_compress_config_ (config, config_size, 
3364                                                   &xconfig);
3365   GNUNET_free (config);  
3366   reply_size = xconfig_size + sizeof (struct GNUNET_TESTBED_SlaveConfiguration);
3367   GNUNET_break (reply_size <= UINT16_MAX);
3368   GNUNET_break (config_size <= UINT16_MAX);
3369   reply = GNUNET_realloc (xconfig, reply_size);
3370   (void) memmove (&reply[1], reply, xconfig_size);
3371   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG);
3372   reply->header.size = htons ((uint16_t) reply_size);
3373   reply->slave_id = msg->slave_id;
3374   reply->operation_id = msg->operation_id;
3375   reply->config_size = htons ((uint16_t) config_size);
3376   queue_message (client, &reply->header);
3377   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3378 }
3379
3380
3381 /**
3382  * Iterator over hash map entries.
3383  *
3384  * @param cls closure
3385  * @param key current key code
3386  * @param value value in the hash map
3387  * @return GNUNET_YES if we should continue to
3388  *         iterate,
3389  *         GNUNET_NO if not.
3390  */
3391 static int
3392 ss_map_free_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
3393 {
3394   struct SharedService *ss = value;
3395
3396   GNUNET_assert (GNUNET_YES ==
3397                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
3398   GNUNET_free (ss->name);
3399   GNUNET_free (ss);
3400   return GNUNET_YES;
3401 }
3402
3403
3404 /**
3405  * Iterator for freeing hash map entries in a slave's reghost_map
3406  *
3407  * @param cls handle to the slave
3408  * @param key current key code
3409  * @param value value in the hash map
3410  * @return GNUNET_YES if we should continue to
3411  *         iterate,
3412  *         GNUNET_NO if not.
3413  */
3414 static int 
3415 reghost_free_iterator (void *cls,
3416                        const struct GNUNET_HashCode * key,
3417                        void *value)
3418 {
3419   struct Slave *slave = cls;
3420   struct RegisteredHostContext *rhc = value;
3421   struct ForwardedOverlayConnectContext *focc;
3422
3423   GNUNET_assert (GNUNET_YES ==
3424                  GNUNET_CONTAINER_multihashmap_remove (slave->reghost_map,
3425                                                        key, value));
3426   while (NULL != (focc = rhc->focc_dll_head))
3427   {
3428     GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head,
3429                                  rhc->focc_dll_tail,
3430                                  focc);
3431     cleanup_focc (focc);
3432   }
3433   if (NULL != rhc->sub_op)
3434     GNUNET_TESTBED_operation_cancel (rhc->sub_op);
3435   if (NULL != rhc->client)
3436   GNUNET_SERVER_client_drop (rhc->client);
3437   GNUNET_free (value);
3438   return GNUNET_YES;
3439 }
3440
3441
3442 /**
3443  * Task to clean up and shutdown nicely
3444  *
3445  * @param cls NULL
3446  * @param tc the TaskContext from scheduler
3447  */
3448 static void
3449 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3450 {
3451   struct LCFContextQueue *lcfq;
3452   uint32_t id;
3453
3454   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
3455   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
3456   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
3457                                                 NULL);
3458   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
3459   if (NULL != lcfq_head)
3460   {
3461     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
3462     {
3463       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
3464       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
3465     }
3466   }
3467   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
3468   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
3469   {
3470     GNUNET_free (lcfq->lcf->msg);
3471     GNUNET_free (lcfq->lcf);
3472     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
3473     GNUNET_free (lcfq);
3474   }
3475   /* Clear peer list */
3476   for (id = 0; id < peer_list_size; id++)
3477     if (NULL != peer_list[id])
3478     {
3479       if (GNUNET_NO == peer_list[id]->is_remote)
3480       {
3481         if (GNUNET_YES == peer_list[id]->details.local.is_running)
3482           GNUNET_TESTING_peer_stop (peer_list[id]->details.local.peer);
3483         GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
3484         GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
3485       }
3486       GNUNET_free (peer_list[id]);
3487     }
3488   GNUNET_free_non_null (peer_list);
3489   /* Clear host list */
3490   for (id = 0; id < host_list_size; id++)
3491     if (NULL != host_list[id])
3492       GNUNET_TESTBED_host_destroy (host_list[id]);
3493   GNUNET_free_non_null (host_list);
3494   /* Clear route list */
3495   for (id = 0; id < route_list_size; id++)
3496     if (NULL != route_list[id])
3497       GNUNET_free (route_list[id]);
3498   GNUNET_free_non_null (route_list);
3499   /* Clear slave_list */
3500   for (id = 0; id < slave_list_size; id++)
3501     if (NULL != slave_list[id])
3502     {
3503       struct HostRegistration *hr_entry;
3504       
3505       while (NULL != (hr_entry = slave_list[id]->hr_dll_head))
3506       {
3507         GNUNET_CONTAINER_DLL_remove (slave_list[id]->hr_dll_head,
3508                                      slave_list[id]->hr_dll_tail,
3509                                      hr_entry);
3510         GNUNET_free (hr_entry);
3511       }
3512       if (NULL != slave_list[id]->rhandle)
3513         GNUNET_TESTBED_cancel_registration (slave_list[id]->rhandle);
3514       (void) GNUNET_CONTAINER_multihashmap_iterate (slave_list[id]->reghost_map,
3515                                                     reghost_free_iterator,
3516                                                     slave_list[id]);
3517       GNUNET_CONTAINER_multihashmap_destroy (slave_list[id]->reghost_map);
3518       if (NULL != slave_list[id]->cfg)
3519         GNUNET_CONFIGURATION_destroy (slave_list[id]->cfg);
3520       if (NULL != slave_list[id]->controller)
3521         GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
3522       if (NULL != slave_list[id]->controller_proc)
3523         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
3524       GNUNET_free (slave_list[id]);
3525     }
3526   GNUNET_free_non_null (slave_list);
3527   if (NULL != master_context)
3528   {
3529     GNUNET_free_non_null (master_context->master_ip);
3530     if (NULL != master_context->system)
3531       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
3532     GNUNET_free (master_context);
3533     master_context = NULL;
3534   }
3535   GNUNET_free_non_null (hostname);
3536   GNUNET_CONFIGURATION_destroy (our_config);
3537 }
3538
3539
3540 /**
3541  * Callback for client disconnect
3542  *
3543  * @param cls NULL
3544  * @param client the client which has disconnected
3545  */
3546 static void
3547 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
3548 {
3549   if (NULL == master_context)
3550     return;
3551   if (client == master_context->client)
3552   {
3553     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
3554     GNUNET_SERVER_client_drop (client);
3555     /* should not be needed as we're terminated by failure to read
3556      * from stdin, but if stdin fails for some reason, this shouldn't
3557      * hurt for now --- might need to revise this later if we ever
3558      * decide that master connections might be temporarily down
3559      * for some reason */
3560     //GNUNET_SCHEDULER_shutdown ();
3561   }
3562 }
3563
3564
3565 /**
3566  * Testbed setup
3567  *
3568  * @param cls closure
3569  * @param server the initialized server
3570  * @param cfg configuration to use
3571  */
3572 static void
3573 testbed_run (void *cls, struct GNUNET_SERVER_Handle *server,
3574              const struct GNUNET_CONFIGURATION_Handle *cfg)
3575 {
3576   static const struct GNUNET_SERVER_MessageHandler message_handlers[] = {
3577     {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
3578     {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
3579     {&handle_configure_shared_service, NULL,
3580      GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
3581     {&handle_link_controllers, NULL,
3582      GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
3583     {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
3584     {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
3585      sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
3586     {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
3587      sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
3588     {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
3589      sizeof (struct GNUNET_TESTBED_PeerStopMessage)},
3590     {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
3591      sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
3592     {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
3593      sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
3594     {&handle_overlay_request_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT,
3595      0},
3596     {handle_slave_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETSLAVECONFIG,
3597      sizeof (struct GNUNET_TESTBED_SlaveGetConfigurationMessage)},
3598     {NULL}
3599   };
3600
3601   GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string 
3602                  (cfg, "testbed", "HOSTNAME", &hostname));
3603   our_config = GNUNET_CONFIGURATION_dup (cfg);
3604   GNUNET_SERVER_add_handlers (server, message_handlers);
3605   GNUNET_SERVER_disconnect_notify (server, &client_disconnect_cb, NULL);
3606   ss_map = GNUNET_CONTAINER_multihashmap_create (5, GNUNET_NO);
3607   shutdown_task_id =
3608       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3609                                     &shutdown_task, NULL);
3610   LOG_DEBUG ("Testbed startup complete\n");
3611   event_mask = 1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED;
3612 }
3613
3614
3615 /**
3616  * The starting point of execution
3617  */
3618 int
3619 main (int argc, char *const *argv)
3620 {
3621   //sleep (15);                 /* Debugging */
3622   return (GNUNET_OK ==
3623           GNUNET_SERVICE_run (argc, argv, "testbed", GNUNET_SERVICE_OPTION_NONE,
3624                               &testbed_run, NULL)) ? 0 : 1;
3625 }
3626
3627 /* end of gnunet-service-testbed.c */