unstable checkpoint save
[oweals/gnunet.git] / src / testbed / gnunet-service-testbed.c
1 /*
2   This file is part of GNUnet.
3   (C) 2012 Christian Grothoff (and other contributing authors)
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 2, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file testbed/gnunet-service-testbed.c
23  * @brief implementation of the TESTBED service
24  * @author Sree Harsha Totakura
25  */
26
27 #include "platform.h"
28 #include "gnunet_service_lib.h"
29 #include "gnunet_server_lib.h"
30 #include "gnunet_transport_service.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_hello_lib.h"
33 #include <zlib.h>
34
35 #include "gnunet_testbed_service.h"
36 #include "testbed.h"
37 #include "testbed_api.h"
38 #include "testbed_api_hosts.h"
39 #include "gnunet_testing_lib-new.h"
40
41 /**
42  * Generic logging
43  */
44 #define LOG(kind,...)                           \
45   GNUNET_log (kind, __VA_ARGS__)
46
47 /**
48  * Debug logging
49  */
50 #define LOG_DEBUG(...)                          \
51   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
52
53 /**
54  * By how much should the arrays lists grow
55  */
56 #define LIST_GROW_STEP 10
57
58 /**
59  * Default timeout for operations which may take some time
60  */
61 #define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
62
63 /**
64  * The main context information associated with the client which started us
65  */
66 struct Context
67 {
68   /**
69    * The client handle associated with this context
70    */
71   struct GNUNET_SERVER_Client *client;
72
73   /**
74    * The network address of the master controller
75    */
76   char *master_ip;
77
78   /**
79    * The TESTING system handle for starting peers locally
80    */
81   struct GNUNET_TESTING_System *system;
82
83   /**
84    * Event mask of event to be responded in this context
85    */
86   uint64_t event_mask;
87
88   /**
89    * Our host id according to this context
90    */
91   uint32_t host_id;
92 };
93
94
95 /**
96  * The message queue for sending messages to clients
97  */
98 struct MessageQueue
99 {
100   /**
101    * The message to be sent
102    */
103   struct GNUNET_MessageHeader *msg;
104
105   /**
106    * The client to send the message to
107    */
108   struct GNUNET_SERVER_Client *client;
109
110   /**
111    * next pointer for DLL
112    */
113   struct MessageQueue *next;
114
115   /**
116    * prev pointer for DLL
117    */
118   struct MessageQueue *prev;
119 };
120
121
122 /**
123  * The structure for identifying a shared service
124  */
125 struct SharedService
126 {
127   /**
128    * The name of the shared service
129    */
130   char *name;
131
132   /**
133    * Number of shared peers per instance of the shared service
134    */
135   uint32_t num_shared;
136
137   /**
138    * Number of peers currently sharing the service
139    */
140   uint32_t num_sharing;
141 };
142
143
144 /**
145  * A routing entry
146  */
147 struct Route
148 {
149   /**
150    * destination host
151    */
152   uint32_t dest;
153
154   /**
155    * The host destination is reachable thru
156    */
157   uint32_t thru;
158 };
159
160
161 /**
162  * Structure representing a connected(directly-linked) controller
163  */
164 struct Slave
165 {
166   /**
167    * The controller process handle if we had started the controller
168    */
169   struct GNUNET_TESTBED_ControllerProc *controller_proc;
170
171   /**
172    * The controller handle
173    */
174   struct GNUNET_TESTBED_Controller *controller;
175
176   /**
177    * The id of the host this controller is running on
178    */
179   uint32_t host_id;
180 };
181
182
183 /**
184  * States of LCFContext
185  */
186 enum LCFContextState
187 {
188   /**
189    * The Context has been initialized; Nothing has been done on it
190    */
191   INIT,
192
193   /**
194    * Delegated host has been registered at the forwarding controller
195    */
196   DELEGATED_HOST_REGISTERED,
197   
198   /**
199    * The slave host has been registred at the forwarding controller
200    */
201   SLAVE_HOST_REGISTERED,
202   
203   /**
204    * The context has been finished (may have error)
205    */
206   FINISHED
207 };
208
209
210 /**
211  * Link controllers request forwarding context
212  */
213 struct LCFContext
214 {
215   /**
216    * The gateway which will pass the link message to delegated host
217    */
218   struct Slave *gateway;
219
220   /**
221    * The controller link message that has to be forwarded to
222    */
223   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
224
225   /**
226    * The client which has asked to perform this operation
227    */
228   struct GNUNET_SERVER_Client *client;
229
230   /**
231    * The host registration handle while registered hosts in this context
232    */
233   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
234
235   /**
236    * The id of the operation which created this context
237    */
238   uint64_t operation_id;
239
240   /**
241    * The state of this context
242    */
243   enum LCFContextState state;
244
245   /**
246    * The delegated host
247    */
248   uint32_t delegated_host_id;
249
250   /**
251    * The slave host
252    */
253   uint32_t slave_host_id;
254
255 };
256
257
258 /**
259  * Structure of a queue entry in LCFContext request queue
260  */
261 struct LCFContextQueue
262 {
263   /**
264    * The LCFContext
265    */
266   struct LCFContext *lcf;
267
268   /**
269    * Head prt for DLL
270    */
271   struct LCFContextQueue *next;
272
273   /**
274    * Tail ptr for DLL
275    */
276   struct LCFContextQueue *prev;
277 };
278
279
280 /**
281  * A locally started peer
282  */
283 struct Peer
284 {
285   union
286   {
287     struct
288     {
289       /**
290        * The peer handle from testing API
291        */
292       struct GNUNET_TESTING_Peer *peer;
293
294       /**
295        * The modified (by GNUNET_TESTING_peer_configure) configuration this
296        * peer is configured with
297        */
298       struct GNUNET_CONFIGURATION_Handle *cfg;
299       
300       /**
301        * Is the peer running
302        */
303       int is_running;
304
305     } local;
306
307     struct
308     {
309       /**
310        * The controller this peer is started through
311        */
312       struct GNUNET_TESTBED_Controller *controller;
313
314     } remote;
315
316   } details;
317
318   /**
319    * Is this peer locally created?
320    */
321   int is_remote;
322
323   /**
324    * Our local reference id for this peer
325    */
326   uint32_t id;
327
328 };
329
330
331 /**
332  * Context information for connecting 2 peers in overlay
333  */
334 struct OverlayConnectContext
335 {
336   /**
337    * The client which has requested for overlay connection
338    */
339   struct GNUNET_SERVER_Client *client;
340
341   /**
342    * the peer which has to connect to the other peer
343    */
344   struct Peer *peer;
345
346   /**
347    * The other peer
348    */
349   struct Peer *other_peer;
350
351   /**
352    * Transport handle of the first peer to get its HELLO
353    */
354   struct GNUNET_TRANSPORT_Handle *p1th;
355
356   /**
357    * Transport handle of other peer to offer first peer's HELLO
358    */
359   struct GNUNET_TRANSPORT_Handle *p2th;
360
361   /**
362    * Core handles of the first peer; used to notify when second peer connects to it
363    */
364   struct GNUNET_CORE_Handle *ch;
365
366   /**
367    * HELLO of the other peer
368    */
369   struct GNUNET_MessageHeader *hello;
370
371   /**
372    * Get hello handle to acquire HELLO of first peer
373    */
374   struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
375
376   /**
377    * The error message we send if this overlay connect operation has timed out
378    */
379   char *emsg;
380
381   /**
382    * The peer identity of the first peer
383    */
384   struct GNUNET_PeerIdentity peer_identity;
385
386   /**
387    * The peer identity of the other peer
388    */
389   struct GNUNET_PeerIdentity other_peer_identity;
390
391   /**
392    * The id of the operation responsible for creating this context
393    */
394   uint64_t op_id;
395
396   /**
397    * The id of the task for sending HELLO of peer 2 to peer 1 and ask peer 1 to
398    * connect to peer 2
399    */
400   GNUNET_SCHEDULER_TaskIdentifier send_hello_task;
401
402   /**
403    * The id of the overlay connect timeout task
404    */
405   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
406
407 };
408
409
410 /**
411  * Context information for operations forwarded to subcontrollers
412  */
413 struct ForwardedOperationContext
414 {
415   /**
416    * The generated operation context
417    */
418   struct OperationContext *opc;
419
420   /**
421    * The client to which we have to reply
422    */
423   struct GNUNET_SERVER_Client *client;
424
425   /**
426    * Closure pointer
427    */
428   void *cls;
429
430   /**
431    * Task ID for the timeout task
432    */
433   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
434
435   /**
436    * The id of the operation that has been forwarded
437    */
438   uint64_t operation_id;
439
440 };
441
442
443 /**
444  * Context information used while linking controllers
445  */
446 struct LinkControllersContext
447 {
448   /**
449    * The client which initiated the link controller operation
450    */
451   struct GNUNET_SERVER_Client *client;
452
453   /**
454    * The ID of the operation
455    */
456   uint64_t operation_id;
457
458   /**
459    * Pointer to the slave handle if we are directly starting/connecting to the controller
460    */
461   struct Slave *slave;
462 };
463
464
465
466 /**
467  * The master context; generated with the first INIT message
468  */
469 static struct Context *master_context;
470
471 /***********/
472 /* Handles */
473 /***********/
474
475 /**
476  * Current Transmit Handle; NULL if no notify transmit exists currently
477  */
478 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
479
480 /****************/
481 /* Lists & Maps */
482 /****************/
483
484 /**
485  * The head for the LCF queue
486  */
487 static struct LCFContextQueue *lcfq_head;
488
489 /**
490  * The tail for the LCF queue
491  */
492 static struct LCFContextQueue *lcfq_tail;
493
494 /**
495  * The message queue head
496  */
497 static struct MessageQueue *mq_head;
498
499 /**
500  * The message queue tail
501  */
502 static struct MessageQueue *mq_tail;
503
504 /**
505  * Array of host list
506  */
507 static struct GNUNET_TESTBED_Host **host_list;
508
509 /**
510  * A list of routes
511  */
512 static struct Route **route_list;
513
514 /**
515  * A list of directly linked neighbours
516  */
517 static struct Slave **slave_list;
518
519 /**
520  * A list of peers we own locally
521  */
522 static struct Peer **peer_list;
523
524 /**
525  * The hashmap of shared services
526  */
527 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
528
529 /**
530  * The size of the host list
531  */
532 static uint32_t host_list_size;
533
534 /**
535  * The size of the route list
536  */
537 static uint32_t route_list_size;
538
539 /**
540  * The size of directly linked neighbours list
541  */
542 static uint32_t slave_list_size;
543
544 /**
545  * The size of the peer list
546  */
547 static uint32_t peer_list_size;
548
549 /*********/
550 /* Tasks */
551 /*********/
552
553 /**
554  * The lcf_task handle
555  */
556 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
557
558 /**
559  * The shutdown task handle
560  */
561 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
562
563
564 /**
565  * Function called to notify a client about the connection begin ready to queue
566  * more data.  "buf" will be NULL and "size" zero if the connection was closed
567  * for writing in the meantime.
568  *
569  * @param cls NULL
570  * @param size number of bytes available in buf
571  * @param buf where the callee should write the message
572  * @return number of bytes written to buf
573  */
574 static size_t
575 transmit_ready_notify (void *cls, size_t size, void *buf)
576 {
577   struct MessageQueue *mq_entry;
578
579   transmit_handle = NULL;
580   mq_entry = mq_head;
581   GNUNET_assert (NULL != mq_entry);
582   if (0 == size)
583     return 0;
584   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
585   size = ntohs (mq_entry->msg->size);
586   memcpy (buf, mq_entry->msg, size);
587   GNUNET_free (mq_entry->msg);
588   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
589   GNUNET_free (mq_entry);
590   mq_entry = mq_head;
591   if (NULL != mq_entry)
592     transmit_handle =
593         GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
594                                              ntohs (mq_entry->msg->size),
595                                              GNUNET_TIME_UNIT_FOREVER_REL,
596                                              &transmit_ready_notify, NULL);
597   return size;
598 }
599
600
601 /**
602  * Queues a message in send queue for sending to the service
603  *
604  * @param client the client to whom the queued message has to be sent
605  * @param msg the message to queue
606  */
607 static void
608 queue_message (struct GNUNET_SERVER_Client *client,
609                struct GNUNET_MessageHeader *msg)
610 {
611   struct MessageQueue *mq_entry;
612   uint16_t type;
613   uint16_t size;
614
615   type = ntohs (msg->type);
616   size = ntohs (msg->size);
617   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
618                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));
619   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
620   mq_entry->msg = msg;
621   mq_entry->client = client;
622   LOG_DEBUG ("Queueing message of type %u, size %u for sending\n", type,
623              ntohs (msg->size));
624   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
625   if (NULL == transmit_handle)
626     transmit_handle =
627         GNUNET_SERVER_notify_transmit_ready (client, size,
628                                              GNUNET_TIME_UNIT_FOREVER_REL,
629                                              &transmit_ready_notify, NULL);
630 }
631
632
633 /**
634  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
635  *
636  * @param ptr the memory block to realloc
637  * @param size the size of ptr
638  * @param new_size the size to which ptr has to be realloc'ed
639  * @return the newly reallocated memory block
640  */
641 static void *
642 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
643 {
644   ptr = GNUNET_realloc (ptr, new_size);
645   if (new_size > size)
646     ptr = memset (ptr + size, 0, new_size - size);
647   return ptr;
648 }
649
650
651 /**
652  * Function to add a host to the current list of known hosts
653  *
654  * @param host the host to add
655  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
656  *           already in use
657  */
658 static int
659 host_list_add (struct GNUNET_TESTBED_Host *host)
660 {
661   uint32_t host_id;
662
663   host_id = GNUNET_TESTBED_host_get_id_ (host);
664   if (host_list_size <= host_id)
665   {
666     host_list =
667         TESTBED_realloc (host_list,
668                          sizeof (struct GNUNET_TESTBED_Host *) * host_list_size,
669                          sizeof (struct GNUNET_TESTBED_Host *) *
670                          (host_list_size + LIST_GROW_STEP));
671     host_list_size += LIST_GROW_STEP;
672   }
673   if (NULL != host_list[host_id])
674   {
675     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
676     return GNUNET_SYSERR;
677   }
678   host_list[host_id] = host;
679   return GNUNET_OK;
680 }
681
682
683 /**
684  * Adds a route to the route list
685  *
686  * @param route the route to add
687  */
688 static void
689 route_list_add (struct Route *route)
690 {
691   if (route->dest >= route_list_size)
692   {
693     route_list =
694         TESTBED_realloc (route_list, sizeof (struct Route *) * route_list_size,
695                          sizeof (struct Route *) * (route_list_size +
696                                                     LIST_GROW_STEP));
697     route_list_size += LIST_GROW_STEP;
698   }
699   GNUNET_assert (NULL == route_list[route->dest]);
700   route_list[route->dest] = route;
701 }
702
703
704 /**
705  * Adds a slave to the slave array
706  *
707  * @param slave the slave controller to add
708  */
709 static void
710 slave_list_add (struct Slave *slave)
711 {
712   if (slave->host_id >= slave_list_size)
713   {
714     slave_list =
715         TESTBED_realloc (slave_list, sizeof (struct Slave *) * slave_list_size,
716                          sizeof (struct Slave *) * (slave_list_size +
717                                                     LIST_GROW_STEP));
718     slave_list_size += LIST_GROW_STEP;
719   }
720   GNUNET_assert (NULL == slave_list[slave->host_id]);
721   slave_list[slave->host_id] = slave;
722 }
723
724
725 /**
726  * Adds a peer to the peer array
727  *
728  * @param peer the peer to add
729  */
730 static void
731 peer_list_add (struct Peer *peer)
732 {
733   uint32_t orig_size;
734
735   orig_size = peer_list_size;
736   if (peer->id >= peer_list_size)
737   {
738     while (peer->id >= peer_list_size)
739       peer_list_size += LIST_GROW_STEP;
740     peer_list =
741         TESTBED_realloc (peer_list, sizeof (struct Peer *) * orig_size,
742                          sizeof (struct Peer *) * peer_list_size);
743   }
744   GNUNET_assert (NULL == peer_list[peer->id]);
745   peer_list[peer->id] = peer;
746 }
747
748
749 /**
750  * Removes a the give peer from the peer array
751  *
752  * @param peer the peer to be removed
753  */
754 static void
755 peer_list_remove (struct Peer *peer)
756 {
757   uint32_t id;
758   uint32_t orig_size;
759
760   peer_list[peer->id] = NULL;
761   orig_size = peer_list_size;
762   while (peer_list_size >= LIST_GROW_STEP)
763   {
764     for (id = peer_list_size - 1;
765          (id >= peer_list_size - LIST_GROW_STEP) && (id != UINT32_MAX); id--)
766       if (NULL != peer_list[id])
767         break;
768     if (id != ((peer_list_size - LIST_GROW_STEP) - 1))
769       break;
770     peer_list_size -= LIST_GROW_STEP;
771   }
772   if (orig_size == peer_list_size)
773     return;
774   peer_list =
775       GNUNET_realloc (peer_list, sizeof (struct Peer *) * peer_list_size);
776 }
777
778
779 /**
780  * Finds the route with directly connected host as destination through which
781  * the destination host can be reached
782  *
783  * @param host_id the id of the destination host
784  * @return the route with directly connected destination host; NULL if no route
785  *           is found
786  */
787 static struct Route *
788 find_dest_route (uint32_t host_id)
789 {
790   struct Route *route;
791
792   while (NULL != (route = route_list[host_id]))
793   {
794     if (route->thru == master_context->host_id)
795       break;
796     host_id = route->thru;
797   }
798   return route;
799 }
800
801
802 /**
803  * Routes message to a host given its host_id
804  *
805  * @param host_id the id of the destination host
806  * @param msg the message to be routed
807  */
808 static void
809 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
810 {
811   GNUNET_break (0);
812 }
813
814
815 /**
816  * Send operation failure message to client
817  *
818  * @param client the client to which the failure message has to be sent to
819  * @param operation_id the id of the failed operation
820  * @param emsg the error message; can be NULL
821  */
822 static void
823 send_operation_fail_msg (struct GNUNET_SERVER_Client *client,
824                          uint64_t operation_id, const char *emsg)
825 {
826   struct GNUNET_TESTBED_OperationFailureEventMessage *msg;
827   uint16_t msize;
828   uint16_t emsg_len;
829
830   msize = sizeof (struct GNUNET_TESTBED_OperationFailureEventMessage);
831   emsg_len = (NULL == emsg) ? 0 : strlen (emsg) + 1;
832   msize += emsg_len;
833   msg = GNUNET_malloc (msize);
834   msg->header.size = htons (msize);
835   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_OPERATIONFAILEVENT);
836   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
837   msg->operation_id = GNUNET_htonll (operation_id);
838   if (0 != emsg_len)
839     memcpy (&msg[1], emsg, emsg_len);
840   queue_message (client, &msg->header);
841 }
842
843
844 /**
845  * Function to send generic operation success message to given client
846  *
847  * @param client the client to send the message to
848  * @param operation_id the id of the operation which was successful
849  */
850 static void
851 send_operation_success_msg (struct GNUNET_SERVER_Client *client,
852                             uint64_t operation_id)
853 {
854   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg;
855   uint16_t msize;
856
857   msize = sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
858   msg = GNUNET_malloc (msize);
859   msg->header.size = htons (msize);
860   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
861   msg->operation_id = GNUNET_htonll (operation_id);
862   msg->event_type = htonl (GNUNET_TESTBED_ET_OPERATION_FINISHED);
863   queue_message (client, &msg->header);
864 }
865
866
867 /**
868  * The  Link Controller forwarding task
869  *
870  * @param cls the LCFContext
871  * @param tc the Task context from scheduler
872  */
873 static void
874 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
875
876
877 /**
878  * Completion callback for host registrations while forwarding Link Controller messages
879  *
880  * @param cls the LCFContext
881  * @param emsg the error message; NULL if host registration is successful
882  */
883 static void
884 lcf_proc_cc (void *cls, const char *emsg)
885 {
886   struct LCFContext *lcf = cls;
887
888   lcf->rhandle = NULL;
889   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
890   switch (lcf->state)
891   {
892   case INIT:
893     if (NULL != emsg)
894       goto registration_error;
895     lcf->state = DELEGATED_HOST_REGISTERED;
896     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
897     break;
898   case DELEGATED_HOST_REGISTERED:
899     if (NULL != emsg)
900       goto registration_error;
901     lcf->state = SLAVE_HOST_REGISTERED;
902     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
903     break;
904   default:
905     GNUNET_assert (0);          /* Shouldn't reach here */
906   }
907   return;
908
909  registration_error:
910   LOG (GNUNET_ERROR_TYPE_WARNING, "Host registration failed with message: %s\n",
911        emsg);
912   lcf->state = FINISHED;
913   lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
914 }
915
916
917 /**
918  * Callback to be called when forwarded link controllers operation is
919  * successfull. We have to relay the reply msg back to the client
920  *
921  * @param cls ForwardedOperationContext
922  * @param msg the peer create success message
923  */
924 static void
925 forwarded_operation_reply_relay (void *cls,
926                                  const struct GNUNET_MessageHeader *msg)
927 {
928   struct ForwardedOperationContext *fopc = cls;
929   struct GNUNET_MessageHeader *dup_msg;
930   uint16_t msize;
931
932   msize = ntohs (msg->size);
933   dup_msg = GNUNET_malloc (msize);
934   (void) memcpy (dup_msg, msg, msize);
935   queue_message (fopc->client, dup_msg);
936   GNUNET_SERVER_client_drop (fopc->client);
937   GNUNET_SCHEDULER_cancel (fopc->timeout_task);
938   GNUNET_free (fopc);
939 }
940
941
942 /**
943  * Task to free resources when forwarded link controllers has been timedout
944  *
945  * @param cls the ForwardedOperationContext
946  * @param tc the task context from scheduler
947  */
948 static void
949 forwarded_operation_timeout (void *cls,
950                              const struct GNUNET_SCHEDULER_TaskContext *tc)
951 {
952   struct ForwardedOperationContext *fopc = cls;
953
954   GNUNET_TESTBED_forward_operation_msg_cancel_ (fopc->opc);
955   send_operation_fail_msg (fopc->client, fopc->operation_id, "Timeout");
956   GNUNET_SERVER_client_drop (fopc->client);
957   GNUNET_free (fopc);
958 }
959
960
961 /**
962  * The  Link Controller forwarding task
963  *
964  * @param cls the LCFContext
965  * @param tc the Task context from scheduler
966  */
967 static void
968 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
969 {
970   struct LCFContext *lcf = cls;
971   struct LCFContextQueue *lcfq;
972   struct ForwardedOperationContext *fopc;
973
974   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
975   switch (lcf->state)
976   {
977   case INIT:
978     if (GNUNET_NO ==
979         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
980                                             lcf->gateway->controller))
981     {
982       lcf->rhandle =
983           GNUNET_TESTBED_register_host (lcf->gateway->controller,
984                                         host_list[lcf->delegated_host_id],
985                                         lcf_proc_cc, lcf);
986     }
987     else
988     {
989       lcf->state = DELEGATED_HOST_REGISTERED;
990       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
991     }
992     break;
993   case DELEGATED_HOST_REGISTERED:
994     if (GNUNET_NO ==
995         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->slave_host_id],
996                                             lcf->gateway->controller))
997     {
998       lcf->rhandle =
999           GNUNET_TESTBED_register_host (lcf->gateway->controller,
1000                                         host_list[lcf->slave_host_id],
1001                                         lcf_proc_cc, lcf);
1002     }
1003     else
1004     {
1005       lcf->state = SLAVE_HOST_REGISTERED;
1006       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1007     }
1008     break;
1009   case SLAVE_HOST_REGISTERED:
1010     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1011     fopc->client = lcf->client;
1012     fopc->operation_id = lcf->operation_id;
1013     fopc->opc =
1014         GNUNET_TESTBED_forward_operation_msg_ (lcf->gateway->controller,
1015                                                lcf->operation_id,
1016                                                &lcf->msg->header,
1017                                                &forwarded_operation_reply_relay,
1018                                                fopc);
1019     fopc->timeout_task =
1020         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1021                                       fopc);
1022     lcf->state = FINISHED;
1023     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
1024     break;
1025   case FINISHED:
1026     lcfq = lcfq_head;
1027     GNUNET_assert (lcfq->lcf == lcf);
1028     GNUNET_free (lcf->msg);
1029     GNUNET_free (lcf);
1030     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1031     GNUNET_free (lcfq);
1032     if (NULL != lcfq_head)
1033       lcf_proc_task_id =
1034           GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
1035   }
1036 }
1037
1038
1039 /**
1040  * Callback for event from slave controllers
1041  *
1042  * @param cls struct Slave *
1043  * @param event information about the event
1044  */
1045 static void
1046 slave_event_callback (void *cls,
1047                       const struct GNUNET_TESTBED_EventInformation *event)
1048 {
1049   GNUNET_break (0);
1050 }
1051
1052
1053 /**
1054  * Callback to signal successfull startup of the controller process
1055  *
1056  * @param cls the closure from GNUNET_TESTBED_controller_start()
1057  * @param cfg the configuration with which the controller has been started;
1058  *          NULL if status is not GNUNET_OK
1059  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1060  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1061  */
1062 static void
1063 slave_status_callback (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
1064                        int status)
1065 {
1066   struct LinkControllersContext *lcc = cls;
1067
1068   if (GNUNET_SYSERR == status)
1069   {
1070     lcc->slave->controller_proc = NULL;
1071     LOG (GNUNET_ERROR_TYPE_WARNING, "Unexpected slave shutdown\n");
1072     GNUNET_SCHEDULER_shutdown ();       /* We too shutdown */
1073     return;
1074   }
1075   lcc->slave->controller =
1076       GNUNET_TESTBED_controller_connect (cfg, host_list[lcc->slave->host_id],
1077                                          master_context->event_mask,
1078                                          &slave_event_callback, lcc->slave);
1079   if (NULL != lcc->slave->controller)
1080     send_operation_success_msg (lcc->client, lcc->operation_id);
1081   else
1082     send_operation_fail_msg (lcc->client, lcc->operation_id,
1083                              "Could not connect to delegated controller");
1084   GNUNET_SERVER_client_drop (lcc->client);
1085   GNUNET_free (lcc);
1086 }
1087
1088
1089 /**
1090  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
1091  *
1092  * @param cls NULL
1093  * @param client identification of the client
1094  * @param message the actual message
1095  */
1096 static void
1097 handle_init (void *cls, struct GNUNET_SERVER_Client *client,
1098              const struct GNUNET_MessageHeader *message)
1099 {
1100   const struct GNUNET_TESTBED_InitMessage *msg;
1101   struct GNUNET_TESTBED_Host *host;
1102   const char *controller_hostname;
1103   uint16_t msize;
1104
1105   if (NULL != master_context)
1106   {
1107     GNUNET_break (0);
1108     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1109     return;
1110   }
1111   msg = (const struct GNUNET_TESTBED_InitMessage *) message;
1112   msize = ntohs (message->size);
1113   if (msize <= sizeof (struct GNUNET_TESTBED_InitMessage))
1114   {
1115     GNUNET_break (0);
1116     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1117     return;
1118   }
1119   msize -= sizeof (struct GNUNET_TESTBED_InitMessage);
1120   controller_hostname = (const char *) &msg[1];
1121   if ('\0' != controller_hostname[msize - 1])
1122   {
1123     GNUNET_break (0);
1124     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1125     return;
1126   }
1127   master_context = GNUNET_malloc (sizeof (struct Context));
1128   master_context->client = client;
1129   master_context->host_id = ntohl (msg->host_id);
1130   master_context->master_ip = GNUNET_strdup (controller_hostname);
1131   LOG_DEBUG ("Master Controller IP: %s\n", master_context->master_ip);
1132   master_context->system =
1133       GNUNET_TESTING_system_create ("testbed", master_context->master_ip);
1134   host =
1135       GNUNET_TESTBED_host_create_with_id (master_context->host_id, NULL, NULL,
1136                                           0);
1137   host_list_add (host);
1138   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
1139   GNUNET_SERVER_client_keep (client);
1140   LOG_DEBUG ("Created master context with host ID: %u\n",
1141              master_context->host_id);
1142   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1143 }
1144
1145
1146 /**
1147  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1148  *
1149  * @param cls NULL
1150  * @param client identification of the client
1151  * @param message the actual message
1152  */
1153 static void
1154 handle_add_host (void *cls, struct GNUNET_SERVER_Client *client,
1155                  const struct GNUNET_MessageHeader *message)
1156 {
1157   struct GNUNET_TESTBED_Host *host;
1158   const struct GNUNET_TESTBED_AddHostMessage *msg;
1159   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
1160   char *username;
1161   char *hostname;
1162   char *emsg;
1163   uint32_t host_id;
1164   uint16_t username_length;
1165   uint16_t hostname_length;
1166   uint16_t reply_size;
1167   uint16_t msize;
1168
1169   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
1170   msize = ntohs (msg->header.size);
1171   username = (char *) &(msg[1]);
1172   username_length = ntohs (msg->user_name_length);
1173   GNUNET_assert (msize > (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length + 1));        /* msg must contain hostname */
1174   if (0 != username_length)
1175     GNUNET_assert ('\0' == username[username_length]);
1176   username_length = (0 == username_length) ? 0 : username_length + 1;
1177   hostname = username + username_length;
1178   hostname_length =
1179       msize - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
1180   GNUNET_assert ('\0' == hostname[hostname_length - 1]);
1181   GNUNET_assert (strlen (hostname) == hostname_length - 1);
1182   host_id = ntohl (msg->host_id);
1183   LOG_DEBUG ("Received ADDHOST message\n");
1184   LOG_DEBUG ("-------host id: %u\n", host_id);
1185   if (NULL != hostname)
1186     LOG_DEBUG ("-------hostname: %s\n", hostname);
1187   if (0 != username_length)
1188     LOG_DEBUG ("-------username: %s\n", username);
1189   else
1190   {
1191     LOG_DEBUG ("-------username: NULL\n");
1192     username = NULL;
1193   }
1194   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
1195   host =
1196       GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
1197                                           ntohs (msg->ssh_port));
1198   GNUNET_assert (NULL != host);
1199   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1200   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
1201   if (GNUNET_OK != host_list_add (host))
1202   {
1203     /* We are unable to add a host */
1204     emsg = "A host exists with given host-id";
1205     LOG_DEBUG ("%s: %u", emsg, host_id);
1206     GNUNET_TESTBED_host_destroy (host);
1207     reply_size += strlen (emsg) + 1;
1208     reply = GNUNET_malloc (reply_size);
1209     memcpy (&reply[1], emsg, strlen (emsg) + 1);
1210   }
1211   else
1212     reply = GNUNET_malloc (reply_size);
1213   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
1214   reply->header.size = htons (reply_size);
1215   reply->host_id = htonl (host_id);
1216   queue_message (client, &reply->header);
1217 }
1218
1219
1220 /**
1221  * Iterator over hash map entries.
1222  *
1223  * @param cls closure
1224  * @param key current key code
1225  * @param value value in the hash map
1226  * @return GNUNET_YES if we should continue to
1227  *         iterate,
1228  *         GNUNET_NO if not.
1229  */
1230 int
1231 ss_exists_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
1232 {
1233   struct SharedService *queried_ss = cls;
1234   struct SharedService *ss = value;
1235
1236   if (0 == strcmp (ss->name, queried_ss->name))
1237     return GNUNET_NO;
1238   else
1239     return GNUNET_YES;
1240 }
1241
1242
1243 /**
1244  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
1245  *
1246  * @param cls NULL
1247  * @param client identification of the client
1248  * @param message the actual message
1249  */
1250 static void
1251 handle_configure_shared_service (void *cls, struct GNUNET_SERVER_Client *client,
1252                                  const struct GNUNET_MessageHeader *message)
1253 {
1254   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
1255   struct SharedService *ss;
1256   char *service_name;
1257   struct GNUNET_HashCode hash;
1258   uint16_t msg_size;
1259   uint16_t service_name_size;
1260
1261   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
1262   msg_size = ntohs (message->size);
1263   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
1264   {
1265     GNUNET_break (0);
1266     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1267     return;
1268   }
1269   service_name_size =
1270       msg_size - sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
1271   service_name = (char *) &msg[1];
1272   if ('\0' != service_name[service_name_size - 1])
1273   {
1274     GNUNET_break (0);
1275     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1276     return;
1277   }
1278   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
1279              service_name, ntohl (msg->num_peers));
1280   if (ntohl (msg->host_id) != master_context->host_id)
1281   {
1282     route_message (ntohl (msg->host_id), message);
1283     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1284     return;
1285   }
1286   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1287   ss = GNUNET_malloc (sizeof (struct SharedService));
1288   ss->name = strdup (service_name);
1289   ss->num_shared = ntohl (msg->num_peers);
1290   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
1291   if (GNUNET_SYSERR ==
1292       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
1293                                                   &ss_exists_iterator, ss))
1294   {
1295     LOG (GNUNET_ERROR_TYPE_WARNING,
1296          "Service %s already configured as a shared service. "
1297          "Ignoring service sharing request \n", ss->name);
1298     GNUNET_free (ss->name);
1299     GNUNET_free (ss);
1300     return;
1301   }
1302   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
1303                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1304 }
1305
1306
1307 /**
1308  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
1309  *
1310  * @param cls NULL
1311  * @param client identification of the client
1312  * @param message the actual message
1313  */
1314 static void
1315 handle_link_controllers (void *cls, struct GNUNET_SERVER_Client *client,
1316                          const struct GNUNET_MessageHeader *message)
1317 {
1318   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
1319   struct GNUNET_CONFIGURATION_Handle *cfg;
1320   struct LCFContextQueue *lcfq;
1321   struct Route *route;
1322   struct Route *new_route;
1323   char *config;
1324   uLongf dest_size;
1325   size_t config_size;
1326   uint32_t delegated_host_id;
1327   uint32_t slave_host_id;
1328   uint16_t msize;
1329
1330   if (NULL == master_context)
1331   {
1332     GNUNET_break (0);
1333     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1334     return;
1335   }
1336   msize = ntohs (message->size);
1337   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
1338   {
1339     GNUNET_break (0);
1340     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1341     return;
1342   }
1343   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
1344   delegated_host_id = ntohl (msg->delegated_host_id);
1345   if (delegated_host_id == master_context->host_id)
1346   {
1347     GNUNET_break (0);
1348     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
1349     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1350     return;
1351   }
1352   if ((delegated_host_id >= host_list_size) ||
1353       (NULL == host_list[delegated_host_id]))
1354   {
1355     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
1356     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1357     return;
1358   }
1359   slave_host_id = ntohl (msg->slave_host_id);
1360   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
1361   {
1362     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
1363     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1364     return;
1365   }
1366   if (slave_host_id == delegated_host_id)
1367   {
1368     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
1369     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1370     return;
1371   }
1372
1373   if (slave_host_id == master_context->host_id) /* Link from us */
1374   {
1375     struct Slave *slave;
1376     struct LinkControllersContext *lcc;
1377
1378     msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1379     config_size = ntohs (msg->config_size);
1380     if ((delegated_host_id < slave_list_size) && (NULL != slave_list[delegated_host_id]))       /* We have already added */
1381     {
1382       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1383            delegated_host_id);
1384       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1385       return;
1386     }
1387     config = GNUNET_malloc (config_size);
1388     dest_size = (uLongf) config_size;
1389     if (Z_OK !=
1390         uncompress ((Bytef *) config, &dest_size, (const Bytef *) &msg[1],
1391                     (uLong) msize))
1392     {
1393       GNUNET_break (0);         /* Compression error */
1394       GNUNET_free (config);
1395       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1396       return;
1397     }
1398     if (config_size != dest_size)
1399     {
1400       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1401       GNUNET_free (config);
1402       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1403       return;
1404     }
1405     cfg = GNUNET_CONFIGURATION_create ();       /* Free here or in lcfcontext */
1406     if (GNUNET_OK !=
1407         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
1408     {
1409       GNUNET_break (0);         /* Configuration parsing error */
1410       GNUNET_free (config);
1411       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1412       return;
1413     }
1414     GNUNET_free (config);
1415     if ((delegated_host_id < slave_list_size) &&
1416         (NULL != slave_list[delegated_host_id]))
1417     {
1418       GNUNET_break (0);         /* Configuration parsing error */
1419       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1420       return;
1421     }
1422     slave = GNUNET_malloc (sizeof (struct Slave));
1423     slave->host_id = delegated_host_id;
1424     slave_list_add (slave);
1425     if (1 != msg->is_subordinate)
1426     {
1427       slave->controller =
1428           GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1429                                              master_context->event_mask,
1430                                              &slave_event_callback, slave);
1431       GNUNET_CONFIGURATION_destroy (cfg);
1432       if (NULL != slave->controller)
1433         send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1434       else
1435         send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1436                                  "Could not connect to delegated controller");
1437       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1438       return;
1439     }
1440     lcc = GNUNET_malloc (sizeof (struct LinkControllersContext));
1441     lcc->operation_id = GNUNET_ntohll (msg->operation_id);
1442     GNUNET_SERVER_client_keep (client);
1443     lcc->client = client;
1444     lcc->slave = slave;
1445     slave->controller_proc =
1446         GNUNET_TESTBED_controller_start (master_context->master_ip,
1447                                          host_list[slave->host_id], cfg,
1448                                          &slave_status_callback, lcc);
1449     GNUNET_CONFIGURATION_destroy (cfg);
1450     new_route = GNUNET_malloc (sizeof (struct Route));
1451     new_route->dest = delegated_host_id;
1452     new_route->thru = master_context->host_id;
1453     route_list_add (new_route);
1454     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1455     return;
1456   }
1457
1458   /* Route the request */
1459   if (slave_host_id >= route_list_size)
1460   {
1461     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1462     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1463     return;
1464   }
1465   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1466   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1467   lcfq->lcf->delegated_host_id = delegated_host_id;
1468   lcfq->lcf->slave_host_id = slave_host_id;
1469   route = find_dest_route (slave_host_id);
1470   GNUNET_assert (NULL != route);        /* because we add routes carefully */
1471   GNUNET_assert (route->dest < slave_list_size);
1472   GNUNET_assert (NULL != slave_list[route->dest]);
1473   lcfq->lcf->state = INIT;
1474   lcfq->lcf->operation_id = GNUNET_ntohll (msg->operation_id);
1475   lcfq->lcf->gateway = slave_list[route->dest];
1476   lcfq->lcf->msg = GNUNET_malloc (msize);
1477   (void) memcpy (lcfq->lcf->msg, msg, msize);
1478   GNUNET_SERVER_client_keep (client);
1479   lcfq->lcf->client = client;
1480   if (NULL == lcfq_head)
1481   {
1482     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1483     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1484     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq->lcf);
1485   }
1486   else
1487     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1488   /* FIXME: Adding a new route should happen after the controllers are linked
1489    * successfully */
1490   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1491   new_route = GNUNET_malloc (sizeof (struct Route));
1492   new_route->dest = delegated_host_id;
1493   new_route->thru = route->dest;
1494   route_list_add (new_route);
1495 }
1496
1497
1498 /**
1499  * The task to be executed if the forwarded peer create operation has been
1500  * timed out
1501  *
1502  * @param cls the FowardedOperationContext
1503  * @param tc the TaskContext from the scheduler
1504  */
1505 static void
1506 peer_create_forward_timeout (void *cls,
1507                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1508 {
1509   struct ForwardedOperationContext *fo_ctxt = cls;
1510
1511   /* send error msg to client */
1512   send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id, "Timedout");
1513   GNUNET_SERVER_client_drop (fo_ctxt->client);
1514   GNUNET_TESTBED_forward_operation_msg_cancel_ (fo_ctxt->opc);
1515   GNUNET_free (fo_ctxt);
1516 }
1517
1518
1519 /**
1520  * Callback to be called when forwarded peer create operation is
1521  * successfull. We have to relay the reply msg back to the client
1522  *
1523  * @param cls ForwardedOperationContext
1524  * @param msg the peer create success message
1525  */
1526 static void
1527 peer_create_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
1528 {
1529   struct ForwardedOperationContext *fo_ctxt = cls;
1530   const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *success_msg;
1531   struct GNUNET_MessageHeader *dup_msg;
1532   struct Peer *peer;
1533   uint16_t msize;
1534
1535   GNUNET_SCHEDULER_cancel (fo_ctxt->timeout_task);
1536   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS)
1537   {
1538     success_msg =
1539         (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *) msg;
1540     peer = GNUNET_malloc (sizeof (struct Peer));
1541     peer->is_remote = GNUNET_YES;
1542     peer->id = ntohl (success_msg->peer_id);
1543     GNUNET_assert (NULL != fo_ctxt->cls);
1544     peer->details.remote.controller = fo_ctxt->cls;
1545     peer_list_add (peer);
1546   }
1547   msize = ntohs (msg->size);
1548   dup_msg = GNUNET_malloc (msize);
1549   (void) memcpy (dup_msg, msg, msize);
1550   queue_message (fo_ctxt->client, dup_msg);
1551   GNUNET_SERVER_client_drop (fo_ctxt->client);
1552   GNUNET_free (fo_ctxt);
1553 }
1554
1555
1556
1557 /**
1558  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1559  *
1560  * @param cls NULL
1561  * @param client identification of the client
1562  * @param message the actual message
1563  */
1564 static void
1565 handle_peer_create (void *cls, struct GNUNET_SERVER_Client *client,
1566                     const struct GNUNET_MessageHeader *message)
1567 {
1568   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1569   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1570   struct GNUNET_CONFIGURATION_Handle *cfg;
1571   struct ForwardedOperationContext *fo_ctxt;
1572   struct Route *route;
1573   struct Peer *peer;
1574   char *config;
1575   size_t dest_size;
1576   int ret;
1577   uint32_t config_size;
1578   uint32_t host_id;
1579   uint32_t peer_id;
1580   uint16_t msize;
1581
1582
1583   msize = ntohs (message->size);
1584   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1585   {
1586     GNUNET_break (0);           /* We need configuration */
1587     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1588     return;
1589   }
1590   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1591   host_id = ntohl (msg->host_id);
1592   peer_id = ntohl (msg->peer_id);
1593   if (UINT32_MAX == peer_id)
1594   {
1595     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1596                              "Cannot create peer with given ID");
1597     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1598     return;
1599   }
1600   if (host_id == master_context->host_id)
1601   {
1602     char *emsg;
1603
1604     /* We are responsible for this peer */
1605     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1606     config_size = ntohl (msg->config_size);
1607     config = GNUNET_malloc (config_size);
1608     dest_size = config_size;
1609     if (Z_OK !=
1610         (ret =
1611          uncompress ((Bytef *) config, (uLongf *) & dest_size,
1612                      (const Bytef *) &msg[1], (uLong) msize)))
1613     {
1614       GNUNET_break (0);         /* uncompression error */
1615       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1616       return;
1617     }
1618     if (config_size != dest_size)
1619     {
1620       GNUNET_break (0);         /* Uncompressed config size mismatch */
1621       GNUNET_free (config);
1622       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1623       return;
1624     }
1625     cfg = GNUNET_CONFIGURATION_create ();
1626     if (GNUNET_OK !=
1627         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
1628     {
1629       GNUNET_break (0);         /* Configuration parsing error */
1630       GNUNET_free (config);
1631       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1632       return;
1633     }
1634     GNUNET_free (config);
1635     peer = GNUNET_malloc (sizeof (struct Peer));
1636     peer->is_remote = GNUNET_NO;
1637     peer->details.local.cfg = cfg;
1638     peer->id = peer_id;
1639     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1640     peer->details.local.peer =
1641         GNUNET_TESTING_peer_configure (master_context->system,
1642                                        peer->details.local.cfg, peer->id,
1643                                        NULL /* Peer id */ ,
1644                                        &emsg);
1645     if (NULL == peer->details.local.peer)
1646     {
1647       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1648       GNUNET_free (emsg);
1649       GNUNET_free (peer);
1650       GNUNET_break (0);
1651       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1652       return;
1653     }
1654     peer->details.local.is_running = GNUNET_NO;
1655     peer_list_add (peer);
1656     reply =
1657         GNUNET_malloc (sizeof
1658                        (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1659     reply->header.size =
1660         htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1661     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1662     reply->peer_id = msg->peer_id;
1663     reply->operation_id = msg->operation_id;
1664     queue_message (client, &reply->header);
1665     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1666     return;
1667   }
1668
1669   /* Forward peer create request */
1670   route = find_dest_route (host_id);
1671   if (NULL == route)
1672   {
1673     GNUNET_break (0);
1674     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1675     return;
1676   }
1677   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1678   GNUNET_SERVER_client_keep (client);
1679   fo_ctxt->client = client;
1680   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);
1681   fo_ctxt->cls = slave_list[route->dest]->controller;
1682   fo_ctxt->opc =
1683       GNUNET_TESTBED_forward_operation_msg_ (slave_list
1684                                              [route->dest]->controller,
1685                                              fo_ctxt->operation_id,
1686                                              &msg->header,
1687                                              peer_create_success_cb, fo_ctxt);
1688   fo_ctxt->timeout_task =
1689       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &peer_create_forward_timeout,
1690                                     fo_ctxt);
1691
1692   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1693 }
1694
1695
1696 /**
1697  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1698  *
1699  * @param cls NULL
1700  * @param client identification of the client
1701  * @param message the actual message
1702  */
1703 static void
1704 handle_peer_destroy (void *cls, struct GNUNET_SERVER_Client *client,
1705                      const struct GNUNET_MessageHeader *message)
1706 {
1707   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1708   struct ForwardedOperationContext *fopc;
1709   struct Peer *peer;
1710   uint32_t peer_id;
1711
1712   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1713   peer_id = ntohl (msg->peer_id);
1714   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1715              peer_id, GNUNET_ntohll (msg->operation_id));
1716   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1717   {
1718     LOG (GNUNET_ERROR_TYPE_ERROR,
1719          "Asked to destroy a non existent peer with id: %u\n", peer_id);
1720     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1721                              "Peer doesn't exist");
1722     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1723     return;
1724   }
1725   peer = peer_list[peer_id];
1726   if (GNUNET_YES == peer->is_remote)
1727   {
1728     /* Forward the destory message to sub controller */
1729     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1730     GNUNET_SERVER_client_keep (client);
1731     fopc->client = client;
1732     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1733     fopc->opc =
1734         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.controller,
1735                                                fopc->operation_id, &msg->header,
1736                                                &forwarded_operation_reply_relay,
1737                                                fopc);
1738     fopc->timeout_task =
1739         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1740                                       fopc);
1741     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1742     return;
1743   }
1744   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
1745   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
1746   peer_list_remove (peer);
1747   GNUNET_free (peer);
1748   send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1749   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1750 }
1751
1752
1753 /**
1754  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1755  *
1756  * @param cls NULL
1757  * @param client identification of the client
1758  * @param message the actual message
1759  */
1760 static void
1761 handle_peer_start (void *cls, struct GNUNET_SERVER_Client *client,
1762                    const struct GNUNET_MessageHeader *message)
1763 {
1764   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1765   struct GNUNET_TESTBED_PeerEventMessage *reply;
1766   struct ForwardedOperationContext *fopc;
1767   struct Peer *peer;
1768   uint32_t peer_id;
1769
1770   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1771   peer_id = ntohl (msg->peer_id);
1772   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1773   {
1774     GNUNET_break (0);
1775     LOG (GNUNET_ERROR_TYPE_ERROR,
1776          "Asked to start a non existent peer with id: %u\n", peer_id);
1777     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1778     return;
1779   }
1780   peer = peer_list[peer_id];
1781   if (GNUNET_YES == peer->is_remote)
1782   {
1783     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1784     GNUNET_SERVER_client_keep (client);
1785     fopc->client = client;
1786     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1787     fopc->opc =
1788         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.controller,
1789                                                fopc->operation_id, &msg->header,
1790                                                &forwarded_operation_reply_relay,
1791                                                fopc);
1792     fopc->timeout_task =
1793         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1794                                       fopc);
1795     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1796     return;
1797   }
1798   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer->details.local.peer))
1799   {
1800     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1801                              "Failed to start");
1802     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1803     return;
1804   }
1805   peer->details.local.is_running = GNUNET_YES;
1806   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1807   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1808   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1809   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1810   reply->host_id = htonl (master_context->host_id);
1811   reply->peer_id = msg->peer_id;
1812   reply->operation_id = msg->operation_id;
1813   queue_message (client, &reply->header);
1814   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1815 }
1816
1817
1818 /**
1819  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1820  *
1821  * @param cls NULL
1822  * @param client identification of the client
1823  * @param message the actual message
1824  */
1825 static void
1826 handle_peer_stop (void *cls, struct GNUNET_SERVER_Client *client,
1827                   const struct GNUNET_MessageHeader *message)
1828 {
1829   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1830   struct GNUNET_TESTBED_PeerEventMessage *reply;
1831   struct ForwardedOperationContext *fopc;
1832   struct Peer *peer;
1833   uint32_t peer_id;
1834
1835   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1836   peer_id = ntohl (msg->peer_id);
1837   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1838   {
1839     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1840                              "Peer not found");
1841     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1842     return;
1843   }
1844   peer = peer_list[peer_id];
1845   if (GNUNET_YES == peer->is_remote)
1846   {
1847     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1848     GNUNET_SERVER_client_keep (client);
1849     fopc->client = client;
1850     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1851     fopc->opc =
1852         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.controller,
1853                                                fopc->operation_id, &msg->header,
1854                                                &forwarded_operation_reply_relay,
1855                                                fopc);
1856     fopc->timeout_task =
1857         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1858                                       fopc);
1859     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1860     return;
1861   }
1862   if (GNUNET_OK != GNUNET_TESTING_peer_stop (peer->details.local.peer))
1863   {
1864     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1865                              "Peer not running");
1866     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1867     return;
1868   }
1869   peer->details.local.is_running = GNUNET_NO;
1870   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1871   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1872   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1873   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1874   reply->host_id = htonl (master_context->host_id);
1875   reply->peer_id = msg->peer_id;
1876   reply->operation_id = msg->operation_id;
1877   queue_message (client, &reply->header);
1878   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1879 }
1880
1881
1882 /**
1883  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1884  *
1885  * @param cls NULL
1886  * @param client identification of the client
1887  * @param message the actual message
1888  */
1889 static void
1890 handle_peer_get_config (void *cls, struct GNUNET_SERVER_Client *client,
1891                         const struct GNUNET_MessageHeader *message)
1892 {
1893   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1894   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1895   struct Peer *peer;
1896   char *config;
1897   char *xconfig;
1898   size_t c_size;
1899   size_t xc_size;
1900   uint32_t peer_id;
1901   uint16_t msize;
1902
1903   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1904   peer_id = ntohl (msg->peer_id);
1905   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1906   {
1907     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1908                              "Peer not found");
1909     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1910     return;
1911   }
1912   peer = peer_list[peer_id];
1913   if (GNUNET_YES == peer->is_remote)
1914   {
1915     /* FIXME: forward to sub controller */
1916     GNUNET_break (0);
1917     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1918     return;
1919   }
1920   config =
1921       GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
1922                                       &c_size);
1923   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1924   GNUNET_free (config);
1925   msize =
1926       xc_size +
1927       sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
1928   reply = GNUNET_realloc (xconfig, msize);
1929   (void) memmove (&reply[1], reply, xc_size);
1930   reply->header.size = htons (msize);
1931   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
1932   reply->peer_id = msg->peer_id;
1933   reply->operation_id = msg->operation_id;
1934   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
1935                                     &reply->peer_identity);
1936   reply->config_size = htons ((uint16_t) c_size);
1937   queue_message (client, &reply->header);
1938   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1939 }
1940
1941
1942 /**
1943  * Task for cleaing up overlay connect context structure
1944  *
1945  * @param cls the overlay connect context
1946  * @param tc the task context
1947  */
1948 static void
1949 occ_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1950 {
1951   struct OverlayConnectContext *occ = cls;
1952
1953   LOG_DEBUG ("Cleaning up occ\n");
1954   GNUNET_free_non_null (occ->emsg);
1955   GNUNET_free_non_null (occ->hello);
1956   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1957     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1958   if (NULL != occ->ch)
1959     GNUNET_CORE_disconnect (occ->ch);
1960   if (NULL != occ->ghh)
1961     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1962   if (NULL != occ->p1th)
1963     GNUNET_TRANSPORT_disconnect (occ->p1th);
1964   if (NULL != occ->p2th)
1965     GNUNET_TRANSPORT_disconnect (occ->p2th);
1966   GNUNET_free (occ);
1967 }
1968
1969
1970 /**
1971  * Task which will be run when overlay connect request has been timed out
1972  *
1973  * @param cls the OverlayConnectContext
1974  * @param tc the TaskContext
1975  */
1976 static void
1977 timeout_overlay_connect (void *cls,
1978                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1979 {
1980   struct OverlayConnectContext *occ = cls;
1981
1982   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1983   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
1984   GNUNET_SERVER_client_drop (occ->client);
1985   occ_cleanup (occ, tc);
1986 }
1987
1988
1989
1990 /**
1991  * Function called to notify transport users that another
1992  * peer connected to us.
1993  *
1994  * @param cls closure
1995  * @param new_peer the peer that connected
1996  * @param ats performance data
1997  * @param ats_count number of entries in ats (excluding 0-termination)
1998  */
1999 static void
2000 overlay_connect_notify (void *cls, const struct GNUNET_PeerIdentity *new_peer,
2001                         const struct GNUNET_ATS_Information *ats,
2002                         unsigned int ats_count)
2003 {
2004   struct OverlayConnectContext *occ = cls;
2005   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
2006   char *new_peer_str;
2007   char *other_peer_str;
2008
2009   LOG_DEBUG ("Overlay connect notify\n");
2010   if (0 ==
2011       memcmp (new_peer, &occ->peer_identity,
2012               sizeof (struct GNUNET_PeerIdentity)))
2013     return;
2014   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
2015   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2016   if (0 !=
2017       memcmp (new_peer, &occ->other_peer_identity,
2018               sizeof (struct GNUNET_PeerIdentity)))
2019   {
2020     LOG_DEBUG ("Unexpected peer %4s connected when expecting peer %4s\n",
2021                new_peer_str, other_peer_str);
2022     GNUNET_free (new_peer_str);
2023     GNUNET_free (other_peer_str);
2024     return;
2025   }
2026   GNUNET_free (new_peer_str);
2027   LOG_DEBUG ("Peer %4s connected to peer %4s\n", other_peer_str, 
2028              GNUNET_i2s (&occ->peer_identity));
2029   GNUNET_free (other_peer_str);
2030   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
2031   {
2032     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
2033     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2034   }
2035   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
2036   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2037   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2038   GNUNET_free_non_null (occ->emsg);
2039   occ->emsg = NULL;
2040   if (NULL != occ->p2th)
2041     GNUNET_TRANSPORT_disconnect (occ->p2th);
2042   occ->p2th = NULL;
2043   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
2044   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2045   msg->header.size =
2046       htons (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2047   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
2048   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
2049   msg->peer1 = htonl (occ->peer->id);
2050   msg->peer2 = htonl (occ->other_peer->id);
2051   msg->operation_id = GNUNET_htonll (occ->op_id);
2052   queue_message (occ->client, &msg->header);
2053   GNUNET_SERVER_client_drop (occ->client);
2054   GNUNET_SCHEDULER_add_now (&occ_cleanup, occ);
2055 }
2056
2057
2058 /**
2059  * Task to offer HELLO of peer 1 to peer 2 and try to make peer 2 to connect to
2060  * peer 1.
2061  *
2062  * @param cls the OverlayConnectContext
2063  * @param tc the TaskContext from scheduler
2064  */
2065 static void
2066 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2067 {
2068   struct OverlayConnectContext *occ = cls;
2069   char *other_peer_str;
2070
2071   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2072   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2073     return;
2074   GNUNET_assert (NULL != occ->hello);
2075   if (GNUNET_YES == occ->other_peer->is_remote)
2076   {
2077     struct GNUNET_TESTBED_RequestConnectMessage *msg;
2078     uint16_t msize;
2079     uint16_t hello_size;
2080
2081     hello_size = ntohs (occ->hello->size);
2082     msize = sizeof (struct GNUNET_TESTBED_RequestConnectMessage) + hello_size;
2083     msg = GNUNET_malloc (msize);
2084     msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_REQUESTCONNECT);
2085     msg->header.size = htons (msize);
2086     msg->peer = htonl (occ->peer->id);
2087     msg->operation_id = GNUNET_htonll (occ->op_id);
2088     (void) memcpy (&msg->peer_identity, &occ->peer_identity,
2089                    sizeof (struct GNUNET_PeerIdentity));
2090     memcpy (msg->hello, occ->hello, hello_size);
2091     GNUNET_TESTBED_queue_message_ (occ->other_peer->details.remote.controller,
2092                                    &msg->header);
2093   }
2094   else
2095   {
2096     other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2097     LOG_DEBUG ("Offering HELLO of %s to %s\n", 
2098                GNUNET_i2s (&occ->peer_identity), other_peer_str);
2099     GNUNET_free (other_peer_str);
2100     GNUNET_TRANSPORT_offer_hello (occ->p2th, occ->hello, NULL, NULL);
2101     GNUNET_TRANSPORT_try_connect (occ->p2th, &occ->peer_identity);
2102   }
2103   occ->send_hello_task =
2104       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &send_hello, occ);
2105 }
2106
2107 /**
2108  * Test for checking whether HELLO message is empty
2109  *
2110  * @param cls empty flag to set
2111  * @param address the HELLO
2112  * @param expiration expiration of the HELLO
2113  * @return
2114  */
2115 static int
2116 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
2117               struct GNUNET_TIME_Absolute expiration)
2118 {
2119   int *empty = cls;
2120
2121   *empty = GNUNET_NO;
2122   return GNUNET_OK;
2123 }
2124
2125
2126 /**
2127  * Function called whenever there is an update to the
2128  * HELLO of peers in the OverlayConnectClosure
2129  *
2130  * @param cls closure
2131  * @param hello our updated HELLO
2132  */
2133 static void
2134 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
2135 {
2136   struct OverlayConnectContext *occ = cls;
2137   int empty;
2138   uint16_t msize;
2139
2140   msize = ntohs (hello->size);
2141   empty = GNUNET_YES;
2142   (void) GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *)
2143                                          hello, GNUNET_NO, &test_address,
2144                                          &empty);
2145   if (GNUNET_YES == empty)
2146   {
2147     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->peer_identity));
2148     return;
2149   }
2150   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->peer_identity));
2151   occ->hello = GNUNET_malloc (msize);
2152   memcpy (occ->hello, hello, msize);
2153   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
2154   occ->ghh = NULL;
2155   GNUNET_TRANSPORT_disconnect (occ->p1th);
2156   occ->p1th = NULL;
2157   GNUNET_free_non_null (occ->emsg);
2158   if (GNUNET_NO == occ->other_peer->is_remote)
2159   {   
2160     occ->p2th =
2161         GNUNET_TRANSPORT_connect (occ->other_peer->details.local.cfg,
2162                                   &occ->other_peer_identity, NULL, NULL, NULL,
2163                                   NULL);
2164     if (NULL == occ->p2th)
2165     {
2166       occ->emsg = GNUNET_strdup ("Cannot connect to TRANSPORT of peer B");
2167       GNUNET_SCHEDULER_cancel (occ->timeout_task);
2168       occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
2169       return;
2170     }
2171   }
2172   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
2173   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
2174 }
2175
2176
2177 /**
2178  * Function called after GNUNET_CORE_connect has succeeded (or failed
2179  * for good).  Note that the private key of the peer is intentionally
2180  * not exposed here; if you need it, your process should try to read
2181  * the private key file directly (which should work if you are
2182  * authorized...).
2183  *
2184  * @param cls closure
2185  * @param server handle to the server, NULL if we failed
2186  * @param my_identity ID of this peer, NULL if we failed
2187  */
2188 static void
2189 core_startup_cb (void *cls, struct GNUNET_CORE_Handle *server,
2190                  const struct GNUNET_PeerIdentity *my_identity)
2191 {
2192   struct OverlayConnectContext *occ = cls;
2193
2194   GNUNET_free_non_null (occ->emsg);
2195   occ->emsg = GNUNET_strdup ("Failed to connect to CORE\n");
2196   if ((NULL == server) || (NULL == my_identity))
2197     goto error_return;
2198   GNUNET_free (occ->emsg);
2199   occ->emsg = NULL;
2200   memcpy (&occ->peer_identity, my_identity,
2201           sizeof (struct GNUNET_PeerIdentity));
2202   occ->p1th =
2203       GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg,
2204                                 &occ->peer_identity, NULL, NULL, NULL, NULL);
2205   if (NULL == occ->p1th)
2206   {
2207     GNUNET_asprintf (&occ->emsg, "Cannot connect to TRANSPORT of peers %4s",
2208                     GNUNET_i2s (&occ->peer_identity));
2209     goto error_return;
2210   }
2211   LOG_DEBUG ("Acquiring HELLO of peer %s\n", GNUNET_i2s (&occ->peer_identity));
2212   occ->emsg = GNUNET_strdup ("Timeout while acquiring HELLO message");
2213   occ->ghh = GNUNET_TRANSPORT_get_hello (occ->p1th, &hello_update_cb, occ);
2214   return;
2215   
2216  error_return:
2217   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2218   occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
2219   return;
2220 }
2221
2222
2223 /**
2224  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
2225  *
2226  * @param cls NULL
2227  * @param client identification of the client
2228  * @param message the actual message
2229  */
2230 static void
2231 handle_overlay_connect (void *cls, struct GNUNET_SERVER_Client *client,
2232                         const struct GNUNET_MessageHeader *message)
2233 {
2234   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
2235   struct OverlayConnectContext *occ;
2236   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
2237     {NULL, 0, 0}
2238   };
2239   uint32_t p1;
2240   uint32_t p2;
2241
2242   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
2243   p1 = ntohl (msg->peer1);
2244   p2 = ntohl (msg->peer2);
2245   GNUNET_assert (p1 < peer_list_size);
2246   GNUNET_assert (NULL != peer_list[p1]);
2247   GNUNET_assert (p2 < peer_list_size);
2248   GNUNET_assert (NULL != peer_list[p2]);
2249   /* FIXME: Add cases where we have to forward overlay connect message to sub
2250    * controllers */
2251   GNUNET_assert (GNUNET_NO == peer_list[p1]->is_remote);
2252   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
2253   GNUNET_SERVER_client_keep (client);
2254   occ->client = client;
2255   occ->peer = peer_list[p1];
2256   occ->other_peer = peer_list[p2];
2257   occ->op_id = GNUNET_ntohll (msg->operation_id);
2258   /* Get the identity of the second peer */  
2259   GNUNET_TESTING_peer_get_identity (occ->other_peer->details.local.peer,
2260                                     &occ->other_peer_identity);
2261   /* Connect to the core of 1st peer and wait for the 2nd peer to connect */
2262   occ->emsg = GNUNET_strdup ("Timeout while connecting to CORE");
2263   occ->ch =
2264       GNUNET_CORE_connect (occ->peer->details.local.cfg, occ, &core_startup_cb,
2265                            &overlay_connect_notify, NULL, NULL, GNUNET_NO, NULL,
2266                            GNUNET_NO, no_handlers);
2267   if (NULL == occ->ch)
2268     occ->timeout_task = 
2269         GNUNET_SCHEDULER_add_now (&timeout_overlay_connect, occ);
2270   else
2271     occ->timeout_task =
2272       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2273                                     (GNUNET_TIME_UNIT_SECONDS, 30),
2274                                     &timeout_overlay_connect, occ);
2275   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2276 }
2277
2278
2279 /**
2280  * Iterator over hash map entries.
2281  *
2282  * @param cls closure
2283  * @param key current key code
2284  * @param value value in the hash map
2285  * @return GNUNET_YES if we should continue to
2286  *         iterate,
2287  *         GNUNET_NO if not.
2288  */
2289 static int
2290 ss_map_free_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
2291 {
2292   struct SharedService *ss = value;
2293
2294   GNUNET_assert (GNUNET_YES ==
2295                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
2296   GNUNET_free (ss->name);
2297   GNUNET_free (ss);
2298   return GNUNET_YES;
2299 }
2300
2301
2302 /**
2303  * Task to clean up and shutdown nicely
2304  *
2305  * @param cls NULL
2306  * @param tc the TaskContext from scheduler
2307  */
2308 static void
2309 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2310 {
2311   struct LCFContextQueue *lcfq;
2312   uint32_t id;
2313
2314   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
2315   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
2316   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
2317                                                 NULL);
2318   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
2319   if (NULL != lcfq_head)
2320   {
2321     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
2322     {
2323       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
2324       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
2325     }
2326     if (NULL != lcfq_head->lcf->rhandle)
2327       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
2328   }
2329   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2330   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
2331   {
2332     GNUNET_free (lcfq->lcf->msg);
2333     GNUNET_free (lcfq->lcf);
2334     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
2335     GNUNET_free (lcfq);
2336   }
2337   /* Clear peer list */
2338   for (id = 0; id < peer_list_size; id++)
2339     if (NULL != peer_list[id])
2340     {
2341       if (GNUNET_NO == peer_list[id]->is_remote)
2342       {
2343         if (GNUNET_YES == peer_list[id]->details.local.is_running)
2344           GNUNET_TESTING_peer_stop (peer_list[id]->details.local.peer);
2345         GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
2346         GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
2347       }
2348       GNUNET_free (peer_list[id]);
2349     }
2350   GNUNET_free_non_null (peer_list);
2351   /* Clear host list */
2352   for (id = 0; id < host_list_size; id++)
2353     if (NULL != host_list[id])
2354       GNUNET_TESTBED_host_destroy (host_list[id]);
2355   GNUNET_free_non_null (host_list);
2356   /* Clear route list */
2357   for (id = 0; id < route_list_size; id++)
2358     if (NULL != route_list[id])
2359       GNUNET_free (route_list[id]);
2360   GNUNET_free_non_null (route_list);
2361   /* Clear slave_list */
2362   for (id = 0; id < slave_list_size; id++)
2363     if (NULL != slave_list[id])
2364     {
2365       if (NULL != slave_list[id]->controller)
2366         GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
2367       if (NULL != slave_list[id]->controller_proc)
2368         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
2369     }
2370   if (NULL != master_context)
2371   {
2372     GNUNET_free_non_null (master_context->master_ip);
2373     if (NULL != master_context->system)
2374       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
2375     GNUNET_free (master_context);
2376     master_context = NULL;
2377   }
2378 }
2379
2380
2381 /**
2382  * Callback for client disconnect
2383  *
2384  * @param cls NULL
2385  * @param client the client which has disconnected
2386  */
2387 static void
2388 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
2389 {
2390   if (NULL == master_context)
2391     return;
2392   if (client == master_context->client)
2393   {
2394     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
2395     GNUNET_SERVER_client_drop (client);
2396     /* should not be needed as we're terminated by failure to read
2397      * from stdin, but if stdin fails for some reason, this shouldn't
2398      * hurt for now --- might need to revise this later if we ever
2399      * decide that master connections might be temporarily down
2400      * for some reason */
2401     //GNUNET_SCHEDULER_shutdown ();
2402   }
2403 }
2404
2405
2406 /**
2407  * Testbed setup
2408  *
2409  * @param cls closure
2410  * @param server the initialized server
2411  * @param cfg configuration to use
2412  */
2413 static void
2414 testbed_run (void *cls, struct GNUNET_SERVER_Handle *server,
2415              const struct GNUNET_CONFIGURATION_Handle *cfg)
2416 {
2417   static const struct GNUNET_SERVER_MessageHandler message_handlers[] = {
2418     {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
2419     {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
2420     {&handle_configure_shared_service, NULL,
2421      GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
2422     {&handle_link_controllers, NULL,
2423      GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
2424     {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
2425     {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
2426      sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
2427     {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
2428      sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
2429     {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
2430      sizeof (struct GNUNET_TESTBED_PeerStopMessage)},
2431     {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
2432      sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
2433     {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
2434      sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
2435     {NULL}
2436   };
2437
2438   GNUNET_SERVER_add_handlers (server, message_handlers);
2439   GNUNET_SERVER_disconnect_notify (server, &client_disconnect_cb, NULL);
2440   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
2441   shutdown_task_id =
2442       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2443                                     &shutdown_task, NULL);
2444   LOG_DEBUG ("Testbed startup complete\n");
2445 }
2446
2447
2448 /**
2449  * The starting point of execution
2450  */
2451 int
2452 main (int argc, char *const *argv)
2453 {
2454   //sleep (15);                 /* Debugging */
2455   return (GNUNET_OK ==
2456           GNUNET_SERVICE_run (argc, argv, "testbed", GNUNET_SERVICE_OPTION_NONE,
2457                               &testbed_run, NULL)) ? 0 : 1;
2458 }
2459
2460 /* end of gnunet-service-testbed.c */