- warn on missing cases
[oweals/gnunet.git] / src / testbed / gnunet-service-testbed.c
1 /*
2   This file is part of GNUnet.
3   (C) 2008--2013 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 "gnunet-service-testbed.h"
28
29 #include <zlib.h>
30
31
32 /**
33  * Context data for GNUNET_MESSAGE_TYPE_TESTBED_SHUTDOWN_PEERS handler
34  */
35 struct HandlerContext_ShutdownPeers
36 {
37   /**
38    * The number of slave we expect to hear from since we forwarded the
39    * GNUNET_MESSAGE_TYPE_TESTBED_SHUTDOWN_PEERS message to them
40    */
41   unsigned int nslaves;
42
43   /**
44    * Did we observe a timeout with respect to this operation at any of the
45    * slaves
46    */
47   int timeout;
48 };
49
50
51 /***********/
52 /* Globals */
53 /***********/
54
55 /**
56  * Our configuration
57  */
58 struct GNUNET_CONFIGURATION_Handle *our_config;
59
60 /**
61  * The master context; generated with the first INIT message
62  */
63 struct Context *GST_context;
64
65 /**
66  * A list of directly linked neighbours
67  */
68 struct Slave **GST_slave_list;
69
70 /**
71  * A list of peers we know about
72  */
73 struct Peer **GST_peer_list;
74
75 /**
76  * Array of hosts
77  */
78 struct GNUNET_TESTBED_Host **GST_host_list;
79
80 /**
81  * DLL head for forwarded operation contexts
82  */
83 struct ForwardedOperationContext *fopcq_head;
84
85 /**
86  * DLL tail for forwarded operation contexts
87  */
88 struct ForwardedOperationContext *fopcq_tail;
89
90 /**
91  * Operation queue for open file descriptors
92  */
93 struct OperationQueue *GST_opq_openfds;
94
95 /**
96  * Timeout for operations which may take some time
97  */
98 const struct GNUNET_TIME_Relative GST_timeout;
99
100 /**
101  * The size of the host list
102  */
103 unsigned int GST_host_list_size;
104
105 /**
106  * The size of directly linked neighbours list
107  */
108 unsigned int GST_slave_list_size;
109
110 /**
111  * The size of the peer list
112  */
113 unsigned int GST_peer_list_size;
114
115
116 /***********************************/
117 /* Local definitions and variables */
118 /***********************************/
119
120 /**
121  * The message queue for sending messages to clients
122  */
123 struct MessageQueue
124 {
125   /**
126    * The message to be sent
127    */
128   struct GNUNET_MessageHeader *msg;
129
130   /**
131    * The client to send the message to
132    */
133   struct GNUNET_SERVER_Client *client;
134
135   /**
136    * next pointer for DLL
137    */
138   struct MessageQueue *next;
139
140   /**
141    * prev pointer for DLL
142    */
143   struct MessageQueue *prev;
144 };
145
146 /**
147  * Our hostname; we give this to all the peers we start
148  */
149 static char *hostname;
150
151 /**
152  * Current Transmit Handle; NULL if no notify transmit exists currently
153  */
154 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
155
156 /**
157  * The head for the LCF queue
158  */
159 static struct LCFContextQueue *lcfq_head;
160
161 /**
162  * The tail for the LCF queue
163  */
164 static struct LCFContextQueue *lcfq_tail;
165
166 /**
167  * The message queue head
168  */
169 static struct MessageQueue *mq_head;
170
171 /**
172  * The message queue tail
173  */
174 static struct MessageQueue *mq_tail;
175
176 /**
177  * The hashmap of shared services
178  */
179 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
180
181 /**
182  * A list of routes
183  */
184 static struct Route **route_list;
185
186 /**
187  * The event mask for the events we listen from sub-controllers
188  */
189 static uint64_t event_mask;
190
191 /**
192  * The size of the route list
193  */
194 static unsigned int route_list_size;
195
196 /**
197  * The lcf_task handle
198  */
199 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
200
201 /**
202  * The shutdown task handle
203  */
204 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
205
206
207 /**
208  * Function called to notify a client about the connection begin ready to queue
209  * more data.  "buf" will be NULL and "size" zero if the connection was closed
210  * for writing in the meantime.
211  *
212  * @param cls NULL
213  * @param size number of bytes available in buf
214  * @param buf where the callee should write the message
215  * @return number of bytes written to buf
216  */
217 static size_t
218 transmit_ready_notify (void *cls, size_t size, void *buf)
219 {
220   struct MessageQueue *mq_entry;
221
222   transmit_handle = NULL;
223   mq_entry = mq_head;
224   GNUNET_assert (NULL != mq_entry);
225   if (0 == size)
226     return 0;
227   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
228   size = ntohs (mq_entry->msg->size);
229   memcpy (buf, mq_entry->msg, size);
230   GNUNET_free (mq_entry->msg);
231   GNUNET_SERVER_client_drop (mq_entry->client);
232   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
233   GNUNET_free (mq_entry);
234   mq_entry = mq_head;
235   if (NULL != mq_entry)
236     transmit_handle =
237         GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
238                                              ntohs (mq_entry->msg->size),
239                                              GNUNET_TIME_UNIT_FOREVER_REL,
240                                              &transmit_ready_notify, NULL);
241   return size;
242 }
243
244
245 /**
246  * Queues a message in send queue for sending to the service
247  *
248  * @param client the client to whom the queued message has to be sent
249  * @param msg the message to queue
250  */
251 void
252 GST_queue_message (struct GNUNET_SERVER_Client *client,
253                    struct GNUNET_MessageHeader *msg)
254 {
255   struct MessageQueue *mq_entry;
256   uint16_t type;
257   uint16_t size;
258
259   type = ntohs (msg->type);
260   size = ntohs (msg->size);
261   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
262                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));
263   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
264   mq_entry->msg = msg;
265   mq_entry->client = client;
266   GNUNET_SERVER_client_keep (client);
267   LOG_DEBUG ("Queueing message of type %u, size %u for sending\n", type,
268              ntohs (msg->size));
269   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
270   if (NULL == transmit_handle)
271     transmit_handle =
272         GNUNET_SERVER_notify_transmit_ready (client, size,
273                                              GNUNET_TIME_UNIT_FOREVER_REL,
274                                              &transmit_ready_notify, NULL);
275 }
276
277
278 /**
279  * Similar to GNUNET_array_grow(); however instead of calling GNUNET_array_grow()
280  * several times we call it only once. The array is also made to grow in steps
281  * of LIST_GROW_STEP.
282  *
283  * @param ptr the array pointer to grow
284  * @param size the size of array
285  * @param accommodate_size the size which the array has to accommdate; after
286  *          this call the array will be big enough to accommdate sizes upto
287  *          accommodate_size
288  */
289 #define array_grow_large_enough(ptr, size, accommodate_size) \
290   do                                                                    \
291   {                                                                     \
292     unsigned int growth_size;                                           \
293     GNUNET_assert (size <= accommodate_size);                            \
294     growth_size = size;                                                 \
295     while (growth_size <= accommodate_size)                             \
296       growth_size += LIST_GROW_STEP;                                    \
297     GNUNET_array_grow (ptr, size, growth_size);                         \
298     GNUNET_assert (size > accommodate_size);                            \
299   } while (0)
300
301
302 /**
303  * Function to add a host to the current list of known hosts
304  *
305  * @param host the host to add
306  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
307  *           already in use
308  */
309 static int
310 host_list_add (struct GNUNET_TESTBED_Host *host)
311 {
312   uint32_t host_id;
313
314   host_id = GNUNET_TESTBED_host_get_id_ (host);
315   if (GST_host_list_size <= host_id)
316     array_grow_large_enough (GST_host_list, GST_host_list_size, host_id);
317   if (NULL != GST_host_list[host_id])
318   {
319     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
320     return GNUNET_SYSERR;
321   }
322   GST_host_list[host_id] = host;
323   return GNUNET_OK;
324 }
325
326
327 /**
328  * Adds a route to the route list
329  *
330  * @param route the route to add
331  */
332 static void
333 route_list_add (struct Route *route)
334 {
335   if (route->dest >= route_list_size)
336     array_grow_large_enough (route_list, route_list_size, route->dest);
337   GNUNET_assert (NULL == route_list[route->dest]);
338   route_list[route->dest] = route;
339 }
340
341
342 /**
343  * Adds a slave to the slave array
344  *
345  * @param slave the slave controller to add
346  */
347 static void
348 slave_list_add (struct Slave *slave)
349 {
350   if (slave->host_id >= GST_slave_list_size)
351     array_grow_large_enough (GST_slave_list, GST_slave_list_size,
352                              slave->host_id);
353   GNUNET_assert (NULL == GST_slave_list[slave->host_id]);
354   GST_slave_list[slave->host_id] = slave;
355 }
356
357
358 /**
359  * Adds a peer to the peer array
360  *
361  * @param peer the peer to add
362  */
363 static void
364 peer_list_add (struct Peer *peer)
365 {
366   if (peer->id >= GST_peer_list_size)
367     array_grow_large_enough (GST_peer_list, GST_peer_list_size, peer->id);
368   GNUNET_assert (NULL == GST_peer_list[peer->id]);
369   GST_peer_list[peer->id] = peer;
370 }
371
372
373 /**
374  * Removes a the give peer from the peer array
375  *
376  * @param peer the peer to be removed
377  */
378 static void
379 peer_list_remove (struct Peer *peer)
380 {
381   unsigned int orig_size;
382   uint32_t id;
383
384   GST_peer_list[peer->id] = NULL;
385   orig_size = GST_peer_list_size;
386   while (GST_peer_list_size >= LIST_GROW_STEP)
387   {
388     for (id = GST_peer_list_size - 1;
389          (id >= GST_peer_list_size - LIST_GROW_STEP) && (id != UINT32_MAX);
390          id--)
391       if (NULL != GST_peer_list[id])
392         break;
393     if (id != ((GST_peer_list_size - LIST_GROW_STEP) - 1))
394       break;
395     GST_peer_list_size -= LIST_GROW_STEP;
396   }
397   if (orig_size == GST_peer_list_size)
398     return;
399   GST_peer_list =
400       GNUNET_realloc (GST_peer_list,
401                       sizeof (struct Peer *) * GST_peer_list_size);
402 }
403
404
405 /**
406  * Finds the route with directly connected host as destination through which
407  * the destination host can be reached
408  *
409  * @param host_id the id of the destination host
410  * @return the route with directly connected destination host; NULL if no route
411  *           is found
412  */
413 struct Route *
414 GST_find_dest_route (uint32_t host_id)
415 {
416   struct Route *route;
417
418   if (route_list_size <= host_id)
419     return NULL;
420   while (NULL != (route = route_list[host_id]))
421   {
422     if (route->thru == GST_context->host_id)
423       break;
424     host_id = route->thru;
425   }
426   return route;
427 }
428
429
430 /**
431  * Routes message to a host given its host_id
432  *
433  * @param host_id the id of the destination host
434  * @param msg the message to be routed
435  */
436 static void
437 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
438 {
439   GNUNET_break (0);
440 }
441
442
443 /**
444  * Send operation failure message to client
445  *
446  * @param client the client to which the failure message has to be sent to
447  * @param operation_id the id of the failed operation
448  * @param emsg the error message; can be NULL
449  */
450 void
451 GST_send_operation_fail_msg (struct GNUNET_SERVER_Client *client,
452                              uint64_t operation_id, const char *emsg)
453 {
454   struct GNUNET_TESTBED_OperationFailureEventMessage *msg;
455   uint16_t msize;
456   uint16_t emsg_len;
457
458   msize = sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
459   emsg_len = (NULL == emsg) ? 0 : strlen (emsg) + 1;
460   msize += emsg_len;
461   msg = GNUNET_malloc (msize);
462   msg->header.size = htons (msize);
463   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_OPERATION_FAIL_EVENT);
464   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
465   msg->operation_id = GNUNET_htonll (operation_id);
466   if (0 != emsg_len)
467     memcpy (&msg[1], emsg, emsg_len);
468   GST_queue_message (client, &msg->header);
469 }
470
471
472 /**
473  * Function to send generic operation success message to given client
474  *
475  * @param client the client to send the message to
476  * @param operation_id the id of the operation which was successful
477  */
478 static void
479 send_operation_success_msg (struct GNUNET_SERVER_Client *client,
480                             uint64_t operation_id)
481 {
482   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg;
483   uint16_t msize;
484
485   msize = sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
486   msg = GNUNET_malloc (msize);
487   msg->header.size = htons (msize);
488   msg->header.type =
489       htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERIC_OPERATION_SUCCESS);
490   msg->operation_id = GNUNET_htonll (operation_id);
491   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
492   GST_queue_message (client, &msg->header);
493 }
494
495
496 /**
497  * Function to send a failure reponse for controller link operation
498  *
499  * @param client the client to send the message to
500  * @param operation_id the operation ID of the controller link request
501  * @param cfg the configuration with which the delegated controller is started.
502  *          Can be NULL if the delegated controller is not started but just
503  *          linked to.
504  * @param emsg set to an error message explaining why the controller link
505  *          failed.  Setting this to NULL signifies success.  !This should be
506  *          NULL if cfg is set!
507  */
508 static void
509 send_controller_link_response (struct GNUNET_SERVER_Client *client,
510                                uint64_t operation_id,
511                                const struct GNUNET_CONFIGURATION_Handle
512                                *cfg,
513                                const char *emsg)
514 {
515   struct GNUNET_TESTBED_ControllerLinkResponse *msg;
516   char *xconfig;
517   size_t config_size;
518   size_t xconfig_size;  
519   uint16_t msize;
520
521   GNUNET_assert ((NULL == cfg) || (NULL == emsg));
522   xconfig = NULL;
523   xconfig_size = 0;
524   config_size = 0;
525   msize = sizeof (struct GNUNET_TESTBED_ControllerLinkResponse);
526   if (NULL != cfg)
527   {
528     xconfig = GNUNET_TESTBED_compress_cfg_ (cfg,
529                                             &config_size,
530                                             &xconfig_size);
531     msize += xconfig_size;
532   }
533   if (NULL != emsg)
534     msize += strlen (emsg);
535   msg = GNUNET_malloc (msize);
536   msg->header.type = htons
537       (GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS_RESULT);
538   msg->header.size = htons (msize);
539   if (NULL == emsg)
540     msg->success = htons (GNUNET_YES);
541   msg->operation_id = GNUNET_htonll (operation_id);
542   msg->config_size = htons ((uint16_t) config_size);
543   if (NULL != xconfig)
544     memcpy (&msg[1], xconfig, xconfig_size);
545   if (NULL != emsg)
546     memcpy (&msg[1], emsg, strlen (emsg));
547   GST_queue_message (client, &msg->header);
548 }
549
550 /**
551  * Callback which will be called after a host registration succeeded or failed
552  *
553  * @param cls the handle to the slave at which the registration is completed
554  * @param emsg the error message; NULL if host registration is successful
555  */
556 static void
557 hr_completion (void *cls, const char *emsg);
558
559
560 /**
561  * Attempts to register the next host in the host registration queue
562  *
563  * @param slave the slave controller whose host registration queue is checked
564  *          for host registrations
565  */
566 static void
567 register_next_host (struct Slave *slave)
568 {
569   struct HostRegistration *hr;
570
571   hr = slave->hr_dll_head;
572   GNUNET_assert (NULL != hr);
573   GNUNET_assert (NULL == slave->rhandle);
574   LOG (GNUNET_ERROR_TYPE_DEBUG, "Registering host %u at %u\n",
575        GNUNET_TESTBED_host_get_id_ (hr->host),
576        GNUNET_TESTBED_host_get_id_ (GST_host_list[slave->host_id]));
577   slave->rhandle =
578       GNUNET_TESTBED_register_host (slave->controller, hr->host, hr_completion,
579                                     slave);
580 }
581
582
583 /**
584  * Callback which will be called to after a host registration succeeded or failed
585  *
586  * @param cls the handle to the slave at which the registration is completed
587  * @param emsg the error message; NULL if host registration is successful
588  */
589 static void
590 hr_completion (void *cls, const char *emsg)
591 {
592   struct Slave *slave = cls;
593   struct HostRegistration *hr;
594
595   slave->rhandle = NULL;
596   hr = slave->hr_dll_head;
597   GNUNET_assert (NULL != hr);
598   LOG (GNUNET_ERROR_TYPE_DEBUG, "Registering host %u at %u successful\n",
599        GNUNET_TESTBED_host_get_id_ (hr->host),
600        GNUNET_TESTBED_host_get_id_ (GST_host_list[slave->host_id]));
601   GNUNET_CONTAINER_DLL_remove (slave->hr_dll_head, slave->hr_dll_tail, hr);
602   if (NULL != hr->cb)
603     hr->cb (hr->cb_cls, emsg);
604   GNUNET_free (hr);
605   if (NULL != slave->hr_dll_head)
606     register_next_host (slave);
607 }
608
609
610 /**
611  * Adds a host registration's request to a slave's registration queue
612  *
613  * @param slave the slave controller at which the given host has to be
614  *          registered
615  * @param cb the host registration completion callback
616  * @param cb_cls the closure for the host registration completion callback
617  * @param host the host which has to be registered
618  */
619 void
620 GST_queue_host_registration (struct Slave *slave,
621                              GNUNET_TESTBED_HostRegistrationCompletion cb,
622                              void *cb_cls, struct GNUNET_TESTBED_Host *host)
623 {
624   struct HostRegistration *hr;
625   int call_register;
626
627   LOG (GNUNET_ERROR_TYPE_DEBUG,
628        "Queueing host registration for host %u at %u\n",
629        GNUNET_TESTBED_host_get_id_ (host),
630        GNUNET_TESTBED_host_get_id_ (GST_host_list[slave->host_id]));
631   hr = GNUNET_malloc (sizeof (struct HostRegistration));
632   hr->cb = cb;
633   hr->cb_cls = cb_cls;
634   hr->host = host;
635   call_register = (NULL == slave->hr_dll_head) ? GNUNET_YES : GNUNET_NO;
636   GNUNET_CONTAINER_DLL_insert_tail (slave->hr_dll_head, slave->hr_dll_tail, hr);
637   if (GNUNET_YES == call_register)
638     register_next_host (slave);
639 }
640
641
642 /**
643  * The  Link Controller forwarding task
644  *
645  * @param cls the LCFContext
646  * @param tc the Task context from scheduler
647  */
648 static void
649 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
650
651
652 /**
653  * Completion callback for host registrations while forwarding Link Controller messages
654  *
655  * @param cls the LCFContext
656  * @param emsg the error message; NULL if host registration is successful
657  */
658 static void
659 lcf_proc_cc (void *cls, const char *emsg)
660 {
661   struct LCFContext *lcf = cls;
662
663   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
664   switch (lcf->state)
665   {
666   case INIT:
667     if (NULL != emsg)
668       goto registration_error;
669     lcf->state = DELEGATED_HOST_REGISTERED;
670     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
671     break;
672   case DELEGATED_HOST_REGISTERED:
673     if (NULL != emsg)
674       goto registration_error;
675     lcf->state = SLAVE_HOST_REGISTERED;
676     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
677     break;
678   default:
679     GNUNET_assert (0);          /* Shouldn't reach here */
680   }
681   return;
682
683 registration_error:
684   LOG (GNUNET_ERROR_TYPE_WARNING, "Host registration failed with message: %s\n",
685        emsg);
686   lcf->state = FINISHED;
687   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
688 }
689
690
691 /**
692  * Callback to relay the reply msg of a forwarded operation back to the client
693  *
694  * @param cls ForwardedOperationContext
695  * @param msg the message to relay
696  */
697 void
698 GST_forwarded_operation_reply_relay (void *cls,
699                                      const struct GNUNET_MessageHeader *msg)
700 {
701   struct ForwardedOperationContext *fopc = cls;
702   struct GNUNET_MessageHeader *dup_msg;
703   uint16_t msize;
704
705   msize = ntohs (msg->size);
706   LOG_DEBUG ("Relaying message with type: %u, size: %u\n", ntohs (msg->type),
707              msize);
708   dup_msg = GNUNET_copy_message (msg);
709   GST_queue_message (fopc->client, dup_msg);
710   GNUNET_SERVER_client_drop (fopc->client);
711   GNUNET_SCHEDULER_cancel (fopc->timeout_task);
712   GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fopc);
713   GNUNET_free (fopc);
714 }
715
716
717 /**
718  * Task to free resources when forwarded operation has been timedout
719  *
720  * @param cls the ForwardedOperationContext
721  * @param tc the task context from scheduler
722  */
723 void
724 GST_forwarded_operation_timeout (void *cls,
725                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
726 {
727   struct ForwardedOperationContext *fopc = cls;
728
729   GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
730   LOG (GNUNET_ERROR_TYPE_DEBUG, "A forwarded operation has timed out\n");
731   GST_send_operation_fail_msg (fopc->client, fopc->operation_id,
732                                "A forwarded operation has timed out");
733   GNUNET_SERVER_client_drop (fopc->client);
734   GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fopc);
735   GNUNET_free (fopc);
736 }
737
738
739 /**
740  * The  Link Controller forwarding task
741  *
742  * @param cls the LCFContext
743  * @param tc the Task context from scheduler
744  */
745 static void
746 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
747
748
749 /**
750  * Task to free resources when forwarded link controllers has been timedout
751  *
752  * @param cls the LCFContext
753  * @param tc the task context from scheduler
754  */
755 static void
756 lcf_forwarded_operation_timeout (void *cls,
757                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
758 {
759   struct LCFContext *lcf = cls;
760
761   lcf->timeout_task = GNUNET_SCHEDULER_NO_TASK;
762   //  GST_forwarded_operation_timeout (lcf->fopc, tc);
763   LOG (GNUNET_ERROR_TYPE_WARNING,
764        "A forwarded controller link operation has timed out\n");
765   send_controller_link_response (lcf->client, lcf->operation_id, NULL,
766                                  "A forwarded controller link operation has "
767                                  "timed out\n");
768   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
769   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
770 }
771
772
773 /**
774  * The  Link Controller forwarding task
775  *
776  * @param cls the LCFContext
777  * @param tc the Task context from scheduler
778  */
779 static void
780 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
781 {
782   struct LCFContext *lcf = cls;
783   struct LCFContextQueue *lcfq;
784
785   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
786   switch (lcf->state)
787   {
788   case INIT:
789     if (GNUNET_NO ==
790         GNUNET_TESTBED_is_host_registered_ (GST_host_list
791                                             [lcf->delegated_host_id],
792                                             lcf->gateway->controller))
793     {
794       GST_queue_host_registration (lcf->gateway, lcf_proc_cc, lcf,
795                                    GST_host_list[lcf->delegated_host_id]);
796     }
797     else
798     {
799       lcf->state = DELEGATED_HOST_REGISTERED;
800       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
801     }
802     break;
803   case DELEGATED_HOST_REGISTERED:
804     if (GNUNET_NO ==
805         GNUNET_TESTBED_is_host_registered_ (GST_host_list[lcf->slave_host_id],
806                                             lcf->gateway->controller))
807     {
808       GST_queue_host_registration (lcf->gateway, lcf_proc_cc, lcf,
809                                    GST_host_list[lcf->slave_host_id]);
810     }
811     else
812     {
813       lcf->state = SLAVE_HOST_REGISTERED;
814       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
815     }
816     break;
817   case SLAVE_HOST_REGISTERED:
818     lcf->op = GNUNET_TESTBED_controller_link (lcf,
819                                               lcf->gateway->controller,
820                                               GST_host_list[lcf->delegated_host_id],
821                                               GST_host_list[lcf->slave_host_id],
822                                               NULL,
823                                               lcf->is_subordinate);
824     lcf->timeout_task =
825         GNUNET_SCHEDULER_add_delayed (GST_timeout, &lcf_forwarded_operation_timeout,
826                                       lcf);
827     lcf->state = FINISHED;
828     break;
829   case FINISHED:
830     lcfq = lcfq_head;
831     GNUNET_assert (lcfq->lcf == lcf);
832     GNUNET_assert (NULL != lcf->cfg);
833     GNUNET_CONFIGURATION_destroy (lcf->cfg);
834     GNUNET_SERVER_client_drop (lcf->client);
835     GNUNET_TESTBED_operation_done (lcf->op);
836     GNUNET_free (lcf);
837     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
838     GNUNET_free (lcfq);
839     if (NULL != lcfq_head)
840       lcf_proc_task_id =
841           GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
842   }
843 }
844
845
846 /**
847  * Callback for event from slave controllers
848  *
849  * @param cls struct Slave *
850  * @param event information about the event
851  */
852 static void
853 slave_event_callback (void *cls,
854                       const struct GNUNET_TESTBED_EventInformation *event)
855 {
856   struct RegisteredHostContext *rhc;
857   struct LCFContext *lcf;
858   struct GNUNET_CONFIGURATION_Handle *cfg;
859   struct GNUNET_TESTBED_Operation *old_op;
860
861   /* We currently only get here when working on RegisteredHostContexts and
862      LCFContexts */
863   GNUNET_assert (GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type);
864   rhc = event->op_cls;
865   if (CLOSURE_TYPE_RHC == rhc->type)
866   {
867     GNUNET_assert (rhc->sub_op == event->op);
868     switch (rhc->state)
869     {
870     case RHC_GET_CFG:
871       cfg = event->details.operation_finished.generic;
872       old_op = rhc->sub_op;
873       rhc->state = RHC_LINK;
874       rhc->sub_op =
875           GNUNET_TESTBED_controller_link (rhc, rhc->gateway->controller,
876                                           rhc->reg_host, rhc->host, cfg,
877                                           GNUNET_NO);
878       GNUNET_TESTBED_operation_done (old_op);
879       break;
880     case RHC_LINK:
881       LOG_DEBUG ("OL: Linking controllers successfull\n");
882       GNUNET_TESTBED_operation_done (rhc->sub_op);
883       rhc->sub_op = NULL;
884       rhc->state = RHC_OL_CONNECT;
885       GST_process_next_focc (rhc);
886       break;
887     default:
888       GNUNET_assert (0);
889     }
890     return;
891   }
892   lcf = event->op_cls;
893   if (CLOSURE_TYPE_LCF == lcf->type)
894   {    
895     GNUNET_assert (lcf->op == event->op);
896     GNUNET_assert (FINISHED == lcf->state);
897     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != lcf->timeout_task);
898     GNUNET_SCHEDULER_cancel (lcf->timeout_task);
899     if (NULL == event->details.operation_finished.emsg)
900       send_controller_link_response (lcf->client, lcf->operation_id,
901                                      GNUNET_TESTBED_host_get_cfg_ 
902                                      (GST_host_list[lcf->delegated_host_id]),
903                                      NULL);
904     else
905       send_controller_link_response (lcf->client, lcf->operation_id,
906                                      NULL,
907                                      event->details.operation_finished.emsg);
908     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
909     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
910     return;
911   }
912   GNUNET_assert (0);
913 }
914
915
916 /**
917  * Callback to signal successfull startup of the controller process
918  *
919  * @param cls the handle to the slave whose status is to be found here
920  * @param cfg the configuration with which the controller has been started;
921  *          NULL if status is not GNUNET_OK
922  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
923  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
924  */
925 static void
926 slave_status_callback (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
927                        int status)
928 {
929   struct Slave *slave = cls;
930   struct LinkControllersContext *lcc;
931
932   lcc = slave->lcc;
933   if (GNUNET_SYSERR == status)
934   {
935     slave->controller_proc = NULL;
936     GST_slave_list[slave->host_id] = NULL;
937     GNUNET_free (slave);
938     slave = NULL;
939     LOG (GNUNET_ERROR_TYPE_WARNING, "Unexpected slave shutdown\n");
940     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
941     goto clean_lcc;
942   }
943   slave->controller =
944       GNUNET_TESTBED_controller_connect (cfg, GST_host_list[slave->host_id],
945                                          event_mask, &slave_event_callback,
946                                          slave);
947   if (NULL != slave->controller)
948   {
949     send_controller_link_response (lcc->client, lcc->operation_id, cfg, NULL);
950   }
951   else
952   {
953     send_controller_link_response (lcc->client, lcc->operation_id, NULL,
954                                    "Could not connect to delegated controller");
955     GNUNET_TESTBED_controller_stop (slave->controller_proc);
956     GST_slave_list[slave->host_id] = NULL;
957     GNUNET_free (slave);
958     slave = NULL;
959   }
960
961 clean_lcc:
962   if (NULL != lcc)
963   {
964     if (NULL != lcc->client)
965     {
966       GNUNET_SERVER_receive_done (lcc->client, GNUNET_OK);
967       GNUNET_SERVER_client_drop (lcc->client);
968       lcc->client = NULL;
969     }
970     GNUNET_free (lcc);
971   }
972   if (NULL != slave)
973     slave->lcc = NULL;
974 }
975
976
977 /**
978  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
979  *
980  * @param cls NULL
981  * @param client identification of the client
982  * @param message the actual message
983  */
984 static void
985 handle_init (void *cls, struct GNUNET_SERVER_Client *client,
986              const struct GNUNET_MessageHeader *message)
987 {
988   const struct GNUNET_TESTBED_InitMessage *msg;
989   struct GNUNET_TESTBED_Host *host;
990   const char *controller_hostname;
991   uint16_t msize;
992
993   if (NULL != GST_context)
994   {
995     LOG_DEBUG ("We are being connected to laterally\n");
996     GNUNET_SERVER_receive_done (client, GNUNET_OK);
997     return;
998   }
999   msg = (const struct GNUNET_TESTBED_InitMessage *) message;
1000   msize = ntohs (message->size);
1001   if (msize <= sizeof (struct GNUNET_TESTBED_InitMessage))
1002   {
1003     GNUNET_break (0);
1004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1005     return;
1006   }
1007   msize -= sizeof (struct GNUNET_TESTBED_InitMessage);
1008   controller_hostname = (const char *) &msg[1];
1009   if ('\0' != controller_hostname[msize - 1])
1010   {
1011     GNUNET_break (0);
1012     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1013     return;
1014   }
1015   GST_context = GNUNET_malloc (sizeof (struct Context));
1016   GNUNET_SERVER_client_keep (client);
1017   GST_context->client = client;
1018   GST_context->host_id = ntohl (msg->host_id);
1019   GST_context->master_ip = GNUNET_strdup (controller_hostname);
1020   LOG_DEBUG ("Our IP: %s\n", GST_context->master_ip);
1021   GST_context->system =
1022       GNUNET_TESTING_system_create ("testbed", GST_context->master_ip,
1023                                     hostname);
1024   host =
1025       GNUNET_TESTBED_host_create_with_id (GST_context->host_id,
1026                                           GST_context->master_ip, NULL,
1027                                           our_config, 0);
1028   host_list_add (host);
1029   LOG_DEBUG ("Created master context with host ID: %u\n", GST_context->host_id);
1030   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1031 }
1032
1033
1034 /**
1035  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1036  *
1037  * @param cls NULL
1038  * @param client identification of the client
1039  * @param message the actual message
1040  */
1041 static void
1042 handle_add_host (void *cls, struct GNUNET_SERVER_Client *client,
1043                  const struct GNUNET_MessageHeader *message)
1044 {
1045   struct GNUNET_TESTBED_Host *host;
1046   const struct GNUNET_TESTBED_AddHostMessage *msg;
1047   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
1048   struct GNUNET_CONFIGURATION_Handle *host_cfg;
1049   char *username;
1050   char *hostname;
1051   char *emsg;
1052   const void *ptr;
1053   uint32_t host_id;
1054   uint16_t username_length;
1055   uint16_t hostname_length;
1056   uint16_t reply_size;
1057   uint16_t msize;
1058
1059   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
1060   msize = ntohs (msg->header.size);
1061   if (msize <= sizeof (struct GNUNET_TESTBED_AddHostMessage))
1062   {
1063     GNUNET_break_op (0);
1064     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1065     return;
1066   }
1067   username_length = ntohs (msg->username_length);
1068   hostname_length = ntohs (msg->hostname_length);
1069   /* msg must contain hostname */
1070   if ((msize <= (sizeof (struct GNUNET_TESTBED_AddHostMessage) + 
1071                  username_length))
1072       || (0 == hostname_length))
1073   {
1074     GNUNET_break_op (0);
1075     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1076     return;
1077   }
1078   /* msg must contain configuration */
1079   if (msize <= (sizeof (struct GNUNET_TESTBED_AddHostMessage) +
1080                 username_length + hostname_length))
1081   {
1082     GNUNET_break_op (0);
1083     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1084     return;
1085   }
1086   username = NULL;
1087   hostname = NULL;
1088   ptr = &msg[1];
1089   if (0 != username_length)
1090   {
1091     username = GNUNET_malloc (username_length + 1);
1092     strncpy (username, ptr, username_length);
1093     ptr += username_length;
1094   }
1095   hostname = GNUNET_malloc (hostname_length + 1);
1096   strncpy (hostname, ptr, hostname_length);
1097   ptr += hostname_length;
1098   if (NULL == (host_cfg = GNUNET_TESTBED_extract_config_ (message)))
1099   {
1100     GNUNET_free_non_null (username);
1101     GNUNET_free_non_null (hostname);
1102     GNUNET_break_op (0);
1103     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1104     return;
1105   }
1106   host_id = ntohl (msg->host_id);
1107   LOG_DEBUG ("Received ADDHOST %u message\n", host_id);
1108   LOG_DEBUG ("-------host id: %u\n", host_id);
1109   LOG_DEBUG ("-------hostname: %s\n", hostname);
1110   if (NULL != username)
1111     LOG_DEBUG ("-------username: %s\n", username);
1112   else
1113     LOG_DEBUG ("-------username: <not given>\n");
1114   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1115   host =
1116       GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1117                                           host_cfg, ntohs (msg->ssh_port));
1118   GNUNET_free_non_null (username);
1119   GNUNET_free (hostname);
1120   GNUNET_CONFIGURATION_destroy (host_cfg);
1121   if (NULL == host)
1122   {
1123     GNUNET_break_op (0);
1124     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1125     return;
1126   }
1127   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1128   if (GNUNET_OK != host_list_add (host))
1129   {
1130     /* We are unable to add a host */
1131     emsg = "A host exists with given host-id";
1132     LOG_DEBUG ("%s: %u", emsg, host_id);
1133     GNUNET_TESTBED_host_destroy (host);
1134     reply_size += strlen (emsg) + 1;
1135     reply = GNUNET_malloc (reply_size);
1136     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1137   }
1138   else
1139   {
1140     LOG_DEBUG ("Added host %u at %u\n", host_id, GST_context->host_id);
1141     reply = GNUNET_malloc (reply_size);
1142   }
1143   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST_SUCCESS);
1144   reply->header.size = htons (reply_size);
1145   reply->host_id = htonl (host_id);
1146   GST_queue_message (client, &reply->header);
1147   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1148 }
1149
1150
1151 /**
1152  * Iterator over hash map entries.
1153  *
1154  * @param cls closure
1155  * @param key current key code
1156  * @param value value in the hash map
1157  * @return GNUNET_YES if we should continue to
1158  *         iterate,
1159  *         GNUNET_NO if not.
1160  */
1161 int
1162 ss_exists_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
1163 {
1164   struct SharedService *queried_ss = cls;
1165   struct SharedService *ss = value;
1166
1167   if (0 == strcmp (ss->name, queried_ss->name))
1168     return GNUNET_NO;
1169   else
1170     return GNUNET_YES;
1171 }
1172
1173
1174 /**
1175  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1176  *
1177  * @param cls NULL
1178  * @param client identification of the client
1179  * @param message the actual message
1180  */
1181 static void
1182 handle_configure_shared_service (void *cls, struct GNUNET_SERVER_Client *client,
1183                                  const struct GNUNET_MessageHeader *message)
1184 {
1185   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1186   struct SharedService *ss;
1187   char *service_name;
1188   struct GNUNET_HashCode hash;
1189   uint16_t msg_size;
1190   uint16_t service_name_size;
1191
1192   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1193   msg_size = ntohs (message->size);
1194   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1195   {
1196     GNUNET_break (0);
1197     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1198     return;
1199   }
1200   service_name_size =
1201       msg_size - sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
1202   service_name = (char *) &msg[1];
1203   if ('\0' != service_name[service_name_size - 1])
1204   {
1205     GNUNET_break (0);
1206     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1207     return;
1208   }
1209   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
1210              service_name, ntohl (msg->num_peers));
1211   if (ntohl (msg->host_id) != GST_context->host_id)
1212   {
1213     route_message (ntohl (msg->host_id), message);
1214     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1215     return;
1216   }
1217   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1218   ss = GNUNET_malloc (sizeof (struct SharedService));
1219   ss->name = strdup (service_name);
1220   ss->num_shared = ntohl (msg->num_peers);
1221   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1222   if (GNUNET_SYSERR ==
1223       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1224                                                   &ss_exists_iterator, ss))
1225   {
1226     LOG (GNUNET_ERROR_TYPE_WARNING,
1227          "Service %s already configured as a shared service. "
1228          "Ignoring service sharing request \n", ss->name);
1229     GNUNET_free (ss->name);
1230     GNUNET_free (ss);
1231     return;
1232   }
1233   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1234                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1235 }
1236
1237
1238 /**
1239  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1240  *
1241  * @param cls NULL
1242  * @param client identification of the client
1243  * @param message the actual message
1244  */
1245 static void
1246 handle_link_controllers (void *cls, struct GNUNET_SERVER_Client *client,
1247                          const struct GNUNET_MessageHeader *message)
1248 {
1249   const struct GNUNET_TESTBED_ControllerLinkRequest *msg;
1250   struct GNUNET_CONFIGURATION_Handle *cfg;
1251   struct LCFContextQueue *lcfq;
1252   struct Route *route;
1253   struct Route *new_route;
1254   uint32_t delegated_host_id;
1255   uint32_t slave_host_id;
1256   uint16_t msize;
1257
1258   if (NULL == GST_context)
1259   {
1260     GNUNET_break (0);
1261     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1262     return;
1263   }
1264   msize = ntohs (message->size);
1265   if (sizeof (struct GNUNET_TESTBED_ControllerLinkRequest) >= msize)
1266   {
1267     GNUNET_break (0);
1268     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1269     return;
1270   }
1271   msg = (const struct GNUNET_TESTBED_ControllerLinkRequest *) message;
1272   delegated_host_id = ntohl (msg->delegated_host_id);
1273   if (delegated_host_id == GST_context->host_id)
1274   {
1275     GNUNET_break (0);
1276     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1277     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1278     return;
1279   }
1280   if ((delegated_host_id >= GST_host_list_size) ||
1281       (NULL == GST_host_list[delegated_host_id]))
1282   {
1283     LOG (GNUNET_ERROR_TYPE_WARNING,
1284          "Delegated host %u not registered with us\n", delegated_host_id);
1285     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1286     return;
1287   }
1288   slave_host_id = ntohl (msg->slave_host_id);
1289   if ((slave_host_id >= GST_host_list_size) ||
1290       (NULL == GST_host_list[slave_host_id]))
1291   {
1292     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host %u not registered with us\n",
1293          slave_host_id);
1294     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1295     return;
1296   }
1297   if (slave_host_id == delegated_host_id)
1298   {
1299     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1300     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1301     return;
1302   }
1303   cfg = GNUNET_TESTBED_extract_config_ (message); /* destroy cfg here or in lcfcontext */
1304   if (NULL == cfg)
1305   {
1306     GNUNET_break (0);         /* Configuration parsing error */
1307     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1308     return;
1309   }
1310   if (slave_host_id == GST_context->host_id)    /* Link from us */
1311   {
1312     struct Slave *slave;
1313     struct LinkControllersContext *lcc;
1314
1315     if ((delegated_host_id < GST_slave_list_size) &&
1316         (NULL != GST_slave_list[delegated_host_id]))
1317     {
1318       GNUNET_break (0);
1319       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1320       return;
1321     }
1322     slave = GNUNET_malloc (sizeof (struct Slave));
1323     slave->host_id = delegated_host_id;
1324     slave->reghost_map = GNUNET_CONTAINER_multihashmap_create (100, GNUNET_NO);
1325     slave_list_add (slave);
1326     if (1 != msg->is_subordinate)
1327     {
1328       slave->controller =
1329           GNUNET_TESTBED_controller_connect (cfg, GST_host_list[slave->host_id],
1330                                              event_mask, &slave_event_callback,
1331                                              slave);
1332       if (NULL != slave->controller)
1333         send_controller_link_response (client,
1334                                        GNUNET_ntohll (msg->operation_id),
1335                                        NULL,
1336                                        NULL);
1337       else
1338         send_controller_link_response (client,
1339                                        GNUNET_ntohll (msg->operation_id),
1340                                        NULL,
1341                                        "Could not connect to delegated controller");
1342       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1343       return;
1344     }
1345     lcc = GNUNET_malloc (sizeof (struct LinkControllersContext));
1346     lcc->operation_id = GNUNET_ntohll (msg->operation_id);
1347     GNUNET_SERVER_client_keep (client);
1348     lcc->client = client;
1349     slave->lcc = lcc;
1350     slave->controller_proc =
1351         GNUNET_TESTBED_controller_start (GST_context->master_ip,
1352                                          GST_host_list[slave->host_id], cfg,
1353                                          &slave_status_callback, slave);
1354     GNUNET_CONFIGURATION_destroy (cfg);
1355     new_route = GNUNET_malloc (sizeof (struct Route));
1356     new_route->dest = delegated_host_id;
1357     new_route->thru = GST_context->host_id;
1358     route_list_add (new_route);
1359     return;
1360   }
1361
1362   /* Route the request */
1363   if (slave_host_id >= route_list_size)
1364   {
1365     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1366     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1367     return;
1368   }
1369   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1370   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1371   lcfq->lcf->type = CLOSURE_TYPE_LCF;
1372   lcfq->lcf->delegated_host_id = delegated_host_id;
1373   lcfq->lcf->slave_host_id = slave_host_id;
1374   route = GST_find_dest_route (slave_host_id);
1375   GNUNET_assert (NULL != route);        /* because we add routes carefully */
1376   GNUNET_assert (route->dest < GST_slave_list_size);
1377   GNUNET_assert (NULL != GST_slave_list[route->dest]);
1378   lcfq->lcf->cfg = cfg;
1379   lcfq->lcf->is_subordinate = msg->is_subordinate;
1380   lcfq->lcf->state = INIT;
1381   lcfq->lcf->operation_id = GNUNET_ntohll (msg->operation_id);
1382   lcfq->lcf->gateway = GST_slave_list[route->dest];
1383   GNUNET_SERVER_client_keep (client);
1384   lcfq->lcf->client = client;
1385   if (NULL == lcfq_head)
1386   {
1387     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1388     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1389     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq->lcf);
1390   }
1391   else
1392     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1393   /* FIXME: Adding a new route should happen after the controllers are linked
1394    * successfully */
1395   if (1 != msg->is_subordinate)
1396   {
1397     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1398     return;
1399   }
1400   if ((delegated_host_id < route_list_size) &&
1401       (NULL != route_list[delegated_host_id]))
1402   {
1403     GNUNET_break_op (0);        /* Are you trying to link delegated host twice
1404                                  * with is subordinate flag set to GNUNET_YES? */
1405     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1406     return;
1407   }
1408   new_route = GNUNET_malloc (sizeof (struct Route));
1409   new_route->dest = delegated_host_id;
1410   new_route->thru = route->dest;
1411   route_list_add (new_route);
1412   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1413 }
1414
1415
1416 /**
1417  * The task to be executed if the forwarded peer create operation has been
1418  * timed out
1419  *
1420  * @param cls the FowardedOperationContext
1421  * @param tc the TaskContext from the scheduler
1422  */
1423 static void
1424 peer_create_forward_timeout (void *cls,
1425                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1426 {
1427   struct ForwardedOperationContext *fopc = cls;
1428
1429   GNUNET_free (fopc->cls);
1430   GST_forwarded_operation_timeout (fopc, tc);
1431 }
1432
1433
1434 /**
1435  * Callback to be called when forwarded peer create operation is successfull. We
1436  * have to relay the reply msg back to the client
1437  *
1438  * @param cls ForwardedOperationContext
1439  * @param msg the peer create success message
1440  */
1441 static void
1442 peer_create_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
1443 {
1444   struct ForwardedOperationContext *fopc = cls;
1445   struct Peer *remote_peer;
1446
1447   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_TESTBED_CREATE_PEER_SUCCESS)
1448   {
1449     GNUNET_assert (NULL != fopc->cls);
1450     remote_peer = fopc->cls;
1451     peer_list_add (remote_peer);
1452   }
1453   GST_forwarded_operation_reply_relay (fopc, msg);
1454 }
1455
1456
1457 /**
1458  * Function to destroy a peer
1459  *
1460  * @param peer the peer structure to destroy
1461  */
1462 void
1463 GST_destroy_peer (struct Peer *peer)
1464 {
1465   GNUNET_break (0 == peer->reference_cnt);
1466   if (GNUNET_YES == peer->is_remote)
1467   {
1468     peer_list_remove (peer);
1469     GNUNET_free (peer);
1470     return;
1471   }
1472   if (GNUNET_YES == peer->details.local.is_running)
1473   {
1474     GNUNET_TESTING_peer_stop (peer->details.local.peer);
1475     peer->details.local.is_running = GNUNET_NO;
1476   }
1477   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
1478   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
1479   peer_list_remove (peer);
1480   GNUNET_free (peer);
1481 }
1482
1483
1484 /**
1485  * Callback to be called when forwarded peer destroy operation is successfull. We
1486  * have to relay the reply msg back to the client
1487  *
1488  * @param cls ForwardedOperationContext
1489  * @param msg the peer create success message
1490  */
1491 static void
1492 peer_destroy_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
1493 {
1494   struct ForwardedOperationContext *fopc = cls;
1495   struct Peer *remote_peer;
1496
1497   if (GNUNET_MESSAGE_TYPE_TESTBED_GENERIC_OPERATION_SUCCESS ==
1498       ntohs (msg->type))
1499   {
1500     remote_peer = fopc->cls;
1501     GNUNET_assert (NULL != remote_peer);
1502     remote_peer->destroy_flag = GNUNET_YES;
1503     if (0 == remote_peer->reference_cnt)
1504       GST_destroy_peer (remote_peer);
1505   }
1506   GST_forwarded_operation_reply_relay (fopc, msg);
1507 }
1508
1509
1510
1511 /**
1512  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1513  *
1514  * @param cls NULL
1515  * @param client identification of the client
1516  * @param message the actual message
1517  */
1518 static void
1519 handle_peer_create (void *cls, struct GNUNET_SERVER_Client *client,
1520                     const struct GNUNET_MessageHeader *message)
1521 {
1522   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1523   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1524   struct GNUNET_CONFIGURATION_Handle *cfg;
1525   struct ForwardedOperationContext *fo_ctxt;
1526   struct Route *route;
1527   struct Peer *peer;
1528   char *config;
1529   size_t dest_size;
1530   int ret;
1531   uint32_t config_size;
1532   uint32_t host_id;
1533   uint32_t peer_id;
1534   uint16_t msize;
1535
1536
1537   msize = ntohs (message->size);
1538   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1539   {
1540     GNUNET_break (0);           /* We need configuration */
1541     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1542     return;
1543   }
1544   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1545   host_id = ntohl (msg->host_id);
1546   peer_id = ntohl (msg->peer_id);
1547   if (UINT32_MAX == peer_id)
1548   {
1549     GST_send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1550                                  "Cannot create peer with given ID");
1551     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1552     return;
1553   }
1554   if (host_id == GST_context->host_id)
1555   {
1556     char *emsg;
1557
1558     /* We are responsible for this peer */
1559     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1560     config_size = ntohl (msg->config_size);
1561     config = GNUNET_malloc (config_size);
1562     dest_size = config_size;
1563     if (Z_OK !=
1564         (ret =
1565          uncompress ((Bytef *) config, (uLongf *) & dest_size,
1566                      (const Bytef *) &msg[1], (uLong) msize)))
1567     {
1568       GNUNET_break (0);         /* uncompression error */
1569       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1570       return;
1571     }
1572     if (config_size != dest_size)
1573     {
1574       GNUNET_break (0);         /* Uncompressed config size mismatch */
1575       GNUNET_free (config);
1576       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1577       return;
1578     }
1579     cfg = GNUNET_CONFIGURATION_create ();
1580     if (GNUNET_OK !=
1581         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
1582     {
1583       GNUNET_break (0);         /* Configuration parsing error */
1584       GNUNET_free (config);
1585       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1586       return;
1587     }
1588     GNUNET_free (config);
1589     GNUNET_CONFIGURATION_set_value_number (cfg, "TESTBED", "PEERID",
1590                                            (unsigned long long) peer_id);
1591     peer = GNUNET_malloc (sizeof (struct Peer));
1592     peer->is_remote = GNUNET_NO;
1593     peer->details.local.cfg = cfg;
1594     peer->id = peer_id;
1595     LOG_DEBUG ("Creating peer with id: %u\n", (unsigned int) peer->id);
1596     peer->details.local.peer =
1597         GNUNET_TESTING_peer_configure (GST_context->system,
1598                                        peer->details.local.cfg, peer->id,
1599                                        NULL /* Peer id */ ,
1600                                        &emsg);
1601     if (NULL == peer->details.local.peer)
1602     {
1603       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1604       GNUNET_free (emsg);
1605       GNUNET_free (peer);
1606       GNUNET_break (0);
1607       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1608       return;
1609     }
1610     peer->details.local.is_running = GNUNET_NO;
1611     peer_list_add (peer);
1612     reply =
1613         GNUNET_malloc (sizeof
1614                        (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1615     reply->header.size =
1616         htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1617     reply->header.type =
1618         htons (GNUNET_MESSAGE_TYPE_TESTBED_CREATE_PEER_SUCCESS);
1619     reply->peer_id = msg->peer_id;
1620     reply->operation_id = msg->operation_id;
1621     GST_queue_message (client, &reply->header);
1622     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1623     return;
1624   }
1625
1626   /* Forward peer create request */
1627   route = GST_find_dest_route (host_id);
1628   if (NULL == route)
1629   {
1630     GNUNET_break (0);
1631     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1632     return;
1633   }
1634
1635   peer = GNUNET_malloc (sizeof (struct Peer));
1636   peer->is_remote = GNUNET_YES;
1637   peer->id = peer_id;
1638   peer->details.remote.slave = GST_slave_list[route->dest];
1639   peer->details.remote.remote_host_id = host_id;
1640   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1641   GNUNET_SERVER_client_keep (client);
1642   fo_ctxt->client = client;
1643   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);
1644   fo_ctxt->cls = peer;          //GST_slave_list[route->dest]->controller;
1645   fo_ctxt->type = OP_PEER_CREATE;
1646   fo_ctxt->opc =
1647       GNUNET_TESTBED_forward_operation_msg_ (GST_slave_list
1648                                              [route->dest]->controller,
1649                                              fo_ctxt->operation_id,
1650                                              &msg->header,
1651                                              peer_create_success_cb, fo_ctxt);
1652   fo_ctxt->timeout_task =
1653       GNUNET_SCHEDULER_add_delayed (GST_timeout, &peer_create_forward_timeout,
1654                                     fo_ctxt);
1655   GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fo_ctxt);
1656   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1657 }
1658
1659
1660 /**
1661  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1662  *
1663  * @param cls NULL
1664  * @param client identification of the client
1665  * @param message the actual message
1666  */
1667 static void
1668 handle_peer_destroy (void *cls, struct GNUNET_SERVER_Client *client,
1669                      const struct GNUNET_MessageHeader *message)
1670 {
1671   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1672   struct ForwardedOperationContext *fopc;
1673   struct Peer *peer;
1674   uint32_t peer_id;
1675
1676   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1677   peer_id = ntohl (msg->peer_id);
1678   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1679              peer_id, GNUNET_ntohll (msg->operation_id));
1680   if ((GST_peer_list_size <= peer_id) || (NULL == GST_peer_list[peer_id]))
1681   {
1682     LOG (GNUNET_ERROR_TYPE_ERROR,
1683          "Asked to destroy a non existent peer with id: %u\n", peer_id);
1684     GST_send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1685                                  "Peer doesn't exist");
1686     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1687     return;
1688   }
1689   peer = GST_peer_list[peer_id];
1690   if (GNUNET_YES == peer->is_remote)
1691   {
1692     /* Forward the destory message to sub controller */
1693     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1694     GNUNET_SERVER_client_keep (client);
1695     fopc->client = client;
1696     fopc->cls = peer;
1697     fopc->type = OP_PEER_DESTROY;
1698     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1699     fopc->opc =
1700         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.
1701                                                slave->controller,
1702                                                fopc->operation_id, &msg->header,
1703                                                &peer_destroy_success_cb, fopc);
1704     fopc->timeout_task =
1705         GNUNET_SCHEDULER_add_delayed (GST_timeout, &GST_forwarded_operation_timeout,
1706                                       fopc);
1707     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
1708     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1709     return;
1710   }
1711   peer->destroy_flag = GNUNET_YES;
1712   if (0 == peer->reference_cnt)
1713     GST_destroy_peer (peer);
1714   else
1715     LOG (GNUNET_ERROR_TYPE_DEBUG,
1716          "Delaying peer destroy as peer is currently in use\n");
1717   send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1718   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1719 }
1720
1721
1722 /**
1723  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1724  *
1725  * @param cls NULL
1726  * @param client identification of the client
1727  * @param message the actual message
1728  */
1729 static void
1730 handle_peer_start (void *cls, struct GNUNET_SERVER_Client *client,
1731                    const struct GNUNET_MessageHeader *message)
1732 {
1733   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1734   struct GNUNET_TESTBED_PeerEventMessage *reply;
1735   struct ForwardedOperationContext *fopc;
1736   struct Peer *peer;
1737   uint32_t peer_id;
1738
1739   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1740   peer_id = ntohl (msg->peer_id);
1741   if ((peer_id >= GST_peer_list_size) || (NULL == GST_peer_list[peer_id]))
1742   {
1743     GNUNET_break (0);
1744     LOG (GNUNET_ERROR_TYPE_ERROR,
1745          "Asked to start a non existent peer with id: %u\n", peer_id);
1746     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1747     return;
1748   }
1749   peer = GST_peer_list[peer_id];
1750   if (GNUNET_YES == peer->is_remote)
1751   {
1752     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1753     GNUNET_SERVER_client_keep (client);
1754     fopc->client = client;
1755     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1756     fopc->type = OP_PEER_START;
1757     fopc->opc =
1758         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.
1759                                                slave->controller,
1760                                                fopc->operation_id, &msg->header,
1761                                                &GST_forwarded_operation_reply_relay,
1762                                                fopc);
1763     fopc->timeout_task =
1764         GNUNET_SCHEDULER_add_delayed (GST_timeout, &GST_forwarded_operation_timeout,
1765                                       fopc);
1766     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
1767     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1768     return;
1769   }
1770   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer->details.local.peer))
1771   {
1772     GST_send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1773                                  "Failed to start");
1774     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1775     return;
1776   }
1777   peer->details.local.is_running = GNUNET_YES;
1778   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1779   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEER_EVENT);
1780   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1781   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1782   reply->host_id = htonl (GST_context->host_id);
1783   reply->peer_id = msg->peer_id;
1784   reply->operation_id = msg->operation_id;
1785   GST_queue_message (client, &reply->header);
1786   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1787 }
1788
1789
1790 /**
1791  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1792  *
1793  * @param cls NULL
1794  * @param client identification of the client
1795  * @param message the actual message
1796  */
1797 static void
1798 handle_peer_stop (void *cls, struct GNUNET_SERVER_Client *client,
1799                   const struct GNUNET_MessageHeader *message)
1800 {
1801   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1802   struct GNUNET_TESTBED_PeerEventMessage *reply;
1803   struct ForwardedOperationContext *fopc;
1804   struct Peer *peer;
1805   uint32_t peer_id;
1806
1807   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1808   peer_id = ntohl (msg->peer_id);
1809   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PEER_STOP for peer %u\n", peer_id);
1810   if ((peer_id >= GST_peer_list_size) || (NULL == GST_peer_list[peer_id]))
1811   {
1812     GST_send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1813                                  "Peer not found");
1814     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1815     return;
1816   }
1817   peer = GST_peer_list[peer_id];
1818   if (GNUNET_YES == peer->is_remote)
1819   {
1820     LOG (GNUNET_ERROR_TYPE_DEBUG, "Forwarding PEER_STOP for peer %u\n",
1821          peer_id);
1822     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1823     GNUNET_SERVER_client_keep (client);
1824     fopc->client = client;
1825     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1826     fopc->type = OP_PEER_STOP;
1827     fopc->opc =
1828         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.
1829                                                slave->controller,
1830                                                fopc->operation_id, &msg->header,
1831                                                &GST_forwarded_operation_reply_relay,
1832                                                fopc);
1833     fopc->timeout_task =
1834         GNUNET_SCHEDULER_add_delayed (GST_timeout, &GST_forwarded_operation_timeout,
1835                                       fopc);
1836     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
1837     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1838     return;
1839   }
1840   if (GNUNET_OK != GNUNET_TESTING_peer_kill (peer->details.local.peer))
1841   {
1842     LOG (GNUNET_ERROR_TYPE_WARNING, "Stopping peer %u failed\n", peer_id);
1843     GST_send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1844                                  "Peer not running");
1845     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1846     return;
1847   }
1848   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %u successfully stopped\n", peer_id);
1849   peer->details.local.is_running = GNUNET_NO;
1850   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1851   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEER_EVENT);
1852   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1853   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1854   reply->host_id = htonl (GST_context->host_id);
1855   reply->peer_id = msg->peer_id;
1856   reply->operation_id = msg->operation_id;
1857   GST_queue_message (client, &reply->header);
1858   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1859   GNUNET_TESTING_peer_wait (peer->details.local.peer);
1860 }
1861
1862
1863 /**
1864  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1865  *
1866  * @param cls NULL
1867  * @param client identification of the client
1868  * @param message the actual message
1869  */
1870 static void
1871 handle_peer_get_config (void *cls, struct GNUNET_SERVER_Client *client,
1872                         const struct GNUNET_MessageHeader *message)
1873 {
1874   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1875   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1876   struct Peer *peer;
1877   char *config;
1878   char *xconfig;
1879   size_t c_size;
1880   size_t xc_size;
1881   uint32_t peer_id;
1882   uint16_t msize;
1883
1884   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1885   peer_id = ntohl (msg->peer_id);
1886   if ((peer_id >= GST_peer_list_size) || (NULL == GST_peer_list[peer_id]))
1887   {
1888     GST_send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1889                                  "Peer not found");
1890     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1891     return;
1892   }
1893   peer = GST_peer_list[peer_id];
1894   if (GNUNET_YES == peer->is_remote)
1895   {
1896     struct ForwardedOperationContext *fopc;
1897
1898     LOG_DEBUG ("Forwarding PEER_GET_CONFIG for peer: %u\n", peer_id);
1899     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1900     GNUNET_SERVER_client_keep (client);
1901     fopc->client = client;
1902     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1903     fopc->type = OP_PEER_INFO;
1904     fopc->opc =
1905         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.
1906                                                slave->controller,
1907                                                fopc->operation_id, &msg->header,
1908                                                &GST_forwarded_operation_reply_relay,
1909                                                fopc);
1910     fopc->timeout_task =
1911         GNUNET_SCHEDULER_add_delayed (GST_timeout, &GST_forwarded_operation_timeout,
1912                                       fopc);
1913     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
1914     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1915     return;
1916   }
1917   LOG_DEBUG ("Received PEER_GET_CONFIG for peer: %u\n", peer_id);
1918   config =
1919       GNUNET_CONFIGURATION_serialize (GST_peer_list[peer_id]->details.local.cfg,
1920                                       &c_size);
1921   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1922   GNUNET_free (config);
1923   msize =
1924       xc_size +
1925       sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
1926   reply = GNUNET_realloc (xconfig, msize);
1927   (void) memmove (&reply[1], reply, xc_size);
1928   reply->header.size = htons (msize);
1929   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEER_CONFIGURATION);
1930   reply->peer_id = msg->peer_id;
1931   reply->operation_id = msg->operation_id;
1932   GNUNET_TESTING_peer_get_identity (GST_peer_list[peer_id]->details.local.peer,
1933                                     &reply->peer_identity);
1934   reply->config_size = htons ((uint16_t) c_size);
1935   GST_queue_message (client, &reply->header);
1936   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1937 }
1938
1939
1940 /**
1941  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETSLAVECONFIG messages
1942  *
1943  * @param cls NULL
1944  * @param client identification of the client
1945  * @param message the actual message
1946  */
1947 static void
1948 handle_slave_get_config (void *cls, struct GNUNET_SERVER_Client *client,
1949                          const struct GNUNET_MessageHeader *message)
1950 {
1951   struct GNUNET_TESTBED_SlaveGetConfigurationMessage *msg;
1952   struct Slave *slave;
1953   struct GNUNET_TESTBED_SlaveConfiguration *reply;
1954   const struct GNUNET_CONFIGURATION_Handle *cfg;
1955   char *config;
1956   char *xconfig;
1957   size_t config_size;
1958   size_t xconfig_size;
1959   size_t reply_size;
1960   uint64_t op_id;
1961   uint32_t slave_id;
1962
1963   msg = (struct GNUNET_TESTBED_SlaveGetConfigurationMessage *) message;
1964   slave_id = ntohl (msg->slave_id);
1965   op_id = GNUNET_ntohll (msg->operation_id);
1966   if ((GST_slave_list_size <= slave_id) || (NULL == GST_slave_list[slave_id]))
1967   {
1968     /* FIXME: Add forwardings for this type of message here.. */
1969     GST_send_operation_fail_msg (client, op_id, "Slave not found");
1970     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1971     return;
1972   }
1973   slave = GST_slave_list[slave_id];
1974   GNUNET_assert (NULL != (cfg = GNUNET_TESTBED_host_get_cfg_ (GST_host_list[slave->host_id])));
1975   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
1976   xconfig_size =
1977       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
1978   GNUNET_free (config);
1979   reply_size = xconfig_size + sizeof (struct GNUNET_TESTBED_SlaveConfiguration);
1980   GNUNET_break (reply_size <= UINT16_MAX);
1981   GNUNET_break (config_size <= UINT16_MAX);
1982   reply = GNUNET_realloc (xconfig, reply_size);
1983   (void) memmove (&reply[1], reply, xconfig_size);
1984   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SLAVE_CONFIGURATION);
1985   reply->header.size = htons ((uint16_t) reply_size);
1986   reply->slave_id = msg->slave_id;
1987   reply->operation_id = msg->operation_id;
1988   reply->config_size = htons ((uint16_t) config_size);
1989   GST_queue_message (client, &reply->header);
1990   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1991 }
1992
1993 struct ManageServiceContext
1994 {
1995
1996   struct ManageServiceContext *next;
1997
1998   struct ManageServiceContext *prev;
1999
2000   struct GNUNET_ARM_Handle *ah;
2001
2002   struct Peer *peer;
2003
2004   struct GNUNET_SERVER_Client *client;
2005   
2006   uint64_t op_id;
2007   
2008   uint8_t start;
2009
2010   uint8_t expired;
2011   
2012 };
2013
2014 static struct ManageServiceContext *mctx_head;
2015
2016 static struct ManageServiceContext *mctx_tail;
2017
2018 static void
2019 cleanup_mctx (struct ManageServiceContext *mctx)
2020 {
2021   mctx->expired = GNUNET_YES;
2022   GNUNET_CONTAINER_DLL_remove (mctx_head, mctx_tail, mctx);
2023   GNUNET_SERVER_client_drop (mctx->client);
2024   GNUNET_ARM_disconnect_and_free (mctx->ah);
2025   GNUNET_assert (0 < mctx->peer->reference_cnt);
2026   mctx->peer->reference_cnt--;
2027   if ( (GNUNET_YES == mctx->peer->destroy_flag)
2028        && (0 == mctx->peer->reference_cnt) )
2029     GST_destroy_peer (mctx->peer);
2030   GNUNET_free (mctx);
2031 }
2032
2033 static void
2034 free_mctxq ()
2035 {
2036   while (NULL != mctx_head)
2037     cleanup_mctx (mctx_head);
2038 }
2039
2040 static const char *
2041 arm_req_string (enum GNUNET_ARM_RequestStatus rs)
2042 {
2043   switch (rs)
2044   {
2045   case GNUNET_ARM_REQUEST_SENT_OK:
2046     return _("Message was sent successfully");
2047   case GNUNET_ARM_REQUEST_CONFIGURATION_ERROR:
2048     return _("Misconfiguration (can't connect to the ARM service)");
2049   case GNUNET_ARM_REQUEST_DISCONNECTED:
2050     return _("We disconnected from ARM before we could send a request");
2051   case GNUNET_ARM_REQUEST_BUSY:
2052     return _("ARM API is busy");
2053   case GNUNET_ARM_REQUEST_TOO_LONG:
2054     return _("Request doesn't fit into a message");
2055   case GNUNET_ARM_REQUEST_TIMEOUT:
2056     return _("Request timed out");
2057   }
2058   return _("Unknown request status");
2059 }
2060
2061 static const char *
2062 arm_ret_string (enum GNUNET_ARM_Result result)
2063 {
2064   switch (result)
2065   {
2066   case GNUNET_ARM_RESULT_STOPPED:
2067     return _("%s is stopped");
2068   case GNUNET_ARM_RESULT_STARTING:
2069     return _("%s is starting");
2070   case GNUNET_ARM_RESULT_STOPPING:
2071     return _("%s is stopping");
2072   case GNUNET_ARM_RESULT_IS_STARTING_ALREADY:
2073     return _("%s is starting already");
2074   case GNUNET_ARM_RESULT_IS_STOPPING_ALREADY:
2075     return _("%s is stopping already");
2076   case GNUNET_ARM_RESULT_IS_STARTED_ALREADY:
2077     return _("%s is started already");
2078   case GNUNET_ARM_RESULT_IS_STOPPED_ALREADY:
2079     return _("%s is stopped already");
2080   case GNUNET_ARM_RESULT_IS_NOT_KNOWN:
2081     return _("%s service is not known to ARM");
2082   case GNUNET_ARM_RESULT_START_FAILED:
2083     return _("%s service failed to start");
2084   case GNUNET_ARM_RESULT_IN_SHUTDOWN:
2085     return _("%s service can't be started because ARM is shutting down");
2086   }
2087   return _("%.s Unknown result code.");
2088 }
2089
2090 static void
2091 service_manage_result_cb (void *cls, struct GNUNET_ARM_Handle *arm,
2092                           enum GNUNET_ARM_RequestStatus rs, 
2093                           const char *service, enum GNUNET_ARM_Result result)
2094 {
2095   struct ManageServiceContext *mctx = cls;
2096   char *emsg;
2097
2098   emsg = NULL;
2099   if (GNUNET_YES == mctx->expired)
2100     return;
2101   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
2102   {
2103     GNUNET_asprintf (&emsg, "Error communicating with Peer %u's ARM: %s",
2104                      mctx->peer->id, arm_req_string (rs));
2105     goto ret;
2106   }
2107   if (1 == mctx->start)
2108     goto service_start_check;
2109   if (! ((GNUNET_ARM_RESULT_STOPPED == result)
2110             || (GNUNET_ARM_RESULT_STOPPING == result)
2111             || (GNUNET_ARM_RESULT_IS_STOPPING_ALREADY == result)
2112             || (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY == result)) )
2113   {
2114     /* stopping a service failed */
2115     GNUNET_asprintf (&emsg, arm_ret_string (result), service);
2116     goto ret;
2117   }
2118   /* service stopped successfully */
2119   goto ret;
2120
2121  service_start_check:
2122   if (! ((GNUNET_ARM_RESULT_STARTING == result)
2123             || (GNUNET_ARM_RESULT_IS_STARTING_ALREADY == result)
2124             || (GNUNET_ARM_RESULT_IS_STARTED_ALREADY == result)) )
2125   {
2126     /* starting a service failed */
2127     GNUNET_asprintf (&emsg, arm_ret_string (result), service);
2128     goto ret;
2129   }
2130   /* service started successfully */
2131   
2132  ret:
2133   if (NULL != emsg)
2134   {
2135     LOG_DEBUG ("%s\n", emsg);
2136     GST_send_operation_fail_msg (mctx->client, mctx->op_id, emsg);
2137   }
2138   else
2139     send_operation_success_msg (mctx->client, mctx->op_id);
2140   GNUNET_free (emsg);
2141   cleanup_mctx (mctx);
2142 }
2143
2144 static void
2145 handle_manage_peer_service (void *cls, struct GNUNET_SERVER_Client *client,
2146                             const struct GNUNET_MessageHeader *message)
2147 {
2148   const struct GNUNET_TESTBED_ManagePeerServiceMessage *msg;
2149   const char* service;
2150   struct Peer *peer;
2151   char *emsg;
2152   struct GNUNET_ARM_Handle *ah;
2153   struct ManageServiceContext *mctx;
2154   struct ForwardedOperationContext *fopc;
2155   uint64_t op_id;
2156   uint32_t peer_id;
2157   uint16_t msize;
2158   
2159
2160   msize = ntohs (message->size);
2161   if (msize <= sizeof (struct GNUNET_TESTBED_ManagePeerServiceMessage))
2162   {
2163     GNUNET_break_op (0);  
2164     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2165     return;
2166   }
2167   msg = (const struct GNUNET_TESTBED_ManagePeerServiceMessage *) message;
2168   service = (const char *) &msg[1];  
2169   if ('\0' != service[msize - sizeof
2170                       (struct GNUNET_TESTBED_ManagePeerServiceMessage) - 1])
2171   {
2172     GNUNET_break_op (0);
2173     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2174     return;
2175   }
2176   if (1 < msg->start)
2177   {
2178     GNUNET_break_op (0);
2179     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2180     return;    
2181   }
2182   peer_id = ntohl (msg->peer_id);
2183   op_id = GNUNET_ntohll (msg->operation_id);
2184   LOG_DEBUG ("Received request to manage service %s on peer %u\n",
2185              service, (unsigned int) peer_id);
2186   if ((GST_peer_list_size <= peer_id)
2187       || (NULL == (peer = GST_peer_list[peer_id])))
2188   {
2189     GNUNET_asprintf (&emsg, "Asked to manage service of a non existent peer "
2190                      "with id: %u", peer_id);
2191     goto err_ret;
2192   }
2193   if (0 == strcasecmp ("arm", service))
2194   {
2195     emsg = GNUNET_strdup ("Cannot start/stop peer's ARM service.  "
2196                           "Use peer start/stop for that");
2197     goto err_ret;
2198   }
2199   if (GNUNET_YES == peer->is_remote)
2200   {
2201     /* Forward the destory message to sub controller */
2202     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2203     GNUNET_SERVER_client_keep (client);
2204     fopc->client = client;
2205     fopc->cls = peer;
2206     fopc->type = OP_MANAGE_SERVICE;
2207     fopc->operation_id = op_id;
2208     fopc->opc =
2209         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.
2210                                                slave->controller,
2211                                                fopc->operation_id, &msg->header,
2212                                                &GST_forwarded_operation_reply_relay,
2213                                                fopc);
2214     fopc->timeout_task =
2215         GNUNET_SCHEDULER_add_delayed (GST_timeout, &GST_forwarded_operation_timeout,
2216                                       fopc);
2217     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fopc);
2218     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2219     return;
2220   }
2221   if ((0 != peer->reference_cnt)
2222       && ( (0 == strcasecmp ("core", service))
2223            || (0 == strcasecmp ("transport", service)) )  )
2224   {
2225     GNUNET_asprintf (&emsg, "Cannot stop %s service of peer with id: %u "
2226                      "since it is required by existing operations",
2227                      service, peer_id);
2228     goto err_ret;
2229   }
2230   ah = GNUNET_ARM_connect (peer->details.local.cfg, NULL, NULL);
2231   if (NULL == ah)
2232   {
2233     GNUNET_asprintf (&emsg,
2234                      "Cannot connect to ARM service of peer with id: %u",
2235                      peer_id);
2236     goto err_ret;
2237   }
2238   mctx = GNUNET_malloc (sizeof (struct ManageServiceContext));
2239   mctx->peer = peer;
2240   peer->reference_cnt++;
2241   mctx->op_id = op_id;
2242   mctx->ah = ah;
2243   GNUNET_SERVER_client_keep (client);
2244   mctx->client = client;
2245   mctx->start = msg->start;
2246   GNUNET_CONTAINER_DLL_insert_tail (mctx_head, mctx_tail, mctx);
2247   if (1 == mctx->start)
2248     GNUNET_ARM_request_service_start (mctx->ah, service,
2249                                       GNUNET_OS_INHERIT_STD_ERR,
2250                                       GST_timeout,
2251                                       service_manage_result_cb,
2252                                       mctx);
2253   else
2254     GNUNET_ARM_request_service_stop (mctx->ah, service,
2255                                      GST_timeout,
2256                                      service_manage_result_cb,
2257                                      mctx);  
2258   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2259   return;
2260
2261  err_ret:
2262   LOG (GNUNET_ERROR_TYPE_ERROR, "%s\n", emsg);
2263   GST_send_operation_fail_msg (client, op_id, emsg);
2264   GNUNET_free (emsg);
2265   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2266 }
2267
2268 /**
2269  * Clears the forwarded operations queue
2270  */
2271 static void
2272 clear_fopcq ()
2273 {
2274   struct ForwardedOperationContext *fopc;
2275   
2276   while (NULL != (fopc = fopcq_head))
2277   {
2278     GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fopc);
2279     GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
2280     if (GNUNET_SCHEDULER_NO_TASK != fopc->timeout_task)
2281       GNUNET_SCHEDULER_cancel (fopc->timeout_task);
2282     GNUNET_SERVER_client_drop (fopc->client);
2283     switch (fopc->type)
2284     {
2285     case OP_PEER_CREATE:
2286       GNUNET_free (fopc->cls);
2287       break;
2288     case OP_SHUTDOWN_PEERS:
2289       {
2290         struct HandlerContext_ShutdownPeers *hc = fopc->cls;
2291         
2292         GNUNET_assert (0 < hc->nslaves);
2293         hc->nslaves--;
2294         if (0 == hc->nslaves)
2295           GNUNET_free (hc);
2296       }
2297       break;
2298     case OP_PEER_START:
2299     case OP_PEER_STOP:
2300     case OP_PEER_DESTROY:
2301     case OP_PEER_INFO:
2302     case OP_OVERLAY_CONNECT:
2303     case OP_LINK_CONTROLLERS:
2304     case OP_GET_SLAVE_CONFIG:
2305     case OP_MANAGE_SERVICE:
2306       break;
2307     case OP_FORWARDED:
2308       GNUNET_assert (0);
2309     };
2310     GNUNET_free (fopc);
2311   }
2312 }
2313
2314
2315 /**
2316  * Task run upon timeout of forwarded SHUTDOWN_PEERS operation
2317  *
2318  * @param cls the ForwardedOperationContext
2319  * @param tc the scheduler task context
2320  */
2321 static void
2322 shutdown_peers_timeout_cb (void *cls,
2323                            const struct GNUNET_SCHEDULER_TaskContext *tc)
2324 {
2325   struct ForwardedOperationContext *fo_ctxt = cls;
2326   struct HandlerContext_ShutdownPeers *hc;
2327
2328   fo_ctxt->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2329   hc = fo_ctxt->cls;
2330   hc->timeout = GNUNET_YES;
2331   GNUNET_assert (0 < hc->nslaves);
2332   hc->nslaves--;
2333   if (0 == hc->nslaves)
2334     GST_send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id,
2335                                  "Timeout at a slave controller");
2336   GNUNET_TESTBED_forward_operation_msg_cancel_ (fo_ctxt->opc);  
2337   GNUNET_SERVER_client_drop (fo_ctxt->client);
2338   GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fo_ctxt);
2339   GNUNET_free (fo_ctxt);
2340 }
2341
2342
2343 /**
2344  * The reply msg handler forwarded SHUTDOWN_PEERS operation.  Checks if a
2345  * success reply is received from all clients and then sends the success message
2346  * to the client
2347  *
2348  * @param cls ForwardedOperationContext
2349  * @param msg the message to relay
2350  */
2351 static void
2352 shutdown_peers_reply_cb (void *cls,
2353                          const struct GNUNET_MessageHeader *msg)
2354 {
2355   struct ForwardedOperationContext *fo_ctxt = cls;
2356   struct HandlerContext_ShutdownPeers *hc;
2357   
2358   hc = fo_ctxt->cls;
2359   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != fo_ctxt->timeout_task);
2360   GNUNET_SCHEDULER_cancel (fo_ctxt->timeout_task);
2361   fo_ctxt->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2362   GNUNET_assert (0 < hc->nslaves);
2363   hc->nslaves--;
2364   if (GNUNET_MESSAGE_TYPE_TESTBED_GENERIC_OPERATION_SUCCESS != 
2365       ntohs (msg->type))
2366     hc->timeout = GNUNET_YES;
2367   if (0 == hc->nslaves)
2368   {
2369     if (GNUNET_YES == hc->timeout)
2370       GST_send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id,
2371                                    "Timeout at a slave controller");
2372     else
2373       send_operation_success_msg (fo_ctxt->client, fo_ctxt->operation_id);
2374   }
2375   GNUNET_SERVER_client_drop (fo_ctxt->client);
2376   GNUNET_CONTAINER_DLL_remove (fopcq_head, fopcq_tail, fo_ctxt);
2377   GNUNET_free (fo_ctxt);
2378 }
2379
2380
2381 /**
2382  * Stops and destroys all peers
2383  */
2384 static void
2385 destroy_peers ()
2386 {
2387   struct Peer *peer;
2388   unsigned int id;
2389
2390   if (NULL == GST_peer_list)
2391     return;
2392   for (id = 0; id < GST_peer_list_size; id++)
2393   {
2394     peer = GST_peer_list[id];
2395     if (NULL == peer)
2396       continue;
2397     /* If destroy flag is set it means that this peer should have been
2398      * destroyed by a context which we destroy before */
2399     GNUNET_break (GNUNET_NO == peer->destroy_flag);
2400     /* counter should be zero as we free all contexts before */
2401     GNUNET_break (0 == peer->reference_cnt);
2402     if ((GNUNET_NO == peer->is_remote) &&
2403         (GNUNET_YES == peer->details.local.is_running))
2404       GNUNET_TESTING_peer_kill (peer->details.local.peer);
2405   }
2406   for (id = 0; id < GST_peer_list_size; id++)
2407   {
2408     peer = GST_peer_list[id];
2409     if (NULL == peer)
2410       continue;    
2411     if (GNUNET_NO == peer->is_remote)
2412     {
2413       if (GNUNET_YES == peer->details.local.is_running)
2414         GNUNET_TESTING_peer_wait (peer->details.local.peer);
2415       GNUNET_TESTING_peer_destroy (peer->details.local.peer);
2416       GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
2417     }
2418     GNUNET_free (peer);
2419   }
2420   GNUNET_free_non_null (GST_peer_list);
2421   GST_peer_list = NULL;
2422   GST_peer_list_size = 0;
2423 }
2424
2425
2426 /**
2427  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_SHUTDOWN_PEERS messages
2428  *
2429  * @param cls NULL
2430  * @param client identification of the client
2431  * @param message the actual message
2432  */
2433 static void
2434 handle_shutdown_peers (void *cls, struct GNUNET_SERVER_Client *client,
2435                        const struct GNUNET_MessageHeader *message)
2436 {
2437   const struct GNUNET_TESTBED_ShutdownPeersMessage *msg;
2438   struct HandlerContext_ShutdownPeers *hc;
2439   struct Slave *slave;
2440   struct ForwardedOperationContext *fo_ctxt;
2441   uint64_t op_id;
2442   unsigned int cnt;
2443
2444   msg = (const struct GNUNET_TESTBED_ShutdownPeersMessage *) message;
2445   LOG_DEBUG ("Received SHUTDOWN_PEERS\n");
2446     /* Stop and destroy all peers */
2447   free_mctxq ();
2448   GST_free_occq ();
2449   GST_free_roccq ();
2450   clear_fopcq ();
2451   /* Forward to all slaves which we have started */
2452   op_id = GNUNET_ntohll (msg->operation_id);
2453   hc = GNUNET_malloc (sizeof (struct HandlerContext_ShutdownPeers));
2454   /* FIXME: have a better implementation where we track which slaves are
2455      started by this controller */
2456   for (cnt = 0; cnt < GST_slave_list_size; cnt++)
2457   {
2458     slave = GST_slave_list[cnt];
2459     if (NULL == slave)
2460       continue;
2461     if (NULL == slave->controller_proc) /* We didn't start the slave */
2462       continue;
2463     LOG_DEBUG ("Forwarding SHUTDOWN_PEERS\n");
2464     hc->nslaves++;
2465     fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
2466     GNUNET_SERVER_client_keep (client);
2467     fo_ctxt->client = client;
2468     fo_ctxt->operation_id = op_id;
2469     fo_ctxt->cls = hc;
2470     fo_ctxt->type = OP_SHUTDOWN_PEERS;
2471     fo_ctxt->opc =
2472         GNUNET_TESTBED_forward_operation_msg_ (slave->controller,
2473                                                fo_ctxt->operation_id,
2474                                                &msg->header,
2475                                                shutdown_peers_reply_cb,
2476                                                fo_ctxt);
2477     fo_ctxt->timeout_task =
2478         GNUNET_SCHEDULER_add_delayed (GST_timeout, &shutdown_peers_timeout_cb,
2479                                       fo_ctxt);
2480     GNUNET_CONTAINER_DLL_insert_tail (fopcq_head, fopcq_tail, fo_ctxt);
2481   }
2482   LOG_DEBUG ("Shutting down peers\n");
2483   destroy_peers ();
2484   if (0 == hc->nslaves)
2485   {
2486     send_operation_success_msg (client, op_id);
2487     GNUNET_free (hc);
2488   }
2489   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
2490 }
2491
2492
2493 /**
2494  * Iterator over hash map entries.
2495  *
2496  * @param cls closure
2497  * @param key current key code
2498  * @param value value in the hash map
2499  * @return GNUNET_YES if we should continue to
2500  *         iterate,
2501  *         GNUNET_NO if not.
2502  */
2503 static int
2504 ss_map_free_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
2505 {
2506   struct SharedService *ss = value;
2507
2508   GNUNET_assert (GNUNET_YES ==
2509                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
2510   GNUNET_free (ss->name);
2511   GNUNET_free (ss);
2512   return GNUNET_YES;
2513 }
2514
2515
2516 /**
2517  * Iterator for freeing hash map entries in a slave's reghost_map
2518  *
2519  * @param cls handle to the slave
2520  * @param key current key code
2521  * @param value value in the hash map
2522  * @return GNUNET_YES if we should continue to
2523  *         iterate,
2524  *         GNUNET_NO if not.
2525  */
2526 static int
2527 reghost_free_iterator (void *cls, const struct GNUNET_HashCode *key,
2528                        void *value)
2529 {
2530   struct Slave *slave = cls;
2531   struct RegisteredHostContext *rhc = value;
2532   struct ForwardedOverlayConnectContext *focc;
2533
2534   GNUNET_assert (GNUNET_YES ==
2535                  GNUNET_CONTAINER_multihashmap_remove (slave->reghost_map, key,
2536                                                        value));
2537   while (NULL != (focc = rhc->focc_dll_head))
2538   {
2539     GNUNET_CONTAINER_DLL_remove (rhc->focc_dll_head, rhc->focc_dll_tail, focc);
2540     GST_cleanup_focc (focc);
2541   }
2542   if (NULL != rhc->sub_op)
2543     GNUNET_TESTBED_operation_done (rhc->sub_op);
2544   if (NULL != rhc->client)
2545     GNUNET_SERVER_client_drop (rhc->client);
2546   GNUNET_free (value);
2547   return GNUNET_YES;
2548 }
2549
2550
2551 /**
2552  * Task to clean up and shutdown nicely
2553  *
2554  * @param cls NULL
2555  * @param tc the TaskContext from scheduler
2556  */
2557 static void
2558 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2559 {
2560   struct LCFContextQueue *lcfq;
2561   struct MessageQueue *mq_entry;
2562   uint32_t id;
2563
2564   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
2565   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
2566   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
2567                                                 NULL);
2568   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
2569   /* cleanup any remaining forwarded operations */
2570   clear_fopcq ();
2571   if (NULL != lcfq_head)
2572   {
2573     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
2574     {
2575       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
2576       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
2577     }
2578   }
2579   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2580   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
2581   {
2582     GNUNET_SERVER_client_drop (lcfq->lcf->client);
2583     GNUNET_assert (NULL != lcfq->lcf->cfg);
2584     GNUNET_CONFIGURATION_destroy (lcfq->lcf->cfg);
2585     GNUNET_free (lcfq->lcf);
2586     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
2587     GNUNET_free (lcfq);
2588   }
2589   free_mctxq ();
2590   GST_free_occq ();
2591   GST_free_roccq ();
2592   /* Clear peer list */
2593   destroy_peers ();
2594   /* Clear host list */
2595   for (id = 0; id < GST_host_list_size; id++)
2596     if (NULL != GST_host_list[id])
2597       GNUNET_TESTBED_host_destroy (GST_host_list[id]);
2598   GNUNET_free_non_null (GST_host_list);
2599   /* Clear route list */
2600   for (id = 0; id < route_list_size; id++)
2601     if (NULL != route_list[id])
2602       GNUNET_free (route_list[id]);
2603   GNUNET_free_non_null (route_list);
2604   /* Clear GST_slave_list */
2605   for (id = 0; id < GST_slave_list_size; id++)
2606     if (NULL != GST_slave_list[id])
2607     {
2608       struct HostRegistration *hr_entry;
2609
2610       while (NULL != (hr_entry = GST_slave_list[id]->hr_dll_head))
2611       {
2612         GNUNET_CONTAINER_DLL_remove (GST_slave_list[id]->hr_dll_head,
2613                                      GST_slave_list[id]->hr_dll_tail, hr_entry);
2614         GNUNET_free (hr_entry);
2615       }
2616       if (NULL != GST_slave_list[id]->rhandle)
2617         GNUNET_TESTBED_cancel_registration (GST_slave_list[id]->rhandle);
2618       (void)
2619           GNUNET_CONTAINER_multihashmap_iterate (GST_slave_list
2620                                                  [id]->reghost_map,
2621                                                  reghost_free_iterator,
2622                                                  GST_slave_list[id]);
2623       GNUNET_CONTAINER_multihashmap_destroy (GST_slave_list[id]->reghost_map);
2624       if (NULL != GST_slave_list[id]->controller)
2625         GNUNET_TESTBED_controller_disconnect (GST_slave_list[id]->controller);
2626       if (NULL != GST_slave_list[id]->controller_proc)
2627         GNUNET_TESTBED_controller_stop (GST_slave_list[id]->controller_proc);
2628       GNUNET_free (GST_slave_list[id]);
2629     }
2630   GNUNET_free_non_null (GST_slave_list);
2631   if (NULL != GST_context)
2632   {
2633     GNUNET_free_non_null (GST_context->master_ip);
2634     if (NULL != GST_context->system)
2635       GNUNET_TESTING_system_destroy (GST_context->system, GNUNET_YES);
2636     GNUNET_SERVER_client_drop (GST_context->client);
2637     GNUNET_free (GST_context);
2638     GST_context = NULL;
2639   }
2640   if (NULL != transmit_handle)
2641     GNUNET_SERVER_notify_transmit_ready_cancel (transmit_handle);
2642   while (NULL != (mq_entry = mq_head))
2643   {
2644     GNUNET_free (mq_entry->msg);
2645     GNUNET_SERVER_client_drop (mq_entry->client);
2646     GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
2647     GNUNET_free (mq_entry);
2648   }
2649   GNUNET_free_non_null (hostname);
2650   GNUNET_CONFIGURATION_destroy (our_config);
2651   /* Free hello cache */
2652   GST_cache_clear ();
2653   GNUNET_TESTBED_operation_queue_destroy_ (GST_opq_openfds);
2654   GST_opq_openfds = NULL;
2655 }
2656
2657
2658 /**
2659  * Callback for client disconnect
2660  *
2661  * @param cls NULL
2662  * @param client the client which has disconnected
2663  */
2664 static void
2665 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
2666 {
2667   if (NULL == GST_context)
2668     return;
2669   if (client == GST_context->client)
2670   {
2671     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
2672     /* should not be needed as we're terminated by failure to read
2673      * from stdin, but if stdin fails for some reason, this shouldn't
2674      * hurt for now --- might need to revise this later if we ever
2675      * decide that master connections might be temporarily down
2676      * for some reason */
2677     //GNUNET_SCHEDULER_shutdown ();
2678   }
2679 }
2680
2681
2682 /**
2683  * Testbed setup
2684  *
2685  * @param cls closure
2686  * @param server the initialized server
2687  * @param cfg configuration to use
2688  */
2689 static void
2690 testbed_run (void *cls, struct GNUNET_SERVER_Handle *server,
2691              const struct GNUNET_CONFIGURATION_Handle *cfg)
2692 {
2693   static const struct GNUNET_SERVER_MessageHandler message_handlers[] = {
2694     {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
2695     {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADD_HOST, 0},
2696     {&handle_configure_shared_service, NULL,
2697      GNUNET_MESSAGE_TYPE_TESTBED_SHARE_SERVICE, 0},
2698     {&handle_link_controllers, NULL,
2699      GNUNET_MESSAGE_TYPE_TESTBED_LINK_CONTROLLERS, 0},
2700     {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATE_PEER, 0},
2701     {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROY_PEER,
2702      sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
2703     {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_START_PEER,
2704      sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
2705     {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOP_PEER,
2706      sizeof (struct GNUNET_TESTBED_PeerStopMessage)},
2707     {&handle_peer_get_config, NULL,
2708      GNUNET_MESSAGE_TYPE_TESTBED_GET_PEER_CONFIGURATION,
2709      sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
2710     {&GST_handle_overlay_connect, NULL,
2711      GNUNET_MESSAGE_TYPE_TESTBED_OVERLAY_CONNECT,
2712      sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
2713     {&GST_handle_remote_overlay_connect, NULL,
2714      GNUNET_MESSAGE_TYPE_TESTBED_REMOTE_OVERLAY_CONNECT, 0},
2715     {&handle_manage_peer_service, NULL,
2716      GNUNET_MESSAGE_TYPE_TESTBED_MANAGE_PEER_SERVICE, 0},
2717     {&handle_slave_get_config, NULL,
2718      GNUNET_MESSAGE_TYPE_TESTBED_GET_SLAVE_CONFIGURATION,
2719      sizeof (struct GNUNET_TESTBED_SlaveGetConfigurationMessage)},
2720     {&handle_shutdown_peers, NULL, GNUNET_MESSAGE_TYPE_TESTBED_SHUTDOWN_PEERS,
2721      sizeof (struct GNUNET_TESTBED_ShutdownPeersMessage)},
2722     {NULL}
2723   };
2724   char *logfile;
2725   unsigned long long num;
2726
2727   if (GNUNET_OK ==
2728       GNUNET_CONFIGURATION_get_value_filename (cfg, "TESTBED", "LOG_FILE",
2729                                                &logfile))
2730   {
2731     GNUNET_break (GNUNET_OK == GNUNET_log_setup ("testbed", "DEBUG", logfile));
2732     GNUNET_free (logfile);
2733   }
2734   GNUNET_assert (GNUNET_OK ==
2735                  GNUNET_CONFIGURATION_get_value_number (cfg, "TESTBED",
2736                                                         "CACHE_SIZE", &num));
2737   GST_cache_init ((unsigned int) num);
2738   GNUNET_assert (GNUNET_OK ==
2739                  GNUNET_CONFIGURATION_get_value_number (cfg, "TESTBED",
2740                                                         "MAX_OPEN_FDS", &num));
2741   GST_opq_openfds = GNUNET_TESTBED_operation_queue_create_ ((unsigned int) num);
2742   GNUNET_assert (GNUNET_OK ==
2743                  GNUNET_CONFIGURATION_get_value_time (cfg, "TESTBED",
2744                                                       "OPERATION_TIMEOUT",
2745                                                       (struct
2746                                                        GNUNET_TIME_Relative *)
2747                                                       &GST_timeout));
2748   GNUNET_assert (GNUNET_OK ==
2749                  GNUNET_CONFIGURATION_get_value_string (cfg, "testbed",
2750                                                         "HOSTNAME", &hostname));  
2751   our_config = GNUNET_CONFIGURATION_dup (cfg);
2752   GNUNET_SERVER_add_handlers (server, message_handlers);
2753   GNUNET_SERVER_disconnect_notify (server, &client_disconnect_cb, NULL);
2754   ss_map = GNUNET_CONTAINER_multihashmap_create (5, GNUNET_NO);
2755   shutdown_task_id =
2756       GNUNET_SCHEDULER_add_delayed_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
2757                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
2758                                                   &shutdown_task, NULL);
2759   LOG_DEBUG ("Testbed startup complete\n");
2760   event_mask = 1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED;
2761 }
2762
2763
2764 /**
2765  * The starting point of execution
2766  */
2767 int
2768 main (int argc, char *const *argv)
2769 {
2770   //sleep (15);                 /* Debugging */
2771   return (GNUNET_OK ==
2772           GNUNET_SERVICE_run (argc, argv, "testbed", GNUNET_SERVICE_OPTION_NONE,
2773                               &testbed_run, NULL)) ? 0 : 1;
2774 }
2775
2776 /* end of gnunet-service-testbed.c */