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