peer create fowarding with tests
[oweals/gnunet.git] / src / testbed / gnunet-service-testbed.c
1 /*
2   This file is part of GNUnet.
3   (C) 2012 Christian Grothoff (and other contributing authors)
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 2, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file testbed/gnunet-service-testbed.c
23  * @brief implementation of the TESTBED service
24  * @author Sree Harsha Totakura
25  */
26
27 #include "platform.h"
28 #include "gnunet_service_lib.h"
29 #include "gnunet_server_lib.h"
30 #include "gnunet_transport_service.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_hello_lib.h"
33 #include <zlib.h>
34
35 #include "gnunet_testbed_service.h"
36 #include "testbed.h"
37 #include "testbed_api.h"
38 #include "testbed_api_hosts.h"
39 #include "gnunet_testing_lib-new.h"
40
41 /**
42  * Generic logging
43  */
44 #define LOG(kind,...)                           \
45   GNUNET_log (kind, __VA_ARGS__)
46
47 /**
48  * Debug logging
49  */
50 #define LOG_DEBUG(...)                          \
51   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
52
53 /**
54  * By how much should the arrays lists grow
55  */
56 #define LIST_GROW_STEP 10
57
58 /**
59  * Default timeout for operations which may take some time
60  */
61 #define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
62
63 /**
64  * The main context information associated with the client which started us
65  */
66 struct Context
67 {
68   /**
69    * The client handle associated with this context
70    */
71   struct GNUNET_SERVER_Client *client;
72
73   /**
74    * The network address of the master controller
75    */
76   char *master_ip;
77
78   /**
79    * The TESTING system handle for starting peers locally
80    */
81   struct GNUNET_TESTING_System *system;
82   
83   /**
84    * Event mask of event to be responded in this context
85    */
86   uint64_t event_mask;
87
88   /**
89    * Our host id according to this context
90    */
91   uint32_t host_id;
92 };
93
94
95 /**
96  * The message queue for sending messages to clients
97  */
98 struct MessageQueue
99 {
100   /**
101    * The message to be sent
102    */
103   struct GNUNET_MessageHeader *msg;
104
105   /**
106    * The client to send the message to
107    */
108   struct GNUNET_SERVER_Client *client;
109   
110   /**
111    * next pointer for DLL
112    */
113   struct MessageQueue *next;
114   
115   /**
116    * prev pointer for DLL
117    */
118   struct MessageQueue *prev;
119 };
120
121
122 /**
123  * The structure for identifying a shared service
124  */
125 struct SharedService
126 {
127   /**
128    * The name of the shared service
129    */
130   char *name;
131
132   /**
133    * Number of shared peers per instance of the shared service
134    */
135   uint32_t num_shared;
136
137   /**
138    * Number of peers currently sharing the service
139    */
140   uint32_t num_sharing;
141 };
142
143
144 /**
145  * A routing entry
146  */
147 struct Route
148 {
149   /**
150    * destination host
151    */
152   uint32_t dest;
153
154   /**
155    * The host destination is reachable thru
156    */
157   uint32_t thru;
158 };
159
160
161 /**
162  * Structure representing a connected(directly-linked) controller
163  */
164 struct Slave
165 {
166   /**
167    * The controller process handle if we had started the controller
168    */
169   struct GNUNET_TESTBED_ControllerProc *controller_proc;
170
171   /**
172    * The controller handle
173    */
174   struct GNUNET_TESTBED_Controller *controller;
175
176   /**
177    * The id of the host this controller is running on
178    */
179   uint32_t host_id;
180 };
181
182
183 /**
184  * States of LCFContext
185  */
186 enum LCFContextState
187   {
188     /**
189      * The Context has been initialized; Nothing has been done on it
190      */
191     INIT,
192
193     /**
194      * Delegated host has been registered at the forwarding controller
195      */
196     DELEGATED_HOST_REGISTERED,
197     
198     /**
199      * The slave host has been registred at the forwarding controller
200      */
201     SLAVE_HOST_REGISTERED,
202
203     /**
204      * The context has been finished (may have error)
205      */
206     FINISHED
207
208   };
209
210
211 /**
212  * Link controllers request forwarding context
213  */
214 struct LCFContext
215 {
216   /**
217    * The gateway which will pass the link message to delegated host
218    */
219   struct Slave *gateway;
220
221   /**
222    * The controller link message that has to be forwarded to
223    */
224   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
225
226   /**
227    * The client which has asked to perform this operation
228    */
229   struct GNUNET_SERVER_Client *client;
230
231   /**
232    * The host registration handle while registered hosts in this context
233    */
234   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
235
236   /**
237    * The id of the operation which created this context
238    */
239   uint64_t operation_id;
240
241   /**
242    * The state of this context
243    */
244   enum LCFContextState state;
245
246   /**
247    * The delegated host
248    */
249   uint32_t delegated_host_id;
250
251   /**
252    * The slave host
253    */
254   uint32_t slave_host_id;
255
256 };
257
258
259 /**
260  * Structure of a queue entry in LCFContext request queue
261  */
262 struct LCFContextQueue
263 {
264   /**
265    * The LCFContext
266    */
267   struct LCFContext *lcf;
268
269   /**
270    * Head prt for DLL
271    */
272   struct LCFContextQueue *next;
273
274   /**
275    * Tail ptr for DLL
276    */
277   struct LCFContextQueue *prev;
278 };
279
280
281 /**
282  * A locally started peer
283  */
284 struct Peer
285 {
286   union
287   {
288     struct 
289     {
290       /**
291        * The peer handle from testing API
292        */
293       struct GNUNET_TESTING_Peer *peer;
294       
295       /**
296        * The modified (by GNUNET_TESTING_peer_configure) configuration this
297        * peer is configured with
298        */
299       struct GNUNET_CONFIGURATION_Handle *cfg;
300
301     } local;
302
303     struct
304     {
305       /**
306        * The controller this peer is started through
307        */
308       struct GNUNET_TESTBED_Controller *controller;
309
310     } remote;
311     
312   } details;
313
314   /**
315    * Our local reference id for this peer
316    */
317   uint32_t id;
318
319   /**
320    * Is this peer local created?
321    */
322   uint32_t is_remote;
323
324 };
325
326
327 /**
328  * State information for overlay connect context
329  */
330 enum OCCState
331   {
332     /**
333      * Initial state
334      */
335     OCC_STATE_INIT,
336
337     /**
338      * Peer 1 has connected to peer0
339      */
340     OCC_STATE_PEER0_SUCCESS,
341
342     /**
343      * Peer 2 has connected to peer1
344      */
345     OCC_STATE_PEER1_SUCCESS,
346
347   };
348
349
350 /**
351  * Context information for connecting 2 peers in overlay
352  */
353 struct OverlayConnectContext
354 {
355   /**
356    * The client which has requested for overlay connection
357    */
358   struct GNUNET_SERVER_Client *client;
359
360   /**
361    * the peer which has to connect to the other peer
362    */
363   struct Peer *peer;
364
365   /**
366    * The other peer
367    */
368   struct Peer *other_peer;
369   
370   /**
371    * Transport handle of the first peer to offer second peer's HELLO
372    */
373   struct GNUNET_TRANSPORT_Handle *p1th;
374
375   /**
376    * Transport handle of other peer to get its HELLO
377    */
378   struct GNUNET_TRANSPORT_Handle *p2th;
379
380   /**
381    * Core handles of the peer which has to connect to other peer
382    */
383   struct GNUNET_CORE_Handle *ch;
384
385   /**
386    * HELLO of the other peer
387    */
388   struct GNUNET_MessageHeader *hello;
389   
390   /**
391    * Get hello handle for the other peer
392    */
393   struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
394
395   /**
396    * The error message we send if this overlay connect operation has timed out
397    */
398   char *emsg;
399   
400   /**
401    * The peer identity of the first peer
402    */
403   struct GNUNET_PeerIdentity peer_identity;
404
405   /**
406    * The peer identity of the other peer
407    */
408   struct GNUNET_PeerIdentity other_peer_identity;
409
410   /**
411    * The id of the operation responsible for creating this context
412    */
413   uint64_t op_id;
414
415   /**
416    * The id of the task for sending HELLO of peer 2 to peer 1 and ask peer 1 to
417    * connect to peer 2
418    */
419   GNUNET_SCHEDULER_TaskIdentifier send_hello_task;
420   
421   /**
422    * The id of the overlay connect timeout task
423    */
424   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
425
426   /**
427    * State information for determining whose HELLOs have been successfully
428    * exchanged
429    */
430   enum OCCState state;
431
432 };
433
434
435 /**
436  * Context information for operations forwarded to subcontrollers
437  */
438 struct ForwardedOperationContext
439 {
440   /**
441    * The generated operation context
442    */
443   struct OperationContext *opc;
444
445   /**
446    * The client to which we have to reply
447    */
448   struct GNUNET_SERVER_Client *client;
449
450   /**
451    * Closure pointer
452    */
453   void *cls;  
454
455   /**
456    * Task ID for the timeout task
457    */
458   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
459
460   /**
461    * The id of the operation that has been forwarded
462    */
463   uint64_t operation_id;  
464
465 };
466
467
468 /**
469  * Context information used while linking controllers
470  */
471 struct LinkControllersContext
472 {
473   /**
474    * The client which initiated the link controller operation
475    */
476   struct GNUNET_SERVER_Client *client;
477
478   /**
479    * The ID of the operation
480    */
481   uint64_t operation_id;
482   
483   /**
484    * Pointer to the slave handle if we are directly starting/connecting to the controller
485    */
486   struct Slave *slave;
487 };
488
489
490
491 /**
492  * The master context; generated with the first INIT message
493  */
494 static struct Context *master_context;
495
496 /***********/
497 /* Handles */
498 /***********/
499
500 /**
501  * Current Transmit Handle; NULL if no notify transmit exists currently
502  */
503 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
504
505 /****************/
506 /* Lists & Maps */
507 /****************/
508
509 /**
510  * The head for the LCF queue
511  */
512 static struct LCFContextQueue *lcfq_head;
513
514 /**
515  * The tail for the LCF queue
516  */
517 static struct LCFContextQueue *lcfq_tail;
518
519 /**
520  * The message queue head
521  */
522 static struct MessageQueue *mq_head;
523
524 /**
525  * The message queue tail
526  */
527 static struct MessageQueue *mq_tail;
528
529 /**
530  * Array of host list
531  */
532 static struct GNUNET_TESTBED_Host **host_list;
533
534 /**
535  * A list of routes
536  */
537 static struct Route **route_list;
538
539 /**
540  * A list of directly linked neighbours
541  */
542 static struct Slave **slave_list;
543
544 /**
545  * A list of peers we own locally
546  */
547 static struct Peer **peer_list;
548
549 /**
550  * The hashmap of shared services
551  */
552 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
553
554 /**
555  * The size of the host list
556  */
557 static uint32_t host_list_size;
558
559 /**
560  * The size of the route list
561  */
562 static uint32_t route_list_size;
563
564 /**
565  * The size of directly linked neighbours list
566  */
567 static uint32_t slave_list_size;
568
569 /**
570  * The size of the peer list
571  */
572 static uint32_t peer_list_size;
573
574 /*********/
575 /* Tasks */
576 /*********/
577
578 /**
579  * The lcf_task handle
580  */
581 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
582
583 /**
584  * The shutdown task handle
585  */
586 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
587
588
589 /**
590  * Function called to notify a client about the connection begin ready to queue
591  * more data.  "buf" will be NULL and "size" zero if the connection was closed
592  * for writing in the meantime.
593  *
594  * @param cls NULL
595  * @param size number of bytes available in buf
596  * @param buf where the callee should write the message
597  * @return number of bytes written to buf
598  */
599 static size_t
600 transmit_ready_notify (void *cls, size_t size, void *buf)
601 {
602   struct MessageQueue *mq_entry;
603
604   transmit_handle = NULL;
605   mq_entry = mq_head;
606   GNUNET_assert (NULL != mq_entry);
607   if (0 == size)
608     return 0;
609   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
610   size = ntohs (mq_entry->msg->size);
611   memcpy (buf, mq_entry->msg, size);
612   GNUNET_free (mq_entry->msg);
613   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
614   GNUNET_free (mq_entry);
615   mq_entry = mq_head;
616   if (NULL != mq_entry)
617     transmit_handle = 
618       GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
619                                            ntohs (mq_entry->msg->size),
620                                            GNUNET_TIME_UNIT_FOREVER_REL,
621                                            &transmit_ready_notify, NULL);
622   return size;
623 }
624
625
626 /**
627  * Queues a message in send queue for sending to the service
628  *
629  * @param client the client to whom the queued message has to be sent
630  * @param msg the message to queue
631  */
632 static void
633 queue_message (struct GNUNET_SERVER_Client *client,
634                struct GNUNET_MessageHeader *msg)
635 {
636   struct MessageQueue *mq_entry;
637   uint16_t type;
638   uint16_t size;
639
640   type = ntohs (msg->type);
641   size = ntohs (msg->size);
642   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
643                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
644   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
645   mq_entry->msg = msg;
646   mq_entry->client = client;
647   LOG_DEBUG ( "Queueing message of type %u, size %u for sending\n", type,
648               ntohs (msg->size));
649   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
650   if (NULL == transmit_handle)
651     transmit_handle = 
652       GNUNET_SERVER_notify_transmit_ready (client, size,
653                                            GNUNET_TIME_UNIT_FOREVER_REL,
654                                            &transmit_ready_notify, NULL);
655 }
656
657
658 /**
659  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
660  *
661  * @param ptr the memory block to realloc
662  * @param size the size of ptr
663  * @param new_size the size to which ptr has to be realloc'ed
664  * @return the newly reallocated memory block
665  */
666 static void *
667 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
668 {
669   ptr = GNUNET_realloc (ptr, new_size);
670   if (new_size > size)
671     ptr = memset (ptr + size, 0, new_size - size);
672   return ptr;
673 }
674
675
676 /**
677  * Function to add a host to the current list of known hosts
678  *
679  * @param host the host to add 
680  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
681  *           already in use
682  */
683 static int
684 host_list_add (struct GNUNET_TESTBED_Host *host)
685 {
686   uint32_t host_id;
687
688   host_id = GNUNET_TESTBED_host_get_id_ (host);
689   if (host_list_size <= host_id)
690   {
691     host_list = 
692       TESTBED_realloc (host_list, 
693                        sizeof (struct GNUNET_TESTBED_Host *) * host_list_size,
694                        sizeof (struct GNUNET_TESTBED_Host *) *
695                        (host_list_size + LIST_GROW_STEP));
696     host_list_size += LIST_GROW_STEP;
697   }
698   if (NULL != host_list[host_id])
699   {
700     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
701     return GNUNET_SYSERR;
702   }
703   host_list[host_id] = host;
704   return GNUNET_OK;
705 }
706
707
708 /**
709  * Adds a route to the route list
710  *
711  * @param route the route to add
712  */
713 static void
714 route_list_add (struct Route *route)
715 {
716   if (route->dest >= route_list_size)
717   {
718     route_list = 
719       TESTBED_realloc (route_list, 
720                        sizeof (struct Route *) * route_list_size,
721                        sizeof (struct Route *) * 
722                        (route_list_size + LIST_GROW_STEP));
723     route_list_size += LIST_GROW_STEP;
724   }
725   GNUNET_assert (NULL == route_list[route->dest]);
726   route_list[route->dest] = route;
727 }
728
729
730 /**
731  * Adds a slave to the slave array
732  *
733  * @param slave the slave controller to add
734  */
735 static void
736 slave_list_add (struct Slave *slave)
737 {
738   if (slave->host_id  >= slave_list_size)
739   {
740     slave_list = TESTBED_realloc (slave_list, 
741                                   sizeof (struct Slave *) *slave_list_size,
742                                   sizeof (struct Slave *) *
743                                   (slave_list_size + LIST_GROW_STEP));
744     slave_list_size += LIST_GROW_STEP;
745   }
746   GNUNET_assert (NULL == slave_list[slave->host_id]);
747   slave_list[slave->host_id] = slave;
748 }
749
750
751 /**
752  * Adds a peer to the peer array
753  *
754  * @param peer the peer to add
755  */
756 static void
757 peer_list_add (struct Peer *peer)
758 {
759   if (peer->id  >= peer_list_size)
760   {
761     peer_list = TESTBED_realloc (peer_list, 
762                                  sizeof (struct Peer *) * peer_list_size,
763                                  sizeof (struct Peer *) *
764                                  (peer_list_size + LIST_GROW_STEP));
765     peer_list_size += LIST_GROW_STEP;
766   }
767   GNUNET_assert (NULL == peer_list[peer->id]);
768   peer_list[peer->id] = peer;
769 }
770
771
772 /**
773  * Removes a the give peer from the peer array
774  *
775  * @param peer the peer to be removed
776  */
777 static void
778 peer_list_remove (struct Peer *peer)
779 {
780   uint32_t id;
781
782   peer_list[peer->id] = NULL;
783   while (peer_list_size >= LIST_GROW_STEP)
784   {
785     for (id = peer_list_size - 1;
786          id > peer_list_size - LIST_GROW_STEP; id--)
787       if (NULL != peer_list[id])
788         break;
789     if (id != peer_list_size - LIST_GROW_STEP)
790       break;
791     peer_list_size -= LIST_GROW_STEP;
792   }
793   peer_list = GNUNET_realloc (peer_list, sizeof (struct GNUNET_TESTBED_Peer*)
794                               * peer_list_size);
795 }
796
797
798 /**
799  * Finds the route with directly connected host as destination through which
800  * the destination host can be reached
801  *
802  * @param host_id the id of the destination host
803  * @return the route with directly connected destination host; NULL if no route
804  *           is found
805  */
806 static struct Route *
807 find_dest_route (uint32_t host_id)
808 {
809   struct Route *route;
810   
811   while(NULL != (route = route_list[host_id]))
812   {
813     if (route->thru == master_context->host_id)
814       break;
815     host_id = route->thru;
816   }
817   return route;
818 }
819
820
821 /**
822  * Routes message to a host given its host_id
823  *
824  * @param host_id the id of the destination host
825  * @param msg the message to be routed
826  */
827 static void
828 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
829 {
830   GNUNET_break (0);
831 }
832
833
834 /**
835  * Send operation failure message to client
836  *
837  * @param client the client to which the failure message has to be sent to
838  * @param operation_id the id of the failed operation
839  * @param emsg the error message; can be NULL
840  */
841 static void
842 send_operation_fail_msg (struct GNUNET_SERVER_Client *client,
843                          uint64_t operation_id,
844                          const char *emsg)
845 {
846   struct GNUNET_TESTBED_OperationFailureEventMessage *msg;
847   uint16_t msize;
848   uint16_t emsg_len;
849   
850   msize = sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);  
851   emsg_len = (NULL == emsg) ? 0 : strlen (emsg) + 1;
852   msize += emsg_len;
853   msg = GNUNET_malloc (msize);
854   msg->header.size = htons (msize);
855   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONEVENT);
856   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
857   msg->operation_id = GNUNET_htonll (operation_id);
858   if (0 != emsg_len)
859     memcpy (&msg[1], emsg, emsg_len);
860   queue_message (client, &msg->header);
861 }
862
863
864 /**
865  * Function to send generic operation success message to given client
866  *
867  * @param client the client to send the message to
868  * @param operation_id the id of the operation which was successful
869  */
870 static void
871 send_operation_success_msg (struct GNUNET_SERVER_Client *client,
872                             uint64_t operation_id)
873 {
874   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg;
875   uint16_t msize;
876   
877   msize = sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);  
878   msg = GNUNET_malloc (msize);
879   msg->header.size = htons (msize);
880   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
881   msg->operation_id = GNUNET_htonll (operation_id);
882   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
883   queue_message (client, &msg->header);  
884 }
885
886
887 /**
888  * The  Link Controller forwarding task
889  *
890  * @param cls the LCFContext
891  * @param tc the Task context from scheduler
892  */
893 static void
894 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
895
896
897 /**
898  * Completion callback for host registrations while forwarding Link Controller messages
899  *
900  * @param cls the LCFContext
901  * @param emsg the error message; NULL if host registration is successful
902  */
903 static void
904 lcf_proc_cc (void *cls, const char *emsg)
905 {
906   struct LCFContext *lcf = cls;
907
908   lcf->rhandle = NULL;
909   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
910   switch (lcf->state)
911   {
912   case INIT:
913     if (NULL != emsg)
914       goto registration_error;
915     lcf->state = DELEGATED_HOST_REGISTERED;
916     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
917     break;
918   case DELEGATED_HOST_REGISTERED:
919      if (NULL != emsg)
920       goto registration_error;
921      lcf->state = SLAVE_HOST_REGISTERED;
922      lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
923      break;
924   default:
925     GNUNET_assert (0);          /* Shouldn't reach here */
926   }  
927   return;
928
929  registration_error:
930   LOG (GNUNET_ERROR_TYPE_WARNING, 
931        "Host registration failed with message: %s\n", emsg);
932   lcf->state = FINISHED;
933   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
934 }
935
936
937 /**
938  * Callback to be called when forwarded link controllers operation is
939  * successfull. We have to relay the reply msg back to the client
940  *
941  * @param cls ForwardedOperationContext
942  * @param msg the peer create success message
943  */
944 static void
945 forwarded_link_controllers_reply_relay (void *cls,
946                                         const struct GNUNET_MessageHeader *msg)
947 {
948   struct ForwardedOperationContext *fopc = cls;
949   struct GNUNET_MessageHeader *dup_msg;  
950   uint16_t msize;
951   
952   msize = ntohs (msg->size);
953   dup_msg = GNUNET_malloc (msize);
954   (void) memcpy (dup_msg, msg, msize);  
955   queue_message (fopc->client, dup_msg);
956   GNUNET_SERVER_client_drop (fopc->client);
957   GNUNET_SCHEDULER_cancel (fopc->timeout_task);  
958   GNUNET_free (fopc);  
959 }
960
961
962 /**
963  * Task to free resources when forwarded link controllers has been timedout
964  *
965  * @param cls the ForwardedOperationContext
966  * @param tc the task context from scheduler
967  */
968 static void
969 forwarded_link_controllers_timeout (void *cls,
970                                     const struct GNUNET_SCHEDULER_TaskContext
971                                     *tc)
972 {
973   struct ForwardedOperationContext *fopc = cls;
974   
975   GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
976   GNUNET_SERVER_client_drop (fopc->client);
977   GNUNET_free (fopc);  
978 }
979
980
981 /**
982  * The  Link Controller forwarding task
983  *
984  * @param cls the LCFContext
985  * @param tc the Task context from scheduler
986  */
987 static void
988 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
989 {
990   struct LCFContext *lcf = cls;
991   struct LCFContextQueue *lcfq;
992   struct ForwardedOperationContext *fopc;
993   
994   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
995   switch (lcf->state)
996   {
997   case INIT:
998     if (GNUNET_NO ==
999         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
1000                                             lcf->gateway->controller))
1001     {
1002       lcf->rhandle =
1003         GNUNET_TESTBED_register_host (lcf->gateway->controller,
1004                                       host_list[lcf->delegated_host_id],
1005                                       lcf_proc_cc, lcf);
1006     }
1007     else
1008     {
1009       lcf->state = DELEGATED_HOST_REGISTERED;
1010       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1011     }
1012     break;
1013   case DELEGATED_HOST_REGISTERED:
1014     if (GNUNET_NO ==
1015         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
1016                                             lcf->gateway->controller))
1017     {
1018       lcf->rhandle =
1019         GNUNET_TESTBED_register_host (lcf->gateway->controller,
1020                                       host_list[lcf->slave_host_id],
1021                                       lcf_proc_cc, lcf);
1022     }
1023     else
1024     {
1025       lcf->state = SLAVE_HOST_REGISTERED;
1026       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1027     }
1028     break;
1029   case SLAVE_HOST_REGISTERED:
1030     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1031     fopc->client = lcf->client;
1032     fopc->operation_id = lcf->operation_id;
1033     fopc->opc = 
1034       GNUNET_TESTBED_forward_operation_msg_ (lcf->gateway->controller,
1035                                              lcf->operation_id,
1036                                              &lcf->msg->header,
1037                                              &forwarded_link_controllers_reply_relay,
1038                                              fopc);
1039     fopc->timeout_task = 
1040       GNUNET_SCHEDULER_add_delayed (TIMEOUT,
1041                                     &forwarded_link_controllers_timeout, fopc);    
1042     lcf->state = FINISHED;
1043     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1044     break;
1045   case FINISHED:
1046     lcfq = lcfq_head;
1047     GNUNET_assert (lcfq->lcf == lcf);
1048     GNUNET_free (lcf->msg);
1049     GNUNET_free (lcf);
1050     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1051     GNUNET_free (lcfq);
1052     if (NULL != lcfq_head)
1053       lcf_proc_task_id = 
1054         GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
1055   }
1056 }
1057
1058
1059 /**
1060  * Callback for event from slave controllers
1061  *
1062  * @param cls struct Slave *
1063  * @param event information about the event
1064  */
1065 static void 
1066 slave_event_callback (void *cls,
1067                       const struct GNUNET_TESTBED_EventInformation *event)
1068 {
1069   GNUNET_break (0);
1070 }
1071
1072
1073 /**
1074  * Callback to signal successfull startup of the controller process
1075  *
1076  * @param cls the closure from GNUNET_TESTBED_controller_start()
1077  * @param cfg the configuration with which the controller has been started;
1078  *          NULL if status is not GNUNET_OK
1079  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1080  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1081  */
1082 static void 
1083 slave_status_callback (void *cls, 
1084                        const struct GNUNET_CONFIGURATION_Handle *cfg,
1085                        int status)
1086 {
1087   struct LinkControllersContext *lcc = cls;
1088
1089   if (GNUNET_SYSERR == status)
1090   {
1091     lcc->slave->controller_proc = NULL;
1092     LOG (GNUNET_ERROR_TYPE_WARNING,
1093          "Unexpected slave shutdown\n");
1094     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
1095     return;
1096   }
1097   lcc->slave->controller =
1098     GNUNET_TESTBED_controller_connect (cfg, host_list[lcc->slave->host_id],
1099                                        master_context->event_mask,
1100                                        &slave_event_callback, lcc->slave);
1101   if (NULL != lcc->slave->controller)
1102     send_operation_success_msg (lcc->client, lcc->operation_id);
1103   else
1104     send_operation_fail_msg (lcc->client, lcc->operation_id,
1105                              "Could not connect to delegated controller");
1106   GNUNET_SERVER_client_drop (lcc->client);
1107   GNUNET_free (lcc);
1108 }
1109
1110
1111 /**
1112  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
1113  *
1114  * @param cls NULL
1115  * @param client identification of the client
1116  * @param message the actual message
1117  */
1118 static void 
1119 handle_init (void *cls,
1120              struct GNUNET_SERVER_Client *client,
1121              const struct GNUNET_MessageHeader *message)
1122 {
1123   const struct GNUNET_TESTBED_InitMessage *msg;
1124   struct GNUNET_TESTBED_Host *host;
1125   const char *controller_hostname;
1126   uint16_t msize;
1127
1128   if (NULL != master_context)
1129   {
1130     GNUNET_break (0);
1131     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1132     return;
1133   }
1134   msg = (const struct GNUNET_TESTBED_InitMessage *) message;
1135   msize = ntohs (message->size);
1136   if (msize <= sizeof (struct GNUNET_TESTBED_InitMessage))
1137   {
1138     GNUNET_break (0);
1139     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1140     return;
1141   }
1142   msize -= sizeof (struct GNUNET_TESTBED_InitMessage);  
1143   controller_hostname = (const char *) &msg[1];
1144   if ('\0' != controller_hostname[msize - 1])
1145   {
1146     GNUNET_break (0);
1147     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1148     return;
1149   }    
1150   master_context = GNUNET_malloc (sizeof (struct Context));
1151   master_context->client = client;
1152   master_context->host_id = ntohl (msg->host_id);
1153   master_context->master_ip = GNUNET_strdup (controller_hostname);  
1154   LOG_DEBUG ("Master Controller IP: %s\n", master_context->master_ip);
1155   master_context->system = 
1156     GNUNET_TESTING_system_create ("testbed", master_context->master_ip);
1157   host = GNUNET_TESTBED_host_create_with_id (master_context->host_id,
1158                                              NULL, NULL, 0);
1159   host_list_add (host);
1160   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
1161   GNUNET_SERVER_client_keep (client);
1162   LOG_DEBUG ("Created master context with host ID: %u\n",
1163              master_context->host_id);
1164   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1165 }
1166
1167
1168 /**
1169  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1170  *
1171  * @param cls NULL
1172  * @param client identification of the client
1173  * @param message the actual message
1174  */
1175 static void 
1176 handle_add_host (void *cls,
1177                  struct GNUNET_SERVER_Client *client,
1178                  const struct GNUNET_MessageHeader *message)
1179 {
1180   struct GNUNET_TESTBED_Host *host;
1181   const struct GNUNET_TESTBED_AddHostMessage *msg;
1182   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
1183   char *username;
1184   char *hostname;
1185   char *emsg;
1186   uint32_t host_id;
1187   uint16_t username_length;
1188   uint16_t hostname_length;
1189   uint16_t reply_size;
1190   uint16_t msize;
1191   
1192   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
1193   msize = ntohs (msg->header.size);
1194   username = (char *) &(msg[1]);
1195   username_length = ntohs (msg->user_name_length);
1196   GNUNET_assert (msize > (sizeof (struct GNUNET_TESTBED_AddHostMessage)
1197                           + username_length + 1)); /* msg must contain hostname */
1198   if (0 != username_length)
1199     GNUNET_assert ('\0' == username[username_length]);
1200   username_length = (0 == username_length) ? 0 : username_length + 1;              
1201   hostname = username + username_length;
1202   hostname_length = msize - (sizeof (struct GNUNET_TESTBED_AddHostMessage)
1203                              + username_length);
1204   GNUNET_assert ('\0' == hostname[hostname_length - 1]);
1205   GNUNET_assert (strlen (hostname) == hostname_length - 1);
1206   host_id = ntohl (msg->host_id);
1207   LOG_DEBUG ("Received ADDHOST message\n");
1208   LOG_DEBUG ("-------host id: %u\n", host_id);
1209   if (NULL != hostname) LOG_DEBUG ("-------hostname: %s\n", hostname);
1210   if (0 != username_length) LOG_DEBUG ("-------username: %s\n", username);
1211   else 
1212   {
1213     LOG_DEBUG ("-------username: NULL\n");
1214     username = NULL;
1215   }
1216   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1217   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1218                                              ntohs (msg->ssh_port));
1219   GNUNET_assert (NULL != host);
1220   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1221   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1222   if (GNUNET_OK != host_list_add (host))
1223   {    
1224     /* We are unable to add a host */
1225     emsg = "A host exists with given host-id";
1226     LOG_DEBUG ("%s: %u", emsg, host_id);
1227     GNUNET_TESTBED_host_destroy (host);
1228     reply_size += strlen (emsg) + 1;
1229     reply = GNUNET_malloc (reply_size);
1230     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1231   }
1232   else
1233     reply = GNUNET_malloc (reply_size);  
1234   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
1235   reply->header.size = htons (reply_size);
1236   reply->host_id = htonl (host_id);  
1237   queue_message (client, &reply->header);
1238 }
1239
1240
1241 /**
1242  * Iterator over hash map entries.
1243  *
1244  * @param cls closure
1245  * @param key current key code
1246  * @param value value in the hash map
1247  * @return GNUNET_YES if we should continue to
1248  *         iterate,
1249  *         GNUNET_NO if not.
1250  */
1251 int ss_exists_iterator (void *cls,
1252                         const struct GNUNET_HashCode * key,
1253                         void *value)
1254 {
1255   struct SharedService *queried_ss = cls;
1256   struct SharedService *ss = value;
1257
1258   if (0 == strcmp (ss->name, queried_ss->name))
1259     return GNUNET_NO;
1260   else
1261     return GNUNET_YES;
1262 }
1263
1264
1265 /**
1266  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1267  *
1268  * @param cls NULL
1269  * @param client identification of the client
1270  * @param message the actual message
1271  */
1272 static void 
1273 handle_configure_shared_service (void *cls,
1274                                  struct GNUNET_SERVER_Client *client,
1275                                  const struct GNUNET_MessageHeader *message)
1276 {
1277   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1278   struct SharedService *ss;
1279   char *service_name;
1280   struct GNUNET_HashCode hash;
1281   uint16_t msg_size;
1282   uint16_t service_name_size;
1283     
1284   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1285   msg_size = ntohs (message->size);
1286   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1287   {
1288     GNUNET_break (0);
1289     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1290     return;
1291   }
1292   service_name_size = msg_size - 
1293     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
1294   service_name = (char *) &msg[1];
1295   if ('\0' != service_name[service_name_size - 1])
1296   {
1297     GNUNET_break (0);
1298     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1299     return;
1300   }
1301   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
1302              service_name, ntohl (msg->num_peers));
1303   if (ntohl (msg->host_id) != master_context->host_id)
1304   {
1305     route_message (ntohl (msg->host_id), message);
1306     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1307     return;
1308   }
1309   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1310   ss = GNUNET_malloc (sizeof (struct SharedService));
1311   ss->name = strdup (service_name);
1312   ss->num_shared = ntohl (msg->num_peers);
1313   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1314   if (GNUNET_SYSERR == 
1315       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1316                                                   &ss_exists_iterator, ss))
1317   {
1318     LOG (GNUNET_ERROR_TYPE_WARNING,
1319          "Service %s already configured as a shared service. "
1320          "Ignoring service sharing request \n", ss->name);
1321     GNUNET_free (ss->name);
1322     GNUNET_free (ss);
1323     return;
1324   }
1325   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1326                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
1327 }
1328
1329
1330 /**
1331  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1332  *
1333  * @param cls NULL
1334  * @param client identification of the client
1335  * @param message the actual message
1336  */
1337 static void 
1338 handle_link_controllers (void *cls,
1339                          struct GNUNET_SERVER_Client *client,
1340                          const struct GNUNET_MessageHeader *message)
1341 {
1342   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1343   struct GNUNET_CONFIGURATION_Handle *cfg;
1344   struct LCFContextQueue *lcfq;
1345   struct Route *route;
1346   struct Route *new_route;
1347   char *config;  
1348   uLongf dest_size;
1349   size_t config_size;
1350   uint32_t delegated_host_id;
1351   uint32_t slave_host_id;
1352   uint16_t msize;
1353    
1354   if (NULL == master_context)
1355   {
1356     GNUNET_break (0);
1357     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1358     return;
1359   }
1360   msize = ntohs (message->size);
1361   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1362   {
1363     GNUNET_break (0);
1364     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1365     return;
1366   }
1367   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1368   delegated_host_id = ntohl (msg->delegated_host_id);
1369   if (delegated_host_id == master_context->host_id)
1370   {
1371     GNUNET_break (0);
1372     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1373     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1374     return;
1375   }
1376   if ((delegated_host_id >= host_list_size) || 
1377       (NULL == host_list[delegated_host_id]))
1378   {
1379     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
1380     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1381     return;
1382   }
1383   slave_host_id = ntohl (msg->slave_host_id);
1384   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1385   {
1386     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
1387     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1388     return;
1389   }
1390   if (slave_host_id == delegated_host_id)
1391   {
1392     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1393     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1394     return;
1395   } 
1396   
1397   if (slave_host_id == master_context->host_id) /* Link from us */
1398   {
1399     struct Slave *slave;
1400     
1401     msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1402     config_size = ntohs (msg->config_size);
1403     if ((delegated_host_id < slave_list_size) && 
1404         (NULL != slave_list[delegated_host_id])) /* We have already added */
1405     {
1406       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1407            delegated_host_id);
1408       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1409       return;
1410     }    
1411     config = GNUNET_malloc (config_size);
1412     dest_size = (uLongf) config_size;    
1413     if (Z_OK != uncompress ((Bytef *) config, &dest_size,
1414                             (const Bytef *) &msg[1], (uLong) msize))
1415     {
1416       GNUNET_break (0);           /* Compression error */
1417       GNUNET_free (config);
1418       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1419       return;
1420     }
1421     if (config_size != dest_size)
1422     {
1423       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1424       GNUNET_free (config);
1425       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1426       return;
1427     }
1428     cfg = GNUNET_CONFIGURATION_create (); /* Free here or in lcfcontext */
1429     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1430                                                        GNUNET_NO))
1431     {
1432       GNUNET_break (0);           /* Configuration parsing error */
1433       GNUNET_free (config);
1434       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1435       return;
1436     }
1437     GNUNET_free (config);
1438     if ((delegated_host_id < slave_list_size) &&
1439         (NULL != slave_list[delegated_host_id]))
1440     {
1441       GNUNET_break (0);           /* Configuration parsing error */
1442       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1443       return;
1444     }
1445     slave = GNUNET_malloc (sizeof (struct Slave));
1446     slave->host_id = delegated_host_id;    
1447     slave_list_add (slave);
1448     if (1 == msg->is_subordinate)
1449     {
1450       struct LinkControllersContext *lcc;
1451       lcc = GNUNET_malloc (sizeof (struct LinkControllersContext));
1452       lcc->operation_id = GNUNET_ntohll (msg->operation_id);
1453       GNUNET_SERVER_client_keep (client);
1454       lcc->client = client;
1455       lcc->slave = slave;      
1456       slave->controller_proc =
1457         GNUNET_TESTBED_controller_start (master_context->master_ip,
1458                                          host_list[slave->host_id],
1459                                          cfg, &slave_status_callback,
1460                                          lcc);
1461     }
1462     else {
1463       slave->controller = 
1464         GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1465                                            master_context->event_mask,
1466                                            &slave_event_callback, slave);
1467       if (NULL != slave->controller)
1468         send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1469       else
1470         send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1471                                  "Could not connect to delegated controller");
1472     }
1473     GNUNET_CONFIGURATION_destroy (cfg);
1474     new_route = GNUNET_malloc (sizeof (struct Route));
1475     new_route->dest = delegated_host_id;
1476     new_route->thru = master_context->host_id;
1477     route_list_add (new_route);
1478     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1479     return;
1480   }
1481
1482   /* Route the request */
1483   if (slave_host_id >= route_list_size)
1484   {
1485     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1486     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1487     return;
1488   }
1489   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1490   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1491   lcfq->lcf->delegated_host_id = delegated_host_id;
1492   lcfq->lcf->slave_host_id = slave_host_id;
1493   route = find_dest_route (slave_host_id);
1494   GNUNET_assert (NULL != route); /* because we add routes carefully */
1495   GNUNET_assert (route->dest < slave_list_size);
1496   GNUNET_assert (NULL != slave_list[route->dest]);  
1497   lcfq->lcf->state = INIT;
1498   lcfq->lcf->operation_id = GNUNET_ntohll (msg->operation_id);
1499   lcfq->lcf->gateway = slave_list[route->dest];
1500   lcfq->lcf->msg = GNUNET_malloc (msize);
1501   (void) memcpy (lcfq->lcf->msg, msg, msize);
1502   GNUNET_SERVER_client_keep (client);
1503   lcfq->lcf->client = client;
1504   if (NULL == lcfq_head)
1505   {
1506     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1507     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1508     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq->lcf);
1509   }
1510   else
1511     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1512   /* FIXME: Adding a new route should happen after the controllers are linked
1513      successfully */
1514   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1515   new_route = GNUNET_malloc (sizeof (struct Route));
1516   new_route->dest = delegated_host_id;
1517   new_route->thru = route->dest;
1518   route_list_add (new_route);
1519 }
1520
1521
1522 /**
1523  * The task to be executed if the forwarded peer create operation has been
1524  * timed out
1525  *
1526  * @param cls the FowardedOperationContext
1527  * @param tc the TaskContext from the scheduler
1528  */
1529 static void
1530 peer_create_forward_timeout (void *cls,
1531                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1532 {
1533   struct ForwardedOperationContext *fo_ctxt = cls;
1534   
1535   /* send error msg to client */
1536   send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id,
1537                            "Timedout");
1538   GNUNET_SERVER_client_drop (fo_ctxt->client);
1539   GNUNET_TESTBED_forward_operation_msg_cancel_ (fo_ctxt->opc);
1540   GNUNET_free (fo_ctxt);  
1541 }
1542
1543
1544 /**
1545  * Callback to be called when forwarded peer create operation is
1546  * successfull. We have to relay the reply msg back to the client
1547  *
1548  * @param cls ForwardedOperationContext
1549  * @param msg the peer create success message
1550  */
1551 static void
1552 peer_create_success_cb (void *cls,
1553                         const struct GNUNET_MessageHeader *msg)
1554 {
1555   struct ForwardedOperationContext *fo_ctxt = cls;
1556   const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *success_msg;
1557   struct GNUNET_MessageHeader *dup_msg;
1558   struct Peer *peer;
1559   uint16_t msize;
1560   
1561   GNUNET_SCHEDULER_cancel (fo_ctxt->timeout_task);
1562   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS)
1563   {
1564     success_msg 
1565       = (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *) msg;
1566     peer = GNUNET_malloc (sizeof (struct Peer));
1567     peer->is_remote = GNUNET_YES;
1568     peer->id = ntohl (success_msg->peer_id);
1569     GNUNET_assert (NULL != fo_ctxt->cls);
1570     peer->details.remote.controller = fo_ctxt->cls;
1571     peer_list_add (peer);    
1572   }
1573   msize = ntohs (msg->size);
1574   dup_msg = GNUNET_malloc (msize);
1575   (void) memcpy (dup_msg, msg, msize);  
1576   queue_message (fo_ctxt->client, dup_msg);
1577   GNUNET_SERVER_client_drop (fo_ctxt->client);
1578   GNUNET_free (fo_ctxt);  
1579 }
1580
1581
1582
1583 /**
1584  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1585  *
1586  * @param cls NULL
1587  * @param client identification of the client
1588  * @param message the actual message
1589  */
1590 static void 
1591 handle_peer_create (void *cls,
1592                     struct GNUNET_SERVER_Client *client,
1593                     const struct GNUNET_MessageHeader *message)
1594 {
1595   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1596   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1597   struct GNUNET_CONFIGURATION_Handle *cfg;
1598   struct ForwardedOperationContext *fo_ctxt;
1599   struct Route *route;
1600   struct Peer *peer;
1601   char *config;
1602   size_t dest_size;
1603   int ret;
1604   uint32_t config_size;
1605   uint32_t host_id;
1606   uint16_t msize;
1607   
1608
1609   msize = ntohs (message->size);
1610   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1611   {
1612     GNUNET_break (0);           /* We need configuration */
1613     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1614     return;
1615   }
1616   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1617   host_id = ntohl (msg->host_id);
1618   if (host_id == master_context->host_id)
1619   {
1620     char *emsg;
1621     
1622     /* We are responsible for this peer */
1623     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1624     config_size = ntohl (msg->config_size);    
1625     config = GNUNET_malloc (config_size);
1626     dest_size = config_size;
1627     if (Z_OK != (ret = uncompress ((Bytef *) config, (uLongf *) &dest_size,
1628                                    (const Bytef *) &msg[1], (uLong) msize)))
1629     {
1630       GNUNET_break (0);           /* uncompression error */
1631       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1632       return;
1633     }
1634     if (config_size != dest_size)
1635     {
1636       GNUNET_break (0);/* Uncompressed config size mismatch */
1637       GNUNET_free (config);
1638       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1639       return;
1640     }
1641     cfg = GNUNET_CONFIGURATION_create ();
1642     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1643                                                        GNUNET_NO))
1644     {
1645       GNUNET_break (0);           /* Configuration parsing error */
1646       GNUNET_free (config);
1647       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1648       return;
1649     }
1650     GNUNET_free (config);
1651     peer = GNUNET_malloc (sizeof (struct Peer));
1652     peer->is_remote = GNUNET_NO;
1653     peer->details.local.cfg = cfg;
1654     peer->id = ntohl (msg->peer_id);
1655     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1656     peer->details.local.peer = 
1657       GNUNET_TESTING_peer_configure (master_context->system,
1658                                      peer->details.local.cfg, peer->id,
1659                                      NULL /* Peer id */,
1660                                      &emsg);
1661     if (NULL == peer->details.local.peer)
1662     {
1663       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1664       GNUNET_free (emsg);
1665       GNUNET_free (peer);
1666       GNUNET_break (0);
1667       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1668       return;
1669     }
1670     peer_list_add (peer);
1671     reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1672     reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1673     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1674     reply->peer_id = msg->peer_id;
1675     reply->operation_id = msg->operation_id;
1676     queue_message (client, &reply->header);
1677     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1678     return;
1679   }
1680   
1681   /* Forward peer create request */
1682   route = find_dest_route (host_id);
1683   if (NULL == route)
1684   {
1685     GNUNET_break (0);
1686     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1687     return;
1688   }
1689   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1690   GNUNET_SERVER_client_keep (client);
1691   fo_ctxt->client = client;
1692   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id); 
1693   fo_ctxt->cls = slave_list[route->dest]->controller;  
1694   fo_ctxt->opc = 
1695     GNUNET_TESTBED_forward_operation_msg_ (slave_list[route->dest]->controller,
1696                                            fo_ctxt->operation_id,
1697                                            &msg->header,
1698                                            peer_create_success_cb, fo_ctxt);
1699   fo_ctxt->timeout_task = 
1700     GNUNET_SCHEDULER_add_delayed (TIMEOUT,
1701                                   &peer_create_forward_timeout, fo_ctxt);
1702                                   
1703   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1704 }
1705
1706
1707 /**
1708  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1709  *
1710  * @param cls NULL
1711  * @param client identification of the client
1712  * @param message the actual message
1713  */
1714 static void 
1715 handle_peer_destroy (void *cls,
1716                      struct GNUNET_SERVER_Client *client,
1717                      const struct GNUNET_MessageHeader *message)
1718 {
1719   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1720   struct Peer *peer;
1721   uint32_t peer_id;
1722   
1723   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1724   peer_id = ntohl (msg->peer_id);
1725   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1726              peer_id, GNUNET_ntohll (msg->operation_id));  
1727   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1728   {
1729     LOG (GNUNET_ERROR_TYPE_ERROR,
1730          "Asked for destroy when peer not created at us\n");
1731     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1732     return;
1733   }
1734   peer = peer_list[peer_id];
1735   if (GNUNET_YES == peer->is_remote)
1736   {
1737     /* Forward the destory message to sub controller */
1738     GNUNET_break (0);
1739     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1740     return;
1741   }
1742   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
1743   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
1744   peer_list_remove (peer);
1745   GNUNET_free (peer);
1746   send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1747   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1748 }
1749
1750
1751 /**
1752  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1753  *
1754  * @param cls NULL
1755  * @param client identification of the client
1756  * @param message the actual message
1757  */
1758 static void 
1759 handle_peer_start (void *cls,
1760                    struct GNUNET_SERVER_Client *client,
1761                    const struct GNUNET_MessageHeader *message)
1762 {
1763   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1764   struct GNUNET_TESTBED_PeerEventMessage *reply;
1765   uint32_t peer_id;
1766
1767   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1768   peer_id = ntohl (msg->peer_id);
1769   if ((peer_id >= peer_list_size) 
1770       || (NULL == peer_list[peer_id]))
1771   {
1772     GNUNET_break (0);
1773     /* FIXME: reply with failure message or forward to slave controller */
1774     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1775     return;
1776   }
1777   if (GNUNET_OK != 
1778       GNUNET_TESTING_peer_start (peer_list[peer_id]->details.local.peer))
1779   {
1780     /* FIXME: return FAILURE message */
1781     GNUNET_break (0);
1782     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1783     return;
1784   }
1785   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1786   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1787   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1788   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1789   reply->host_id = htonl (master_context->host_id);
1790   reply->peer_id = msg->peer_id;
1791   reply->operation_id = msg->operation_id;
1792   queue_message (client, &reply->header);
1793   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1794 }
1795
1796
1797 /**
1798  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1799  *
1800  * @param cls NULL
1801  * @param client identification of the client
1802  * @param message the actual message
1803  */
1804 static void 
1805 handle_peer_stop (void *cls,
1806                   struct GNUNET_SERVER_Client *client,
1807                   const struct GNUNET_MessageHeader *message)
1808 {
1809   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1810   struct GNUNET_TESTBED_PeerEventMessage *reply;
1811   uint32_t peer_id;
1812
1813   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1814   peer_id = ntohl (msg->peer_id);
1815   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1816   {
1817     GNUNET_break (0);           /* FIXME: route to slave? */
1818     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1819     return;
1820   }
1821   if (GNUNET_OK != 
1822       GNUNET_TESTING_peer_stop (peer_list[peer_id]->details.local.peer))
1823   {
1824     /* FIXME: return FAILURE message */
1825     GNUNET_break (0);
1826     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1827     return;
1828   }
1829   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1830   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1831   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1832   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1833   reply->host_id = htonl (master_context->host_id);
1834   reply->peer_id = msg->peer_id;
1835   reply->operation_id = msg->operation_id;
1836   queue_message (client, &reply->header);
1837   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1838 }
1839
1840
1841 /**
1842  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1843  *
1844  * @param cls NULL
1845  * @param client identification of the client
1846  * @param message the actual message
1847  */
1848 static void 
1849 handle_peer_get_config (void *cls,
1850                         struct GNUNET_SERVER_Client *client,
1851                         const struct GNUNET_MessageHeader *message)
1852 {
1853   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1854   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1855   struct Peer *peer;
1856   char *config;
1857   char *xconfig;
1858   size_t c_size;
1859   size_t xc_size;  
1860   uint32_t peer_id;
1861   uint16_t msize;
1862   
1863   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1864   peer_id = ntohl (msg->peer_id);
1865   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1866   {
1867     /* FIXME: return FAILURE message */
1868     GNUNET_break (0);
1869     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1870     return;
1871   }
1872   peer = peer_list[peer_id];
1873   if (GNUNET_YES == peer->is_remote)
1874   {
1875     /* FIXME: forward to sub controller */
1876     GNUNET_break (0);
1877     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1878     return;
1879   }
1880   config =
1881     GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
1882                                     &c_size);
1883   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1884   GNUNET_free (config);
1885   msize = xc_size + sizeof (struct
1886                             GNUNET_TESTBED_PeerConfigurationInformationMessage);
1887   reply = GNUNET_realloc (xconfig, msize);
1888   (void) memmove (&reply[1], reply, xc_size);
1889   reply->header.size = htons (msize);
1890   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
1891   reply->peer_id = msg->peer_id;
1892   reply->operation_id = msg->operation_id;
1893   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
1894                                     &reply->peer_identity);
1895   reply->config_size = htons ((uint16_t) c_size);
1896   queue_message (client, &reply->header);
1897   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1898 }
1899
1900
1901 /**
1902  * Task for cleaing up overlay connect context structure
1903  *
1904  * @param cls the overlay connect context
1905  * @param tc the task context
1906  */
1907 static void
1908 occ_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1909 {
1910   struct OverlayConnectContext *occ = cls;
1911
1912   GNUNET_free_non_null (occ->emsg);
1913   GNUNET_free_non_null (occ->hello);
1914   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1915     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1916   if (NULL != occ->ch)
1917     GNUNET_CORE_disconnect (occ->ch);
1918   if (NULL != occ->ghh)
1919     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1920   if (NULL != occ->p1th)
1921     GNUNET_TRANSPORT_disconnect (occ->p1th);
1922   if (NULL != occ->p2th)
1923     GNUNET_TRANSPORT_disconnect (occ->p2th);
1924   GNUNET_free (occ);
1925 }
1926
1927
1928 /**
1929  * Task which will be run when overlay connect request has been timed out
1930  *
1931  * @param 
1932  * @return 
1933  */
1934 static void
1935 timeout_overlay_connect (void *cls,
1936                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1937 {
1938   struct OverlayConnectContext *occ = cls;
1939
1940   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1941   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
1942   GNUNET_SERVER_client_drop (occ->client);
1943   occ_cleanup (occ, tc);
1944 }
1945
1946
1947
1948 /**
1949  * Function called to notify transport users that another
1950  * peer connected to us.
1951  *
1952  * @param cls closure
1953  * @param new_peer the peer that connected
1954  * @param ats performance data
1955  * @param ats_count number of entries in ats (excluding 0-termination)
1956  */
1957 static void 
1958 overlay_connect_notify (void *cls,
1959                         const struct GNUNET_PeerIdentity * new_peer,
1960                         const struct GNUNET_ATS_Information * ats,
1961                         unsigned int ats_count)
1962 {
1963   struct OverlayConnectContext *occ = cls;
1964   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
1965   char *new_peer_str;
1966   char *other_peer_str;
1967
1968   LOG_DEBUG ("Overlay connect notify\n");
1969   if (0 == memcmp (new_peer, &occ->peer_identity, 
1970                    sizeof (struct GNUNET_PeerIdentity)))
1971     return;
1972   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
1973   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
1974   if (0 != memcmp (new_peer, &occ->other_peer_identity,
1975                    sizeof (struct GNUNET_PeerIdentity)))
1976   {
1977     LOG_DEBUG ("Unexpected peer %4s connected to peer %4s\n",
1978                new_peer_str, other_peer_str);
1979     GNUNET_free (new_peer_str);
1980     GNUNET_free (other_peer_str);
1981     return;
1982   }
1983   LOG_DEBUG ("Peer %4s connected to peer %4s\n", new_peer_str, other_peer_str);
1984   GNUNET_free (new_peer_str);
1985   GNUNET_free (other_peer_str);
1986   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1987   {
1988     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1989     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
1990   }
1991   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
1992   GNUNET_SCHEDULER_cancel (occ->timeout_task);
1993   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1994   GNUNET_free_non_null (occ->emsg);
1995   occ->emsg = NULL;
1996   GNUNET_TRANSPORT_disconnect (occ->p1th);
1997   occ->p1th = NULL;
1998   /* Peer 1 has connected connect to peer2 - now send overlay connect success message */
1999   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
2000   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2001   msg->header.size = htons (sizeof (struct
2002                                     GNUNET_TESTBED_ConnectionEventMessage));
2003   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
2004   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
2005   msg->peer1 = htonl (occ->peer->id);
2006   msg->peer2 = htonl (occ->other_peer->id);
2007   msg->operation_id = GNUNET_htonll (occ->op_id);
2008   queue_message (occ->client, &msg->header);
2009   GNUNET_SERVER_client_drop (occ->client);
2010   GNUNET_SCHEDULER_add_now (&occ_cleanup, occ);
2011 }
2012
2013
2014 static void
2015 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2016 {
2017   struct OverlayConnectContext *occ = cls;
2018   char *other_peer_str;
2019
2020   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2021   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2022     return;
2023   GNUNET_assert (NULL != occ->hello);
2024   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2025   LOG_DEBUG ("Offering HELLO of %s to %s\n", other_peer_str, GNUNET_i2s (&occ->peer_identity));
2026   GNUNET_free (other_peer_str);
2027   GNUNET_TRANSPORT_offer_hello (occ->p1th, occ->hello, NULL, NULL);
2028   GNUNET_TRANSPORT_try_connect (occ->p1th, &occ->other_peer_identity);
2029   occ->send_hello_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2030                                                        &send_hello, occ);
2031 }
2032
2033 /**
2034  * Test for checking whether HELLO message is empty
2035  *
2036  * @param cls empty flag to set
2037  * @param address the HELLO
2038  * @param expiration expiration of the HELLO
2039  * @return 
2040  */
2041 static int
2042 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
2043               struct GNUNET_TIME_Absolute expiration)
2044 {
2045   int *empty = cls;
2046
2047   *empty = GNUNET_NO;
2048   return GNUNET_OK;
2049 }
2050
2051
2052 /**
2053  * Function called whenever there is an update to the
2054  * HELLO of peers in the OverlayConnectClosure
2055  *
2056  * @param cls closure
2057  * @param hello our updated HELLO
2058  */
2059 static void 
2060 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
2061 {
2062   struct OverlayConnectContext *occ = cls;
2063   int empty;
2064   uint16_t msize;
2065   
2066   msize = ntohs (hello->size);
2067   if (msize < 0)
2068   {
2069     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2070                 "HELLO message of peer %s is of size 0\n",
2071                 &occ->other_peer_identity);
2072     return;
2073   }
2074   empty = GNUNET_YES;
2075   (void) 
2076     GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *) hello,
2077                                     GNUNET_NO, &test_address, &empty);
2078   if (GNUNET_YES == empty)
2079   {
2080     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->other_peer_identity));
2081     return;
2082   }
2083   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->other_peer_identity));
2084   occ->hello = GNUNET_malloc (msize);
2085   memcpy (occ->hello, hello, msize);
2086   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
2087   occ->ghh = NULL;
2088   GNUNET_TRANSPORT_disconnect (occ->p2th);
2089   occ->p2th = NULL;
2090   GNUNET_free_non_null (occ->emsg);  
2091   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
2092   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
2093 }
2094
2095
2096 /**
2097  * Function called after GNUNET_CORE_connect has succeeded (or failed
2098  * for good).  Note that the private key of the peer is intentionally
2099  * not exposed here; if you need it, your process should try to read
2100  * the private key file directly (which should work if you are
2101  * authorized...).
2102  *
2103  * @param cls closure
2104  * @param server handle to the server, NULL if we failed
2105  * @param my_identity ID of this peer, NULL if we failed
2106  */
2107 static void 
2108 core_startup_cb (void *cls, struct GNUNET_CORE_Handle * server,
2109                  const struct GNUNET_PeerIdentity *my_identity)
2110 {
2111   struct OverlayConnectContext *occ = cls;
2112
2113   GNUNET_free_non_null (occ->emsg);
2114   occ->emsg = NULL;
2115   memcpy (&occ->peer_identity, my_identity, sizeof (struct GNUNET_PeerIdentity));
2116   occ->p1th =
2117     GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg, 
2118                               &occ->peer_identity, NULL, NULL, NULL, NULL);
2119   /* Connect to the transport of 2nd peer and get its HELLO message */
2120   GNUNET_TESTING_peer_get_identity (occ->other_peer->details.local.peer,
2121                                     &occ->other_peer_identity);
2122   occ->p2th = 
2123     GNUNET_TRANSPORT_connect (occ->other_peer->details.local.cfg,
2124                               &occ->other_peer_identity,
2125                               NULL, NULL, NULL, NULL);
2126   if ((NULL == occ->p1th) || (NULL == occ->p2th))
2127   {
2128     occ->emsg = GNUNET_strdup ("Cannot connect to TRANSPORTs of peers");
2129     goto send_failure;
2130   }
2131   LOG_DEBUG ("Acquiring HELLO of peer %s\n", GNUNET_i2s
2132              (&occ->other_peer_identity));
2133   occ->emsg = GNUNET_strdup ("Timeout while acquiring HELLO message");
2134   occ->ghh = GNUNET_TRANSPORT_get_hello (occ->p2th, &hello_update_cb, occ);
2135   return;
2136
2137  send_failure:
2138   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2139   occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);  
2140 }
2141
2142
2143 /**
2144  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
2145  *
2146  * @param cls NULL
2147  * @param client identification of the client
2148  * @param message the actual message
2149  */
2150 static void 
2151 handle_overlay_connect (void *cls,
2152                         struct GNUNET_SERVER_Client *client,
2153                         const struct GNUNET_MessageHeader *message)
2154 {
2155   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
2156   struct OverlayConnectContext *occ;
2157   struct GNUNET_CORE_MessageHandler no_handlers[] = {
2158     {NULL, 0, 0}
2159   };
2160   uint32_t p1;
2161   uint32_t p2;
2162
2163   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
2164   p1 = ntohl (msg->peer1);
2165   p2 = ntohl (msg->peer2);
2166   GNUNET_assert (p1 < peer_list_size);
2167   GNUNET_assert (NULL != peer_list[p1]);
2168   GNUNET_assert (p2 < peer_list_size);
2169   GNUNET_assert (NULL != peer_list[p2]);
2170   /* FIXME: Add cases where we have to forward overlay connect message to sub
2171      controllers */
2172   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
2173   GNUNET_SERVER_client_keep (client);
2174   occ->client = client;
2175   occ->state = OCC_STATE_INIT;
2176   occ->peer = peer_list[p1];
2177   occ->other_peer = peer_list[p2];
2178   occ->op_id = GNUNET_ntohll (msg->operation_id);
2179   occ->timeout_task =
2180     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2181                                   (GNUNET_TIME_UNIT_SECONDS, 30),
2182                                   &timeout_overlay_connect, occ);   
2183   /* Connect to the core of 1st peer and wait for the 2nd peer to connect */
2184   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
2185   occ->ch = 
2186     GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
2187                          &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
2188                          GNUNET_NO, no_handlers);
2189   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2190 }
2191
2192
2193 /**
2194  * Iterator over hash map entries.
2195  *
2196  * @param cls closure
2197  * @param key current key code
2198  * @param value value in the hash map
2199  * @return GNUNET_YES if we should continue to
2200  *         iterate,
2201  *         GNUNET_NO if not.
2202  */
2203 static int 
2204 ss_map_free_iterator (void *cls,
2205                       const struct GNUNET_HashCode * key, void *value)
2206 {
2207   struct SharedService *ss = value;
2208
2209   GNUNET_assert (GNUNET_YES ==
2210                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
2211   GNUNET_free (ss->name);
2212   GNUNET_free (ss);
2213   return GNUNET_YES;
2214 }
2215
2216
2217 /**
2218  * Task to clean up and shutdown nicely
2219  *
2220  * @param cls NULL
2221  * @param tc the TaskContext from scheduler
2222  */
2223 static void
2224 shutdown_task (void *cls,
2225                const struct GNUNET_SCHEDULER_TaskContext *tc)
2226 {
2227   struct LCFContextQueue *lcfq;
2228   uint32_t id;
2229
2230   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
2231   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
2232   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
2233                                                 NULL);
2234   GNUNET_CONTAINER_multihashmap_destroy (ss_map);  
2235   if (NULL != lcfq_head)
2236   {
2237     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
2238     {
2239       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
2240       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
2241     }
2242     if (NULL != lcfq_head->lcf->rhandle)
2243       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
2244   }
2245   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2246   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
2247   {
2248     GNUNET_free (lcfq->lcf->msg);
2249     GNUNET_free (lcfq->lcf);
2250     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
2251     GNUNET_free (lcfq);
2252   }
2253   /* Clear peer list */
2254   for (id = 0; id < peer_list_size; id++)
2255     if (NULL != peer_list[id])
2256     {
2257       if (GNUNET_NO == peer_list[id]->is_remote)
2258       {        
2259         GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
2260         GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
2261       }      
2262       GNUNET_free (peer_list[id]);
2263     }
2264   GNUNET_free_non_null (peer_list);
2265   /* Clear host list */
2266   for (id = 0; id < host_list_size; id++)
2267     if (NULL != host_list[id])
2268       GNUNET_TESTBED_host_destroy (host_list[id]);
2269   GNUNET_free_non_null (host_list);
2270   /* Clear route list */
2271   for (id = 0; id < route_list_size; id++)
2272     if (NULL != route_list[id])
2273       GNUNET_free (route_list[id]);
2274   GNUNET_free_non_null (route_list);
2275   /* Clear slave_list */
2276   for (id = 0; id < slave_list_size; id++)
2277     if (NULL != slave_list[id])
2278     {
2279       if (NULL != slave_list[id]->controller)
2280         GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
2281       if (NULL != slave_list[id]->controller_proc)
2282         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
2283     }
2284   if (NULL != master_context)
2285   {  
2286     GNUNET_free_non_null (master_context->master_ip);
2287     if (NULL != master_context->system)
2288       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
2289     GNUNET_free (master_context);
2290     master_context = NULL;
2291   }
2292 }
2293
2294
2295 /**
2296  * Callback for client disconnect
2297  *
2298  * @param cls NULL
2299  * @param client the client which has disconnected
2300  */
2301 static void
2302 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
2303 {
2304   if (NULL == master_context)
2305     return;
2306   if (client == master_context->client)
2307   {
2308     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
2309     GNUNET_SERVER_client_drop (client);
2310     /* should not be needed as we're terminated by failure to read
2311        from stdin, but if stdin fails for some reason, this shouldn't 
2312        hurt for now --- might need to revise this later if we ever
2313        decide that master connections might be temporarily down 
2314        for some reason */
2315     //GNUNET_SCHEDULER_shutdown ();
2316   }
2317 }
2318
2319
2320 /**
2321  * Testbed setup
2322  *
2323  * @param cls closure
2324  * @param server the initialized server
2325  * @param cfg configuration to use
2326  */
2327 static void 
2328 testbed_run (void *cls,
2329              struct GNUNET_SERVER_Handle *server,
2330              const struct GNUNET_CONFIGURATION_Handle *cfg)
2331 {
2332   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
2333     {
2334       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
2335       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
2336       {&handle_configure_shared_service, NULL,
2337        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
2338       {&handle_link_controllers, NULL,
2339        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
2340       {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
2341       {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
2342        sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
2343       {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
2344        sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
2345       {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
2346        sizeof (struct GNUNET_TESTBED_PeerStopMessage)},      
2347       {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
2348        sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
2349       {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
2350        sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
2351       {NULL}
2352     };
2353
2354   GNUNET_SERVER_add_handlers (server,
2355                               message_handlers);
2356   GNUNET_SERVER_disconnect_notify (server,
2357                                    &client_disconnect_cb,
2358                                    NULL);
2359   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
2360   shutdown_task_id = 
2361     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2362                                   &shutdown_task,
2363                                   NULL);
2364   LOG_DEBUG ("Testbed startup complete\n");
2365 }
2366
2367
2368 /**
2369  * The starting point of execution
2370  */
2371 int main (int argc, char *const *argv)
2372 {
2373   //sleep (15);                 /* Debugging */
2374   return
2375     (GNUNET_OK ==
2376      GNUNET_SERVICE_run (argc,
2377                          argv,
2378                          "testbed",
2379                          GNUNET_SERVICE_OPTION_NONE,
2380                          &testbed_run,
2381                          NULL)) ? 0 : 1;
2382 }