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