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