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