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