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