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