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