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