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