removed OCC state
[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
1372     msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
1373     config_size = ntohs (msg->config_size);
1374     if ((delegated_host_id < slave_list_size) && (NULL != slave_list[delegated_host_id]))       /* We have already added */
1375     {
1376       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
1377            delegated_host_id);
1378       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1379       return;
1380     }
1381     config = GNUNET_malloc (config_size);
1382     dest_size = (uLongf) config_size;
1383     if (Z_OK !=
1384         uncompress ((Bytef *) config, &dest_size, (const Bytef *) &msg[1],
1385                     (uLong) msize))
1386     {
1387       GNUNET_break (0);         /* Compression error */
1388       GNUNET_free (config);
1389       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1390       return;
1391     }
1392     if (config_size != dest_size)
1393     {
1394       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
1395       GNUNET_free (config);
1396       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1397       return;
1398     }
1399     cfg = GNUNET_CONFIGURATION_create ();       /* Free here or in lcfcontext */
1400     if (GNUNET_OK !=
1401         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
1402     {
1403       GNUNET_break (0);         /* Configuration parsing error */
1404       GNUNET_free (config);
1405       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1406       return;
1407     }
1408     GNUNET_free (config);
1409     if ((delegated_host_id < slave_list_size) &&
1410         (NULL != slave_list[delegated_host_id]))
1411     {
1412       GNUNET_break (0);         /* Configuration parsing error */
1413       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1414       return;
1415     }
1416     slave = GNUNET_malloc (sizeof (struct Slave));
1417     slave->host_id = delegated_host_id;
1418     slave_list_add (slave);
1419     if (1 == msg->is_subordinate)
1420     {
1421       struct LinkControllersContext *lcc;
1422
1423       lcc = GNUNET_malloc (sizeof (struct LinkControllersContext));
1424       lcc->operation_id = GNUNET_ntohll (msg->operation_id);
1425       GNUNET_SERVER_client_keep (client);
1426       lcc->client = client;
1427       lcc->slave = slave;
1428       slave->controller_proc =
1429           GNUNET_TESTBED_controller_start (master_context->master_ip,
1430                                            host_list[slave->host_id], cfg,
1431                                            &slave_status_callback, lcc);
1432     }
1433     else
1434     {
1435       slave->controller =
1436           GNUNET_TESTBED_controller_connect (cfg, host_list[slave->host_id],
1437                                              master_context->event_mask,
1438                                              &slave_event_callback, slave);
1439       if (NULL != slave->controller)
1440         send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1441       else
1442         send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1443                                  "Could not connect to delegated controller");
1444     }
1445     GNUNET_CONFIGURATION_destroy (cfg);
1446     new_route = GNUNET_malloc (sizeof (struct Route));
1447     new_route->dest = delegated_host_id;
1448     new_route->thru = master_context->host_id;
1449     route_list_add (new_route);
1450     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1451     return;
1452   }
1453
1454   /* Route the request */
1455   if (slave_host_id >= route_list_size)
1456   {
1457     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1458     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1459     return;
1460   }
1461   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1462   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1463   lcfq->lcf->delegated_host_id = delegated_host_id;
1464   lcfq->lcf->slave_host_id = slave_host_id;
1465   route = find_dest_route (slave_host_id);
1466   GNUNET_assert (NULL != route);        /* because we add routes carefully */
1467   GNUNET_assert (route->dest < slave_list_size);
1468   GNUNET_assert (NULL != slave_list[route->dest]);
1469   lcfq->lcf->state = INIT;
1470   lcfq->lcf->operation_id = GNUNET_ntohll (msg->operation_id);
1471   lcfq->lcf->gateway = slave_list[route->dest];
1472   lcfq->lcf->msg = GNUNET_malloc (msize);
1473   (void) memcpy (lcfq->lcf->msg, msg, msize);
1474   GNUNET_SERVER_client_keep (client);
1475   lcfq->lcf->client = client;
1476   if (NULL == lcfq_head)
1477   {
1478     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1479     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1480     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq->lcf);
1481   }
1482   else
1483     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1484   /* FIXME: Adding a new route should happen after the controllers are linked
1485    * successfully */
1486   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1487   new_route = GNUNET_malloc (sizeof (struct Route));
1488   new_route->dest = delegated_host_id;
1489   new_route->thru = route->dest;
1490   route_list_add (new_route);
1491 }
1492
1493
1494 /**
1495  * The task to be executed if the forwarded peer create operation has been
1496  * timed out
1497  *
1498  * @param cls the FowardedOperationContext
1499  * @param tc the TaskContext from the scheduler
1500  */
1501 static void
1502 peer_create_forward_timeout (void *cls,
1503                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1504 {
1505   struct ForwardedOperationContext *fo_ctxt = cls;
1506
1507   /* send error msg to client */
1508   send_operation_fail_msg (fo_ctxt->client, fo_ctxt->operation_id, "Timedout");
1509   GNUNET_SERVER_client_drop (fo_ctxt->client);
1510   GNUNET_TESTBED_forward_operation_msg_cancel_ (fo_ctxt->opc);
1511   GNUNET_free (fo_ctxt);
1512 }
1513
1514
1515 /**
1516  * Callback to be called when forwarded peer create operation is
1517  * successfull. We have to relay the reply msg back to the client
1518  *
1519  * @param cls ForwardedOperationContext
1520  * @param msg the peer create success message
1521  */
1522 static void
1523 peer_create_success_cb (void *cls, const struct GNUNET_MessageHeader *msg)
1524 {
1525   struct ForwardedOperationContext *fo_ctxt = cls;
1526   const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *success_msg;
1527   struct GNUNET_MessageHeader *dup_msg;
1528   struct Peer *peer;
1529   uint16_t msize;
1530
1531   GNUNET_SCHEDULER_cancel (fo_ctxt->timeout_task);
1532   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS)
1533   {
1534     success_msg =
1535         (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *) msg;
1536     peer = GNUNET_malloc (sizeof (struct Peer));
1537     peer->is_remote = GNUNET_YES;
1538     peer->id = ntohl (success_msg->peer_id);
1539     GNUNET_assert (NULL != fo_ctxt->cls);
1540     peer->details.remote.controller = fo_ctxt->cls;
1541     peer_list_add (peer);
1542   }
1543   msize = ntohs (msg->size);
1544   dup_msg = GNUNET_malloc (msize);
1545   (void) memcpy (dup_msg, msg, msize);
1546   queue_message (fo_ctxt->client, dup_msg);
1547   GNUNET_SERVER_client_drop (fo_ctxt->client);
1548   GNUNET_free (fo_ctxt);
1549 }
1550
1551
1552
1553 /**
1554  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1555  *
1556  * @param cls NULL
1557  * @param client identification of the client
1558  * @param message the actual message
1559  */
1560 static void
1561 handle_peer_create (void *cls, struct GNUNET_SERVER_Client *client,
1562                     const struct GNUNET_MessageHeader *message)
1563 {
1564   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1565   struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *reply;
1566   struct GNUNET_CONFIGURATION_Handle *cfg;
1567   struct ForwardedOperationContext *fo_ctxt;
1568   struct Route *route;
1569   struct Peer *peer;
1570   char *config;
1571   size_t dest_size;
1572   int ret;
1573   uint32_t config_size;
1574   uint32_t host_id;
1575   uint32_t peer_id;
1576   uint16_t msize;
1577
1578
1579   msize = ntohs (message->size);
1580   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1581   {
1582     GNUNET_break (0);           /* We need configuration */
1583     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1584     return;
1585   }
1586   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1587   host_id = ntohl (msg->host_id);
1588   peer_id = ntohl (msg->peer_id);
1589   if (UINT32_MAX == peer_id)
1590   {
1591     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1592                              "Cannot create peer with given ID");
1593     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1594     return;
1595   }
1596   if (host_id == master_context->host_id)
1597   {
1598     char *emsg;
1599
1600     /* We are responsible for this peer */
1601     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1602     config_size = ntohl (msg->config_size);
1603     config = GNUNET_malloc (config_size);
1604     dest_size = config_size;
1605     if (Z_OK !=
1606         (ret =
1607          uncompress ((Bytef *) config, (uLongf *) & dest_size,
1608                      (const Bytef *) &msg[1], (uLong) msize)))
1609     {
1610       GNUNET_break (0);         /* uncompression error */
1611       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1612       return;
1613     }
1614     if (config_size != dest_size)
1615     {
1616       GNUNET_break (0);         /* Uncompressed config size mismatch */
1617       GNUNET_free (config);
1618       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1619       return;
1620     }
1621     cfg = GNUNET_CONFIGURATION_create ();
1622     if (GNUNET_OK !=
1623         GNUNET_CONFIGURATION_deserialize (cfg, config, config_size, GNUNET_NO))
1624     {
1625       GNUNET_break (0);         /* Configuration parsing error */
1626       GNUNET_free (config);
1627       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1628       return;
1629     }
1630     GNUNET_free (config);
1631     peer = GNUNET_malloc (sizeof (struct Peer));
1632     peer->is_remote = GNUNET_NO;
1633     peer->details.local.cfg = cfg;
1634     peer->id = peer_id;
1635     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1636     peer->details.local.peer =
1637         GNUNET_TESTING_peer_configure (master_context->system,
1638                                        peer->details.local.cfg, peer->id,
1639                                        NULL /* Peer id */ ,
1640                                        &emsg);
1641     if (NULL == peer->details.local.peer)
1642     {
1643       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1644       GNUNET_free (emsg);
1645       GNUNET_free (peer);
1646       GNUNET_break (0);
1647       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1648       return;
1649     }
1650     peer_list_add (peer);
1651     reply =
1652         GNUNET_malloc (sizeof
1653                        (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1654     reply->header.size =
1655         htons (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage));
1656     reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS);
1657     reply->peer_id = msg->peer_id;
1658     reply->operation_id = msg->operation_id;
1659     queue_message (client, &reply->header);
1660     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1661     return;
1662   }
1663
1664   /* Forward peer create request */
1665   route = find_dest_route (host_id);
1666   if (NULL == route)
1667   {
1668     GNUNET_break (0);
1669     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1670     return;
1671   }
1672   fo_ctxt = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1673   GNUNET_SERVER_client_keep (client);
1674   fo_ctxt->client = client;
1675   fo_ctxt->operation_id = GNUNET_ntohll (msg->operation_id);
1676   fo_ctxt->cls = slave_list[route->dest]->controller;
1677   fo_ctxt->opc =
1678       GNUNET_TESTBED_forward_operation_msg_ (slave_list
1679                                              [route->dest]->controller,
1680                                              fo_ctxt->operation_id,
1681                                              &msg->header,
1682                                              peer_create_success_cb, fo_ctxt);
1683   fo_ctxt->timeout_task =
1684       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &peer_create_forward_timeout,
1685                                     fo_ctxt);
1686
1687   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1688 }
1689
1690
1691 /**
1692  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1693  *
1694  * @param cls NULL
1695  * @param client identification of the client
1696  * @param message the actual message
1697  */
1698 static void
1699 handle_peer_destroy (void *cls, struct GNUNET_SERVER_Client *client,
1700                      const struct GNUNET_MessageHeader *message)
1701 {
1702   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1703   struct ForwardedOperationContext *fopc;
1704   struct Peer *peer;
1705   uint32_t peer_id;
1706
1707   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1708   peer_id = ntohl (msg->peer_id);
1709   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1710              peer_id, GNUNET_ntohll (msg->operation_id));
1711   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1712   {
1713     LOG (GNUNET_ERROR_TYPE_ERROR,
1714          "Asked to destroy a non existent peer with id: %u\n", peer_id);
1715     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1716                              "Peer doesn't exist");
1717     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1718     return;
1719   }
1720   peer = peer_list[peer_id];
1721   if (GNUNET_YES == peer->is_remote)
1722   {
1723     /* Forward the destory message to sub controller */
1724     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1725     GNUNET_SERVER_client_keep (client);
1726     fopc->client = client;
1727     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1728     fopc->opc =
1729         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.controller,
1730                                                fopc->operation_id, &msg->header,
1731                                                &forwarded_operation_reply_relay,
1732                                                fopc);
1733     fopc->timeout_task =
1734         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1735                                       fopc);
1736     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1737     return;
1738   }
1739   GNUNET_TESTING_peer_destroy (peer->details.local.peer);
1740   GNUNET_CONFIGURATION_destroy (peer->details.local.cfg);
1741   peer_list_remove (peer);
1742   GNUNET_free (peer);
1743   send_operation_success_msg (client, GNUNET_ntohll (msg->operation_id));
1744   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1745 }
1746
1747
1748 /**
1749  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1750  *
1751  * @param cls NULL
1752  * @param client identification of the client
1753  * @param message the actual message
1754  */
1755 static void
1756 handle_peer_start (void *cls, struct GNUNET_SERVER_Client *client,
1757                    const struct GNUNET_MessageHeader *message)
1758 {
1759   const struct GNUNET_TESTBED_PeerStartMessage *msg;
1760   struct GNUNET_TESTBED_PeerEventMessage *reply;
1761   struct ForwardedOperationContext *fopc;
1762   struct Peer *peer;
1763   uint32_t peer_id;
1764
1765   msg = (const struct GNUNET_TESTBED_PeerStartMessage *) message;
1766   peer_id = ntohl (msg->peer_id);
1767   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1768   {
1769     GNUNET_break (0);
1770     LOG (GNUNET_ERROR_TYPE_ERROR,
1771          "Asked to start a non existent peer with id: %u\n", peer_id);
1772     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1773     return;
1774   }
1775   peer = peer_list[peer_id];
1776   if (GNUNET_YES == peer->is_remote)
1777   {
1778     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1779     GNUNET_SERVER_client_keep (client);
1780     fopc->client = client;
1781     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1782     fopc->opc =
1783         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.controller,
1784                                                fopc->operation_id, &msg->header,
1785                                                &forwarded_operation_reply_relay,
1786                                                fopc);
1787     fopc->timeout_task =
1788         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1789                                       fopc);
1790     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1791     return;
1792   }
1793   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer->details.local.peer))
1794   {
1795     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1796                              "Failed to start");
1797     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1798     return;
1799   }
1800   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1801   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1802   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1803   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_START);
1804   reply->host_id = htonl (master_context->host_id);
1805   reply->peer_id = msg->peer_id;
1806   reply->operation_id = msg->operation_id;
1807   queue_message (client, &reply->header);
1808   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1809 }
1810
1811
1812 /**
1813  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1814  *
1815  * @param cls NULL
1816  * @param client identification of the client
1817  * @param message the actual message
1818  */
1819 static void
1820 handle_peer_stop (void *cls, struct GNUNET_SERVER_Client *client,
1821                   const struct GNUNET_MessageHeader *message)
1822 {
1823   const struct GNUNET_TESTBED_PeerStopMessage *msg;
1824   struct GNUNET_TESTBED_PeerEventMessage *reply;
1825   struct ForwardedOperationContext *fopc;
1826   struct Peer *peer;
1827   uint32_t peer_id;
1828
1829   msg = (const struct GNUNET_TESTBED_PeerStopMessage *) message;
1830   peer_id = ntohl (msg->peer_id);
1831   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1832   {
1833     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1834                              "Peer not found");
1835     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1836     return;
1837   }
1838   peer = peer_list[peer_id];
1839   if (GNUNET_YES == peer->is_remote)
1840   {
1841     fopc = GNUNET_malloc (sizeof (struct ForwardedOperationContext));
1842     GNUNET_SERVER_client_keep (client);
1843     fopc->client = client;
1844     fopc->operation_id = GNUNET_ntohll (msg->operation_id);
1845     fopc->opc =
1846         GNUNET_TESTBED_forward_operation_msg_ (peer->details.remote.controller,
1847                                                fopc->operation_id, &msg->header,
1848                                                &forwarded_operation_reply_relay,
1849                                                fopc);
1850     fopc->timeout_task =
1851         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &forwarded_operation_timeout,
1852                                       fopc);
1853     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1854     return;
1855   }
1856   if (GNUNET_OK != GNUNET_TESTING_peer_stop (peer->details.local.peer))
1857   {
1858     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1859                              "Peer not running");
1860     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1861     return;
1862   }
1863   reply = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1864   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEEREVENT);
1865   reply->header.size = htons (sizeof (struct GNUNET_TESTBED_PeerEventMessage));
1866   reply->event_type = htonl (GNUNET_TESTBED_ET_PEER_STOP);
1867   reply->host_id = htonl (master_context->host_id);
1868   reply->peer_id = msg->peer_id;
1869   reply->operation_id = msg->operation_id;
1870   queue_message (client, &reply->header);
1871   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1872 }
1873
1874
1875 /**
1876  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG messages
1877  *
1878  * @param cls NULL
1879  * @param client identification of the client
1880  * @param message the actual message
1881  */
1882 static void
1883 handle_peer_get_config (void *cls, struct GNUNET_SERVER_Client *client,
1884                         const struct GNUNET_MessageHeader *message)
1885 {
1886   const struct GNUNET_TESTBED_PeerGetConfigurationMessage *msg;
1887   struct GNUNET_TESTBED_PeerConfigurationInformationMessage *reply;
1888   struct Peer *peer;
1889   char *config;
1890   char *xconfig;
1891   size_t c_size;
1892   size_t xc_size;
1893   uint32_t peer_id;
1894   uint16_t msize;
1895
1896   msg = (const struct GNUNET_TESTBED_PeerGetConfigurationMessage *) message;
1897   peer_id = ntohl (msg->peer_id);
1898   if ((peer_id >= peer_list_size) || (NULL == peer_list[peer_id]))
1899   {
1900     send_operation_fail_msg (client, GNUNET_ntohll (msg->operation_id),
1901                              "Peer not found");
1902     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1903     return;
1904   }
1905   peer = peer_list[peer_id];
1906   if (GNUNET_YES == peer->is_remote)
1907   {
1908     /* FIXME: forward to sub controller */
1909     GNUNET_break (0);
1910     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1911     return;
1912   }
1913   config =
1914       GNUNET_CONFIGURATION_serialize (peer_list[peer_id]->details.local.cfg,
1915                                       &c_size);
1916   xc_size = GNUNET_TESTBED_compress_config_ (config, c_size, &xconfig);
1917   GNUNET_free (config);
1918   msize =
1919       xc_size +
1920       sizeof (struct GNUNET_TESTBED_PeerConfigurationInformationMessage);
1921   reply = GNUNET_realloc (xconfig, msize);
1922   (void) memmove (&reply[1], reply, xc_size);
1923   reply->header.size = htons (msize);
1924   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONFIG);
1925   reply->peer_id = msg->peer_id;
1926   reply->operation_id = msg->operation_id;
1927   GNUNET_TESTING_peer_get_identity (peer_list[peer_id]->details.local.peer,
1928                                     &reply->peer_identity);
1929   reply->config_size = htons ((uint16_t) c_size);
1930   queue_message (client, &reply->header);
1931   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1932 }
1933
1934
1935 /**
1936  * Task for cleaing up overlay connect context structure
1937  *
1938  * @param cls the overlay connect context
1939  * @param tc the task context
1940  */
1941 static void
1942 occ_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1943 {
1944   struct OverlayConnectContext *occ = cls;
1945
1946   GNUNET_free_non_null (occ->emsg);
1947   GNUNET_free_non_null (occ->hello);
1948   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
1949     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
1950   if (NULL != occ->ch)
1951     GNUNET_CORE_disconnect (occ->ch);
1952   if (NULL != occ->ghh)
1953     GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
1954   if (NULL != occ->p1th)
1955     GNUNET_TRANSPORT_disconnect (occ->p1th);
1956   if (NULL != occ->p2th)
1957     GNUNET_TRANSPORT_disconnect (occ->p2th);
1958   GNUNET_free (occ);
1959 }
1960
1961
1962 /**
1963  * Task which will be run when overlay connect request has been timed out
1964  *
1965  * @param cls the OverlayConnectContext
1966  * @param tc the TaskContext
1967  */
1968 static void
1969 timeout_overlay_connect (void *cls,
1970                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1971 {
1972   struct OverlayConnectContext *occ = cls;
1973
1974   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1975   send_operation_fail_msg (occ->client, occ->op_id, occ->emsg);
1976   GNUNET_SERVER_client_drop (occ->client);
1977   occ_cleanup (occ, tc);
1978 }
1979
1980
1981
1982 /**
1983  * Function called to notify transport users that another
1984  * peer connected to us.
1985  *
1986  * @param cls closure
1987  * @param new_peer the peer that connected
1988  * @param ats performance data
1989  * @param ats_count number of entries in ats (excluding 0-termination)
1990  */
1991 static void
1992 overlay_connect_notify (void *cls, const struct GNUNET_PeerIdentity *new_peer,
1993                         const struct GNUNET_ATS_Information *ats,
1994                         unsigned int ats_count)
1995 {
1996   struct OverlayConnectContext *occ = cls;
1997   struct GNUNET_TESTBED_ConnectionEventMessage *msg;
1998   char *new_peer_str;
1999   char *other_peer_str;
2000
2001   LOG_DEBUG ("Overlay connect notify\n");
2002   if (0 ==
2003       memcmp (new_peer, &occ->peer_identity,
2004               sizeof (struct GNUNET_PeerIdentity)))
2005     return;
2006   new_peer_str = GNUNET_strdup (GNUNET_i2s (new_peer));
2007   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2008   if (0 !=
2009       memcmp (new_peer, &occ->other_peer_identity,
2010               sizeof (struct GNUNET_PeerIdentity)))
2011   {
2012     LOG_DEBUG ("Unexpected peer %4s connected to peer %4s\n", new_peer_str,
2013                other_peer_str);
2014     GNUNET_free (new_peer_str);
2015     GNUNET_free (other_peer_str);
2016     return;
2017   }
2018   GNUNET_free (new_peer_str);
2019   LOG_DEBUG ("Peer %4s connected to peer %4s\n", other_peer_str, 
2020              GNUNET_i2s (&occ->peer_identity));
2021   GNUNET_free (other_peer_str);
2022   if (GNUNET_SCHEDULER_NO_TASK != occ->send_hello_task)
2023   {
2024     GNUNET_SCHEDULER_cancel (occ->send_hello_task);
2025     occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2026   }
2027   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != occ->timeout_task);
2028   GNUNET_SCHEDULER_cancel (occ->timeout_task);
2029   occ->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2030   GNUNET_free_non_null (occ->emsg);
2031   occ->emsg = NULL;
2032   GNUNET_TRANSPORT_disconnect (occ->p2th);
2033   occ->p2th = NULL;
2034   LOG_DEBUG ("Peers connected - Sending overlay connect success\n");
2035   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2036   msg->header.size =
2037       htons (sizeof (struct GNUNET_TESTBED_ConnectionEventMessage));
2038   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_PEERCONEVENT);
2039   msg->event_type = htonl (GNUNET_TESTBED_ET_CONNECT);
2040   msg->peer1 = htonl (occ->peer->id);
2041   msg->peer2 = htonl (occ->other_peer->id);
2042   msg->operation_id = GNUNET_htonll (occ->op_id);
2043   queue_message (occ->client, &msg->header);
2044   GNUNET_SERVER_client_drop (occ->client);
2045   GNUNET_SCHEDULER_add_now (&occ_cleanup, occ);
2046 }
2047
2048
2049 /**
2050  * Task to offer HELLO of peer 1 to peer 2 and try to make peer 2 to connect to
2051  * peer 1.
2052  *
2053  * @param cls the OverlayConnectContext
2054  * @param tc the TaskContext from scheduler
2055  */
2056 static void
2057 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2058 {
2059   struct OverlayConnectContext *occ = cls;
2060   char *other_peer_str;
2061
2062   occ->send_hello_task = GNUNET_SCHEDULER_NO_TASK;
2063   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2064     return;
2065   GNUNET_assert (NULL != occ->hello);
2066   other_peer_str = GNUNET_strdup (GNUNET_i2s (&occ->other_peer_identity));
2067   LOG_DEBUG ("Offering HELLO of %s to %s\n", 
2068              GNUNET_i2s (&occ->peer_identity), other_peer_str);
2069   GNUNET_free (other_peer_str);
2070   GNUNET_TRANSPORT_offer_hello (occ->p2th, occ->hello, NULL, NULL);
2071   GNUNET_TRANSPORT_try_connect (occ->p2th, &occ->peer_identity);
2072   occ->send_hello_task =
2073       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &send_hello, occ);
2074 }
2075
2076 /**
2077  * Test for checking whether HELLO message is empty
2078  *
2079  * @param cls empty flag to set
2080  * @param address the HELLO
2081  * @param expiration expiration of the HELLO
2082  * @return
2083  */
2084 static int
2085 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
2086               struct GNUNET_TIME_Absolute expiration)
2087 {
2088   int *empty = cls;
2089
2090   *empty = GNUNET_NO;
2091   return GNUNET_OK;
2092 }
2093
2094
2095 /**
2096  * Function called whenever there is an update to the
2097  * HELLO of peers in the OverlayConnectClosure
2098  *
2099  * @param cls closure
2100  * @param hello our updated HELLO
2101  */
2102 static void
2103 hello_update_cb (void *cls, const struct GNUNET_MessageHeader *hello)
2104 {
2105   struct OverlayConnectContext *occ = cls;
2106   int empty;
2107   uint16_t msize;
2108
2109   msize = ntohs (hello->size);
2110   empty = GNUNET_YES;
2111   (void) GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *)
2112                                          hello, GNUNET_NO, &test_address,
2113                                          &empty);
2114   if (GNUNET_YES == empty)
2115   {
2116     LOG_DEBUG ("HELLO of %s is empty\n", GNUNET_i2s (&occ->peer_identity));
2117     return;
2118   }
2119   LOG_DEBUG ("Received HELLO of %s\n", GNUNET_i2s (&occ->peer_identity));
2120   occ->hello = GNUNET_malloc (msize);
2121   memcpy (occ->hello, hello, msize);
2122   GNUNET_TRANSPORT_get_hello_cancel (occ->ghh);
2123   occ->ghh = NULL;
2124   GNUNET_TRANSPORT_disconnect (occ->p1th);
2125   occ->p1th = NULL;
2126   GNUNET_free_non_null (occ->emsg);
2127   occ->emsg = GNUNET_strdup ("Timeout while offering HELLO to other peer");
2128   occ->send_hello_task = GNUNET_SCHEDULER_add_now (&send_hello, occ);
2129 }
2130
2131
2132 /**
2133  * Function called after GNUNET_CORE_connect has succeeded (or failed
2134  * for good).  Note that the private key of the peer is intentionally
2135  * not exposed here; if you need it, your process should try to read
2136  * the private key file directly (which should work if you are
2137  * authorized...).
2138  *
2139  * @param cls closure
2140  * @param server handle to the server, NULL if we failed
2141  * @param my_identity ID of this peer, NULL if we failed
2142  */
2143 static void
2144 core_startup_cb (void *cls, struct GNUNET_CORE_Handle *server,
2145                  const struct GNUNET_PeerIdentity *my_identity)
2146 {
2147   struct OverlayConnectContext *occ = cls;
2148
2149   GNUNET_free_non_null (occ->emsg);
2150   occ->emsg = NULL;
2151   memcpy (&occ->peer_identity, my_identity,
2152           sizeof (struct GNUNET_PeerIdentity));
2153   occ->p1th =
2154       GNUNET_TRANSPORT_connect (occ->peer->details.local.cfg,
2155                                 &occ->peer_identity, NULL, NULL, NULL, NULL);
2156   /* Connect to the transport of 2nd peer and get its HELLO message */
2157   GNUNET_TESTING_peer_get_identity (occ->other_peer->details.local.peer,
2158                                     &occ->other_peer_identity);
2159   occ->p2th =
2160       GNUNET_TRANSPORT_connect (occ->other_peer->details.local.cfg,
2161                                 &occ->other_peer_identity, NULL, NULL, NULL,
2162                                 NULL);
2163   if ((NULL == occ->p1th) || (NULL == occ->p2th))
2164   {
2165     occ->emsg = GNUNET_strdup ("Cannot connect to TRANSPORTs of peers");
2166     GNUNET_SCHEDULER_cancel (occ->timeout_task);
2167     occ->timeout_task = GNUNET_SCHEDULER_add_now (&timeout_overlay_connect,
2168                                                   occ);
2169     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 }
2175
2176
2177 /**
2178  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT messages
2179  *
2180  * @param cls NULL
2181  * @param client identification of the client
2182  * @param message the actual message
2183  */
2184 static void
2185 handle_overlay_connect (void *cls, struct GNUNET_SERVER_Client *client,
2186                         const struct GNUNET_MessageHeader *message)
2187 {
2188   const struct GNUNET_TESTBED_OverlayConnectMessage *msg;
2189   struct OverlayConnectContext *occ;
2190
2191   struct GNUNET_CORE_MessageHandler no_handlers[] = {
2192     {NULL, 0, 0}
2193   };
2194   uint32_t p1;
2195   uint32_t p2;
2196
2197   msg = (const struct GNUNET_TESTBED_OverlayConnectMessage *) message;
2198   p1 = ntohl (msg->peer1);
2199   p2 = ntohl (msg->peer2);
2200   GNUNET_assert (p1 < peer_list_size);
2201   GNUNET_assert (NULL != peer_list[p1]);
2202   GNUNET_assert (p2 < peer_list_size);
2203   GNUNET_assert (NULL != peer_list[p2]);
2204   /* FIXME: Add cases where we have to forward overlay connect message to sub
2205    * controllers */
2206   occ = GNUNET_malloc (sizeof (struct OverlayConnectContext));
2207   GNUNET_SERVER_client_keep (client);
2208   occ->client = client;
2209   occ->peer = peer_list[p1];
2210   occ->other_peer = peer_list[p2];
2211   occ->op_id = GNUNET_ntohll (msg->operation_id);
2212   occ->timeout_task =
2213       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2214                                     (GNUNET_TIME_UNIT_SECONDS, 30),
2215                                     &timeout_overlay_connect, occ);
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   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2223 }
2224
2225
2226 /**
2227  * Iterator over hash map entries.
2228  *
2229  * @param cls closure
2230  * @param key current key code
2231  * @param value value in the hash map
2232  * @return GNUNET_YES if we should continue to
2233  *         iterate,
2234  *         GNUNET_NO if not.
2235  */
2236 static int
2237 ss_map_free_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
2238 {
2239   struct SharedService *ss = value;
2240
2241   GNUNET_assert (GNUNET_YES ==
2242                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
2243   GNUNET_free (ss->name);
2244   GNUNET_free (ss);
2245   return GNUNET_YES;
2246 }
2247
2248
2249 /**
2250  * Task to clean up and shutdown nicely
2251  *
2252  * @param cls NULL
2253  * @param tc the TaskContext from scheduler
2254  */
2255 static void
2256 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2257 {
2258   struct LCFContextQueue *lcfq;
2259   uint32_t id;
2260
2261   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
2262   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
2263   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
2264                                                 NULL);
2265   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
2266   if (NULL != lcfq_head)
2267   {
2268     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
2269     {
2270       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
2271       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
2272     }
2273     if (NULL != lcfq_head->lcf->rhandle)
2274       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
2275   }
2276   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
2277   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
2278   {
2279     GNUNET_free (lcfq->lcf->msg);
2280     GNUNET_free (lcfq->lcf);
2281     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
2282     GNUNET_free (lcfq);
2283   }
2284   /* Clear peer list */
2285   for (id = 0; id < peer_list_size; id++)
2286     if (NULL != peer_list[id])
2287     {
2288       if (GNUNET_NO == peer_list[id]->is_remote)
2289       {
2290         GNUNET_TESTING_peer_destroy (peer_list[id]->details.local.peer);
2291         GNUNET_CONFIGURATION_destroy (peer_list[id]->details.local.cfg);
2292       }
2293       GNUNET_free (peer_list[id]);
2294     }
2295   GNUNET_free_non_null (peer_list);
2296   /* Clear host list */
2297   for (id = 0; id < host_list_size; id++)
2298     if (NULL != host_list[id])
2299       GNUNET_TESTBED_host_destroy (host_list[id]);
2300   GNUNET_free_non_null (host_list);
2301   /* Clear route list */
2302   for (id = 0; id < route_list_size; id++)
2303     if (NULL != route_list[id])
2304       GNUNET_free (route_list[id]);
2305   GNUNET_free_non_null (route_list);
2306   /* Clear slave_list */
2307   for (id = 0; id < slave_list_size; id++)
2308     if (NULL != slave_list[id])
2309     {
2310       if (NULL != slave_list[id]->controller)
2311         GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
2312       if (NULL != slave_list[id]->controller_proc)
2313         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
2314     }
2315   if (NULL != master_context)
2316   {
2317     GNUNET_free_non_null (master_context->master_ip);
2318     if (NULL != master_context->system)
2319       GNUNET_TESTING_system_destroy (master_context->system, GNUNET_YES);
2320     GNUNET_free (master_context);
2321     master_context = NULL;
2322   }
2323 }
2324
2325
2326 /**
2327  * Callback for client disconnect
2328  *
2329  * @param cls NULL
2330  * @param client the client which has disconnected
2331  */
2332 static void
2333 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
2334 {
2335   if (NULL == master_context)
2336     return;
2337   if (client == master_context->client)
2338   {
2339     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
2340     GNUNET_SERVER_client_drop (client);
2341     /* should not be needed as we're terminated by failure to read
2342      * from stdin, but if stdin fails for some reason, this shouldn't
2343      * hurt for now --- might need to revise this later if we ever
2344      * decide that master connections might be temporarily down
2345      * for some reason */
2346     //GNUNET_SCHEDULER_shutdown ();
2347   }
2348 }
2349
2350
2351 /**
2352  * Testbed setup
2353  *
2354  * @param cls closure
2355  * @param server the initialized server
2356  * @param cfg configuration to use
2357  */
2358 static void
2359 testbed_run (void *cls, struct GNUNET_SERVER_Handle *server,
2360              const struct GNUNET_CONFIGURATION_Handle *cfg)
2361 {
2362   static const struct GNUNET_SERVER_MessageHandler message_handlers[] = {
2363     {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT, 0},
2364     {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
2365     {&handle_configure_shared_service, NULL,
2366      GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
2367     {&handle_link_controllers, NULL,
2368      GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
2369     {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
2370     {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
2371      sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
2372     {&handle_peer_start, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STARTPEER,
2373      sizeof (struct GNUNET_TESTBED_PeerStartMessage)},
2374     {&handle_peer_stop, NULL, GNUNET_MESSAGE_TYPE_TESTBED_STOPPEER,
2375      sizeof (struct GNUNET_TESTBED_PeerStopMessage)},
2376     {&handle_peer_get_config, NULL, GNUNET_MESSAGE_TYPE_TESTBED_GETPEERCONFIG,
2377      sizeof (struct GNUNET_TESTBED_PeerGetConfigurationMessage)},
2378     {&handle_overlay_connect, NULL, GNUNET_MESSAGE_TYPE_TESTBED_OLCONNECT,
2379      sizeof (struct GNUNET_TESTBED_OverlayConnectMessage)},
2380     {NULL}
2381   };
2382
2383   GNUNET_SERVER_add_handlers (server, message_handlers);
2384   GNUNET_SERVER_disconnect_notify (server, &client_disconnect_cb, NULL);
2385   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
2386   shutdown_task_id =
2387       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2388                                     &shutdown_task, NULL);
2389   LOG_DEBUG ("Testbed startup complete\n");
2390 }
2391
2392
2393 /**
2394  * The starting point of execution
2395  */
2396 int
2397 main (int argc, char *const *argv)
2398 {
2399   //sleep (15);                 /* Debugging */
2400   return (GNUNET_OK ==
2401           GNUNET_SERVICE_run (argc, argv, "testbed", GNUNET_SERVICE_OPTION_NONE,
2402                               &testbed_run, NULL)) ? 0 : 1;
2403 }
2404
2405 /* end of gnunet-service-testbed.c */