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