-LCFContext
[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 <zlib.h>
31
32 #include "testbed.h"
33 #include "gnunet_testbed_service.h"
34 #include "testbed_api_hosts.h"
35
36 /**
37  * Generic logging
38  */
39 #define LOG(kind,...)                           \
40   GNUNET_log (kind, __VA_ARGS__)
41
42 /**
43  * Debug logging
44  */
45 #define LOG_DEBUG(...)                          \
46   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
47
48 struct Context
49 {
50   /**
51    * The client handle associated with this context
52    */
53   struct GNUNET_SERVER_Client *client;
54   
55   /**
56    * Event mask of event to be responded in this context
57    */
58   uint64_t event_mask;
59
60   /**
61    * Our host id according to this context
62    */
63   uint32_t host_id;
64 };
65
66
67 /**
68  * The message queue for sending messages to clients
69  */
70 struct MessageQueue
71 {
72   /**
73    * The message to be sent
74    */
75   struct GNUNET_MessageHeader *msg;
76
77   /**
78    * The client to send the message to
79    */
80   struct GNUNET_SERVER_Client *client;
81   
82   /**
83    * next pointer for DLL
84    */
85   struct MessageQueue *next;
86   
87   /**
88    * prev pointer for DLL
89    */
90   struct MessageQueue *prev;
91 };
92
93
94 /**
95  * The structure for identifying a shared service
96  */
97 struct SharedService
98 {
99   /**
100    * The name of the shared service
101    */
102   char *name;
103
104   /**
105    * Number of shared peers per instance of the shared service
106    */
107   uint32_t num_shared;
108
109   /**
110    * Number of peers currently sharing the service
111    */
112   uint32_t num_sharing;
113 };
114
115
116 /**
117  * A routing entry
118  */
119 struct Route
120 {
121   /**
122    * The forwarding (next hop) host id
123    */
124   uint32_t next_hop;
125
126   /**
127    * The controller handle if we have started the controller at the next hop
128    * host 
129    */
130   struct GNUNET_TESTBED_Controller *fcontroller;
131 };
132
133
134 /**
135  * States of LCFContext
136  */
137 enum LCFContextState
138   {
139     /**
140      * The Context has been initialized; Nothing has been done on it
141      */
142     INIT,
143
144     /**
145      * Delegated host has been registered at the forwarding controller
146      */
147     DELEGATED_HOST_REGISTERED,
148     
149     /**
150      * The slave host has been registred at the forwarding controller
151      */
152     SLAVE_HOST_REGISTERED,
153
154     /**
155      * The context has been finished (may have error)
156      */
157     FINISHED
158
159   };
160
161
162 /**
163  * Link controllers request forwarding context
164  */
165 struct LCFContext
166 {
167   /**
168    * The configuration
169    */
170   struct GNUNET_CONFIGURATION_Handle *cfg;
171
172   /**
173    * The handle of the controller this request has to be forwarded to
174    */
175   struct GNUNET_TESTBED_Controller *fcontroller;
176
177   /**
178    * The host registration handle while registered hosts in this context
179    */
180   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
181
182   /**
183    * Should the delegated host be started by the slave host?
184    */
185   int is_subordinate;
186
187   /**
188    * The state of this context
189    */
190   enum LCFContextState state;
191
192   /**
193    * The delegated host
194    */
195   uint32_t delegated_host_id;
196
197   /**
198    * The slave host
199    */
200   uint32_t slave_host_id;
201
202 };
203
204
205 /**
206  * Structure of a queue entry in LCFContext request queue
207  */
208 struct LCFContextQueue
209 {
210   /**
211    * The LCFContext
212    */
213   struct LCFContext *lcf;
214
215   /**
216    * Head prt for DLL
217    */
218   struct LCFContextQueue *next;
219
220   /**
221    * Tail ptr for DLL
222    */
223   struct LCFContextQueue *prev;
224 };
225
226
227 /**
228  * Wrapped stdin.
229  */
230 static struct GNUNET_DISK_FileHandle *fh;
231
232 /**
233  * The master context; generated with the first INIT message
234  */
235 static struct Context *master_context;
236
237 /**
238  * The shutdown task handle
239  */
240 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
241
242 /**
243  * Array of host list
244  */
245 static struct GNUNET_TESTBED_Host **host_list;
246
247 /**
248  * The size of the host list
249  */
250 static uint32_t host_list_size;
251
252 /**
253  * A list of routes
254  */
255 static struct Route **route_list;
256
257 /**
258  * The size of the route list
259  */
260 static uint32_t route_list_size;
261
262 /**
263  * The message queue head
264  */
265 static struct MessageQueue *mq_head;
266
267 /**
268  * The message queue tail
269  */
270 static struct MessageQueue *mq_tail;
271
272 /**
273  * The head for the LCF queue
274  */
275 static struct LCFContextQueue *lcfq_head;
276
277 /**
278  * The tail for the LCF queue
279  */
280 static struct LCFContextQueue *lcfq_tail;
281
282 /**
283  * Current Transmit Handle; NULL if no notify transmit exists currently
284  */
285 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
286
287 /**
288  * The hashmap of shared services
289  */
290 struct GNUNET_CONTAINER_MultiHashMap *ss_map;
291
292
293 /**
294  * Function called to notify a client about the connection begin ready to queue
295  * more data.  "buf" will be NULL and "size" zero if the connection was closed
296  * for writing in the meantime.
297  *
298  * @param cls NULL
299  * @param size number of bytes available in buf
300  * @param buf where the callee should write the message
301  * @return number of bytes written to buf
302  */
303 static size_t
304 transmit_ready_notify (void *cls, size_t size, void *buf)
305 {
306   struct MessageQueue *mq_entry;
307
308   transmit_handle = NULL;
309   mq_entry = mq_head;
310   GNUNET_assert (NULL != mq_entry);
311   if (0 == size)
312     return 0;
313   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
314   size = ntohs (mq_entry->msg->size);
315   memcpy (buf, mq_entry->msg, size);
316   GNUNET_free (mq_entry->msg);
317   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
318   GNUNET_free (mq_entry);
319   mq_entry = mq_head;
320   if (NULL != mq_entry)
321     transmit_handle = 
322       GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
323                                            ntohs (mq_entry->msg->size),
324                                            GNUNET_TIME_UNIT_FOREVER_REL,
325                                            &transmit_ready_notify, NULL);
326   return size;
327 }
328
329
330 /**
331  * Queues a message in send queue for sending to the service
332  *
333  * @param client the client to whom the queued message has to be sent
334  * @param msg the message to queue
335  */
336 static void
337 queue_message (struct GNUNET_SERVER_Client *client,
338                struct GNUNET_MessageHeader *msg)
339 {
340   struct MessageQueue *mq_entry;
341   uint16_t type;
342   uint16_t size;
343
344   type = ntohs (msg->type);
345   size = ntohs (msg->size);
346   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
347                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
348   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
349   mq_entry->msg = msg;
350   mq_entry->client = client;
351   LOG_DEBUG ( "Queueing message of type %u, size %u for sending\n", type,
352               ntohs (msg->size));
353   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
354   if (NULL == transmit_handle)
355     transmit_handle = 
356       GNUNET_SERVER_notify_transmit_ready (client, size,
357                                            GNUNET_TIME_UNIT_FOREVER_REL,
358                                            &transmit_ready_notify, NULL);
359 }
360
361
362 /**
363  * Function to add a host to the current list of known hosts
364  *
365  * @param host the host to add 
366  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
367  *           already in use
368  */
369 static int
370 host_list_add (struct GNUNET_TESTBED_Host *host)
371 {
372   uint32_t host_id;
373   
374   host_id = GNUNET_TESTBED_host_get_id_ (host);
375   if (host_list_size <= host_id)
376   {
377     host_list = GNUNET_realloc (host_list, 
378                                 sizeof (struct GNUNET_TESTBED_Host *)
379                                 * (host_id + 10));
380     host_list_size += (host_id + 10);
381   }
382   if (NULL != host_list[host_id])
383   {
384     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
385     return GNUNET_SYSERR;
386   }
387   host_list[host_id] = host;
388   return GNUNET_OK;
389 }
390
391
392 /**
393  * Routes message to a host given its host_id
394  *
395  * @param host_id the id of the destination host
396  * @param msg the message to be routed
397  */
398 static void
399 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
400 {
401   GNUNET_break (0);
402 }
403
404
405 /**
406  * The  Link Controller forwarding task
407  *
408  * @param cls the LCFContext
409  * @param tc the Task context from scheduler
410  */
411 static void
412 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
413
414
415 /**
416  * Completion callback for host registrations while forwarding Link Controller messages
417  *
418  * @param cls the LCFContext
419  * @param emsg the error message; NULL if host registration is successful
420  */
421 static void
422 lcf_proc_cc (void *cls, const char *emsg)
423 {
424   struct LCFContext *lcf = cls;
425
426   lcf->rhandle = NULL;
427   switch (lcf->state)
428   {
429   case INIT:
430     if (NULL != emsg)
431       goto registration_error;
432     lcf->state = DELEGATED_HOST_REGISTERED;
433     (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
434     break;
435   case DELEGATED_HOST_REGISTERED:
436      if (NULL != emsg)
437       goto registration_error;
438      lcf->state = SLAVE_HOST_REGISTERED;
439      (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
440      break;
441   default:
442     GNUNET_assert (0);          /* Shouldn't reach here */
443   }  
444   return;
445
446  registration_error:
447   LOG (GNUNET_ERROR_TYPE_WARNING, 
448        "Host registration failed with message: %s\n", emsg);
449   lcf->state = FINISHED;
450   (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
451 }
452
453
454 /**
455  * The  Link Controller forwarding task
456  *
457  * @param cls the LCFContext
458  * @param tc the Task context from scheduler
459  */
460 static void
461 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
462 {
463   struct LCFContext *lcf = cls;
464   struct LCFContextQueue *lcfq;
465
466   switch (lcf->state)
467   {
468   case INIT:
469     if (GNUNET_NO ==
470         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
471                                             lcf->fcontroller))
472     {
473       lcf->rhandle =
474         GNUNET_TESTBED_register_host (lcf->fcontroller,
475                                       host_list[lcf->delegated_host_id],
476                                       lcf_proc_cc, lcf);                                                   
477     }
478     else
479     {
480       lcf->state = DELEGATED_HOST_REGISTERED;
481       (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
482     }
483     break;
484   case DELEGATED_HOST_REGISTERED:
485     if (GNUNET_NO ==
486         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
487                                             lcf->fcontroller))
488     {
489       lcf->rhandle =
490         GNUNET_TESTBED_register_host (lcf->fcontroller,
491                                       host_list[lcf->slave_host_id],
492                                       lcf_proc_cc, lcf);                                                   
493     }
494     else
495     {
496       lcf->state = SLAVE_HOST_REGISTERED;
497       (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
498     }
499     break;
500   case SLAVE_HOST_REGISTERED:
501     GNUNET_TESTBED_controller_link (lcf->fcontroller,
502                                     host_list[lcf->delegated_host_id],
503                                     host_list[lcf->slave_host_id],
504                                     lcf->cfg, lcf->is_subordinate);
505     lcf->state = FINISHED;
506     break;
507   case FINISHED:
508     lcfq = lcfq_head;
509     GNUNET_CONFIGURATION_destroy (lcfq->lcf->cfg);
510     GNUNET_free (lcfq->lcf);
511     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
512     GNUNET_free (lcfq);
513     if (NULL != lcfq_head)
514       (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
515   }
516 }
517
518
519 /**
520  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
521  *
522  * @param cls NULL
523  * @param client identification of the client
524  * @param message the actual message
525  */
526 static void 
527 handle_init (void *cls,
528              struct GNUNET_SERVER_Client *client,
529              const struct GNUNET_MessageHeader *message)
530 {
531   const struct GNUNET_TESTBED_InitMessage *msg;
532   struct GNUNET_TESTBED_Host *host;
533
534   if (NULL != master_context)
535   {
536     GNUNET_break (0);
537     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
538     return;
539   }
540   msg = (const struct GNUNET_TESTBED_InitMessage *) message;  
541   master_context = GNUNET_malloc (sizeof (struct Context));
542   master_context->client = client;
543   master_context->host_id = ntohl (msg->host_id);
544   host = GNUNET_TESTBED_host_create_with_id (master_context->host_id,
545                                              NULL, NULL, 0);
546   host_list_add (host);
547   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
548   GNUNET_SERVER_client_keep (client);
549   LOG_DEBUG ("Created master context with host ID: %u\n",
550              master_context->host_id);
551   GNUNET_SERVER_receive_done (client, GNUNET_OK);
552 }
553
554
555 /**
556  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
557  *
558  * @param cls NULL
559  * @param client identification of the client
560  * @param message the actual message
561  */
562 static void 
563 handle_add_host (void *cls,
564                  struct GNUNET_SERVER_Client *client,
565                  const struct GNUNET_MessageHeader *message)
566 {
567   struct GNUNET_TESTBED_Host *host;
568   const struct GNUNET_TESTBED_AddHostMessage *msg;
569   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
570   char *username;
571   char *hostname;
572   char *emsg;
573   uint32_t host_id;
574   uint16_t username_length;
575   uint16_t hostname_length;
576   uint16_t reply_size;
577   
578   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
579   username_length = ntohs (msg->user_name_length);
580   username_length = (0 == username_length) ? 0 : username_length + 1;
581   username = (char *) &(msg[1]);
582   hostname = username + username_length;
583   if (ntohs (message->size) <=
584       (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length))
585   {
586     GNUNET_break (0);
587     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
588     return;
589   }
590   hostname_length = ntohs (message->size)
591     - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
592   if (strlen (hostname) != hostname_length)
593   {
594     GNUNET_break (0);
595     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
596     return;
597   }
598   host_id = ntohl (msg->host_id);
599   LOG_DEBUG ("Received ADDHOST message\n");
600   LOG_DEBUG ("-------host id: %u\n", host_id);
601   if (NULL != hostname) LOG_DEBUG ("-------hostname: %s\n", hostname);
602   if (NULL != username) LOG_DEBUG ("-------username: %s\n", username);
603   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
604   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
605                                              ntohs (msg->ssh_port));
606   GNUNET_SERVER_receive_done (client, GNUNET_OK);
607   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
608   if (GNUNET_OK != host_list_add (host))
609   {    
610     /* We are unable to add a host */  
611     emsg = "A host exists with given host-id";
612     LOG_DEBUG ("%s: %u", emsg, host_id);
613     GNUNET_TESTBED_host_destroy (host);
614     reply_size += strlen (emsg) + 1;
615     reply = GNUNET_malloc (reply_size);
616     memcpy (&reply[1], emsg, strlen (emsg) + 1);
617   }
618   else
619     reply = GNUNET_malloc (reply_size);  
620   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
621   reply->header.size = htons (reply_size);
622   reply->host_id = htonl (host_id);  
623   queue_message (client, (struct GNUNET_MessageHeader *) reply);
624 }
625
626
627 /**
628  * Iterator over hash map entries.
629  *
630  * @param cls closure
631  * @param key current key code
632  * @param value value in the hash map
633  * @return GNUNET_YES if we should continue to
634  *         iterate,
635  *         GNUNET_NO if not.
636  */
637 int ss_exists_iterator (void *cls,
638                         const struct GNUNET_HashCode * key,
639                         void *value)
640 {
641   struct SharedService *queried_ss = cls;
642   struct SharedService *ss = value;
643
644   if (0 == strcmp (ss->name, queried_ss->name))
645     return GNUNET_NO;
646   else
647     return GNUNET_YES;
648 }
649
650 /**
651  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
652  *
653  * @param cls NULL
654  * @param client identification of the client
655  * @param message the actual message
656  */
657 static void 
658 handle_configure_shared_service (void *cls,
659                                  struct GNUNET_SERVER_Client *client,
660                                  const struct GNUNET_MessageHeader *message)
661 {
662   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
663   struct SharedService *ss;
664   char *service_name;
665   struct GNUNET_HashCode hash;
666   uint16_t msg_size;
667   uint16_t service_name_size;
668     
669   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
670   msg_size = ntohs (message->size);
671   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
672   {
673     GNUNET_break (0);
674     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
675     return;
676   }
677   service_name_size = msg_size - 
678     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
679   service_name = (char *) &msg[1];
680   if ('\0' != service_name[service_name_size - 1])
681   {
682     GNUNET_break (0);
683     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
684     return;
685   }
686   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
687              service_name, ntohl (msg->num_peers));
688   if (ntohl (msg->host_id) != master_context->host_id)
689   {
690     route_message (ntohl (msg->host_id), message);
691     GNUNET_SERVER_receive_done (client, GNUNET_OK);
692     return;
693   }
694   GNUNET_SERVER_receive_done (client, GNUNET_OK);
695   ss = GNUNET_malloc (sizeof (struct SharedService));
696   ss->name = strdup (service_name);
697   ss->num_shared = ntohl (msg->num_peers);
698   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
699   if (GNUNET_SYSERR == 
700       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
701                                                   &ss_exists_iterator, ss))
702   {
703     LOG (GNUNET_ERROR_TYPE_WARNING,
704          "Service %s already configured as a shared service. "
705          "Ignoring service sharing request \n", ss->name);
706     GNUNET_free (ss->name);
707     GNUNET_free (ss);
708     return;
709   }
710   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
711                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
712 }
713
714
715 /**
716  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
717  *
718  * @param cls NULL
719  * @param client identification of the client
720  * @param message the actual message
721  */
722 static void 
723 handle_link_controllers (void *cls,
724                          struct GNUNET_SERVER_Client *client,
725                          const struct GNUNET_MessageHeader *message)
726 {
727   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
728   struct GNUNET_CONFIGURATION_Handle *cfg;
729   struct LCFContextQueue *lcfq;
730   struct Route *route;
731   char *config;  
732   uLongf dest_size;
733   size_t config_size;
734   uint32_t delegated_host_id;
735   uint32_t slave_host_id;
736   uint16_t msize;
737    
738   msize = ntohs (message->size);
739   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
740   {
741     GNUNET_break (0);
742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
743     return;
744   }
745   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
746   delegated_host_id = ntohl (msg->delegated_host_id);
747   if (delegated_host_id == master_context->host_id)
748   {
749     GNUNET_break (0);
750     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
751     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
752     return;
753   }
754   if ((delegated_host_id >= host_list_size) || 
755       (NULL == host_list[delegated_host_id]))
756   {
757     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
758     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
759     return;
760   }
761   slave_host_id = ntohl (msg->slave_host_id);
762   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
763   {
764     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
765     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
766     return;
767   }
768
769   config_size = ntohs (msg->config_size);
770   config = GNUNET_malloc (config_size);
771   dest_size = (uLongf) config_size;
772   msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
773   if (Z_OK != uncompress ((Bytef *) config, &dest_size,
774                           (const Bytef *) &msg[1], (uLong) msize))
775   {
776     GNUNET_break (0);           /* Compression error */
777     GNUNET_free (config);
778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
779     return;
780   }
781   GNUNET_assert (config_size == dest_size);
782   cfg = GNUNET_CONFIGURATION_create ();
783   if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
784                                                      GNUNET_NO))
785   {
786     GNUNET_break (0);           /* Configuration parsing error */
787     GNUNET_break (config);
788     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
789     return;
790   }
791   GNUNET_free (config);
792
793   /* If delegated host and slave host are not same we have to forward
794      towards delegated host */
795   if (slave_host_id != delegated_host_id)
796   {
797     if ((slave_host_id >= route_list_size) ||
798         (NULL == (route = route_list[slave_host_id])) ||
799         (NULL == route->fcontroller))
800     {
801       LOG (GNUNET_ERROR_TYPE_WARNING, "Not route towards slave host");
802       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
803       return;
804     }
805     if (slave_host_id == route->next_hop) /* Slave directly connected */
806     {
807       /* Then make slave host and delegated host same so that slave
808          will startup directly link to the delegated host */
809       slave_host_id = delegated_host_id;
810     }
811     lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
812     lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
813     lcfq->lcf->delegated_host_id = delegated_host_id;
814     lcfq->lcf->slave_host_id = slave_host_id;
815     lcfq->lcf->is_subordinate =
816       (1 == msg->is_subordinate) ? GNUNET_YES : GNUNET_NO;
817     lcfq->lcf->state = INIT;
818     lcfq->lcf->fcontroller = route->fcontroller;
819     lcfq->lcf->cfg = cfg;
820     if (NULL == lcfq_head)
821     {
822       GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
823       (void) GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq);
824     }
825     else
826       GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
827     GNUNET_SERVER_receive_done (client, GNUNET_OK);
828     return;
829   }
830   GNUNET_SERVER_receive_done (client, GNUNET_OK);
831   /* If we are not the slave controller then we have to route the request
832      towards the slave controller */
833   if (1 == msg->is_subordinate)
834   {
835     GNUNET_break (0);           /* FIXME: Implement the slave controller
836                                    startup */ 
837   }  
838   GNUNET_CONFIGURATION_destroy (cfg);
839 }
840
841
842 /**
843  * Iterator over hash map entries.
844  *
845  * @param cls closure
846  * @param key current key code
847  * @param value value in the hash map
848  * @return GNUNET_YES if we should continue to
849  *         iterate,
850  *         GNUNET_NO if not.
851  */
852 static int 
853 ss_map_free_iterator (void *cls,
854                       const struct GNUNET_HashCode * key, void *value)
855 {
856   struct SharedService *ss = value;
857
858   GNUNET_assert (GNUNET_YES ==
859                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
860   GNUNET_free (ss->name);
861   GNUNET_free (ss);
862   return GNUNET_YES;
863 }
864
865
866 /**
867  * Task to clean up and shutdown nicely
868  *
869  * @param cls NULL
870  * @param tc the TaskContext from scheduler
871  */
872 static void
873 shutdown_task (void *cls,
874                const struct GNUNET_SCHEDULER_TaskContext *tc)
875 {
876   uint32_t host_id;
877   uint32_t route_id;
878
879   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
880   GNUNET_SCHEDULER_shutdown ();
881   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
882   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
883                                                 NULL);
884   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
885   if (NULL != fh)
886   {
887     GNUNET_DISK_file_close (fh);
888     fh = NULL;
889   }
890   /* Clear host list */
891   for (host_id = 0; host_id < host_list_size; host_id++)
892     if (NULL != host_list[host_id])
893       GNUNET_TESTBED_host_destroy (host_list[host_id]);
894   GNUNET_free_non_null (host_list);
895   /* Clear route list */
896   for (route_id = 0; route_id < route_list_size; route_id++)
897     if (NULL != route_list[route_id])
898     {
899       if (NULL != route_list[route_id]->fcontroller)
900         GNUNET_TESTBED_controller_stop (route_list[route_id]->fcontroller);
901       GNUNET_free (route_list[route_id]);
902     }
903   GNUNET_free_non_null (route_list);
904   GNUNET_free_non_null (master_context);
905 }
906
907
908 /**
909  * Callback for client disconnect
910  *
911  * @param cls NULL
912  * @param client the client which has disconnected
913  */
914 static void
915 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
916 {
917   if (NULL == master_context)
918     return;
919   if (client == master_context->client)
920   {
921     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
922     GNUNET_SERVER_client_drop (client);
923     /* should not be needed as we're terminated by failure to read
924        from stdin, but if stdin fails for some reason, this shouldn't 
925        hurt for now --- might need to revise this later if we ever
926        decide that master connections might be temporarily down 
927        for some reason */
928     GNUNET_SCHEDULER_shutdown ();
929   }
930 }
931
932
933 /**
934  * Testbed setup
935  *
936  * @param cls closure
937  * @param server the initialized server
938  * @param cfg configuration to use
939  */
940 static void 
941 testbed_run (void *cls,
942              struct GNUNET_SERVER_Handle *server,
943              const struct GNUNET_CONFIGURATION_Handle *cfg)
944 {
945   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
946     {
947       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT,
948        sizeof (struct GNUNET_TESTBED_InitMessage)},
949       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
950       {&handle_configure_shared_service, NULL,
951        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
952       {&handle_link_controllers, NULL,
953        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
954       {NULL}
955     };
956
957   GNUNET_SERVER_add_handlers (server,
958                               message_handlers);
959   GNUNET_SERVER_disconnect_notify (server,
960                                    &client_disconnect_cb,
961                                    NULL);
962   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
963   fh = GNUNET_DISK_get_handle_from_native (stdin);
964   if (NULL == fh)
965     shutdown_task_id = 
966       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,                                  
967                                     &shutdown_task,
968                                     NULL);
969   else
970     shutdown_task_id = 
971       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
972                                       fh,
973                                       &shutdown_task,
974                                       NULL);
975 }
976
977
978 /**
979  * The starting point of execution
980  */
981 int main (int argc, char *const *argv)
982 {
983   return
984     (GNUNET_OK ==
985      GNUNET_SERVICE_run (argc,
986                          argv,
987                          "testbed",
988                          GNUNET_SERVICE_OPTION_NONE,
989                          &testbed_run,
990                          NULL)) ? 0 : 1;
991 }