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