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