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