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