kill all peers first and wait for them later
[oweals/gnunet.git] / src / testbed / gnunet-service-testbed.c
1 /*
2   This file is part of GNUnet.
3   (C) 2012 Christian Grothoff (and other contributing authors)
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 2, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file testbed/gnunet-service-testbed.c
23  * @brief implementation of the TESTBED service
24  * @author Sree Harsha Totakura
25  */
26
27 #include "platform.h"
28 #include "gnunet_service_lib.h"
29 #include "gnunet_server_lib.h"
30 #include "gnunet_transport_service.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_hello_lib.h"
33 #include <zlib.h>
34
35 #include "gnunet_testbed_service.h"
36 #include "testbed.h"
37 #include "testbed_api.h"
38 #include "testbed_api_hosts.h"
39 #include "gnunet_testing_lib-new.h"
40
41 /**
42  * Generic logging
43  */
44 #define LOG(kind,...)                           \
45   GNUNET_log (kind, __VA_ARGS__)
46
47 /**
48  * Debug logging
49  */
50 #define LOG_DEBUG(...)                          \
51   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
52
53 /**
54  * By how much should the arrays lists grow
55  */
56 #define LIST_GROW_STEP 10
57
58 /**
59  * Default timeout for operations which may take some time
60  */
61 #define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
62
63 /**
64  * The main context information associated with the client which started us
65  */
66 struct Context
67 {
68   /**
69    * The client handle associated with this context
70    */
71   struct GNUNET_SERVER_Client *client;
72
73   /**
74    * The network address of the master controller
75    */
76   char *master_ip;
77
78   /**
79    * The TESTING system handle for starting peers locally
80    */
81   struct GNUNET_TESTING_System *system;
82   
83   /**
84    * 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 uint32_t host_list_size;
924
925 /**
926  * The size of the route list
927  */
928 static uint32_t route_list_size;
929
930 /**
931  * The size of directly linked neighbours list
932  */
933 static uint32_t slave_list_size;
934
935 /**
936  * The size of the peer list
937  */
938 static uint32_t 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_realloc; however clears tail part of newly allocated memory
1028  *
1029  * @param ptr the memory block to realloc
1030  * @param size the size of ptr
1031  * @param new_size the size to which ptr has to be realloc'ed
1032  * @return the newly reallocated memory block
1033  */
1034 static void *
1035 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
1036 {
1037   ptr = GNUNET_realloc (ptr, new_size);
1038   if (new_size > size)
1039     (void) memset (ptr + size, 0, new_size - size);
1040   return ptr;
1041 }
1042
1043
1044 /**
1045  * Function to add a host to the current list of known hosts
1046  *
1047  * @param host the host to add
1048  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
1049  *           already in use
1050  */
1051 static int
1052 host_list_add (struct GNUNET_TESTBED_Host *host)
1053 {
1054   uint32_t host_id;
1055   uint32_t orig_size;
1056
1057   host_id = GNUNET_TESTBED_host_get_id_ (host);
1058   orig_size = host_list_size;  
1059   if (host_list_size <= host_id)
1060   {
1061     while (host_list_size <= host_id)
1062       host_list_size += LIST_GROW_STEP;
1063     host_list =
1064         TESTBED_realloc (host_list,
1065                          sizeof (struct GNUNET_TESTBED_Host *) * orig_size,
1066                          sizeof (struct GNUNET_TESTBED_Host *)
1067                          * host_list_size);
1068   }
1069   if (NULL != host_list[host_id])
1070   {
1071     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
1072     return GNUNET_SYSERR;
1073   }
1074   host_list[host_id] = host;
1075   return GNUNET_OK;
1076 }
1077
1078
1079 /**
1080  * Adds a route to the route list
1081  *
1082  * @param route the route to add
1083  */
1084 static void
1085 route_list_add (struct Route *route)
1086 {
1087   uint32_t orig_size;
1088
1089   orig_size = route_list_size;  
1090   if (route->dest >= route_list_size)
1091   {
1092     while (route->dest >= route_list_size)
1093       route_list_size += LIST_GROW_STEP;
1094     route_list =
1095         TESTBED_realloc (route_list,
1096                          sizeof (struct Route *) * orig_size,
1097                          sizeof (struct Route *) * route_list_size);
1098   }
1099   GNUNET_assert (NULL == route_list[route->dest]);
1100   route_list[route->dest] = route;
1101 }
1102
1103
1104 /**
1105  * Adds a slave to the slave array
1106  *
1107  * @param slave the slave controller to add
1108  */
1109 static void
1110 slave_list_add (struct Slave *slave)
1111 {
1112   uint32_t orig_size;
1113
1114   orig_size = slave_list_size;  
1115   if (slave->host_id >= slave_list_size)
1116   {
1117     while (slave->host_id >= slave_list_size)
1118       slave_list_size += LIST_GROW_STEP;
1119     slave_list =
1120         TESTBED_realloc (slave_list, sizeof (struct Slave *) * orig_size,
1121                          sizeof (struct Slave *) * slave_list_size);
1122   }
1123   GNUNET_assert (NULL == slave_list[slave->host_id]);
1124   slave_list[slave->host_id] = slave;
1125 }
1126
1127
1128 /**
1129  * Adds a peer to the peer array
1130  *
1131  * @param peer the peer to add
1132  */
1133 static void
1134 peer_list_add (struct Peer *peer)
1135 {
1136   uint32_t orig_size;
1137
1138   orig_size = peer_list_size;
1139   if (peer->id >= peer_list_size)
1140   {
1141     while (peer->id >= peer_list_size)
1142       peer_list_size += LIST_GROW_STEP;
1143     peer_list =
1144         TESTBED_realloc (peer_list, sizeof (struct Peer *) * orig_size,
1145                          sizeof (struct Peer *) * peer_list_size);
1146   }  
1147   GNUNET_assert (NULL == peer_list[peer->id]);
1148   peer_list[peer->id] = peer;
1149 }
1150
1151
1152 /**
1153  * Removes a the give peer from the peer array
1154  *
1155  * @param peer the peer to be removed
1156  */
1157 static void
1158 peer_list_remove (struct Peer *peer)
1159 {
1160   uint32_t id;
1161   uint32_t orig_size;
1162
1163   peer_list[peer->id] = NULL;
1164   orig_size = peer_list_size;
1165   while (peer_list_size >= LIST_GROW_STEP)
1166   {
1167     for (id = peer_list_size - 1;
1168          (id >= peer_list_size - LIST_GROW_STEP) && (id != UINT32_MAX); id--)
1169       if (NULL != peer_list[id])
1170         break;
1171     if (id != ((peer_list_size - LIST_GROW_STEP) - 1))
1172       break;
1173     peer_list_size -= LIST_GROW_STEP;
1174   }
1175   if (orig_size == peer_list_size)
1176     return;
1177   peer_list =
1178       GNUNET_realloc (peer_list, sizeof (struct Peer *) * peer_list_size);
1179 }
1180
1181
1182 /**
1183  * Finds the route with directly connected host as destination through which
1184  * the destination host can be reached
1185  *
1186  * @param host_id the id of the destination host
1187  * @return the route with directly connected destination host; NULL if no route
1188  *           is found
1189  */
1190 static struct Route *
1191 find_dest_route (uint32_t host_id)
1192 {
1193   struct Route *route;
1194
1195   if (route_list_size <= host_id)
1196     return NULL;
1197   while (NULL != (route = route_list[host_id]))
1198   {
1199     if (route->thru == master_context->host_id)
1200       break;
1201     host_id = route->thru;
1202   }
1203   return route;
1204 }
1205
1206
1207 /**
1208  * Routes message to a host given its host_id
1209  *
1210  * @param host_id the id of the destination host
1211  * @param msg the message to be routed
1212  */
1213 static void
1214 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
1215 {
1216   GNUNET_break (0);
1217 }
1218
1219
1220 /**
1221  * Send operation failure message to client
1222  *
1223  * @param client the client to which the failure message has to be sent to
1224  * @param operation_id the id of the failed operation
1225  * @param emsg the error message; can be NULL
1226  */
1227 static void
1228 send_operation_fail_msg (struct GNUNET_SERVER_Client *client,
1229                          uint64_t operation_id, const char *emsg)
1230 {
1231   struct GNUNET_TESTBED_OperationFailureEventMessage *msg;
1232   uint16_t msize;
1233   uint16_t emsg_len;
1234
1235   msize = sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
1236   emsg_len = (NULL == emsg) ? 0 : strlen (emsg) + 1;
1237   msize += emsg_len;
1238   msg = GNUNET_malloc (msize);
1239   msg->header.size = htons (msize);
1240   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONFAILEVENT);
1241   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1242   msg->operation_id = GNUNET_htonll (operation_id);
1243   if (0 != emsg_len)
1244     memcpy (&msg[1], emsg, emsg_len);
1245   queue_message (client, &msg->header);
1246 }
1247
1248
1249 /**
1250  * Function to send generic operation success message to given client
1251  *
1252  * @param client the client to send the message to
1253  * @param operation_id the id of the operation which was successful
1254  */
1255 static void
1256 send_operation_success_msg (struct GNUNET_SERVER_Client *client,
1257                             uint64_t operation_id)
1258 {
1259   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg;
1260   uint16_t msize;
1261
1262   msize = sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1263   msg = GNUNET_malloc (msize);
1264   msg->header.size = htons (msize);
1265   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1266   msg->operation_id = GNUNET_htonll (operation_id);
1267   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1268   queue_message (client, &msg->header);
1269 }
1270
1271
1272 /**
1273  * Callback which will be called to after a host registration succeeded or failed
1274  *
1275  * @param cls the handle to the slave at which the registration is completed
1276  * @param emsg the error message; NULL if host registration is successful
1277  */
1278 static void 
1279 hr_completion (void *cls, const char *emsg);
1280
1281
1282 /**
1283  * Attempts to register the next host in the host registration queue
1284  *
1285  * @param slave the slave controller whose host registration queue is checked
1286  *          for host registrations
1287  */
1288 static void
1289 register_next_host (struct Slave *slave)
1290 {
1291   struct HostRegistration *hr;
1292   
1293   hr = slave->hr_dll_head;
1294   GNUNET_assert (NULL != hr);
1295   GNUNET_assert (NULL == slave->rhandle);
1296   LOG (GNUNET_ERROR_TYPE_DEBUG,
1297        "Registering host %u at %u\n",
1298        GNUNET_TESTBED_host_get_id_ (hr->host),
1299        GNUNET_TESTBED_host_get_id_ (host_list[slave->host_id]));
1300   slave->rhandle = GNUNET_TESTBED_register_host (slave->controller,
1301                                                  hr->host,
1302                                                  hr_completion,
1303                                                  slave);
1304 }
1305
1306
1307 /**
1308  * Callback which will be called to after a host registration succeeded or failed
1309  *
1310  * @param cls the handle to the slave at which the registration is completed
1311  * @param emsg the error message; NULL if host registration is successful
1312  */
1313 static void 
1314 hr_completion (void *cls, const char *emsg)
1315 {
1316   struct Slave *slave = cls;
1317   struct HostRegistration *hr;
1318
1319   slave->rhandle = NULL;
1320   hr = slave->hr_dll_head;
1321   GNUNET_assert (NULL != hr);
1322   LOG (GNUNET_ERROR_TYPE_DEBUG,
1323        "Registering host %u at %u successful\n",
1324        GNUNET_TESTBED_host_get_id_ (hr->host),
1325        GNUNET_TESTBED_host_get_id_ (host_list[slave->host_id]));
1326   GNUNET_CONTAINER_DLL_remove (slave->hr_dll_head,
1327                                slave->hr_dll_tail,
1328                                hr);
1329   if (NULL != hr->cb)
1330     hr->cb (hr->cb_cls, emsg);
1331   GNUNET_free (hr);
1332   if (NULL != slave->hr_dll_head)
1333     register_next_host (slave);
1334 }
1335
1336
1337 /**
1338  * Adds a host registration's request to a slave's registration queue
1339  *
1340  * @param slave the slave controller at which the given host has to be
1341  *          registered 
1342  * @param cb the host registration completion callback
1343  * @param cb_cls the closure for the host registration completion callback
1344  * @param host the host which has to be registered
1345  */
1346 static void
1347 queue_host_registration (struct Slave *slave,
1348                          GNUNET_TESTBED_HostRegistrationCompletion cb,
1349                          void *cb_cls,
1350                          struct GNUNET_TESTBED_Host *host)
1351 {
1352   struct HostRegistration *hr;
1353   int call_register;
1354
1355   LOG (GNUNET_ERROR_TYPE_DEBUG,
1356        "Queueing host registration for host %u at %u\n",
1357        GNUNET_TESTBED_host_get_id_ (host),
1358        GNUNET_TESTBED_host_get_id_ (host_list[slave->host_id]));
1359   hr = GNUNET_malloc (sizeof (struct HostRegistration));
1360   hr->cb = cb;
1361   hr->cb_cls = cb_cls;
1362   hr->host = host;
1363   call_register = (NULL == slave->hr_dll_head) ? GNUNET_YES : GNUNET_NO;
1364   GNUNET_CONTAINER_DLL_insert_tail (slave->hr_dll_head,
1365                                     slave->hr_dll_tail,
1366                                     hr);
1367   if (GNUNET_YES == call_register)
1368     register_next_host (slave);
1369 }
1370
1371
1372 /**
1373  * The  Link Controller forwarding task
1374  *
1375  * @param cls the LCFContext
1376  * @param tc the Task context from scheduler
1377  */
1378 static void
1379 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1380
1381
1382 /**
1383  * Completion callback for host registrations while forwarding Link Controller messages
1384  *
1385  * @param cls the LCFContext
1386  * @param emsg the error message; NULL if host registration is successful
1387  */
1388 static void
1389 lcf_proc_cc (void *cls, const char *emsg)
1390 {
1391   struct LCFContext *lcf = cls;
1392
1393   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1394   switch (lcf->state)
1395   {
1396   case INIT:
1397     if (NULL != emsg)
1398       goto registration_error;
1399     lcf->state = DELEGATED_HOST_REGISTERED;
1400     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1401     break;
1402   case DELEGATED_HOST_REGISTERED:
1403     if (NULL != emsg)
1404       goto registration_error;
1405     lcf->state = SLAVE_HOST_REGISTERED;
1406     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1407     break;
1408   default:
1409     GNUNET_assert (0);          /* Shouldn't reach here */
1410   }
1411   return;
1412
1413  registration_error:
1414   LOG (GNUNET_ERROR_TYPE_WARNING, "Host registration failed with message: %s\n",
1415        emsg);
1416   lcf->state = FINISHED;
1417   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1418 }
1419
1420
1421 /**
1422  * Callback to relay the reply msg of a forwarded operation back to the client
1423  *
1424  * @param cls ForwardedOperationContext
1425  * @param msg the message to relay
1426  */
1427 static void
1428 forwarded_operation_reply_relay (void *cls,
1429                                  const struct GNUNET_MessageHeader *msg)
1430 {
1431   struct ForwardedOperationContext *fopc = cls;
1432   struct GNUNET_MessageHeader *dup_msg;
1433   uint16_t msize;
1434
1435   msize = ntohs (msg->size);
1436   LOG_DEBUG ("Relaying message with type: %u, size: %u\n", ntohs (msg->type),
1437              msize);
1438   dup_msg = GNUNET_copy_message (msg);
1439   queue_message (fopc->client, dup_msg);
1440   GNUNET_SERVER_client_drop (fopc->client);
1441   GNUNET_SCHEDULER_cancel (fopc->timeout_task);
1442   GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fopc);
1443   GNUNET_free (fopc);
1444 }
1445
1446
1447 /**
1448  * Task to free resources when forwarded operation has been timedout
1449  *
1450  * @param cls the ForwardedOperationContext
1451  * @param tc the task context from scheduler
1452  */
1453 static void
1454 forwarded_operation_timeout (void *cls,
1455                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1456 {
1457   struct ForwardedOperationContext *fopc = cls;
1458
1459   GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
1460   LOG (GNUNET_ERROR_TYPE_WARNING, "A forwarded operation has timed out\n");
1461   send_operation_fail_msg (fopc->client, fopc->operation_id, "Timeout");
1462   GNUNET_SERVER_client_drop (fopc->client);
1463   GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fopc);
1464   GNUNET_free (fopc);
1465 }
1466
1467
1468 /**
1469  * The  Link Controller forwarding task
1470  *
1471  * @param cls the LCFContext
1472  * @param tc the Task context from scheduler
1473  */
1474 static void
1475 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1476
1477
1478 /**
1479  * Callback to be called when forwarded link controllers operation is
1480  * successfull. We have to relay the reply msg back to the client
1481  *
1482  * @param cls the LCFContext
1483  * @param msg the message to relay
1484  */
1485 static void
1486 lcf_forwarded_operation_reply_relay (void *cls,
1487                                      const struct GNUNET_MessageHeader *msg)
1488 {
1489   struct LCFContext *lcf = cls;
1490
1491   GNUNET_assert (NULL != lcf->fopc);
1492   forwarded_operation_reply_relay (lcf->fopc, msg);
1493   lcf->fopc = NULL;
1494   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1495   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1496 }
1497
1498
1499 /**
1500  * Task to free resources when forwarded link controllers has been timedout
1501  *
1502  * @param cls the LCFContext
1503  * @param tc the task context from scheduler
1504  */
1505 static void
1506 lcf_forwarded_operation_timeout (void *cls,
1507                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1508 {
1509   struct LCFContext *lcf = cls;
1510
1511   GNUNET_assert (NULL != lcf->fopc);
1512   lcf->fopc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1513   forwarded_operation_timeout (lcf->fopc, tc);
1514   lcf->fopc = NULL;
1515   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1516   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1517 }
1518
1519
1520 /**
1521  * The  Link Controller forwarding task
1522  *
1523  * @param cls the LCFContext
1524  * @param tc the Task context from scheduler
1525  */
1526 static void
1527 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1528 {
1529   struct LCFContext *lcf = cls;
1530   struct LCFContextQueue *lcfq;
1531
1532   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
1533   switch (lcf->state)
1534   {
1535   case INIT:
1536     if (GNUNET_NO ==
1537         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
1538                                             lcf->gateway->controller))
1539     {
1540       queue_host_registration (lcf->gateway,
1541                                lcf_proc_cc, lcf,
1542                                host_list[lcf->delegated_host_id]);
1543     }
1544     else
1545     {
1546       lcf->state = DELEGATED_HOST_REGISTERED;
1547       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1548     }
1549     break;
1550   case DELEGATED_HOST_REGISTERED:
1551     if (GNUNET_NO ==
1552         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
1553                                             lcf->gateway->controller))
1554     {
1555       queue_host_registration (lcf->gateway,
1556                                lcf_proc_cc, lcf,
1557                                host_list[lcf->slave_host_id]);
1558     }
1559     else
1560     {
1561       lcf->state = SLAVE_HOST_REGISTERED;
1562       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1563     }
1564     break;
1565   case SLAVE_HOST_REGISTERED:
1566     lcf->fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1567     lcf->fopc->client = lcf->client;
1568     lcf->fopc->operation_id = lcf->operation_id;
1569     lcf->fopc->type = OP_LINK_CONTROLLERS;
1570     lcf->fopc->opc =
1571         GNUNET_TESTBED_forward_operation_msg_ (lcf->gateway->controller,
1572                                                lcf->operation_id,
1573                                                &lcf->msg->header,
1574                                                &lcf_forwarded_operation_reply_relay,
1575                                                lcf);
1576     lcf->fopc->timeout_task =
1577         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &lcf_forwarded_operation_timeout,
1578                                       lcf);
1579     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, lcf->fopc);
1580     lcf->state = FINISHED;
1581     break;
1582   case FINISHED:
1583     lcfq = lcfq_head;
1584     GNUNET_assert (lcfq->lcf == lcf);
1585     GNUNET_free (lcf->msg);
1586     GNUNET_free (lcf);
1587     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1588     GNUNET_free (lcfq);
1589     if (NULL != lcfq_head)
1590       lcf_proc_task_id =
1591           GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
1592   }
1593 }
1594
1595
1596 /**
1597  * Cleans up ForwardedOverlayConnectContext
1598  *
1599  * @param focc the ForwardedOverlayConnectContext to cleanup
1600  */
1601 static void
1602 cleanup_focc (struct ForwardedOverlayConnectContext *focc)
1603 {
1604   GNUNET_free_non_null (focc->orig_msg);
1605   GNUNET_free (focc);
1606 }
1607
1608
1609 /**
1610  * Processes a forwarded overlay connect context in the queue of the given RegisteredHostContext
1611  *
1612  * @param rhc the RegisteredHostContext
1613  */
1614 static void
1615 process_next_focc (struct RegisteredHostContext *rhc);
1616
1617
1618 /**
1619  * Timeout task for cancelling a forwarded overlay connect connect
1620  *
1621  * @param cls the ForwardedOverlayConnectContext
1622  * @param tc the task context from the scheduler
1623  */
1624 static void
1625 forwarded_overlay_connect_timeout (void *cls,
1626                                    const struct GNUNET_SCHEDULER_TaskContext
1627                                    *tc)
1628 {
1629   struct ForwardedOperationContext *fopc = cls;
1630   struct RegisteredHostContext *rhc;
1631   struct ForwardedOverlayConnectContext *focc;
1632   
1633   rhc = fopc->cls;
1634   focc = rhc->focc_dll_head;
1635   GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head, rhc->focc_dll_tail, focc);
1636   cleanup_focc (focc);
1637   LOG_DEBUG ("Overlay linking between peers %u and %u failed\n",
1638              focc->peer1, focc->peer2);
1639   forwarded_operation_timeout (cls, tc);
1640   if (NULL != rhc->focc_dll_head)
1641     process_next_focc (rhc);
1642 }
1643
1644
1645 /**
1646  * Callback to be called when forwarded overlay connection operation has a reply
1647  * from the sub-controller successfull. We have to relay the reply msg back to
1648  * the client
1649  *
1650  * @param cls ForwardedOperationContext
1651  * @param msg the peer create success message
1652  */
1653 static void
1654 forwarded_overlay_connect_listener (void *cls,
1655                                     const struct GNUNET_MessageHeader *msg)
1656 {
1657   struct ForwardedOperationContext *fopc = cls;
1658   struct RegisteredHostContext *rhc;
1659   struct ForwardedOverlayConnectContext *focc;
1660   
1661   rhc = fopc->cls;
1662   forwarded_operation_reply_relay (cls, msg);
1663   focc = rhc->focc_dll_head;
1664   GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head, rhc->focc_dll_tail, focc);
1665   cleanup_focc (focc);
1666   if (NULL != rhc->focc_dll_head)
1667     process_next_focc (rhc);
1668 }
1669
1670
1671 /**
1672  * Processes a forwarded overlay connect context in the queue of the given RegisteredHostContext
1673  *
1674  * @param rhc the RegisteredHostContext
1675  */
1676 static void
1677 process_next_focc (struct RegisteredHostContext *rhc)
1678 {
1679   struct ForwardedOperationContext *fopc;
1680   struct ForwardedOverlayConnectContext *focc;
1681
1682   focc = rhc->focc_dll_head;
1683   GNUNET_assert (NULL != focc);
1684   GNUNET_assert (RHC_OL_CONNECT == rhc->state);
1685   fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1686   GNUNET_SERVER_client_keep (rhc->client);
1687   fopc->client = rhc->client;  
1688   fopc->operation_id = focc->operation_id;
1689   fopc->cls = rhc;
1690   fopc->type = OP_OVERLAY_CONNECT;
1691   fopc->opc =
1692         GNUNET_TESTBED_forward_operation_msg_ (rhc->gateway->controller,
1693                                                focc->operation_id, focc->orig_msg,
1694                                                &forwarded_overlay_connect_listener,
1695                                                fopc);
1696   GNUNET_free (focc->orig_msg);
1697   focc->orig_msg = NULL;
1698   fopc->timeout_task =
1699       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_overlay_connect_timeout,
1700                                     fopc);
1701   GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
1702 }
1703
1704
1705 /**
1706  * Callback for event from slave controllers
1707  *
1708  * @param cls struct Slave *
1709  * @param event information about the event
1710  */
1711 static void
1712 slave_event_callback (void *cls,
1713                       const struct GNUNET_TESTBED_EventInformation *event)
1714 {
1715   struct RegisteredHostContext *rhc;
1716   struct GNUNET_CONFIGURATION_Handle *cfg;
1717   struct GNUNET_TESTBED_Operation *old_op;
1718   
1719   /* We currently only get here when working on RegisteredHostContexts */
1720   GNUNET_assert (GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type);
1721   rhc = event->details.operation_finished.op_cls;
1722   GNUNET_assert (rhc->sub_op == event->details.operation_finished.operation);
1723   switch (rhc->state)
1724   {
1725   case RHC_GET_CFG:
1726     cfg = event->details.operation_finished.generic;
1727     old_op = rhc->sub_op;
1728     rhc->state = RHC_LINK;
1729     rhc->sub_op =
1730         GNUNET_TESTBED_controller_link (rhc,
1731                                         rhc->gateway->controller,
1732                                         rhc->reg_host,
1733                                         rhc->host,
1734                                         cfg,
1735                                         GNUNET_NO);
1736     GNUNET_TESTBED_operation_done (old_op);
1737     break;
1738   case RHC_LINK:
1739     LOG_DEBUG ("OL: Linking controllers successfull\n");
1740     GNUNET_TESTBED_operation_done (rhc->sub_op);
1741     rhc->sub_op = NULL;
1742     rhc->state = RHC_OL_CONNECT;
1743     process_next_focc (rhc);
1744     break;
1745   default:
1746     GNUNET_assert (0);
1747   }
1748 }
1749
1750
1751 /**
1752  * Callback to signal successfull startup of the controller process
1753  *
1754  * @param cls the handle to the slave whose status is to be found here
1755  * @param cfg the configuration with which the controller has been started;
1756  *          NULL if status is not GNUNET_OK
1757  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1758  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1759  */
1760 static void
1761 slave_status_callback (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
1762                        int status)
1763 {
1764   struct Slave *slave = cls;
1765   struct LinkControllersContext *lcc;
1766
1767   lcc = slave->lcc;
1768   if (GNUNET_SYSERR == status)
1769   {
1770     slave->controller_proc = NULL;
1771     slave_list[slave->host_id] = NULL;
1772     if (NULL != slave->cfg)
1773       GNUNET_CONFIGURATION_destroy (slave->cfg);
1774     GNUNET_free (slave);
1775     slave = NULL;
1776     LOG (GNUNET_ERROR_TYPE_WARNING, "Unexpected slave shutdown\n");
1777     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
1778     goto clean_lcc;
1779   }
1780   slave->controller =
1781       GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1782                                          event_mask,
1783                                          &slave_event_callback, slave);
1784   if (NULL != slave->controller)
1785   {
1786     send_operation_success_msg (lcc->client, lcc->operation_id);
1787     slave->cfg = GNUNET_CONFIGURATION_dup (cfg);
1788   }
1789   else
1790   {
1791     send_operation_fail_msg (lcc->client, lcc->operation_id,
1792                              "Could not connect to delegated controller");
1793     GNUNET_TESTBED_controller_stop (slave->controller_proc);
1794     slave_list[slave->host_id] = NULL;
1795     GNUNET_free (slave);
1796     slave = NULL;
1797   }
1798
1799  clean_lcc:
1800   if (NULL != lcc)
1801   {
1802     if (NULL != lcc->client)
1803     {
1804       GNUNET_SERVER_receive_done (lcc->client, GNUNET_OK);
1805       GNUNET_SERVER_client_drop (lcc->client);
1806       lcc->client = NULL;
1807     }
1808     GNUNET_free (lcc);
1809   }
1810   if (NULL != slave)
1811     slave->lcc = NULL;
1812 }
1813
1814
1815 /**
1816  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
1817  *
1818  * @param cls NULL
1819  * @param client identification of the client
1820  * @param message the actual message
1821  */
1822 static void
1823 handle_init (void *cls, struct GNUNET_SERVER_Client *client,
1824              const struct GNUNET_MessageHeader *message)
1825 {
1826   const struct GNUNET_TESTBED_InitMessage *msg;
1827   struct GNUNET_TESTBED_Host *host;
1828   const char *controller_hostname;
1829   uint16_t msize;
1830
1831   if (NULL != master_context)
1832   {
1833     LOG_DEBUG ("We are being connected to laterally\n");
1834     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1835     return;
1836   }
1837   msg = (const struct GNUNET_TESTBED_InitMessage *) message;
1838   msize = ntohs (message->size);
1839   if (msize <= sizeof (struct GNUNET_TESTBED_InitMessage))
1840   {
1841     GNUNET_break (0);
1842     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1843     return;
1844   }
1845   msize -= sizeof (struct GNUNET_TESTBED_InitMessage);
1846   controller_hostname = (const char *) &msg[1];
1847   if ('\0' != controller_hostname[msize - 1])
1848   {
1849     GNUNET_break (0);
1850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1851     return;
1852   }
1853   master_context = GNUNET_malloc (sizeof (struct Context));
1854   GNUNET_SERVER_client_keep (client);
1855   master_context->client = client;
1856   master_context->host_id = ntohl (msg->host_id);
1857   master_context->master_ip = GNUNET_strdup (controller_hostname);
1858   LOG_DEBUG ("Our IP: %s\n", master_context->master_ip);
1859   master_context->system =
1860       GNUNET_TESTING_system_create ("testbed", master_context->master_ip, hostname);
1861   host =
1862       GNUNET_TESTBED_host_create_with_id (master_context->host_id,
1863                                           master_context->master_ip,
1864                                           NULL,
1865                                           0);
1866   host_list_add (host);
1867   LOG_DEBUG ("Created master context with host ID: %u\n",
1868              master_context->host_id);
1869   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1870 }
1871
1872
1873 /**
1874  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1875  *
1876  * @param cls NULL
1877  * @param client identification of the client
1878  * @param message the actual message
1879  */
1880 static void
1881 handle_add_host (void *cls, struct GNUNET_SERVER_Client *client,
1882                  const struct GNUNET_MessageHeader *message)
1883 {
1884   struct GNUNET_TESTBED_Host *host;
1885   const struct GNUNET_TESTBED_AddHostMessage *msg;
1886   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
1887   char *username;
1888   char *hostname;
1889   char *emsg;
1890   uint32_t host_id;
1891   uint16_t username_length;
1892   uint16_t hostname_length;
1893   uint16_t reply_size;
1894   uint16_t msize;
1895
1896   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
1897   msize = ntohs (msg->header.size);
1898   username = (char *) &msg[1];
1899   username_length = ntohs (msg->user_name_length);
1900   if (0 != username_length)
1901     username_length++;
1902   /* msg must contain hostname */
1903   GNUNET_assert (msize > (sizeof (struct GNUNET_TESTBED_AddHostMessage) +
1904                           username_length + 1));
1905   if (0 != username_length)
1906     GNUNET_assert ('\0' == username[username_length - 1]);
1907   hostname = username + username_length;
1908   hostname_length =
1909       msize - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
1910   GNUNET_assert ('\0' == hostname[hostname_length - 1]);
1911   GNUNET_assert (strlen (hostname) == hostname_length - 1);
1912   host_id = ntohl (msg->host_id);
1913   LOG_DEBUG ("Received ADDHOST %u message\n", host_id);
1914   LOG_DEBUG ("-------host id: %u\n", host_id);
1915   LOG_DEBUG ("-------hostname: %s\n", hostname);
1916   if (0 != username_length)
1917     LOG_DEBUG ("-------username: %s\n", username);
1918   else
1919   {
1920     LOG_DEBUG ("-------username: NULL\n");
1921     username = NULL;
1922   }
1923   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1924   host =
1925       GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1926                                           ntohs (msg->ssh_port));
1927   GNUNET_assert (NULL != host);
1928   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1929   if (GNUNET_OK != host_list_add (host))
1930   {
1931     /* We are unable to add a host */
1932     emsg = "A host exists with given host-id";
1933     LOG_DEBUG ("%s: %u", emsg, host_id);
1934     GNUNET_TESTBED_host_destroy (host);
1935     reply_size += strlen (emsg) + 1;
1936     reply = GNUNET_malloc (reply_size);
1937     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1938   }
1939   else
1940   {
1941     LOG_DEBUG ("Added host %u at %u\n",
1942                host_id, master_context->host_id);
1943     reply = GNUNET_malloc (reply_size);
1944   }
1945   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
1946   reply->header.size = htons (reply_size);
1947   reply->host_id = htonl (host_id);
1948   queue_message (client, &reply->header);
1949   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1950 }
1951
1952
1953 /**
1954  * Iterator over hash map entries.
1955  *
1956  * @param cls closure
1957  * @param key current key code
1958  * @param value value in the hash map
1959  * @return GNUNET_YES if we should continue to
1960  *         iterate,
1961  *         GNUNET_NO if not.
1962  */
1963 int
1964 ss_exists_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
1965 {
1966   struct SharedService *queried_ss = cls;
1967   struct SharedService *ss = value;
1968
1969   if (0 == strcmp (ss->name, queried_ss->name))
1970     return GNUNET_NO;
1971   else
1972     return GNUNET_YES;
1973 }
1974
1975
1976 /**
1977  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1978  *
1979  * @param cls NULL
1980  * @param client identification of the client
1981  * @param message the actual message
1982  */
1983 static void
1984 handle_configure_shared_service (void *cls, struct GNUNET_SERVER_Client *client,
1985                                  const struct GNUNET_MessageHeader *message)
1986 {
1987   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1988   struct SharedService *ss;
1989   char *service_name;
1990   struct GNUNET_HashCode hash;
1991   uint16_t msg_size;
1992   uint16_t service_name_size;
1993
1994   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1995   msg_size = ntohs (message->size);
1996   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1997   {
1998     GNUNET_break (0);
1999     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2000     return;
2001   }
2002   service_name_size =
2003       msg_size - sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
2004   service_name = (char *) &msg[1];
2005   if ('\0' != service_name[service_name_size - 1])
2006   {
2007     GNUNET_break (0);
2008     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2009     return;
2010   }
2011   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
2012              service_name, ntohl (msg->num_peers));
2013   if (ntohl (msg->host_id) != master_context->host_id)
2014   {
2015     route_message (ntohl (msg->host_id), message);
2016     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2017     return;
2018   }
2019   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2020   ss = GNUNET_malloc (sizeof (struct SharedService));
2021   ss->name = strdup (service_name);
2022   ss->num_shared = ntohl (msg->num_peers);
2023   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
2024   if (GNUNET_SYSERR ==
2025       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
2026                                                   &ss_exists_iterator, ss))
2027   {
2028     LOG (GNUNET_ERROR_TYPE_WARNING,
2029          "Service %s already configured as a shared service. "
2030          "Ignoring service sharing request \n", ss->name);
2031     GNUNET_free (ss->name);
2032     GNUNET_free (ss);
2033     return;
2034   }
2035   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
2036                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2037 }
2038
2039
2040 /**
2041  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
2042  *
2043  * @param cls NULL
2044  * @param client identification of the client
2045  * @param message the actual message
2046  */
2047 static void
2048 handle_link_controllers (void *cls, struct GNUNET_SERVER_Client *client,
2049                          const struct GNUNET_MessageHeader *message)
2050 {
2051   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
2052   struct GNUNET_CONFIGURATION_Handle *cfg;
2053   struct LCFContextQueue *lcfq;
2054   struct Route *route;
2055   struct Route *new_route;
2056   char *config;
2057   uLongf dest_size;
2058   size_t config_size;
2059   uint32_t delegated_host_id;
2060   uint32_t slave_host_id;
2061   uint16_t msize;
2062
2063   if (NULL == master_context)
2064   {
2065     GNUNET_break (0);
2066     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2067     return;
2068   }
2069   msize = ntohs (message->size);
2070   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
2071   {
2072     GNUNET_break (0);
2073     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2074     return;
2075   }
2076   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
2077   delegated_host_id = ntohl (msg->delegated_host_id);
2078   if (delegated_host_id == master_context->host_id)
2079   {
2080     GNUNET_break (0);
2081     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
2082     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2083     return;
2084   }
2085   if ((delegated_host_id >= host_list_size) ||
2086       (NULL == host_list[delegated_host_id]))
2087   {
2088     LOG (GNUNET_ERROR_TYPE_WARNING,
2089          "Delegated host %u not registered with us\n", delegated_host_id);
2090     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2091     return;
2092   }
2093   slave_host_id = ntohl (msg->slave_host_id);
2094   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
2095   {
2096     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host %u not registered with us\n",
2097          slave_host_id);
2098     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2099     return;
2100   }
2101   if (slave_host_id == delegated_host_id)
2102   {
2103     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
2104     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2105     return;
2106   }
2107
2108   if (slave_host_id == master_context->host_id) /* Link from us */
2109   {
2110     struct Slave *slave;
2111     struct LinkControllersContext *lcc;
2112
2113     msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
2114     config_size = ntohs (msg->config_size);
2115     if ((delegated_host_id < slave_list_size) && (NULL != slave_list[delegated_host_id]))       /* We have already added */
2116     {
2117       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
2118            delegated_host_id);
2119       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2120       return;
2121     }
2122     config = GNUNET_malloc (config_size);
2123     dest_size = (uLongf) config_size;
2124     if (Z_OK !=
2125         uncompress ((Bytef *) config, &dest_size, (const Bytef *) &msg[1],
2126                     (uLong) msize))
2127     {
2128       GNUNET_break (0);         /* Compression error */
2129       GNUNET_free (config);
2130       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2131       return;
2132     }
2133     if (config_size != dest_size)
2134     {
2135       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
2136       GNUNET_free (config);
2137       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2138       return;
2139     }
2140     cfg = GNUNET_CONFIGURATION_create ();       /* Free here or in lcfcontext */
2141     if (GNUNET_OK !=
2142         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
2143     {
2144       GNUNET_break (0);         /* Configuration parsing error */
2145       GNUNET_free (config);
2146       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2147       return;
2148     }
2149     GNUNET_free (config);
2150     if ((delegated_host_id < slave_list_size) &&
2151         (NULL != slave_list[delegated_host_id]))
2152     {
2153       GNUNET_break (0);         /* Configuration parsing error */
2154       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2155       return;
2156     }
2157     slave = GNUNET_malloc (sizeof (struct Slave));
2158     slave->host_id = delegated_host_id;
2159     slave->reghost_map = GNUNET_CONTAINER_multihashmap_create (100, GNUNET_NO);
2160     slave_list_add (slave);
2161     if (1 != msg->is_subordinate)
2162     {
2163       slave->controller =
2164           GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
2165                                              event_mask,
2166                                              &slave_event_callback, slave);
2167       slave->cfg = cfg;
2168       if (NULL != slave->controller)
2169         send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
2170       else
2171         send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2172                                  "Could not connect to delegated controller");
2173       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2174       return;
2175     }
2176     lcc = GNUNET_malloc (sizeof (struct LinkControllersContext));
2177     lcc->operation_id = GNUNET_ntohll (msg->operation_id);
2178     GNUNET_SERVER_client_keep (client);
2179     lcc->client = client;
2180     slave->lcc = lcc;
2181     slave->controller_proc =
2182         GNUNET_TESTBED_controller_start (master_context->master_ip,
2183                                          host_list[slave->host_id], cfg,
2184                                          &slave_status_callback, slave);
2185     GNUNET_CONFIGURATION_destroy (cfg);
2186     new_route = GNUNET_malloc (sizeof (struct Route));
2187     new_route->dest = delegated_host_id;
2188     new_route->thru = master_context->host_id;
2189     route_list_add (new_route);
2190     return;
2191   }
2192
2193   /* Route the request */
2194   if (slave_host_id >= route_list_size)
2195   {
2196     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
2197     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2198     return;
2199   }
2200   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
2201   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
2202   lcfq->lcf->delegated_host_id = delegated_host_id;
2203   lcfq->lcf->slave_host_id = slave_host_id;
2204   route = find_dest_route (slave_host_id);
2205   GNUNET_assert (NULL != route);        /* because we add routes carefully */
2206   GNUNET_assert (route->dest < slave_list_size);
2207   GNUNET_assert (NULL != slave_list[route->dest]);
2208   lcfq->lcf->state = INIT;
2209   lcfq->lcf->operation_id = GNUNET_ntohll (msg->operation_id);
2210   lcfq->lcf->gateway = slave_list[route->dest];
2211   lcfq->lcf->msg = GNUNET_malloc (msize);
2212   (void) memcpy (lcfq->lcf->msg, msg, msize);
2213   GNUNET_SERVER_client_keep (client);
2214   lcfq->lcf->client = client;
2215   if (NULL == lcfq_head)
2216   {
2217     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2218     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
2219     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq->lcf);
2220   }
2221   else
2222     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
2223   /* FIXME: Adding a new route should happen after the controllers are linked
2224    * successfully */
2225   if (1 != msg->is_subordinate)
2226   {
2227     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2228     return;
2229   }
2230   if ((delegated_host_id < route_list_size)
2231       && (NULL != route_list[delegated_host_id]))
2232   {
2233     GNUNET_break_op (0);        /* Are you trying to link delegated host twice
2234                                    with is subordinate flag set to GNUNET_YES? */
2235     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2236     return;
2237   }
2238   new_route = GNUNET_malloc (sizeof (struct Route));
2239   new_route->dest = delegated_host_id;
2240   new_route->thru = route->dest;
2241   route_list_add (new_route);
2242   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2243 }
2244
2245
2246 /**
2247  * The task to be executed if the forwarded peer create operation has been
2248  * timed out
2249  *
2250  * @param cls the FowardedOperationContext
2251  * @param tc the TaskContext from the scheduler
2252  */
2253 static void
2254 peer_create_forward_timeout (void *cls,
2255                              const struct GNUNET_SCHEDULER_TaskContext *tc)
2256 {
2257   struct ForwardedOperationContext *fopc = cls;
2258
2259   GNUNET_free (fopc->cls);
2260   forwarded_operation_timeout (fopc, tc);
2261 }
2262
2263
2264 /**
2265  * Callback to be called when forwarded peer create operation is successfull. We
2266  * have to relay the reply msg back to the client
2267  *
2268  * @param cls ForwardedOperationContext
2269  * @param msg the peer create success message
2270  */
2271 static void
2272 peer_create_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
2273 {
2274   struct ForwardedOperationContext *fopc = cls;
2275   struct Peer *remote_peer;
2276
2277   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS)
2278   {
2279     GNUNET_assert (NULL != fopc->cls);
2280     remote_peer = fopc->cls;
2281     peer_list_add (remote_peer);
2282   }
2283   forwarded_operation_reply_relay (fopc, msg);
2284 }
2285
2286
2287 /**
2288  * Function to destroy a peer
2289  *
2290  * @param peer the peer structure to destroy
2291  */
2292 static void
2293 destroy_peer (struct Peer *peer)
2294 {
2295   GNUNET_break (0 == peer->reference_cnt);
2296   if (GNUNET_YES == peer->is_remote)
2297   {
2298     peer_list_remove (peer);
2299     GNUNET_free (peer);
2300     return;
2301   }
2302   if (GNUNET_YES == peer->details.local.is_running)
2303   {
2304     GNUNET_TESTING_peer_stop (peer->details.local.peer);
2305     peer->details.local.is_running = GNUNET_NO;
2306   }
2307   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
2308   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
2309   peer_list_remove (peer);
2310   GNUNET_free (peer);
2311 }
2312
2313
2314 /**
2315  * Callback to be called when forwarded peer destroy operation is successfull. We
2316  * have to relay the reply msg back to the client
2317  *
2318  * @param cls ForwardedOperationContext
2319  * @param msg the peer create success message
2320  */
2321 static void
2322 peer_destroy_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
2323 {
2324   struct ForwardedOperationContext *fopc = cls;
2325   struct Peer *remote_peer;
2326
2327   if (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS == ntohs (msg->type))
2328   {
2329     remote_peer = fopc->cls;
2330     GNUNET_assert (NULL != remote_peer);
2331     remote_peer->destroy_flag = GNUNET_YES;
2332     if (0 == remote_peer->reference_cnt)
2333       destroy_peer (remote_peer);
2334   }
2335   forwarded_operation_reply_relay (fopc, msg);
2336 }
2337
2338
2339
2340 /**
2341  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
2342  *
2343  * @param cls NULL
2344  * @param client identification of the client
2345  * @param message the actual message
2346  */
2347 static void
2348 handle_peer_create (void *cls, struct GNUNET_SERVER_Client *client,
2349                     const struct GNUNET_MessageHeader *message)
2350 {
2351   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
2352   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
2353   struct GNUNET_CONFIGURATION_Handle *cfg;
2354   struct ForwardedOperationContext *fo_ctxt;
2355   struct Route *route;
2356   struct Peer *peer;
2357   char *config;
2358   size_t dest_size;
2359   int ret;
2360   uint32_t config_size;
2361   uint32_t host_id;
2362   uint32_t peer_id;
2363   uint16_t msize;
2364
2365
2366   msize = ntohs (message->size);
2367   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
2368   {
2369     GNUNET_break (0);           /* We need configuration */
2370     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2371     return;
2372   }
2373   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
2374   host_id = ntohl (msg->host_id);
2375   peer_id = ntohl (msg->peer_id);
2376   if (UINT32_MAX == peer_id)
2377   {
2378     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2379                              "Cannot create peer with given ID");
2380     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2381     return;
2382   }
2383   if (host_id == master_context->host_id)
2384   {
2385     char *emsg;
2386
2387     /* We are responsible for this peer */
2388     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
2389     config_size = ntohl (msg->config_size);
2390     config = GNUNET_malloc (config_size);
2391     dest_size = config_size;
2392     if (Z_OK !=
2393         (ret =
2394          uncompress ((Bytef *) config, (uLongf *) & dest_size,
2395                      (const Bytef *) &msg[1], (uLong) msize)))
2396     {
2397       GNUNET_break (0);         /* uncompression error */
2398       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2399       return;
2400     }
2401     if (config_size != dest_size)
2402     {
2403       GNUNET_break (0);         /* Uncompressed config size mismatch */
2404       GNUNET_free (config);
2405       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2406       return;
2407     }
2408     cfg = GNUNET_CONFIGURATION_create ();
2409     if (GNUNET_OK !=
2410         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
2411     {
2412       GNUNET_break (0);         /* Configuration parsing error */
2413       GNUNET_free (config);
2414       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2415       return;
2416     }
2417     GNUNET_free (config);
2418     peer = GNUNET_malloc (sizeof (struct Peer));
2419     peer->is_remote = GNUNET_NO;
2420     peer->details.local.cfg = cfg;
2421     peer->id = peer_id;
2422     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
2423     peer->details.local.peer =
2424         GNUNET_TESTING_peer_configure (master_context->system,
2425                                        peer->details.local.cfg, peer->id,
2426                                        NULL /* Peer id */ ,
2427                                        &emsg);
2428     if (NULL == peer->details.local.peer)
2429     {
2430       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
2431       GNUNET_free (emsg);
2432       GNUNET_free (peer);
2433       GNUNET_break (0);
2434       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2435       return;
2436     }
2437     peer->details.local.is_running = GNUNET_NO;
2438     peer_list_add (peer);
2439     reply =
2440         GNUNET_malloc (sizeof
2441                        (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
2442     reply->header.size =
2443         htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
2444     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
2445     reply->peer_id = msg->peer_id;
2446     reply->operation_id = msg->operation_id;
2447     queue_message (client, &reply->header);
2448     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2449     return;
2450   }
2451
2452   /* Forward peer create request */
2453   route = find_dest_route (host_id);
2454   if (NULL == route)
2455   {
2456     GNUNET_break (0);
2457     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2458     return;
2459   }
2460
2461   peer = GNUNET_malloc (sizeof (struct Peer));
2462   peer->is_remote = GNUNET_YES;
2463   peer->id = peer_id;
2464   peer->details.remote.slave = slave_list[route->dest];
2465   peer->details.remote.remote_host_id = host_id;
2466   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2467   GNUNET_SERVER_client_keep (client);
2468   fo_ctxt->client = client;
2469   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);
2470   fo_ctxt->cls = peer; //slave_list[route->dest]->controller;
2471   fo_ctxt->type = OP_PEER_CREATE;
2472   fo_ctxt->opc =
2473       GNUNET_TESTBED_forward_operation_msg_ (slave_list [route->dest]->controller,
2474                                              fo_ctxt->operation_id,
2475                                              &msg->header,
2476                                              peer_create_success_cb, fo_ctxt);
2477   fo_ctxt->timeout_task =
2478       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &peer_create_forward_timeout,
2479                                     fo_ctxt);
2480   GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fo_ctxt);
2481   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2482 }
2483
2484
2485 /**
2486  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
2487  *
2488  * @param cls NULL
2489  * @param client identification of the client
2490  * @param message the actual message
2491  */
2492 static void
2493 handle_peer_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2494                      const struct GNUNET_MessageHeader *message)
2495 {
2496   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
2497   struct ForwardedOperationContext *fopc;
2498   struct Peer *peer;
2499   uint32_t peer_id;
2500
2501   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
2502   peer_id = ntohl (msg->peer_id);
2503   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
2504              peer_id, GNUNET_ntohll (msg->operation_id));
2505   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
2506   {
2507     LOG (GNUNET_ERROR_TYPE_ERROR,
2508          "Asked to destroy a non existent peer with id: %u\n", peer_id);
2509     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2510                              "Peer doesn't exist");
2511     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2512     return;
2513   }
2514   peer = peer_list[peer_id];
2515   if (GNUNET_YES == peer->is_remote)
2516   {
2517     /* Forward the destory message to sub controller */
2518     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2519     GNUNET_SERVER_client_keep (client);
2520     fopc->client = client;
2521     fopc->cls = peer;
2522     fopc->type = OP_PEER_DESTROY;
2523     fopc->operation_id = GNUNET_ntohll (msg->operation_id);    
2524     fopc->opc = 
2525         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2526                                                fopc->operation_id, &msg->header,
2527                                                &peer_destroy_success_cb,
2528                                                fopc);
2529     fopc->timeout_task =
2530         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2531                                       fopc);
2532     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
2533     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2534     return;
2535   }
2536   peer->destroy_flag = GNUNET_YES;
2537   if (0 == peer->reference_cnt)
2538     destroy_peer (peer);
2539   else
2540     LOG (GNUNET_ERROR_TYPE_DEBUG,
2541          "Delaying peer destroy as peer is currently in use\n");
2542   send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
2543   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2544 }
2545
2546
2547 /**
2548  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
2549  *
2550  * @param cls NULL
2551  * @param client identification of the client
2552  * @param message the actual message
2553  */
2554 static void
2555 handle_peer_start (void *cls, struct GNUNET_SERVER_Client *client,
2556                    const struct GNUNET_MessageHeader *message)
2557 {
2558   const struct GNUNET_TESTBED_PeerStartMessage *msg;
2559   struct GNUNET_TESTBED_PeerEventMessage *reply;
2560   struct ForwardedOperationContext *fopc;
2561   struct Peer *peer;
2562   uint32_t peer_id;
2563
2564   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
2565   peer_id = ntohl (msg->peer_id);
2566   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
2567   {
2568     GNUNET_break (0);
2569     LOG (GNUNET_ERROR_TYPE_ERROR,
2570          "Asked to start a non existent peer with id: %u\n", peer_id);
2571     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2572     return;
2573   }
2574   peer = peer_list[peer_id];
2575   if (GNUNET_YES == peer->is_remote)
2576   {
2577     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2578     GNUNET_SERVER_client_keep (client);
2579     fopc->client = client;
2580     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2581     fopc->type = OP_PEER_START;
2582     fopc->opc =
2583         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2584                                                fopc->operation_id, &msg->header,
2585                                                &forwarded_operation_reply_relay,
2586                                                fopc);
2587     fopc->timeout_task =
2588         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2589                                       fopc);
2590     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
2591     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2592     return;
2593   }
2594   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer->details.local.peer))
2595   {
2596     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2597                              "Failed to start");
2598     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2599     return;
2600   }
2601   peer->details.local.is_running = GNUNET_YES;
2602   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2603   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
2604   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2605   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
2606   reply->host_id = htonl (master_context->host_id);
2607   reply->peer_id = msg->peer_id;
2608   reply->operation_id = msg->operation_id;
2609   queue_message (client, &reply->header);
2610   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2611 }
2612
2613
2614 /**
2615  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
2616  *
2617  * @param cls NULL
2618  * @param client identification of the client
2619  * @param message the actual message
2620  */
2621 static void
2622 handle_peer_stop (void *cls, struct GNUNET_SERVER_Client *client,
2623                   const struct GNUNET_MessageHeader *message)
2624 {
2625   const struct GNUNET_TESTBED_PeerStopMessage *msg;
2626   struct GNUNET_TESTBED_PeerEventMessage *reply;
2627   struct ForwardedOperationContext *fopc;
2628   struct Peer *peer;
2629   uint32_t peer_id;
2630
2631   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
2632   peer_id = ntohl (msg->peer_id);
2633   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
2634   {
2635     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2636                              "Peer not found");
2637     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2638     return;
2639   }
2640   peer = peer_list[peer_id];
2641   if (GNUNET_YES == peer->is_remote)
2642   {
2643     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2644     GNUNET_SERVER_client_keep (client);
2645     fopc->client = client;
2646     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2647     fopc->type = OP_PEER_STOP;
2648     fopc->opc =
2649         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2650                                                fopc->operation_id, &msg->header,
2651                                                &forwarded_operation_reply_relay,
2652                                                fopc);
2653     fopc->timeout_task =
2654         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2655                                       fopc);
2656     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
2657     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2658     return;
2659   }
2660   if (GNUNET_OK != GNUNET_TESTING_peer_stop (peer->details.local.peer))
2661   {
2662     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2663                              "Peer not running");
2664     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2665     return;
2666   }
2667   peer->details.local.is_running = GNUNET_NO;
2668   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2669   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
2670   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
2671   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
2672   reply->host_id = htonl (master_context->host_id);
2673   reply->peer_id = msg->peer_id;
2674   reply->operation_id = msg->operation_id;
2675   queue_message (client, &reply->header);
2676   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2677 }
2678
2679
2680 /**
2681  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
2682  *
2683  * @param cls NULL
2684  * @param client identification of the client
2685  * @param message the actual message
2686  */
2687 static void
2688 handle_peer_get_config (void *cls, struct GNUNET_SERVER_Client *client,
2689                         const struct GNUNET_MessageHeader *message)
2690 {
2691   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
2692   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
2693   struct Peer *peer;
2694   char *config;
2695   char *xconfig;
2696   size_t c_size;
2697   size_t xc_size;
2698   uint32_t peer_id;
2699   uint16_t msize;
2700
2701   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
2702   peer_id = ntohl (msg->peer_id);
2703   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
2704   {
2705     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
2706                              "Peer not found");
2707     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2708     return;
2709   }
2710   peer = peer_list[peer_id];
2711   if (GNUNET_YES == peer->is_remote)
2712   {
2713     struct ForwardedOperationContext *fopc;
2714     
2715     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2716     GNUNET_SERVER_client_keep (client);
2717     fopc->client = client;
2718     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
2719     fopc->type = OP_PEER_INFO;
2720     fopc->opc =
2721         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
2722                                                fopc->operation_id, &msg->header,
2723                                                &forwarded_operation_reply_relay,
2724                                                fopc);
2725     fopc->timeout_task =
2726         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
2727                                       fopc);
2728     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc); 
2729     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2730     return;
2731   }
2732   config =
2733       GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
2734                                       &c_size);
2735   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
2736   GNUNET_free (config);
2737   msize =
2738       xc_size +
2739       sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
2740   reply = GNUNET_realloc (xconfig, msize);
2741   (void) memmove (&reply[1], reply, xc_size);
2742   reply->header.size = htons (msize);
2743   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
2744   reply->peer_id = msg->peer_id;
2745   reply->operation_id = msg->operation_id;
2746   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
2747                                     &reply->peer_identity);
2748   reply->config_size = htons ((uint16_t) c_size);
2749   queue_message (client, &reply->header);
2750   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2751 }
2752
2753
2754 /**
2755  * Cleanup overlay connect context structure
2756  *
2757  * @param occ the overlay connect context
2758  */
2759 static void
2760 cleanup_occ (struct OverlayConnectContext *occ)
2761 {
2762   LOG_DEBUG ("Cleaning up occ\n");
2763   GNUNET_free_non_null (occ->emsg);
2764   GNUNET_free_non_null (occ->hello);
2765   GNUNET_SERVER_client_drop (occ->client);
2766   if (NULL != occ->opc)
2767     GNUNET_TESTBED_forward_operation_msg_cancel_ (occ->opc);
2768   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
2769     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
2770   if (GNUNET_SCHEDULER_NO_TASK != occ->cleanup_task)
2771     GNUNET_SCHEDULER_cancel (occ->cleanup_task);
2772   if (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task)
2773     GNUNET_SCHEDULER_cancel (occ->timeout_task);
2774   if (NULL != occ->ch)
2775   {
2776     GNUNET_CORE_disconnect (occ->ch);
2777     occ->peer->reference_cnt--;
2778   }
2779   if (NULL != occ->ghh)
2780     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
2781   if (NULL != occ->ohh)
2782     GNUNET_TRANSPORT_offer_hello_cancel (occ->ohh);
2783   if (GNUNET_SCHEDULER_NO_TASK != occ->tcc.task)
2784     GNUNET_SCHEDULER_cancel (occ->tcc.task);
2785   if (NULL != occ->tcc.tch)
2786     GNUNET_TRANSPORT_try_connect_cancel (occ->tcc.tch);
2787   if (NULL != occ->p1th)
2788   {
2789     GNUNET_TRANSPORT_disconnect (occ->p1th);
2790     occ->peer->reference_cnt--;
2791   }
2792   if (NULL != occ->tcc.th)
2793   {
2794     GNUNET_TRANSPORT_disconnect (occ->tcc.th);
2795     peer_list[occ->other_peer_id]->reference_cnt--;
2796   }
2797   if ((GNUNET_YES == occ->peer->destroy_flag)
2798       && (0 == occ->peer->reference_cnt))
2799     destroy_peer (occ->peer);
2800   if ((NULL == occ->peer2_controller)
2801       && (GNUNET_YES == peer_list[occ->other_peer_id]->destroy_flag)
2802         && (0 == peer_list[occ->other_peer_id]->reference_cnt))
2803       destroy_peer (peer_list[occ->other_peer_id]);  
2804   GNUNET_CONTAINER_DLL_remove (occq_head, occq_tail, occ);
2805   GNUNET_free (occ);
2806 }
2807
2808
2809 /**
2810  * Task for cleaing up overlay connect context structure
2811  *
2812  * @param cls the overlay connect context
2813  * @param tc the task context
2814  */
2815 static void
2816 do_cleanup_occ (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2817 {
2818   struct OverlayConnectContext *occ = cls;
2819   
2820   occ->cleanup_task = GNUNET_SCHEDULER_NO_TASK;
2821   cleanup_occ (occ);
2822 }
2823
2824
2825 /**
2826  * Task which will be run when overlay connect request has been timed out
2827  *
2828  * @param cls the OverlayConnectContext
2829  * @param tc the TaskContext
2830  */
2831 static void
2832 timeout_overlay_connect (void *cls,
2833                          const struct GNUNET_SCHEDULER_TaskContext *tc)
2834 {
2835   struct OverlayConnectContext *occ = cls;
2836
2837   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2838   LOG (GNUNET_ERROR_TYPE_WARNING,
2839        "Timeout while connecting peers %u and %u\n",
2840        occ->peer_id, occ->other_peer_id);
2841   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
2842   cleanup_occ (occ);
2843 }
2844
2845
2846
2847 /**
2848  * Function called to notify transport users that another
2849  * peer connected to us.
2850  *
2851  * @param cls closure
2852  * @param new_peer the peer that connected
2853  * @param ats performance data
2854  * @param ats_count number of entries in ats (excluding 0-termination)
2855  */
2856 static void
2857 overlay_connect_notify (void *cls, const struct GNUNET_PeerIdentity *new_peer,
2858                         const struct GNUNET_ATS_Information *ats,
2859                         unsigned int ats_count)
2860 {
2861   struct OverlayConnectContext *occ = cls;
2862   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
2863   char *new_peer_str;
2864   char *other_peer_str;
2865
2866   LOG_DEBUG ("Overlay connect notify\n");
2867   if (0 ==
2868       memcmp (new_peer, &occ->peer_identity,
2869               sizeof (struct GNUNET_PeerIdentity)))
2870     return;
2871   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
2872   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2873   if (0 !=
2874       memcmp (new_peer, &occ->other_peer_identity,
2875               sizeof (struct GNUNET_PeerIdentity)))
2876   {
2877     LOG_DEBUG ("Unexpected peer %4s connected when expecting peer %4s\n",
2878                new_peer_str, other_peer_str);
2879     GNUNET_free (new_peer_str);
2880     GNUNET_free (other_peer_str);
2881     return;
2882   }
2883   GNUNET_free (new_peer_str);
2884   LOG_DEBUG ("Peer %4s connected to peer %4s\n", other_peer_str, 
2885              GNUNET_i2s (&occ->peer_identity));
2886   GNUNET_free (other_peer_str);
2887   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
2888   {
2889     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
2890     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2891   }
2892   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
2893   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2894   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2895   if (GNUNET_SCHEDULER_NO_TASK != occ->tcc.task)
2896   {
2897     GNUNET_SCHEDULER_cancel (occ->tcc.task);
2898     occ->tcc.task = GNUNET_SCHEDULER_NO_TASK;
2899   }
2900   GNUNET_free_non_null (occ->emsg);
2901   occ->emsg = NULL;
2902   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
2903   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2904   msg->header.size =
2905       htons (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2906   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
2907   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
2908   msg->peer1 = htonl (occ->peer_id);
2909   msg->peer2 = htonl (occ->other_peer_id);
2910   msg->operation_id = GNUNET_htonll (occ->op_id);
2911   queue_message (occ->client, &msg->header);
2912   occ->cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup_occ, occ);
2913   //cleanup_occ (occ);
2914 }
2915
2916
2917 /**
2918  * Task to ask transport of a peer to connect to another peer
2919  *
2920  * @param cls the TryConnectContext
2921  * @param tc the scheduler task context
2922  */
2923 static void
2924 try_connect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2925
2926
2927 /**
2928  * Callback to be called with result of the try connect request.
2929  *
2930  * @param cls the overlay connect context
2931  * @param result GNUNET_OK if message was transmitted to transport service
2932  *               GNUNET_SYSERR if message was not transmitted to transport service
2933  */
2934 static void 
2935 try_connect_cb (void *cls, const int result)
2936 {
2937   struct TryConnectContext *tcc = cls;
2938
2939   tcc->tch = NULL;
2940   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == tcc->task);
2941   tcc->task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2942                                             (GNUNET_TIME_UNIT_MILLISECONDS,
2943                                              pow (10, ++tcc->retries)),
2944                                             &try_connect_task, tcc);
2945 }
2946
2947
2948 /**
2949  * Task to ask transport of a peer to connect to another peer
2950  *
2951  * @param cls the TryConnectContext
2952  * @param tc the scheduler task context
2953  */
2954 static void
2955 try_connect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2956 {
2957   struct TryConnectContext *tcc = cls;
2958
2959   tcc->task = GNUNET_SCHEDULER_NO_TASK;
2960   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2961     return;
2962   GNUNET_assert (NULL == tcc->tch);
2963   GNUNET_assert (NULL != tcc->pid);
2964   GNUNET_assert (NULL != tcc->th);
2965   tcc->tch = GNUNET_TRANSPORT_try_connect (tcc->th, tcc->pid, &try_connect_cb, tcc);
2966 }
2967
2968
2969 /**
2970  * Task to offer HELLO of peer 1 to peer 2 and try to make peer 2 to connect to
2971  * peer 1.
2972  *
2973  * @param cls the OverlayConnectContext
2974  * @param tc the TaskContext from scheduler
2975  */
2976 static void
2977 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2978
2979
2980 /**
2981  * Task that is run when hello has been sent
2982  *
2983  * @param cls the overlay connect context
2984  * @param tc the scheduler task context; if tc->reason =
2985  *          GNUNET_SCHEDULER_REASON_TIMEOUT then sending HELLO failed; if
2986  *          GNUNET_SCHEDULER_REASON_READ_READY is succeeded
2987  */
2988 static void
2989 occ_hello_sent_cb (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2990 {
2991   struct OverlayConnectContext *occ = cls;
2992
2993   occ->ohh = NULL;
2994   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == occ->send_hello_task);
2995   if (GNUNET_SCHEDULER_REASON_TIMEOUT == tc->reason)
2996   {
2997     GNUNET_free_non_null (occ->emsg);
2998     occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
2999     occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
3000     return;
3001   }
3002   if (GNUNET_SCHEDULER_REASON_READ_READY != tc->reason)
3003     return;
3004   GNUNET_free_non_null (occ->emsg);
3005   occ->emsg = GNUNET_strdup ("Timeout while try connect\n");
3006   occ->tcc.pid =  &occ->peer_identity;
3007   occ->tcc.task = GNUNET_SCHEDULER_add_now (&try_connect_task, &occ->tcc);
3008 }
3009
3010
3011 /**
3012  * Task to offer HELLO of peer 1 to peer 2 and try to make peer 2 to connect to
3013  * peer 1.
3014  *
3015  * @param cls the OverlayConnectContext
3016  * @param tc the TaskContext from scheduler
3017  */
3018 static void
3019 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3020 {
3021   struct OverlayConnectContext *occ = cls;
3022   char *other_peer_str;
3023
3024   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
3025   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3026     return;
3027   GNUNET_assert (NULL != occ->hello);
3028   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
3029   if (NULL != occ->peer2_controller)
3030   {
3031     struct GNUNET_TESTBED_RequestConnectMessage *msg;
3032     uint16_t msize;
3033     uint16_t hello_size;
3034
3035     LOG_DEBUG ("Offering HELLO of %s to %s via Remote Overlay Request\n", 
3036                GNUNET_i2s (&occ->peer_identity), other_peer_str);
3037     hello_size = ntohs (occ->hello->size);
3038     msize = sizeof (struct GNUNET_TESTBED_RequestConnectMessage) + hello_size;
3039     msg = GNUNET_malloc (msize);
3040     msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT);
3041     msg->header.size = htons (msize);
3042     msg->peer = htonl (occ->other_peer_id);
3043     msg->operation_id = GNUNET_htonll (occ->op_id);
3044     (void) memcpy (&msg->peer_identity, &occ->peer_identity,
3045                    sizeof (struct GNUNET_PeerIdentity));
3046     memcpy (msg->hello, occ->hello, hello_size);
3047     GNUNET_TESTBED_queue_message_ (occ->peer2_controller, &msg->header);
3048   }
3049   else
3050   {
3051     LOG_DEBUG ("Offering HELLO of %s to %s\n", 
3052                GNUNET_i2s (&occ->peer_identity), other_peer_str);
3053     occ->ohh = GNUNET_TRANSPORT_offer_hello (occ->tcc.th,
3054                                              occ->hello,
3055                                              occ_hello_sent_cb,
3056                                              occ);
3057     if (NULL == occ->ohh)
3058     {
3059       GNUNET_break (0);
3060       occ->send_hello_task =
3061           GNUNET_SCHEDULER_add_delayed
3062           (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3063                                           100 + GNUNET_CRYPTO_random_u32
3064                                           (GNUNET_CRYPTO_QUALITY_WEAK, 500)),
3065            &send_hello, occ);
3066     }
3067   }
3068   GNUNET_free (other_peer_str);  
3069 }
3070
3071 /**
3072  * Test for checking whether HELLO message is empty
3073  *
3074  * @param cls empty flag to set
3075  * @param address the HELLO
3076  * @param expiration expiration of the HELLO
3077  * @return
3078  */
3079 static int
3080 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
3081               struct GNUNET_TIME_Absolute expiration)
3082 {
3083   int *empty = cls;
3084
3085   *empty = GNUNET_NO;
3086   return GNUNET_OK;
3087 }
3088
3089
3090 /**
3091  * Function called whenever there is an update to the HELLO of peers in the
3092  * OverlayConnectClosure. If we have a valid HELLO, we connect to the peer 2's
3093  * transport and offer peer 1's HELLO and ask peer 2 to connect to peer 1
3094  *
3095  * @param cls closure
3096  * @param hello our updated HELLO
3097  */
3098 static void
3099 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
3100 {
3101   struct OverlayConnectContext *occ = cls;
3102   int empty;
3103   uint16_t msize;
3104
3105   msize = ntohs (hello->size);
3106   empty = GNUNET_YES;
3107   (void) GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *)
3108                                          hello, GNUNET_NO, &test_address,
3109                                          &empty);
3110   if (GNUNET_YES == empty)
3111   {
3112     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->peer_identity));
3113     return;
3114   }
3115   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->peer_identity));
3116   occ->hello = GNUNET_malloc (msize);
3117   memcpy (occ->hello, hello, msize);
3118   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
3119   occ->ghh = NULL;
3120   GNUNET_TRANSPORT_disconnect (occ->p1th);
3121   occ->p1th = NULL;
3122   occ->peer->reference_cnt--;
3123   GNUNET_free_non_null (occ->emsg);
3124   if (NULL == occ->peer2_controller)
3125   {
3126     peer_list[occ->other_peer_id]->reference_cnt++;
3127     occ->tcc.th =
3128         GNUNET_TRANSPORT_connect (peer_list[occ->other_peer_id]->details.local.cfg,
3129                                   &occ->other_peer_identity, NULL, NULL, NULL,
3130                                   NULL);
3131     if (NULL == occ->tcc.th)
3132     {
3133       GNUNET_asprintf (&occ->emsg, "Cannot connect to TRANSPORT of %s\n",
3134                        GNUNET_i2s (&occ->other_peer_identity));
3135       GNUNET_SCHEDULER_cancel (occ->timeout_task);
3136       occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
3137       return;
3138     }
3139   }
3140   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
3141   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
3142 }
3143
3144
3145 /**
3146  * Function called after GNUNET_CORE_connect has succeeded (or failed
3147  * for good).  Note that the private key of the peer is intentionally
3148  * not exposed here; if you need it, your process should try to read
3149  * the private key file directly (which should work if you are
3150  * authorized...).
3151  *
3152  * @param cls closure
3153  * @param server handle to the server, NULL if we failed
3154  * @param my_identity ID of this peer, NULL if we failed
3155  */
3156 static void
3157 core_startup_cb (void *cls, struct GNUNET_CORE_Handle *server,
3158                  const struct GNUNET_PeerIdentity *my_identity)
3159 {
3160   struct OverlayConnectContext *occ = cls;
3161
3162   GNUNET_free_non_null (occ->emsg);
3163   occ->emsg = GNUNET_strdup ("Failed to connect to CORE\n");
3164   if ((NULL == server) || (NULL == my_identity))
3165     goto error_return;
3166   GNUNET_free (occ->emsg);
3167   occ->ch = server;
3168   occ->emsg = NULL;
3169   memcpy (&occ->peer_identity, my_identity,
3170           sizeof (struct GNUNET_PeerIdentity));
3171   occ->peer->reference_cnt++;
3172   occ->p1th =
3173       GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg,
3174                                 &occ->peer_identity, NULL, NULL, NULL, NULL);
3175   if (NULL == occ->p1th)
3176   {
3177     GNUNET_asprintf (&occ->emsg, "Cannot connect to TRANSPORT of peers %4s",
3178                     GNUNET_i2s (&occ->peer_identity));
3179     goto error_return;
3180   }
3181   LOG_DEBUG ("Acquiring HELLO of peer %s\n", GNUNET_i2s (&occ->peer_identity));
3182   occ->emsg = GNUNET_strdup ("Timeout while acquiring HELLO message");
3183   occ->ghh = GNUNET_TRANSPORT_get_hello (occ->p1th, &hello_update_cb, occ);
3184   return;
3185   
3186  error_return:
3187   GNUNET_SCHEDULER_cancel (occ->timeout_task);
3188   occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
3189   return;
3190 }
3191
3192
3193 /**
3194  * Callback to be called when forwarded get peer config operation as part of
3195  * overlay connect is successfull. Connection to Peer 1's core is made and is
3196  * checked for new connection from peer 2
3197  *
3198  * @param cls ForwardedOperationContext
3199  * @param msg the peer create success message
3200  */
3201 static void
3202 overlay_connect_get_config (void *cls, const struct GNUNET_MessageHeader *msg)
3203 {
3204   struct OverlayConnectContext *occ = cls;
3205   const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *cmsg;
3206   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
3207     {NULL, 0, 0}
3208   };
3209
3210   occ->opc = NULL;
3211   if (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG != ntohs (msg->type))
3212     goto error_return;
3213   cmsg = (const struct GNUNET_TESTBED_PeerConfigurationInformationMessage *)
3214       msg;
3215   memcpy (&occ->other_peer_identity, &cmsg->peer_identity,
3216           sizeof (struct GNUNET_PeerIdentity));
3217   GNUNET_free_non_null (occ->emsg);
3218   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
3219   occ->peer->reference_cnt++;
3220   occ->ch =
3221       GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
3222                            &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
3223                            GNUNET_NO, no_handlers);
3224   if (NULL == occ->ch)
3225     goto error_return;
3226   return;
3227
3228  error_return:
3229   GNUNET_SCHEDULER_cancel (occ->timeout_task);
3230   occ->timeout_task = 
3231       GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
3232 }
3233
3234
3235 /**
3236  * Callback which will be called to after a host registration succeeded or failed
3237  *
3238  * @param cls the RegisteredHostContext
3239  * @param emsg the error message; NULL if host registration is successful
3240  */
3241 static void 
3242 registeredhost_registration_completion (void *cls, const char *emsg)
3243 {
3244   struct RegisteredHostContext *rhc = cls;
3245   struct GNUNET_CONFIGURATION_Handle *cfg;
3246   uint32_t peer2_host_id;
3247
3248   /* if (NULL != rhc->focc_dll_head) */
3249   /*   process_next_focc (rhc); */
3250   peer2_host_id = GNUNET_TESTBED_host_get_id_ (rhc->reg_host);
3251   GNUNET_assert (RHC_INIT == rhc->state);
3252   GNUNET_assert (NULL == rhc->sub_op);
3253   if ((NULL == rhc->gateway2)
3254       || ((peer2_host_id < slave_list_size) /* Check if we have the needed config */
3255           && (NULL != slave_list[peer2_host_id])))
3256   {
3257     rhc->state = RHC_LINK;
3258     cfg = (NULL == rhc->gateway2) ? our_config : slave_list[peer2_host_id]->cfg;
3259     rhc->sub_op =
3260         GNUNET_TESTBED_controller_link (rhc,
3261                                         rhc->gateway->controller,
3262                                         rhc->reg_host,
3263                                         rhc->host,
3264                                         cfg,
3265                                         GNUNET_NO);
3266     return;
3267   }
3268   rhc->state = RHC_GET_CFG;
3269   rhc->sub_op =  GNUNET_TESTBED_get_slave_config (rhc,
3270                                                   rhc->gateway2->controller,
3271                                                   rhc->reg_host);
3272 }
3273
3274
3275 /**
3276  * Iterator to match a registered host context
3277  *
3278  * @param cls pointer 2 pointer of RegisteredHostContext
3279  * @param key current key code
3280  * @param value value in the hash map
3281  * @return GNUNET_YES if we should continue to
3282  *         iterate,
3283  *         GNUNET_NO if not.
3284  */
3285 static int 
3286 reghost_match_iterator (void *cls,
3287                         const struct GNUNET_HashCode * key,
3288                         void *value)
3289 {
3290   struct RegisteredHostContext **rh = cls;
3291   struct RegisteredHostContext *rh_val = value;
3292
3293   if ((rh_val->host == (*rh)->host) && (rh_val->reg_host == (*rh)->reg_host))
3294   {
3295     GNUNET_free (*rh);
3296     *rh = rh_val;
3297     return GNUNET_NO;
3298   }
3299   return GNUNET_YES;
3300 }
3301
3302
3303 /**
3304  * Function to generate the hashcode corresponding to a RegisteredHostContext
3305  *
3306  * @param reg_host the host which is being registered in RegisteredHostContext
3307  * @param host the host of the controller which has to connect to the above rhost
3308  * @return the hashcode
3309  */
3310 static struct GNUNET_HashCode
3311 hash_hosts (struct GNUNET_TESTBED_Host *reg_host,
3312             struct GNUNET_TESTBED_Host *host)
3313 {
3314   struct GNUNET_HashCode hash;
3315   uint32_t host_ids[2];
3316
3317   host_ids[0] = GNUNET_TESTBED_host_get_id_ (reg_host);
3318   host_ids[1] = GNUNET_TESTBED_host_get_id_ (host);
3319   GNUNET_CRYPTO_hash (host_ids, sizeof (host_ids), &hash);
3320   return hash;
3321 }
3322
3323
3324 /**
3325  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
3326  *
3327  * @param cls NULL
3328  * @param client identification of the client
3329  * @param message the actual message
3330  */
3331 static void
3332 handle_overlay_connect (void *cls, struct GNUNET_SERVER_Client *client,
3333                         const struct GNUNET_MessageHeader *message)
3334 {
3335   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
3336   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
3337     {NULL, 0, 0}
3338   };
3339   struct Peer *peer;
3340   struct OverlayConnectContext *occ;
3341   struct GNUNET_TESTBED_Controller *peer2_controller;
3342   uint64_t operation_id;
3343   uint32_t p1;
3344   uint32_t p2; 
3345   uint32_t peer2_host_id;
3346
3347   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
3348   p1 = ntohl (msg->peer1);
3349   p2 = ntohl (msg->peer2);
3350   peer2_host_id = ntohl (msg->peer2_host_id);
3351   GNUNET_assert (p1 < peer_list_size);
3352   GNUNET_assert (NULL != peer_list[p1]);
3353   peer = peer_list[p1];
3354   operation_id = GNUNET_ntohll (msg->operation_id);  
3355   LOG_DEBUG ("Received overlay connect for peers %u and %u with op id: 0x%lx\n",
3356              p1, p2, operation_id);
3357   if (GNUNET_YES == peer->is_remote)
3358   {
3359     struct ForwardedOperationContext *fopc;
3360     struct Route *route_to_peer2_host;
3361     struct Route *route_to_peer1_host;
3362
3363     LOG_DEBUG ("Forwarding overlay connect\n");
3364     route_to_peer2_host = NULL;
3365     route_to_peer1_host = NULL;
3366     route_to_peer2_host = find_dest_route (peer2_host_id);
3367     if ((NULL != route_to_peer2_host) 
3368         || (peer2_host_id == master_context->host_id))
3369     {
3370       /* Peer 2 either below us OR with us */
3371       route_to_peer1_host = 
3372           find_dest_route (peer_list[p1]->details.remote.remote_host_id);
3373       /* Because we get this message only if we know where peer 1 is */
3374       GNUNET_assert (NULL != route_to_peer1_host);
3375       if ((peer2_host_id == master_context->host_id) 
3376           || (route_to_peer2_host->dest != route_to_peer1_host->dest))
3377       {
3378         /* Peer2 is either with us OR peer1 and peer2 can be reached through
3379            different gateways */
3380         struct GNUNET_HashCode hash;
3381         struct RegisteredHostContext *rhc;
3382         int skip_focc;
3383
3384         rhc = GNUNET_malloc (sizeof (struct RegisteredHostContext));
3385         if (NULL != route_to_peer2_host)
3386           rhc->reg_host = host_list[route_to_peer2_host->dest];
3387         else
3388           rhc->reg_host = host_list[master_context->host_id];
3389         rhc->host = host_list[route_to_peer1_host->dest];
3390         GNUNET_assert (NULL != rhc->reg_host);
3391         GNUNET_assert (NULL != rhc->host);
3392         rhc->gateway = peer->details.remote.slave;
3393         rhc->gateway2 = (NULL == route_to_peer2_host) ? NULL :
3394             slave_list[route_to_peer2_host->dest];
3395         rhc->state = RHC_INIT;
3396         GNUNET_SERVER_client_keep (client);
3397         rhc->client = client;
3398         hash = hash_hosts (rhc->reg_host, rhc->host);
3399         skip_focc = GNUNET_NO;
3400         if ((GNUNET_NO == 
3401              GNUNET_CONTAINER_multihashmap_contains
3402              (peer->details.remote.slave->reghost_map, &hash))
3403             || (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple
3404                 (peer->details.remote.slave->reghost_map, &hash,
3405                  reghost_match_iterator, &rhc)))
3406         {
3407           /* create and add a new registerd host context */
3408           /* add the focc to its queue */
3409           GNUNET_CONTAINER_multihashmap_put
3410               (peer->details.remote.slave->reghost_map,
3411                &hash, rhc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3412           GNUNET_assert (NULL != host_list[peer2_host_id]);
3413           queue_host_registration (peer->details.remote.slave,
3414                                    registeredhost_registration_completion, rhc,
3415                                    host_list[peer2_host_id]);
3416         }
3417         else {
3418           /* rhc is now set to the existing one from the hash map by
3419              reghost_match_iterator() */
3420           /* if queue is empty then ignore creating focc and proceed with
3421              normal forwarding */                 
3422           if (RHC_OL_CONNECT == rhc->state)
3423             skip_focc = GNUNET_YES;
3424         }
3425         if (GNUNET_NO == skip_focc)
3426         {
3427           struct ForwardedOverlayConnectContext *focc;
3428
3429           focc = GNUNET_malloc (sizeof (struct ForwardedOverlayConnectContext));
3430           focc->peer1 = p1;
3431           focc->peer2 = p2;
3432           focc->peer2_host_id = peer2_host_id;
3433           focc->orig_msg = GNUNET_copy_message (message);
3434           focc->operation_id = operation_id;
3435           GNUNET_CONTAINER_DLL_insert_tail (rhc->focc_dll_head,
3436                                             rhc->focc_dll_tail,
3437                                             focc);
3438           GNUNET_SERVER_receive_done (client, GNUNET_OK);
3439           return;
3440         }
3441       }
3442     }
3443     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
3444     GNUNET_SERVER_client_keep (client);
3445     fopc->client = client;
3446     fopc->operation_id = operation_id;
3447     fopc->type = OP_OVERLAY_CONNECT;
3448     fopc->opc = 
3449         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.slave->controller,
3450                                                operation_id, message,
3451                                                &forwarded_operation_reply_relay,
3452                                                fopc);
3453     fopc->timeout_task =
3454         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
3455                                       fopc);
3456     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
3457     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3458     return;
3459   }
3460
3461   peer2_controller = NULL;
3462   if ((p2 >= peer_list_size) || (NULL == peer_list[p2]))
3463   {   
3464     if ((peer2_host_id >= slave_list_size)
3465         || (NULL ==slave_list[peer2_host_id]))
3466     {
3467       LOG (GNUNET_ERROR_TYPE_WARNING,
3468            "Configuration of peer2's controller missing for connecting peers"
3469            "%u and %u\n", p1, p2);      
3470       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3471       return;
3472     }
3473     peer2_controller = slave_list[peer2_host_id]->controller;
3474     if (NULL == peer2_controller)
3475     {
3476       GNUNET_break (0);       /* What's going on? */
3477       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3478       return;
3479     }
3480   }
3481   else
3482   {
3483     if (GNUNET_YES == peer_list[p2]->is_remote)
3484       peer2_controller = peer_list[p2]->details.remote.slave->controller;
3485   }
3486   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
3487   GNUNET_CONTAINER_DLL_insert_tail (occq_head, occq_tail, occ);
3488   GNUNET_SERVER_client_keep (client);
3489   occ->client = client;
3490   occ->peer_id = p1;
3491   occ->other_peer_id = p2;
3492   occ->peer = peer_list[p1];
3493   occ->op_id = GNUNET_ntohll (msg->operation_id);
3494   occ->peer2_controller = peer2_controller;
3495   /* Get the identity of the second peer */
3496   if (NULL != occ->peer2_controller)
3497   {
3498     struct GNUNET_TESTBED_PeerGetConfigurationMessage cmsg;
3499
3500     cmsg.header.size = 
3501         htons (sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage));
3502     cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG);
3503     cmsg.peer_id = msg->peer2;
3504     cmsg.operation_id = msg->operation_id;
3505     occ->opc = 
3506         GNUNET_TESTBED_forward_operation_msg_ (occ->peer2_controller,
3507                                                occ->op_id, &cmsg.header,
3508                                                &overlay_connect_get_config,
3509                                                occ);
3510     occ->emsg = 
3511         GNUNET_strdup ("Timeout while getting peer identity of peer B\n");
3512     occ->timeout_task =
3513         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3514                                       (GNUNET_TIME_UNIT_SECONDS, 30),
3515                                       &timeout_overlay_connect, occ);
3516     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3517     return;
3518   }
3519   GNUNET_TESTING_peer_get_identity (peer_list[occ->other_peer_id]->details.local.peer,
3520                                     &occ->other_peer_identity);
3521   /* Connect to the core of 1st peer and wait for the 2nd peer to connect */
3522   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
3523   occ->peer->reference_cnt++;
3524   occ->ch =
3525       GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
3526                            &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
3527                            GNUNET_NO, no_handlers);
3528   if (NULL == occ->ch)
3529     occ->timeout_task = 
3530         GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
3531   else
3532     occ->timeout_task =
3533         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3534                                       (GNUNET_TIME_UNIT_SECONDS, 30),
3535                                       &timeout_overlay_connect, occ);
3536   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3537 }
3538
3539
3540 /**
3541  * Function to cleanup RequestOverlayConnectContext and any associated tasks
3542  * with it
3543  *
3544  * @param rocc the RequestOverlayConnectContext
3545  */
3546 static void
3547 cleanup_rocc (struct RequestOverlayConnectContext *rocc)
3548 {
3549   LOG_DEBUG ("Cleaning up rocc\n");
3550   if (GNUNET_SCHEDULER_NO_TASK != rocc->attempt_connect_task_id)
3551     GNUNET_SCHEDULER_cancel (rocc->attempt_connect_task_id);
3552   if (GNUNET_SCHEDULER_NO_TASK != rocc->timeout_rocc_task_id)
3553     GNUNET_SCHEDULER_cancel (rocc->timeout_rocc_task_id);
3554   if (NULL != rocc->ohh)
3555     GNUNET_TRANSPORT_offer_hello_cancel (rocc->ohh);
3556   if (NULL != rocc->tcc.tch)
3557     GNUNET_TRANSPORT_try_connect_cancel (rocc->tcc.tch);
3558   if (GNUNET_SCHEDULER_NO_TASK != rocc->tcc.task)
3559     GNUNET_SCHEDULER_cancel (rocc->tcc.task);
3560   GNUNET_TRANSPORT_disconnect (rocc->tcc.th);
3561   rocc->peer->reference_cnt--;
3562   if ((GNUNET_YES == rocc->peer->destroy_flag)
3563       && (0 == rocc->peer->reference_cnt))
3564     destroy_peer (rocc->peer);
3565   GNUNET_free_non_null (rocc->hello);
3566   GNUNET_CONTAINER_DLL_remove (roccq_head, roccq_tail, rocc);
3567   GNUNET_free (rocc);
3568 }
3569
3570
3571 /**
3572  * Task to timeout rocc and cleanit up
3573  *
3574  * @param cls the RequestOverlayConnectContext
3575  * @param tc the TaskContext from scheduler
3576  */
3577 static void
3578 timeout_rocc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3579 {
3580   struct RequestOverlayConnectContext *rocc = cls;
3581   
3582   rocc->timeout_rocc_task_id = GNUNET_SCHEDULER_NO_TASK;
3583   cleanup_rocc (rocc);
3584 }
3585
3586
3587 /**
3588  * Function called to notify transport users that another
3589  * peer connected to us.
3590  *
3591  * @param cls closure
3592  * @param new_peer the peer that connected
3593  * @param ats performance data
3594  * @param ats_count number of entries in ats (excluding 0-termination)
3595  */
3596 static void 
3597 transport_connect_notify (void *cls, const struct GNUNET_PeerIdentity *new_peer,
3598                           const struct GNUNET_ATS_Information * ats,
3599                           uint32_t ats_count)
3600 {
3601   struct RequestOverlayConnectContext *rocc = cls;
3602
3603   LOG_DEBUG ("Request Overlay connect notify\n");
3604   if (0 != memcmp (new_peer, &rocc->a_id, sizeof (struct GNUNET_PeerIdentity)))
3605     return;
3606   LOG_DEBUG ("Peer %4s connected\n", GNUNET_i2s (&rocc->a_id));
3607   cleanup_rocc (rocc);
3608 }
3609
3610
3611 /**
3612  * Task to offer the HELLO message to the peer and ask it to connect to the peer
3613  * whose identity is in RequestOverlayConnectContext
3614  *
3615  * @param cls the RequestOverlayConnectContext
3616  * @param tc the TaskContext from scheduler
3617  */
3618 static void
3619 attempt_connect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3620
3621
3622 /**
3623  * Task that is run when hello has been sent
3624  *
3625  * @param cls the overlay connect context
3626  * @param tc the scheduler task context; if tc->reason =
3627  *          GNUNET_SCHEDULER_REASON_TIMEOUT then sending HELLO failed; if
3628  *          GNUNET_SCHEDULER_REASON_READ_READY is succeeded
3629  */
3630 static void
3631 rocc_hello_sent_cb (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3632 {
3633   struct RequestOverlayConnectContext *rocc = cls;
3634   
3635   rocc->ohh = NULL;
3636   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == rocc->attempt_connect_task_id);
3637   if (GNUNET_SCHEDULER_REASON_TIMEOUT == tc->reason)
3638   {
3639     GNUNET_break (0);
3640     rocc->attempt_connect_task_id =
3641         GNUNET_SCHEDULER_add_now (&attempt_connect_task,
3642                                   rocc);
3643     return;
3644   }
3645   if (GNUNET_SCHEDULER_REASON_READ_READY != tc->reason)
3646     return;
3647   rocc->tcc.task = GNUNET_SCHEDULER_add_now (&try_connect_task, &rocc->tcc);
3648 }
3649
3650
3651 /**
3652  * Task to offer the HELLO message to the peer and ask it to connect to the peer
3653  * whose identity is in RequestOverlayConnectContext
3654  *
3655  * @param cls the RequestOverlayConnectContext
3656  * @param tc the TaskContext from scheduler
3657  */
3658 static void
3659 attempt_connect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3660 {
3661   struct RequestOverlayConnectContext *rocc = cls;
3662
3663   rocc->attempt_connect_task_id = GNUNET_SCHEDULER_NO_TASK;
3664   rocc->ohh = GNUNET_TRANSPORT_offer_hello (rocc->tcc.th, rocc->hello,
3665                                             rocc_hello_sent_cb, rocc);
3666   if (NULL == rocc->ohh)
3667     rocc->attempt_connect_task_id = 
3668         GNUNET_SCHEDULER_add_delayed 
3669         (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3670                                         100 + GNUNET_CRYPTO_random_u32
3671                                         (GNUNET_CRYPTO_QUALITY_WEAK, 500)),
3672          &attempt_connect_task, rocc);
3673 }
3674
3675
3676 /**
3677  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT messages
3678  *
3679  * @param cls NULL
3680  * @param client identification of the client
3681  * @param message the actual message
3682  */
3683 static void
3684 handle_overlay_request_connect (void *cls, struct GNUNET_SERVER_Client *client,
3685                                 const struct GNUNET_MessageHeader *message)
3686 {
3687   const struct GNUNET_TESTBED_RequestConnectMessage *msg;
3688   struct RequestOverlayConnectContext *rocc;
3689   struct Peer *peer;
3690   uint32_t peer_id;
3691   uint16_t msize;
3692   uint16_t hsize;
3693   
3694   msize = ntohs (message->size);
3695   if (sizeof (struct GNUNET_TESTBED_RequestConnectMessage) >= msize)
3696   {
3697     GNUNET_break (0);
3698     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3699     return;
3700   }  
3701   msg = (const struct GNUNET_TESTBED_RequestConnectMessage *) message;
3702   if ((NULL == msg->hello) || 
3703       (GNUNET_MESSAGE_TYPE_HELLO != ntohs (msg->hello->type)))
3704   {
3705     GNUNET_break (0);
3706     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3707     return;
3708   }
3709   hsize = ntohs (msg->hello->size);
3710   if ((sizeof (struct GNUNET_TESTBED_RequestConnectMessage) + hsize) != msize)
3711   {
3712     GNUNET_break (0);
3713     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3714     return;
3715   }
3716   peer_id = ntohl (msg->peer);
3717   if ((peer_id >= peer_list_size) || (NULL == (peer = peer_list[peer_id])))
3718   {
3719     GNUNET_break_op (0);
3720     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3721     return;
3722   }
3723   if (GNUNET_YES == peer->is_remote)
3724   {
3725     struct GNUNET_MessageHeader *msg2;
3726     
3727     msg2 = GNUNET_copy_message (message);
3728     GNUNET_TESTBED_queue_message_ (peer->details.remote.slave->controller, msg2);
3729     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3730     return;
3731   }
3732   rocc = GNUNET_malloc (sizeof (struct RequestOverlayConnectContext));
3733   GNUNET_CONTAINER_DLL_insert_tail (roccq_head, roccq_tail, rocc);
3734   rocc->peer = peer;
3735   rocc->peer->reference_cnt++;
3736   rocc->tcc.th = GNUNET_TRANSPORT_connect (rocc->peer->details.local.cfg, NULL, rocc,
3737                                            NULL, &transport_connect_notify, NULL);
3738   if (NULL == rocc->tcc.th)
3739   {
3740     GNUNET_break (0);
3741     GNUNET_free (rocc);
3742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3743     return;
3744   }
3745   memcpy (&rocc->a_id, &msg->peer_identity,
3746           sizeof (struct GNUNET_PeerIdentity));
3747   rocc->tcc.pid = &rocc->a_id;
3748   rocc->hello = GNUNET_malloc (hsize);
3749   memcpy (rocc->hello, msg->hello, hsize);
3750   rocc->attempt_connect_task_id =
3751       GNUNET_SCHEDULER_add_now (&attempt_connect_task, rocc);
3752   rocc->timeout_rocc_task_id =
3753       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &timeout_rocc_task, rocc);
3754   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3755 }
3756
3757
3758 /**
3759  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETSLAVECONFIG messages
3760  *
3761  * @param cls NULL
3762  * @param client identification of the client
3763  * @param message the actual message
3764  */
3765 static void
3766 handle_slave_get_config (void *cls, struct GNUNET_SERVER_Client *client,
3767                          const struct GNUNET_MessageHeader *message)
3768 {
3769   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
3770   struct Slave *slave;  
3771   struct GNUNET_TESTBED_SlaveConfiguration *reply;
3772   char *config;
3773   char *xconfig;
3774   size_t config_size;
3775   size_t xconfig_size;
3776   size_t reply_size;
3777   uint64_t op_id;
3778   uint32_t slave_id;
3779
3780   msg = (struct GNUNET_TESTBED_SlaveGetConfigurationMessage *) message;
3781   slave_id = ntohl (msg->slave_id);
3782   op_id = GNUNET_ntohll (msg->operation_id);
3783   if ((slave_list_size <= slave_id) || (NULL == slave_list[slave_id]))
3784   {
3785     /* FIXME: Add forwardings for this type of message here.. */
3786     send_operation_fail_msg (client, op_id, "Slave not found");
3787     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3788     return;
3789   }
3790   slave = slave_list[slave_id];
3791   if (NULL == slave->cfg)
3792   {
3793     send_operation_fail_msg (client, op_id,
3794                              "Configuration not found (slave not started by me)");
3795     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3796     return;
3797   }
3798   config = GNUNET_CONFIGURATION_serialize (slave->cfg, &config_size);
3799   xconfig_size = GNUNET_TESTBED_compress_config_ (config, config_size, 
3800                                                   &xconfig);
3801   GNUNET_free (config);  
3802   reply_size = xconfig_size + sizeof (struct GNUNET_TESTBED_SlaveConfiguration);
3803   GNUNET_break (reply_size <= UINT16_MAX);
3804   GNUNET_break (config_size <= UINT16_MAX);
3805   reply = GNUNET_realloc (xconfig, reply_size);
3806   (void) memmove (&reply[1], reply, xconfig_size);
3807   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SLAVECONFIG);
3808   reply->header.size = htons ((uint16_t) reply_size);
3809   reply->slave_id = msg->slave_id;
3810   reply->operation_id = msg->operation_id;
3811   reply->config_size = htons ((uint16_t) config_size);
3812   queue_message (client, &reply->header);
3813   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3814 }
3815
3816
3817 /**
3818  * Iterator over hash map entries.
3819  *
3820  * @param cls closure
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 ss_map_free_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
3829 {
3830   struct SharedService *ss = value;
3831
3832   GNUNET_assert (GNUNET_YES ==
3833                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
3834   GNUNET_free (ss->name);
3835   GNUNET_free (ss);
3836   return GNUNET_YES;
3837 }
3838
3839
3840 /**
3841  * Iterator for freeing hash map entries in a slave's reghost_map
3842  *
3843  * @param cls handle to the slave
3844  * @param key current key code
3845  * @param value value in the hash map
3846  * @return GNUNET_YES if we should continue to
3847  *         iterate,
3848  *         GNUNET_NO if not.
3849  */
3850 static int 
3851 reghost_free_iterator (void *cls,
3852                        const struct GNUNET_HashCode * key,
3853                        void *value)
3854 {
3855   struct Slave *slave = cls;
3856   struct RegisteredHostContext *rhc = value;
3857   struct ForwardedOverlayConnectContext *focc;
3858
3859   GNUNET_assert (GNUNET_YES ==
3860                  GNUNET_CONTAINER_multihashmap_remove (slave->reghost_map,
3861                                                        key, value));
3862   while (NULL != (focc = rhc->focc_dll_head))
3863   {
3864     GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head,
3865                                  rhc->focc_dll_tail,
3866                                  focc);
3867     cleanup_focc (focc);
3868   }
3869   if (NULL != rhc->sub_op)
3870     GNUNET_TESTBED_operation_done (rhc->sub_op);
3871   if (NULL != rhc->client)
3872   GNUNET_SERVER_client_drop (rhc->client);
3873   GNUNET_free (value);
3874   return GNUNET_YES;
3875 }
3876
3877
3878 /**
3879  * Task to clean up and shutdown nicely
3880  *
3881  * @param cls NULL
3882  * @param tc the TaskContext from scheduler
3883  */
3884 static void
3885 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3886 {
3887   struct LCFContextQueue *lcfq;
3888   struct OverlayConnectContext *occ;
3889   struct RequestOverlayConnectContext *rocc;
3890   struct ForwardedOperationContext *fopc;
3891   struct MessageQueue *mq_entry;
3892   uint32_t id;
3893
3894   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
3895   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
3896   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
3897                                                 NULL);
3898   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
3899   /* cleanup any remaining forwarded operations */
3900   while (NULL != (fopc = fopcq_head))
3901   {
3902     GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fopc);
3903     GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
3904     if (GNUNET_SCHEDULER_NO_TASK != fopc->timeout_task)
3905       GNUNET_SCHEDULER_cancel (fopc->timeout_task);
3906     GNUNET_SERVER_client_drop (fopc->client);
3907     switch (fopc->type)
3908     {
3909     case OP_PEER_CREATE:
3910       GNUNET_free (fopc->cls);
3911       break;
3912     case OP_PEER_START:
3913     case OP_PEER_STOP:
3914     case OP_PEER_DESTROY:
3915     case OP_PEER_INFO:
3916     case OP_OVERLAY_CONNECT:
3917     case OP_LINK_CONTROLLERS:
3918     case OP_GET_SLAVE_CONFIG:
3919       break;
3920     case OP_FORWARDED:
3921       GNUNET_assert (0);
3922     };
3923     GNUNET_free (fopc);
3924   }
3925   if (NULL != lcfq_head)
3926   {
3927     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
3928     {
3929       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
3930       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
3931     }
3932   }
3933   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
3934   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
3935   {
3936     GNUNET_free (lcfq->lcf->msg);
3937     GNUNET_free (lcfq->lcf);
3938     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
3939     GNUNET_free (lcfq);
3940   }
3941   while (NULL != (occ = occq_head))
3942     cleanup_occ (occ);
3943   while (NULL != (rocc = roccq_head))
3944     cleanup_rocc (rocc);
3945   /* Clear peer list */
3946   for (id = 0; id < peer_list_size; id++)
3947     if (NULL != peer_list[id])
3948     {
3949       /* If destroy flag is set it means that this peer should have been
3950          destroyed by a context which we destroy before */
3951       GNUNET_break (GNUNET_NO == peer_list[id]->destroy_flag);
3952       /* counter should be zero as we free all contexts before */
3953       GNUNET_break (0 == peer_list[id]->reference_cnt);      
3954       if ( (GNUNET_NO == peer_list[id]->is_remote)
3955            && (GNUNET_YES == peer_list[id]->details.local.is_running))
3956         GNUNET_TESTING_peer_kill (peer_list[id]->details.local.peer);
3957     }
3958   for (id = 0; id < peer_list_size; id++)
3959     if (NULL != peer_list[id])
3960     {
3961       if (GNUNET_NO == peer_list[id]->is_remote)
3962       {
3963         if (GNUNET_YES == peer_list[id]->details.local.is_running)
3964           GNUNET_TESTING_peer_wait (peer_list[id]->details.local.peer);
3965         GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
3966         GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
3967       }
3968       GNUNET_free (peer_list[id]);
3969     }
3970   GNUNET_free_non_null (peer_list);
3971   /* Clear host list */
3972   for (id = 0; id < host_list_size; id++)
3973     if (NULL != host_list[id])
3974       GNUNET_TESTBED_host_destroy (host_list[id]);
3975   GNUNET_free_non_null (host_list);
3976   /* Clear route list */
3977   for (id = 0; id < route_list_size; id++)
3978     if (NULL != route_list[id])
3979       GNUNET_free (route_list[id]);
3980   GNUNET_free_non_null (route_list);
3981   /* Clear slave_list */
3982   for (id = 0; id < slave_list_size; id++)
3983     if (NULL != slave_list[id])
3984     {
3985       struct HostRegistration *hr_entry;
3986       
3987       while (NULL != (hr_entry = slave_list[id]->hr_dll_head))
3988       {
3989         GNUNET_CONTAINER_DLL_remove (slave_list[id]->hr_dll_head,
3990                                      slave_list[id]->hr_dll_tail,
3991                                      hr_entry);
3992         GNUNET_free (hr_entry);
3993       }
3994       if (NULL != slave_list[id]->rhandle)
3995         GNUNET_TESTBED_cancel_registration (slave_list[id]->rhandle);
3996       (void) GNUNET_CONTAINER_multihashmap_iterate (slave_list[id]->reghost_map,
3997                                                     reghost_free_iterator,
3998                                                     slave_list[id]);
3999       GNUNET_CONTAINER_multihashmap_destroy (slave_list[id]->reghost_map);
4000       if (NULL != slave_list[id]->cfg)
4001         GNUNET_CONFIGURATION_destroy (slave_list[id]->cfg);
4002       if (NULL != slave_list[id]->controller)
4003         GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
4004       if (NULL != slave_list[id]->controller_proc)
4005         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
4006       GNUNET_free (slave_list[id]);
4007     }
4008   GNUNET_free_non_null (slave_list);
4009   if (NULL != master_context)
4010   {
4011     GNUNET_free_non_null (master_context->master_ip);
4012     if (NULL != master_context->system)
4013       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
4014     GNUNET_SERVER_client_drop (master_context->client);
4015     GNUNET_free (master_context);
4016     master_context = NULL;
4017   }
4018   if (NULL != transmit_handle)
4019     GNUNET_SERVER_notify_transmit_ready_cancel (transmit_handle);  
4020   while (NULL != (mq_entry = mq_head))
4021   {
4022     GNUNET_free (mq_entry->msg);
4023     GNUNET_SERVER_client_drop (mq_entry->client);
4024     GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);    
4025     GNUNET_free (mq_entry);
4026   }
4027   GNUNET_free_non_null (hostname);
4028   GNUNET_CONFIGURATION_destroy (our_config);
4029 }
4030
4031
4032 /**
4033  * Callback for client disconnect
4034  *
4035  * @param cls NULL
4036  * @param client the client which has disconnected
4037  */
4038 static void
4039 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
4040 {
4041   if (NULL == master_context)
4042     return;
4043   if (client == master_context->client)
4044   {
4045     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
4046     /* should not be needed as we're terminated by failure to read
4047      * from stdin, but if stdin fails for some reason, this shouldn't
4048      * hurt for now --- might need to revise this later if we ever
4049      * decide that master connections might be temporarily down
4050      * for some reason */
4051     //GNUNET_SCHEDULER_shutdown ();
4052   }
4053 }
4054
4055
4056 /**
4057  * Testbed setup
4058  *
4059  * @param cls closure
4060  * @param server the initialized server
4061  * @param cfg configuration to use
4062  */
4063 static void
4064 testbed_run (void *cls, struct GNUNET_SERVER_Handle *server,
4065              const struct GNUNET_CONFIGURATION_Handle *cfg)
4066 {
4067   static const struct GNUNET_SERVER_MessageHandler message_handlers[] = {
4068     {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
4069     {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
4070     {&handle_configure_shared_service, NULL,
4071      GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
4072     {&handle_link_controllers, NULL,
4073      GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
4074     {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
4075     {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
4076      sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
4077     {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
4078      sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
4079     {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
4080      sizeof (struct GNUNET_TESTBED_PeerStopMessage)},
4081     {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
4082      sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
4083     {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
4084      sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
4085     {&handle_overlay_request_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT,
4086      0},
4087     {handle_slave_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETSLAVECONFIG,
4088      sizeof (struct GNUNET_TESTBED_SlaveGetConfigurationMessage)},
4089     {NULL}
4090   };
4091
4092   GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string 
4093                  (cfg, "testbed", "HOSTNAME", &hostname));
4094   our_config = GNUNET_CONFIGURATION_dup (cfg);
4095   GNUNET_SERVER_add_handlers (server, message_handlers);
4096   GNUNET_SERVER_disconnect_notify (server, &client_disconnect_cb, NULL);
4097   ss_map = GNUNET_CONTAINER_multihashmap_create (5, GNUNET_NO);
4098   shutdown_task_id =
4099       GNUNET_SCHEDULER_add_delayed_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
4100                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
4101                                                   &shutdown_task, NULL);
4102   LOG_DEBUG ("Testbed startup complete\n");
4103   event_mask = 1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED;
4104 }
4105
4106
4107 /**
4108  * The starting point of execution
4109  */
4110 int
4111 main (int argc, char *const *argv)
4112 {
4113   //sleep (15);                 /* Debugging */
4114   return (GNUNET_OK ==
4115           GNUNET_SERVICE_run (argc, argv, "testbed", GNUNET_SERVICE_OPTION_NONE,
4116                               &testbed_run, NULL)) ? 0 : 1;
4117 }
4118
4119 /* end of gnunet-service-testbed.c */