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