fixed LCF forwarding
[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 <zlib.h>
32
33 #include "gnunet_testbed_service.h"
34 #include "testbed.h"
35 #include "testbed_api.h"
36 #include "testbed_api_hosts.h"
37 #include "gnunet_testing_lib-new.h"
38
39 /**
40  * Generic logging
41  */
42 #define LOG(kind,...)                           \
43   GNUNET_log (kind, __VA_ARGS__)
44
45 /**
46  * Debug logging
47  */
48 #define LOG_DEBUG(...)                          \
49   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
50
51
52 #define LIST_GROW_STEP 10
53
54 struct Context
55 {
56   /**
57    * The client handle associated with this context
58    */
59   struct GNUNET_SERVER_Client *client;
60
61   /**
62    * The network address of the master controller
63    */
64   char *master_ip;
65
66   /**
67    * The TESTING system handle for starting peers locally
68    */
69   struct GNUNET_TESTING_System *system;
70   
71   /**
72    * Event mask of event to be responded in this context
73    */
74   uint64_t event_mask;
75
76   /**
77    * Our host id according to this context
78    */
79   uint32_t host_id;
80 };
81
82
83 /**
84  * The message queue for sending messages to clients
85  */
86 struct MessageQueue
87 {
88   /**
89    * The message to be sent
90    */
91   struct GNUNET_MessageHeader *msg;
92
93   /**
94    * The client to send the message to
95    */
96   struct GNUNET_SERVER_Client *client;
97   
98   /**
99    * next pointer for DLL
100    */
101   struct MessageQueue *next;
102   
103   /**
104    * prev pointer for DLL
105    */
106   struct MessageQueue *prev;
107 };
108
109
110 /**
111  * The structure for identifying a shared service
112  */
113 struct SharedService
114 {
115   /**
116    * The name of the shared service
117    */
118   char *name;
119
120   /**
121    * Number of shared peers per instance of the shared service
122    */
123   uint32_t num_shared;
124
125   /**
126    * Number of peers currently sharing the service
127    */
128   uint32_t num_sharing;
129 };
130
131
132 /**
133  * A routing entry
134  */
135 struct Route
136 {
137   /**
138    * destination host
139    */
140   uint32_t dest;
141
142   /**
143    * The host destination is reachable thru
144    */
145   uint32_t thru;
146 };
147
148
149 /**
150  * Structure representing a connected(directly-linked) controller
151  */
152 struct Slave
153 {
154   /**
155    * The controller process handle if we had started the controller
156    */
157   struct GNUNET_TESTBED_ControllerProc *controller_proc;
158
159   /**
160    * The controller handle
161    */
162   struct GNUNET_TESTBED_Controller *controller;
163
164   /**
165    * The id of the host this controller is running on
166    */
167   uint32_t host_id;
168 };
169
170
171 /**
172  * States of LCFContext
173  */
174 enum LCFContextState
175   {
176     /**
177      * The Context has been initialized; Nothing has been done on it
178      */
179     INIT,
180
181     /**
182      * Delegated host has been registered at the forwarding controller
183      */
184     DELEGATED_HOST_REGISTERED,
185     
186     /**
187      * The slave host has been registred at the forwarding controller
188      */
189     SLAVE_HOST_REGISTERED,
190
191     /**
192      * The context has been finished (may have error)
193      */
194     FINISHED
195
196   };
197
198
199 /**
200  * Link controllers request forwarding context
201  */
202 struct LCFContext
203 {
204   /**
205    * The serialized and compressed configuration
206    */
207   char *sxcfg;
208
209   /**
210    * The gateway which will pass the link message to delegated host
211    */
212   struct Slave *gateway;
213
214   /**
215    * The host registration handle while registered hosts in this context
216    */
217   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
218
219   /**
220    * The size of the compressed serialized configuration
221    */
222   size_t sxcfg_size;
223
224   /**
225    * The size of the uncompressed configuration
226    */
227   size_t scfg_size;
228
229   /**
230    * Should the delegated host be started by the slave host?
231    */
232   int is_subordinate;
233
234   /**
235    * The state of this context
236    */
237   enum LCFContextState state;
238
239   /**
240    * The delegated host
241    */
242   uint32_t delegated_host_id;
243
244   /**
245    * The slave host
246    */
247   uint32_t slave_host_id;
248
249 };
250
251
252 /**
253  * Structure of a queue entry in LCFContext request queue
254  */
255 struct LCFContextQueue
256 {
257   /**
258    * The LCFContext
259    */
260   struct LCFContext *lcf;
261
262   /**
263    * Head prt for DLL
264    */
265   struct LCFContextQueue *next;
266
267   /**
268    * Tail ptr for DLL
269    */
270   struct LCFContextQueue *prev;
271 };
272
273
274 /**
275  * A locally started peer
276  */
277 struct Peer
278 {
279   /**
280    * The peer handle from testing API
281    */
282   struct GNUNET_TESTING_Peer *peer;
283
284   /**
285    * The modified (by GNUNET_TESTING_peer_configure) configuration this peer is
286    * configured with
287    */
288   struct GNUNET_CONFIGURATION_Handle *cfg;
289
290   /**
291    * Our local reference id for this peer
292    */
293   uint32_t id;
294
295 };
296
297
298 /**
299  * Context information for connecting 2 peers in overlay
300  */
301 struct OverlayConnectContext
302 {
303   /**
304    * peer 1
305    */
306   struct Peer *peer1;
307   
308   /**
309    * peer 2
310    */
311   struct Peer *peer2;
312
313   /**
314    * Transport handle of peer1
315    */
316   struct GNUNET_TRANSPORT_Handle *peer1_transport;
317   
318   /**
319    * Transport handle of peer2
320    */
321   struct GNUNET_TRANSPORT_Handle *peer2_transport;
322   
323   /**
324    * HELLO of peer1
325    */
326   struct GNUNET_MessageHeader *peer1_hello;
327   
328   /**
329    * HELLO of peer2
330    */
331   struct GNUNET_MessageHeader *peer2_hello;
332
333   /**
334    * Get hello handle for peer1
335    */
336   struct GNUNET_TRANSPORT_GetHelloHandle *peer1_ghh;
337   
338   /**
339    * Get hello handle for peer2
340    */
341   struct GNUNET_TRANSPORT_GetHelloHandle *peer2_ghh;
342 };
343
344
345 /**
346  * The master context; generated with the first INIT message
347  */
348 static struct Context *master_context;
349
350 /***********/
351 /* Handles */
352 /***********/
353
354 /**
355  * Current Transmit Handle; NULL if no notify transmit exists currently
356  */
357 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
358
359 /****************/
360 /* Lists & Maps */
361 /****************/
362
363 /**
364  * The head for the LCF queue
365  */
366 static struct LCFContextQueue *lcfq_head;
367
368 /**
369  * The tail for the LCF queue
370  */
371 static struct LCFContextQueue *lcfq_tail;
372
373 /**
374  * The message queue head
375  */
376 static struct MessageQueue *mq_head;
377
378 /**
379  * The message queue tail
380  */
381 static struct MessageQueue *mq_tail;
382
383 /**
384  * Array of host list
385  */
386 static struct GNUNET_TESTBED_Host **host_list;
387
388 /**
389  * A list of routes
390  */
391 static struct Route **route_list;
392
393 /**
394  * A list of directly linked neighbours
395  */
396 static struct Slave **slave_list;
397
398 /**
399  * A list of peers we own locally
400  */
401 static struct Peer **peer_list;
402
403 /**
404  * The hashmap of shared services
405  */
406 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
407
408 /**
409  * The size of the host list
410  */
411 static uint32_t host_list_size;
412
413 /**
414  * The size of the route list
415  */
416 static uint32_t route_list_size;
417
418 /**
419  * The size of directly linked neighbours list
420  */
421 static uint32_t slave_list_size;
422
423 /**
424  * The size of the peer list
425  */
426 static uint32_t peer_list_size;
427
428 /*********/
429 /* Tasks */
430 /*********/
431
432 /**
433  * The lcf_task handle
434  */
435 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
436
437 /**
438  * The shutdown task handle
439  */
440 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
441
442
443 /**
444  * Function called to notify a client about the connection begin ready to queue
445  * more data.  "buf" will be NULL and "size" zero if the connection was closed
446  * for writing in the meantime.
447  *
448  * @param cls NULL
449  * @param size number of bytes available in buf
450  * @param buf where the callee should write the message
451  * @return number of bytes written to buf
452  */
453 static size_t
454 transmit_ready_notify (void *cls, size_t size, void *buf)
455 {
456   struct MessageQueue *mq_entry;
457
458   transmit_handle = NULL;
459   mq_entry = mq_head;
460   GNUNET_assert (NULL != mq_entry);
461   if (0 == size)
462     return 0;
463   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
464   size = ntohs (mq_entry->msg->size);
465   memcpy (buf, mq_entry->msg, size);
466   GNUNET_free (mq_entry->msg);
467   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
468   GNUNET_free (mq_entry);
469   mq_entry = mq_head;
470   if (NULL != mq_entry)
471     transmit_handle = 
472       GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
473                                            ntohs (mq_entry->msg->size),
474                                            GNUNET_TIME_UNIT_FOREVER_REL,
475                                            &transmit_ready_notify, NULL);
476   return size;
477 }
478
479
480 /**
481  * Queues a message in send queue for sending to the service
482  *
483  * @param client the client to whom the queued message has to be sent
484  * @param msg the message to queue
485  */
486 static void
487 queue_message (struct GNUNET_SERVER_Client *client,
488                struct GNUNET_MessageHeader *msg)
489 {
490   struct MessageQueue *mq_entry;
491   uint16_t type;
492   uint16_t size;
493
494   type = ntohs (msg->type);
495   size = ntohs (msg->size);
496   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
497                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
498   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
499   mq_entry->msg = msg;
500   mq_entry->client = client;
501   LOG_DEBUG ( "Queueing message of type %u, size %u for sending\n", type,
502               ntohs (msg->size));
503   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
504   if (NULL == transmit_handle)
505     transmit_handle = 
506       GNUNET_SERVER_notify_transmit_ready (client, size,
507                                            GNUNET_TIME_UNIT_FOREVER_REL,
508                                            &transmit_ready_notify, NULL);
509 }
510
511
512 /**
513  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
514  *
515  * @param ptr the memory block to realloc
516  * @param size the size of ptr
517  * @param new_size the size to which ptr has to be realloc'ed
518  * @return the newly reallocated memory block
519  */
520 static void *
521 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
522 {
523   ptr = GNUNET_realloc (ptr, new_size);
524   if (new_size > size)
525     ptr = memset (ptr + size, 0, new_size - size);
526   return ptr;
527 }
528
529
530 /**
531  * Function to add a host to the current list of known hosts
532  *
533  * @param host the host to add 
534  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
535  *           already in use
536  */
537 static int
538 host_list_add (struct GNUNET_TESTBED_Host *host)
539 {
540   uint32_t host_id;
541
542   host_id = GNUNET_TESTBED_host_get_id_ (host);
543   if (host_list_size <= host_id)
544   {
545     host_list = 
546       TESTBED_realloc (host_list, 
547                        sizeof (struct GNUNET_TESTBED_Host *) * host_list_size,
548                        sizeof (struct GNUNET_TESTBED_Host *) *
549                        (host_list_size + LIST_GROW_STEP));
550     host_list_size += LIST_GROW_STEP;
551   }
552   if (NULL != host_list[host_id])
553   {
554     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
555     return GNUNET_SYSERR;
556   }
557   host_list[host_id] = host;
558   return GNUNET_OK;
559 }
560
561
562 /**
563  * Adds a route to the route list
564  *
565  * @param route the route to add
566  */
567 static void
568 route_list_add (struct Route *route)
569 {
570   if (route->dest >= route_list_size)
571   {
572     route_list = 
573       TESTBED_realloc (route_list, 
574                        sizeof (struct Route *) * route_list_size,
575                        sizeof (struct Route *) * 
576                        (route_list_size + LIST_GROW_STEP));
577     route_list_size += LIST_GROW_STEP;
578   }
579   GNUNET_assert (NULL == route_list[route->dest]);
580   route_list[route->dest] = route;
581 }
582
583
584 /**
585  * Adds a slave to the slave array
586  *
587  * @param slave the slave controller to add
588  */
589 static void
590 slave_list_add (struct Slave *slave)
591 {
592   if (slave->host_id  >= slave_list_size)
593   {
594     slave_list = TESTBED_realloc (slave_list, 
595                                   sizeof (struct Slave *) *slave_list_size,
596                                   sizeof (struct Slave *) *
597                                   (slave_list_size + LIST_GROW_STEP));
598     slave_list_size += LIST_GROW_STEP;
599   }
600   GNUNET_assert (NULL == slave_list[slave->host_id]);
601   slave_list[slave->host_id] = slave;
602 }
603
604
605 /**
606  * Adds a peer to the peer array
607  *
608  * @param peer the peer to add
609  */
610 static void
611 peer_list_add (struct Peer *peer)
612 {
613   if (peer->id  >= peer_list_size)
614   {
615     peer_list = TESTBED_realloc (peer_list, 
616                                  sizeof (struct Peer *) * peer_list_size,
617                                  sizeof (struct Peer *) *
618                                  (peer_list_size + LIST_GROW_STEP));
619     peer_list_size += LIST_GROW_STEP;
620   }
621   GNUNET_assert (NULL == peer_list[peer->id]);
622   peer_list[peer->id] = peer;
623 }
624
625
626 /**
627  * Routes message to a host given its host_id
628  *
629  * @param host_id the id of the destination host
630  * @param msg the message to be routed
631  */
632 static void
633 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
634 {
635   GNUNET_break (0);
636 }
637
638
639 /**
640  * The  Link Controller forwarding task
641  *
642  * @param cls the LCFContext
643  * @param tc the Task context from scheduler
644  */
645 static void
646 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
647
648
649 /**
650  * Completion callback for host registrations while forwarding Link Controller messages
651  *
652  * @param cls the LCFContext
653  * @param emsg the error message; NULL if host registration is successful
654  */
655 static void
656 lcf_proc_cc (void *cls, const char *emsg)
657 {
658   struct LCFContext *lcf = cls;
659
660   lcf->rhandle = NULL;
661   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
662   switch (lcf->state)
663   {
664   case INIT:
665     if (NULL != emsg)
666       goto registration_error;
667     lcf->state = DELEGATED_HOST_REGISTERED;
668     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
669     break;
670   case DELEGATED_HOST_REGISTERED:
671      if (NULL != emsg)
672       goto registration_error;
673      lcf->state = SLAVE_HOST_REGISTERED;
674      lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
675      break;
676   default:
677     GNUNET_assert (0);          /* Shouldn't reach here */
678   }  
679   return;
680
681  registration_error:
682   LOG (GNUNET_ERROR_TYPE_WARNING, 
683        "Host registration failed with message: %s\n", emsg);
684   lcf->state = FINISHED;
685   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
686 }
687
688
689 /**
690  * The  Link Controller forwarding task
691  *
692  * @param cls the LCFContext
693  * @param tc the Task context from scheduler
694  */
695 static void
696 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
697 {
698   struct LCFContext *lcf = cls;
699   struct LCFContextQueue *lcfq;
700
701   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
702   switch (lcf->state)
703   {
704   case INIT:
705     if (GNUNET_NO ==
706         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
707                                             lcf->gateway->controller))
708     {
709       lcf->rhandle =
710         GNUNET_TESTBED_register_host (lcf->gateway->controller,
711                                       host_list[lcf->delegated_host_id],
712                                       lcf_proc_cc, lcf);
713     }
714     else
715     {
716       lcf->state = DELEGATED_HOST_REGISTERED;
717       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
718     }
719     break;
720   case DELEGATED_HOST_REGISTERED:
721     if (GNUNET_NO ==
722         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
723                                             lcf->gateway->controller))
724     {
725       lcf->rhandle =
726         GNUNET_TESTBED_register_host (lcf->gateway->controller,
727                                       host_list[lcf->slave_host_id],
728                                       lcf_proc_cc, lcf);
729     }
730     else
731     {
732       lcf->state = SLAVE_HOST_REGISTERED;
733       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
734     }
735     break;
736   case SLAVE_HOST_REGISTERED:
737     GNUNET_TESTBED_controller_link_2 (lcf->gateway->controller,
738                                       host_list[lcf->delegated_host_id],
739                                       host_list[lcf->slave_host_id],
740                                       lcf->sxcfg, lcf->sxcfg_size,
741                                       lcf->scfg_size,
742                                       lcf->is_subordinate);
743     lcf->state = FINISHED;
744     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
745     break;
746   case FINISHED:
747     lcfq = lcfq_head;
748     GNUNET_assert (lcfq->lcf == lcf);
749     GNUNET_free (lcf->sxcfg);
750     GNUNET_free (lcf);
751     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
752     GNUNET_free (lcfq);
753     if (NULL != lcfq_head)
754       lcf_proc_task_id = 
755         GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
756   }
757 }
758
759
760 /**
761  * Callback for event from slave controllers
762  *
763  * @param cls struct Slave *
764  * @param event information about the event
765  */
766 static void 
767 slave_event_callback(void *cls,
768                      const struct GNUNET_TESTBED_EventInformation *event)
769 {
770   GNUNET_break (0);
771 }
772
773
774 /**
775  * Callback to signal successfull startup of the controller process
776  *
777  * @param cls the closure from GNUNET_TESTBED_controller_start()
778  * @param cfg the configuration with which the controller has been started;
779  *          NULL if status is not GNUNET_OK
780  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
781  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
782  */
783 static void 
784 slave_status_callback (void *cls, 
785                        const struct GNUNET_CONFIGURATION_Handle *cfg,
786                        int status)
787 {
788   struct Slave *slave = cls;
789
790   if (GNUNET_SYSERR == status)
791   {
792     slave->controller_proc = NULL;
793     LOG (GNUNET_ERROR_TYPE_WARNING,
794          "Unexpected slave shutdown\n");
795     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
796     return;
797   }
798   slave->controller =
799     GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
800                                        master_context->event_mask,
801                                        &slave_event_callback, slave);
802 }
803
804
805 /**
806  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
807  *
808  * @param cls NULL
809  * @param client identification of the client
810  * @param message the actual message
811  */
812 static void 
813 handle_init (void *cls,
814              struct GNUNET_SERVER_Client *client,
815              const struct GNUNET_MessageHeader *message)
816 {
817   const struct GNUNET_TESTBED_InitMessage *msg;
818   struct GNUNET_TESTBED_Host *host;
819   void *addr;
820   size_t addrlen;
821
822   if (NULL != master_context)
823   {
824     GNUNET_break (0);
825     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
826     return;
827   }
828   msg = (const struct GNUNET_TESTBED_InitMessage *) message;  
829   master_context = GNUNET_malloc (sizeof (struct Context));
830   master_context->client = client;
831   master_context->host_id = ntohl (msg->host_id);
832   GNUNET_assert (GNUNET_OK == 
833                  GNUNET_SERVER_client_get_address (client, &addr, &addrlen));
834   master_context->master_ip = GNUNET_malloc (NI_MAXHOST);
835   if (0 != getnameinfo (addr, addrlen, master_context->master_ip, NI_MAXHOST,
836                         NULL, 0, NI_NUMERICHOST))
837   {
838     LOG (GNUNET_ERROR_TYPE_WARNING,
839          "Cannot determine the ip of master controller: %s\n", STRERROR (errno));
840     GNUNET_free (addr);
841     GNUNET_free (master_context->master_ip);
842     GNUNET_assert (0);
843   }
844   GNUNET_free (addr);
845   if (0 == strcasecmp (master_context->master_ip, "localhost"))
846   {                             /* Hack for connections via unix sockets */
847     LOG_DEBUG ("May be using local sockets - assuming loopback for master ip\n");
848     GNUNET_free (master_context->master_ip);
849     master_context->master_ip = strdup ("127.0.0.1");
850   }
851   LOG_DEBUG ("Master Controller IP: %s\n", master_context->master_ip);
852   master_context->system = 
853     GNUNET_TESTING_system_create ("testbed", master_context->master_ip);
854   host = GNUNET_TESTBED_host_create_with_id (master_context->host_id,
855                                              NULL, NULL, 0);
856   host_list_add (host);
857   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
858   GNUNET_SERVER_client_keep (client);
859   LOG_DEBUG ("Created master context with host ID: %u\n",
860              master_context->host_id);
861   GNUNET_SERVER_receive_done (client, GNUNET_OK);
862 }
863
864
865 /**
866  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
867  *
868  * @param cls NULL
869  * @param client identification of the client
870  * @param message the actual message
871  */
872 static void 
873 handle_add_host (void *cls,
874                  struct GNUNET_SERVER_Client *client,
875                  const struct GNUNET_MessageHeader *message)
876 {
877   struct GNUNET_TESTBED_Host *host;
878   const struct GNUNET_TESTBED_AddHostMessage *msg;
879   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
880   char *username;
881   char *hostname;
882   char *emsg;
883   uint32_t host_id;
884   uint16_t username_length;
885   uint16_t hostname_length;
886   uint16_t reply_size;
887   
888   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
889   username_length = ntohs (msg->user_name_length);
890   username_length = (0 == username_length) ? 0 : username_length + 1;
891   username = (char *) &(msg[1]);
892   hostname = username + username_length;
893   if (ntohs (message->size) <=
894       (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length))
895   {
896     GNUNET_break (0);
897     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
898     return;
899   }
900   hostname_length = ntohs (message->size)
901     - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
902   if (strlen (hostname) != hostname_length - 1)
903   {
904     GNUNET_break (0);
905     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
906     return;
907   }
908   host_id = ntohl (msg->host_id);
909   LOG_DEBUG ("Received ADDHOST message\n");
910   LOG_DEBUG ("-------host id: %u\n", host_id);
911   if (NULL != hostname) LOG_DEBUG ("-------hostname: %s\n", hostname);
912   if (0 != username_length) LOG_DEBUG ("-------username: %s\n", username);
913   else LOG_DEBUG ("-------username: NULL\n");
914   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
915   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
916                                              ntohs (msg->ssh_port));
917   GNUNET_SERVER_receive_done (client, GNUNET_OK);
918   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
919   if (GNUNET_OK != host_list_add (host))
920   {    
921     /* We are unable to add a host */  
922     emsg = "A host exists with given host-id";
923     LOG_DEBUG ("%s: %u", emsg, host_id);
924     GNUNET_TESTBED_host_destroy (host);
925     reply_size += strlen (emsg) + 1;
926     reply = GNUNET_malloc (reply_size);
927     memcpy (&reply[1], emsg, strlen (emsg) + 1);
928   }
929   else
930     reply = GNUNET_malloc (reply_size);  
931   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
932   reply->header.size = htons (reply_size);
933   reply->host_id = htonl (host_id);  
934   queue_message (client, (struct GNUNET_MessageHeader *) reply);
935 }
936
937
938 /**
939  * Iterator over hash map entries.
940  *
941  * @param cls closure
942  * @param key current key code
943  * @param value value in the hash map
944  * @return GNUNET_YES if we should continue to
945  *         iterate,
946  *         GNUNET_NO if not.
947  */
948 int ss_exists_iterator (void *cls,
949                         const struct GNUNET_HashCode * key,
950                         void *value)
951 {
952   struct SharedService *queried_ss = cls;
953   struct SharedService *ss = value;
954
955   if (0 == strcmp (ss->name, queried_ss->name))
956     return GNUNET_NO;
957   else
958     return GNUNET_YES;
959 }
960
961
962 /**
963  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
964  *
965  * @param cls NULL
966  * @param client identification of the client
967  * @param message the actual message
968  */
969 static void 
970 handle_configure_shared_service (void *cls,
971                                  struct GNUNET_SERVER_Client *client,
972                                  const struct GNUNET_MessageHeader *message)
973 {
974   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
975   struct SharedService *ss;
976   char *service_name;
977   struct GNUNET_HashCode hash;
978   uint16_t msg_size;
979   uint16_t service_name_size;
980     
981   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
982   msg_size = ntohs (message->size);
983   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
984   {
985     GNUNET_break (0);
986     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
987     return;
988   }
989   service_name_size = msg_size - 
990     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
991   service_name = (char *) &msg[1];
992   if ('\0' != service_name[service_name_size - 1])
993   {
994     GNUNET_break (0);
995     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
996     return;
997   }
998   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
999              service_name, ntohl (msg->num_peers));
1000   if (ntohl (msg->host_id) != master_context->host_id)
1001   {
1002     route_message (ntohl (msg->host_id), message);
1003     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1004     return;
1005   }
1006   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1007   ss = GNUNET_malloc (sizeof (struct SharedService));
1008   ss->name = strdup (service_name);
1009   ss->num_shared = ntohl (msg->num_peers);
1010   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1011   if (GNUNET_SYSERR == 
1012       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1013                                                   &ss_exists_iterator, ss))
1014   {
1015     LOG (GNUNET_ERROR_TYPE_WARNING,
1016          "Service %s already configured as a shared service. "
1017          "Ignoring service sharing request \n", ss->name);
1018     GNUNET_free (ss->name);
1019     GNUNET_free (ss);
1020     return;
1021   }
1022   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1023                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
1024 }
1025
1026
1027 /**
1028  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1029  *
1030  * @param cls NULL
1031  * @param client identification of the client
1032  * @param message the actual message
1033  */
1034 static void 
1035 handle_link_controllers (void *cls,
1036                          struct GNUNET_SERVER_Client *client,
1037                          const struct GNUNET_MessageHeader *message)
1038 {
1039   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1040   struct GNUNET_CONFIGURATION_Handle *cfg;
1041   struct LCFContextQueue *lcfq;
1042   struct Route *route;
1043   struct Route *new_route;
1044   char *config;  
1045   uLongf dest_size;
1046   size_t config_size;
1047   uint32_t delegated_host_id;
1048   uint32_t slave_host_id;
1049   uint16_t msize;
1050    
1051   if (NULL == master_context)
1052   {
1053     GNUNET_break (0);
1054     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1055     return;
1056   }
1057   msize = ntohs (message->size);
1058   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1059   {
1060     GNUNET_break (0);
1061     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1062     return;
1063   }
1064   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1065   delegated_host_id = ntohl (msg->delegated_host_id);
1066   if (delegated_host_id == master_context->host_id)
1067   {
1068     GNUNET_break (0);
1069     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1070     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1071     return;
1072   }
1073   if ((delegated_host_id >= host_list_size) || 
1074       (NULL == host_list[delegated_host_id]))
1075   {
1076     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
1077     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1078     return;
1079   }
1080   slave_host_id = ntohl (msg->slave_host_id);
1081   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1082   {
1083     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
1084     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1085     return;
1086   }
1087   if (slave_host_id == delegated_host_id)
1088   {
1089     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1090     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1091     return;
1092   }
1093   msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1094   config_size = ntohs (msg->config_size);
1095   
1096   if (slave_host_id == master_context->host_id) /* Link from us */
1097   {
1098     struct Slave *slave;
1099
1100     if ((delegated_host_id < slave_list_size) && 
1101         (NULL != slave_list[delegated_host_id])) /* We have already added */
1102     {
1103       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1104            delegated_host_id);
1105       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1106       return;
1107     }    
1108     config = GNUNET_malloc (config_size);
1109     dest_size = (uLongf) config_size;    
1110     if (Z_OK != uncompress ((Bytef *) config, &dest_size,
1111                             (const Bytef *) &msg[1], (uLong) msize))
1112     {
1113       GNUNET_break (0);           /* Compression error */
1114       GNUNET_free (config);
1115       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1116       return;
1117     }
1118     if (config_size == dest_size)
1119     {
1120       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1121       GNUNET_free (config);
1122       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1123     }
1124     cfg = GNUNET_CONFIGURATION_create (); /* Free here or in lcfcontext */
1125     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1126                                                        GNUNET_NO))
1127     {
1128       GNUNET_break (0);           /* Configuration parsing error */
1129       GNUNET_free (config);
1130       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1131       return;
1132     }
1133     GNUNET_free (config);
1134     if ((delegated_host_id < slave_list_size) &&
1135         (NULL != slave_list[delegated_host_id]))
1136     {
1137       GNUNET_break (0);           /* Configuration parsing error */
1138       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1139       return;
1140     }
1141     slave = GNUNET_malloc (sizeof (struct Slave));
1142     slave->host_id = delegated_host_id;    
1143     slave_list_add (slave);    
1144     if (1 == msg->is_subordinate)
1145     {
1146       slave->controller_proc =
1147         GNUNET_TESTBED_controller_start (master_context->master_ip,
1148                                          host_list[slave->host_id],
1149                                          cfg, &slave_status_callback,
1150                                          slave);
1151     }
1152     else {
1153       slave->controller = 
1154         GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1155                                            master_context->event_mask,
1156                                            &slave_event_callback, slave);
1157     }
1158     GNUNET_CONFIGURATION_destroy (cfg);
1159     new_route = GNUNET_malloc (sizeof (struct Route));
1160     new_route->dest = delegated_host_id;
1161     new_route->thru = master_context->host_id;
1162     route_list_add (new_route);
1163     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1164     return;
1165   }
1166
1167   /* Route the request */
1168   if (slave_host_id >= route_list_size)
1169   {
1170     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1171     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1172     return;
1173   }
1174   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1175   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1176   lcfq->lcf->delegated_host_id = delegated_host_id;
1177   lcfq->lcf->slave_host_id = slave_host_id;
1178   while (NULL != (route = route_list[slave_host_id]))
1179   {
1180     if (route->thru == master_context->host_id)
1181       break;
1182     slave_host_id = route->thru;
1183   }
1184   GNUNET_assert (NULL != route); /* because we add routes carefully */
1185   GNUNET_assert (route->dest < slave_list_size);
1186   GNUNET_assert (NULL != slave_list[route->dest]);  
1187   lcfq->lcf->is_subordinate =
1188     (1 == msg->is_subordinate) ? GNUNET_YES : GNUNET_NO;
1189   lcfq->lcf->state = INIT;
1190   lcfq->lcf->gateway = slave_list[route->dest];
1191   lcfq->lcf->sxcfg_size = msize;
1192   lcfq->lcf->sxcfg = GNUNET_malloc (msize);
1193   lcfq->lcf->scfg_size = config_size;
1194   (void) memcpy (lcfq->lcf->sxcfg, &msg[1], msize);
1195   if (NULL == lcfq_head)
1196   {
1197     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1198     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1199     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq);
1200   }
1201   else
1202     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1203   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1204   new_route = GNUNET_malloc (sizeof (struct Route));
1205   new_route->dest = delegated_host_id;
1206   new_route->thru = route->dest;
1207   route_list_add (new_route);
1208 }
1209
1210
1211 /**
1212  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1213  *
1214  * @param cls NULL
1215  * @param client identification of the client
1216  * @param message the actual message
1217  */
1218 static void 
1219 handle_peer_create (void *cls,
1220                     struct GNUNET_SERVER_Client *client,
1221                     const struct GNUNET_MessageHeader *message)
1222 {
1223   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1224   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1225   struct GNUNET_CONFIGURATION_Handle *cfg;
1226   char *config;
1227   size_t dest_size;
1228   int ret;
1229   uint32_t config_size;
1230   uint16_t msize;
1231   
1232
1233   msize = ntohs (message->size);
1234   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1235   {
1236     GNUNET_break (0);           /* We need configuration */
1237     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1238     return;
1239   }
1240   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1241   if (ntohl (msg->host_id) == master_context->host_id)
1242   {
1243     struct Peer *peer;
1244     char *emsg;
1245     
1246     /* We are responsible for this peer */
1247     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1248     config_size = ntohl (msg->config_size);    
1249     config = GNUNET_malloc (config_size);
1250     dest_size = config_size;
1251     if (Z_OK != (ret = uncompress ((Bytef *) config, (uLongf *) &dest_size,
1252                                    (const Bytef *) &msg[1], (uLong) msize)))
1253     {
1254       GNUNET_break (0);           /* uncompression error */
1255       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1256       return;
1257     }
1258     if (config_size != dest_size)
1259     {
1260       GNUNET_break (0);/* Uncompressed config size mismatch */
1261       GNUNET_free (config);
1262       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1263       return;
1264     }
1265     cfg = GNUNET_CONFIGURATION_create ();
1266     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1267                                                        GNUNET_NO))
1268     {
1269       GNUNET_break (0);           /* Configuration parsing error */
1270       GNUNET_free (config);
1271       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1272       return;
1273     }
1274     GNUNET_free (config);
1275     peer = GNUNET_malloc (sizeof (struct Peer));
1276     peer->cfg = cfg;
1277     peer->id = ntohl (msg->peer_id);
1278     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1279     peer->peer = GNUNET_TESTING_peer_configure (master_context->system, peer->cfg,
1280                                                 peer->id,
1281                                                 NULL /* Peer id */,
1282                                                 &emsg);
1283     if (NULL == peer->peer)
1284     {
1285       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1286       GNUNET_free (emsg);
1287       GNUNET_break (0);
1288       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1289       return;
1290     }
1291     peer_list_add (peer);
1292     reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1293     reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1294     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1295     reply->peer_id = msg->peer_id;
1296     reply->operation_id = msg->operation_id;
1297     queue_message (client, &reply->header);
1298     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1299     return;
1300   }
1301
1302   /* FIXME: Forward the peer to other host */
1303   GNUNET_break (0);
1304   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1305 }
1306
1307
1308 /**
1309  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1310  *
1311  * @param cls NULL
1312  * @param client identification of the client
1313  * @param message the actual message
1314  */
1315 static void 
1316 handle_peer_destroy (void *cls,
1317                      struct GNUNET_SERVER_Client *client,
1318                      const struct GNUNET_MessageHeader *message)
1319 {
1320   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1321   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *reply;
1322   uint32_t peer_id;
1323   uint32_t id;
1324   uint16_t reply_size;
1325   
1326   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1327   peer_id = ntohl (msg->peer_id);
1328   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1329              peer_id, GNUNET_ntohll (msg->operation_id));
1330   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1331   {
1332     GNUNET_break (0);
1333     /* FIXME: Reply with failure event message or forward to slave controller */
1334     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1335     return;
1336   }  
1337   GNUNET_TESTING_peer_destroy (peer_list[peer_id]->peer);
1338   GNUNET_CONFIGURATION_destroy (peer_list[peer_id]->cfg);
1339   GNUNET_free (peer_list[peer_id]);
1340   peer_list[peer_id] = NULL;
1341   for (id = 0; id < LIST_GROW_STEP; id++)
1342   {
1343     if (((peer_id + id >= peer_list_size) ||
1344          (NULL != peer_list[peer_id])))
1345       break;
1346   }
1347   if (LIST_GROW_STEP == id)
1348   {
1349     peer_list_size -= LIST_GROW_STEP;
1350     peer_list = GNUNET_realloc (peer_list, peer_list_size);
1351   }
1352   reply_size = 
1353     sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1354   reply = GNUNET_malloc (reply_size);
1355   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1356   reply->header.size = htons (reply_size);
1357   reply->operation_id = msg->operation_id;
1358   reply->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
1359   queue_message (client, &reply->header);
1360   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1361 }
1362
1363
1364 /**
1365  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1366  *
1367  * @param cls NULL
1368  * @param client identification of the client
1369  * @param message the actual message
1370  */
1371 static void 
1372 handle_peer_start (void *cls,
1373                    struct GNUNET_SERVER_Client *client,
1374                    const struct GNUNET_MessageHeader *message)
1375 {
1376   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1377   struct GNUNET_TESTBED_PeerEventMessage *reply;
1378   uint32_t peer_id;
1379
1380   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1381   peer_id = ntohl (msg->peer_id);
1382   if ((peer_id >= peer_list_size) 
1383       || (NULL == peer_list[peer_id]))
1384   {
1385     GNUNET_break (0);
1386     /* FIXME: reply with failure message or forward to slave controller */
1387     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1388     return;
1389   }
1390   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer_list[peer_id]->peer))
1391   {
1392     /* FIXME: return FAILURE message */
1393     GNUNET_break (0);
1394     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1395     return;
1396   }
1397   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1398   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1399   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1400   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1401   reply->host_id = htonl (master_context->host_id);
1402   reply->peer_id = msg->peer_id;
1403   reply->operation_id = msg->operation_id;
1404   queue_message (client, &reply->header);
1405   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1406 }
1407
1408
1409 /**
1410  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1411  *
1412  * @param cls NULL
1413  * @param client identification of the client
1414  * @param message the actual message
1415  */
1416 static void 
1417 handle_peer_stop (void *cls,
1418                   struct GNUNET_SERVER_Client *client,
1419                   const struct GNUNET_MessageHeader *message)
1420 {
1421   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1422   struct GNUNET_TESTBED_PeerEventMessage *reply;
1423   uint32_t peer_id;
1424
1425   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1426   peer_id = ntohl (msg->peer_id);
1427   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1428   {
1429     GNUNET_break (0);           /* FIXME: route to slave? */
1430     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1431     return;
1432   }
1433   if (GNUNET_OK != GNUNET_TESTING_peer_stop (peer_list[peer_id]->peer))
1434   {
1435     /* FIXME: return FAILURE message */
1436     GNUNET_break (0);
1437     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1438     return;
1439   }
1440   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1441   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1442   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1443   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1444   reply->host_id = htonl (master_context->host_id);
1445   reply->peer_id = msg->peer_id;
1446   reply->operation_id = msg->operation_id;
1447   queue_message (client, &reply->header);
1448   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1449 }
1450
1451
1452 /**
1453  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1454  *
1455  * @param cls NULL
1456  * @param client identification of the client
1457  * @param message the actual message
1458  */
1459 static void 
1460 handle_peer_get_config (void *cls,
1461                         struct GNUNET_SERVER_Client *client,
1462                         const struct GNUNET_MessageHeader *message)
1463 {
1464   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1465   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1466   char *config;
1467   char *xconfig;
1468   size_t c_size;
1469   size_t xc_size;  
1470   uint32_t peer_id;
1471   uint16_t msize;
1472   
1473   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1474   peer_id = ntohl (msg->peer_id);
1475   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1476   {
1477     /* FIXME: return FAILURE message */
1478     GNUNET_break (0);
1479     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1480   }
1481   config = GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->cfg,
1482                                            &c_size);
1483   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1484   GNUNET_free (config);
1485   msize = xc_size + sizeof (struct
1486                             GNUNET_TESTBED_PeerConfigurationInformationMessage);
1487   reply = GNUNET_realloc (xconfig, msize);
1488   (void) memmove (&reply[1], reply, xc_size);
1489   reply->header.size = htons (msize);
1490   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
1491   reply->peer_id = msg->peer_id;
1492   reply->operation_id = msg->operation_id;
1493   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->peer,
1494                                     &reply->peer_identity);
1495   reply->config_size = htons ((uint16_t) c_size);
1496   queue_message (client, &reply->header);
1497   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1498 }
1499
1500
1501
1502 /**
1503  * Function called whenever there is an update to the
1504  * HELLO of this peer.
1505  *
1506  * @param cls closure
1507  * @param hello our updated HELLO
1508  */
1509 static void 
1510 hello_update_cb (void *cls,
1511                  const struct GNUNET_MessageHeader *hello)
1512 {
1513   GNUNET_break(0);  
1514 }
1515
1516
1517 /**
1518  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
1519  *
1520  * @param cls NULL
1521  * @param client identification of the client
1522  * @param message the actual message
1523  */
1524 static void 
1525 handle_overlay_connect (void *cls,
1526                         struct GNUNET_SERVER_Client *client,
1527                         const struct GNUNET_MessageHeader *message)
1528 {
1529   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
1530   struct OverlayConnectContext *occ;
1531   uint32_t p1;
1532   uint32_t p2;
1533
1534   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
1535   p1 = ntohl (msg->peer1);
1536   p2 = ntohl (msg->peer2);
1537   GNUNET_assert (p1 < peer_list_size);
1538   GNUNET_assert (NULL != peer_list[p1]);
1539   GNUNET_assert (p2 < peer_list_size);
1540   GNUNET_assert (NULL != peer_list[p2]);
1541   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
1542   occ->peer1 = peer_list[p1];
1543   occ->peer2 = peer_list[p2];
1544   occ->peer1_transport = GNUNET_TRANSPORT_connect (occ->peer1->cfg, NULL, occ,
1545                                                    NULL, NULL, NULL);
1546   occ->peer2_transport = GNUNET_TRANSPORT_connect (occ->peer2->cfg, NULL, occ,
1547                                                    NULL, NULL, NULL);
1548   occ->peer1_ghh = GNUNET_TRANSPORT_get_hello (occ->peer1_transport, &hello_update_cb, occ);
1549   occ->peer2_ghh = GNUNET_TRANSPORT_get_hello (occ->peer2_transport, &hello_update_cb, occ);
1550 }
1551
1552
1553 /**
1554  * Iterator over hash map entries.
1555  *
1556  * @param cls closure
1557  * @param key current key code
1558  * @param value value in the hash map
1559  * @return GNUNET_YES if we should continue to
1560  *         iterate,
1561  *         GNUNET_NO if not.
1562  */
1563 static int 
1564 ss_map_free_iterator (void *cls,
1565                       const struct GNUNET_HashCode * key, void *value)
1566 {
1567   struct SharedService *ss = value;
1568
1569   GNUNET_assert (GNUNET_YES ==
1570                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
1571   GNUNET_free (ss->name);
1572   GNUNET_free (ss);
1573   return GNUNET_YES;
1574 }
1575
1576
1577 /**
1578  * Task to clean up and shutdown nicely
1579  *
1580  * @param cls NULL
1581  * @param tc the TaskContext from scheduler
1582  */
1583 static void
1584 shutdown_task (void *cls,
1585                const struct GNUNET_SCHEDULER_TaskContext *tc)
1586 {
1587   struct LCFContextQueue *lcfq;
1588   uint32_t id;
1589
1590   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
1591   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
1592   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
1593                                                 NULL);
1594   GNUNET_CONTAINER_multihashmap_destroy (ss_map);  
1595   if (NULL != lcfq_head)
1596   {
1597     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
1598     {
1599       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
1600       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
1601     }
1602     if (NULL != lcfq_head->lcf->rhandle)
1603       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
1604   }
1605   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1606   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
1607   {
1608     GNUNET_free (lcfq->lcf->sxcfg);
1609     GNUNET_free (lcfq->lcf);
1610     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1611     GNUNET_free (lcfq);
1612   }
1613   /* Clear peer list */
1614   for (id = 0; id < peer_list_size; id++)
1615     if (NULL != peer_list[id])
1616     {
1617       GNUNET_TESTING_peer_destroy (peer_list[id]->peer);
1618       GNUNET_CONFIGURATION_destroy (peer_list[id]->cfg);
1619       GNUNET_free (peer_list[id]);
1620     }
1621   GNUNET_free_non_null (peer_list);
1622   /* Clear host list */
1623   for (id = 0; id < host_list_size; id++)
1624     if (NULL != host_list[id])
1625       GNUNET_TESTBED_host_destroy (host_list[id]);
1626   GNUNET_free_non_null (host_list);
1627   /* Clear route list */
1628   for (id = 0; id < route_list_size; id++)
1629     if (NULL != route_list[id])
1630       GNUNET_free (route_list[id]);
1631   GNUNET_free_non_null (route_list);
1632   /* Clear slave_list */
1633   for (id = 0; id < slave_list_size; id++)
1634     if (NULL != slave_list[id])
1635     {
1636       GNUNET_assert (NULL != slave_list[id]->controller);
1637       GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
1638       if (NULL != slave_list[id]->controller_proc)
1639         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
1640     }
1641   if (NULL != master_context)
1642   {  
1643     GNUNET_free_non_null (master_context->master_ip);
1644     if (NULL != master_context->system)
1645       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
1646     GNUNET_free (master_context);
1647     master_context = NULL;
1648   }
1649 }
1650
1651
1652 /**
1653  * Callback for client disconnect
1654  *
1655  * @param cls NULL
1656  * @param client the client which has disconnected
1657  */
1658 static void
1659 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
1660 {
1661   if (NULL == master_context)
1662     return;
1663   if (client == master_context->client)
1664   {
1665     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
1666     GNUNET_SERVER_client_drop (client);
1667     /* should not be needed as we're terminated by failure to read
1668        from stdin, but if stdin fails for some reason, this shouldn't 
1669        hurt for now --- might need to revise this later if we ever
1670        decide that master connections might be temporarily down 
1671        for some reason */
1672     //GNUNET_SCHEDULER_shutdown ();
1673   }
1674 }
1675
1676
1677 /**
1678  * Testbed setup
1679  *
1680  * @param cls closure
1681  * @param server the initialized server
1682  * @param cfg configuration to use
1683  */
1684 static void 
1685 testbed_run (void *cls,
1686              struct GNUNET_SERVER_Handle *server,
1687              const struct GNUNET_CONFIGURATION_Handle *cfg)
1688 {
1689   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
1690     {
1691       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT,
1692        sizeof (struct GNUNET_TESTBED_InitMessage)},
1693       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
1694       {&handle_configure_shared_service, NULL,
1695        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
1696       {&handle_link_controllers, NULL,
1697        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
1698       {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
1699       {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
1700        sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
1701       {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
1702        sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
1703       {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
1704        sizeof (struct GNUNET_TESTBED_PeerStopMessage)},      
1705       {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
1706        sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
1707       {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
1708        sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
1709       {NULL}
1710     };
1711
1712   GNUNET_SERVER_add_handlers (server,
1713                               message_handlers);
1714   GNUNET_SERVER_disconnect_notify (server,
1715                                    &client_disconnect_cb,
1716                                    NULL);
1717   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
1718   shutdown_task_id = 
1719     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1720                                   &shutdown_task,
1721                                   NULL);
1722   LOG_DEBUG ("Testbed startup complete\n");
1723 }
1724
1725
1726 /**
1727  * The starting point of execution
1728  */
1729 int main (int argc, char *const *argv)
1730 {
1731   return
1732     (GNUNET_OK ==
1733      GNUNET_SERVICE_run (argc,
1734                          argv,
1735                          "testbed",
1736                          GNUNET_SERVICE_OPTION_NONE,
1737                          &testbed_run,
1738                          NULL)) ? 0 : 1;
1739 }