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