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