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