-fixing #2493
[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 <zlib.h>
31
32 #include "testbed.h"
33 #include "gnunet_testbed_service.h"
34 #include "testbed_api_hosts.h"
35 #include "gnunet_testing_lib-new.h"
36
37 /**
38  * Generic logging
39  */
40 #define LOG(kind,...)                           \
41   GNUNET_log (kind, __VA_ARGS__)
42
43 /**
44  * Debug logging
45  */
46 #define LOG_DEBUG(...)                          \
47   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
48
49
50 #define LIST_GROW_STEP 10
51
52 struct Context
53 {
54   /**
55    * The client handle associated with this context
56    */
57   struct GNUNET_SERVER_Client *client;
58   
59   /**
60    * Event mask of event to be responded in this context
61    */
62   uint64_t event_mask;
63
64   /**
65    * Our host id according to this context
66    */
67   uint32_t host_id;
68 };
69
70
71 /**
72  * The message queue for sending messages to clients
73  */
74 struct MessageQueue
75 {
76   /**
77    * The message to be sent
78    */
79   struct GNUNET_MessageHeader *msg;
80
81   /**
82    * The client to send the message to
83    */
84   struct GNUNET_SERVER_Client *client;
85   
86   /**
87    * next pointer for DLL
88    */
89   struct MessageQueue *next;
90   
91   /**
92    * prev pointer for DLL
93    */
94   struct MessageQueue *prev;
95 };
96
97
98 /**
99  * The structure for identifying a shared service
100  */
101 struct SharedService
102 {
103   /**
104    * The name of the shared service
105    */
106   char *name;
107
108   /**
109    * Number of shared peers per instance of the shared service
110    */
111   uint32_t num_shared;
112
113   /**
114    * Number of peers currently sharing the service
115    */
116   uint32_t num_sharing;
117 };
118
119
120 /**
121  * A routing entry
122  */
123 struct Route
124 {
125   /**
126    * destination host
127    */
128   uint32_t dest;
129
130   /**
131    * The host destination is reachable thru
132    */
133   uint32_t thru;
134 };
135
136
137 /**
138  * Structure representing a connected(directly-linked) controller
139  */
140 struct Slave
141 {
142   /**
143    * The controller process handle if we had started the controller
144    */
145   struct GNUNET_TESTBED_ControllerProc *controller_proc;
146
147   /**
148    * The controller handle
149    */
150   struct GNUNET_TESTBED_Controller *controller;
151
152   /**
153    * The id of the host this controller is running on
154    */
155   uint32_t host_id;
156 };
157
158
159 /**
160  * States of LCFContext
161  */
162 enum LCFContextState
163   {
164     /**
165      * The Context has been initialized; Nothing has been done on it
166      */
167     INIT,
168
169     /**
170      * Delegated host has been registered at the forwarding controller
171      */
172     DELEGATED_HOST_REGISTERED,
173     
174     /**
175      * The context has been finished (may have error)
176      */
177     FINISHED
178
179   };
180
181
182 /**
183  * Link controllers request forwarding context
184  */
185 struct LCFContext
186 {
187   /**
188    * The serialized and compressed configuration
189    */
190   char *sxcfg;
191
192   /**
193    * The gateway which will pass the link message to delegated host
194    */
195   struct Slave *gateway;
196
197   /**
198    * The host registration handle while registered hosts in this context
199    */
200   struct GNUNET_TESTBED_HostRegistrationHandle *rhandle;
201
202   /**
203    * The size of the compressed serialized configuration
204    */
205   size_t sxcfg_size;
206
207   /**
208    * The size of the uncompressed configuration
209    */
210   size_t scfg_size;
211
212   /**
213    * Should the delegated host be started by the slave host?
214    */
215   int is_subordinate;
216
217   /**
218    * The state of this context
219    */
220   enum LCFContextState state;
221
222   /**
223    * The delegated host
224    */
225   uint32_t delegated_host_id;
226   
227
228 };
229
230
231 /**
232  * Structure of a queue entry in LCFContext request queue
233  */
234 struct LCFContextQueue
235 {
236   /**
237    * The LCFContext
238    */
239   struct LCFContext *lcf;
240
241   /**
242    * Head prt for DLL
243    */
244   struct LCFContextQueue *next;
245
246   /**
247    * Tail ptr for DLL
248    */
249   struct LCFContextQueue *prev;
250 };
251
252
253 /**
254  * A locally started peer
255  */
256 struct Peer
257 {
258   /**
259    * The peer handle from testing API
260    */
261   struct GNUNET_TESTING_Peer *peer;
262
263   /**
264    * The modified (by GNUNET_TESTING_peer_configure) configuration this peer is
265    * configured with
266    */
267   struct GNUNET_CONFIGURATION_Handle *cfg;
268
269   /**
270    * Our local reference id for this peer
271    */
272   uint32_t id;
273
274 };
275
276
277 /**
278  * The master context; generated with the first INIT message
279  */
280 static struct Context *master_context;
281
282 /***********/
283 /* Handles */
284 /***********/
285
286 /**
287  * Wrapped stdin.
288  */
289 static struct GNUNET_DISK_FileHandle *fh;
290
291 /**
292  * Current Transmit Handle; NULL if no notify transmit exists currently
293  */
294 static struct GNUNET_SERVER_TransmitHandle *transmit_handle;
295
296 /****************/
297 /* Lists & Maps */
298 /****************/
299
300 /**
301  * The head for the LCF queue
302  */
303 static struct LCFContextQueue *lcfq_head;
304
305 /**
306  * The tail for the LCF queue
307  */
308 static struct LCFContextQueue *lcfq_tail;
309
310 /**
311  * The message queue head
312  */
313 static struct MessageQueue *mq_head;
314
315 /**
316  * The message queue tail
317  */
318 static struct MessageQueue *mq_tail;
319
320 /**
321  * Array of host list
322  */
323 static struct GNUNET_TESTBED_Host **host_list;
324
325 /**
326  * A list of routes
327  */
328 static struct Route **route_list;
329
330 /**
331  * A list of directly linked neighbours
332  */
333 static struct Slave **slave_list;
334
335 /**
336  * A list of peers we own locally
337  */
338 static struct Peer **peer_list;
339
340 /**
341  * The hashmap of shared services
342  */
343 static struct GNUNET_CONTAINER_MultiHashMap *ss_map;
344
345 /**
346  * The size of the host list
347  */
348 static uint32_t host_list_size;
349
350 /**
351  * The size of the route list
352  */
353 static uint32_t route_list_size;
354
355 /**
356  * The size of directly linked neighbours list
357  */
358 static uint32_t slave_list_size;
359
360 /**
361  * The size of the peer list
362  */
363 static uint32_t peer_list_size;
364
365 /*********/
366 /* Tasks */
367 /*********/
368
369 /**
370  * The lcf_task handle
371  */
372 static GNUNET_SCHEDULER_TaskIdentifier lcf_proc_task_id;
373
374 /**
375  * The shutdown task handle
376  */
377 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
378
379 /******************/
380 /* Testing System */
381 /******************/
382
383 /**
384  * Handle to the local testing system - for starting peers locally
385  */
386 static struct GNUNET_TESTING_System *test_system;
387
388
389 /**
390  * Function called to notify a client about the connection begin ready to queue
391  * more data.  "buf" will be NULL and "size" zero if the connection was closed
392  * for writing in the meantime.
393  *
394  * @param cls NULL
395  * @param size number of bytes available in buf
396  * @param buf where the callee should write the message
397  * @return number of bytes written to buf
398  */
399 static size_t
400 transmit_ready_notify (void *cls, size_t size, void *buf)
401 {
402   struct MessageQueue *mq_entry;
403
404   transmit_handle = NULL;
405   mq_entry = mq_head;
406   GNUNET_assert (NULL != mq_entry);
407   if (0 == size)
408     return 0;
409   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
410   size = ntohs (mq_entry->msg->size);
411   memcpy (buf, mq_entry->msg, size);
412   GNUNET_free (mq_entry->msg);
413   GNUNET_CONTAINER_DLL_remove (mq_head, mq_tail, mq_entry);
414   GNUNET_free (mq_entry);
415   mq_entry = mq_head;
416   if (NULL != mq_entry)
417     transmit_handle = 
418       GNUNET_SERVER_notify_transmit_ready (mq_entry->client,
419                                            ntohs (mq_entry->msg->size),
420                                            GNUNET_TIME_UNIT_FOREVER_REL,
421                                            &transmit_ready_notify, NULL);
422   return size;
423 }
424
425
426 /**
427  * Queues a message in send queue for sending to the service
428  *
429  * @param client the client to whom the queued message has to be sent
430  * @param msg the message to queue
431  */
432 static void
433 queue_message (struct GNUNET_SERVER_Client *client,
434                struct GNUNET_MessageHeader *msg)
435 {
436   struct MessageQueue *mq_entry;
437   uint16_t type;
438   uint16_t size;
439
440   type = ntohs (msg->type);
441   size = ntohs (msg->size);
442   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
443                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
444   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
445   mq_entry->msg = msg;
446   mq_entry->client = client;
447   LOG_DEBUG ( "Queueing message of type %u, size %u for sending\n", type,
448               ntohs (msg->size));
449   GNUNET_CONTAINER_DLL_insert_tail (mq_head, mq_tail, mq_entry);
450   if (NULL == transmit_handle)
451     transmit_handle = 
452       GNUNET_SERVER_notify_transmit_ready (client, size,
453                                            GNUNET_TIME_UNIT_FOREVER_REL,
454                                            &transmit_ready_notify, NULL);
455 }
456
457
458 /**
459  * Similar to GNUNET_realloc; however clears tail part of newly allocated memory
460  *
461  * @param ptr the memory block to realloc
462  * @param size the size of ptr
463  * @param new_size the size to which ptr has to be realloc'ed
464  * @return the newly reallocated memory block
465  */
466 static void *
467 TESTBED_realloc (void *ptr, size_t size, size_t new_size)
468 {
469   ptr = GNUNET_realloc (ptr, new_size);
470   if (new_size > size)
471     ptr = memset (ptr + size, 0, new_size - size);
472   return ptr;
473 }
474
475
476 /**
477  * Function to add a host to the current list of known hosts
478  *
479  * @param host the host to add 
480  * @return GNUNET_OK on success; GNUNET_SYSERR on failure due to host-id
481  *           already in use
482  */
483 static int
484 host_list_add (struct GNUNET_TESTBED_Host *host)
485 {
486   uint32_t host_id;
487
488   host_id = GNUNET_TESTBED_host_get_id_ (host);
489   if (host_list_size <= host_id)
490   {
491     host_list = 
492       TESTBED_realloc (host_list, 
493                        sizeof (struct GNUNET_TESTBED_Host *) * host_list_size,
494                        sizeof (struct GNUNET_TESTBED_Host *) *
495                        (host_list_size + LIST_GROW_STEP));
496     host_list_size += LIST_GROW_STEP;
497   }
498   if (NULL != host_list[host_id])
499   {
500     LOG_DEBUG ("A host with id: %u already exists\n", host_id);
501     return GNUNET_SYSERR;
502   }
503   host_list[host_id] = host;
504   return GNUNET_OK;
505 }
506
507
508 /**
509  * Adds a route to the route list
510  *
511  * @param route the route to add
512  */
513 static void
514 route_list_add (struct Route *route)
515 {
516   if (route->dest >= route_list_size)
517   {
518     route_list = 
519       TESTBED_realloc (route_list, 
520                        sizeof (struct Route *) * route_list_size,
521                        sizeof (struct Route *) * 
522                        (route_list_size + LIST_GROW_STEP));
523     route_list_size += LIST_GROW_STEP;
524   }
525   GNUNET_assert (NULL == route_list[route->dest]);
526   route_list[route->dest] = route;
527 }
528
529
530 /**
531  * Adds a slave to the slave array
532  *
533  * @param route the route to add
534  */
535 static void
536 slave_list_add (struct Slave *slave)
537 {
538   if (slave->host_id  >= slave_list_size)
539   {
540     slave_list = TESTBED_realloc (slave_list, 
541                                  sizeof (struct Slave *) *slave_list_size,
542                                  sizeof (struct Slave *) *
543                                  (slave_list_size) + LIST_GROW_STEP);
544     slave_list_size += LIST_GROW_STEP;
545   }
546   GNUNET_assert (NULL == slave_list[slave->host_id]);
547   slave_list[slave->host_id] = slave;
548 }
549
550
551 /**
552  * Adds a peer to the peer array
553  *
554  * @param route the route to add
555  */
556 static void
557 peer_list_add (struct Peer *peer)
558 {
559   if (peer->id  >= peer_list_size)
560   {
561     peer_list = TESTBED_realloc (peer_list, 
562                                  sizeof (struct Peer *) * peer_list_size,
563                                  sizeof (struct Peer *) *
564                                  (peer_list_size + LIST_GROW_STEP));
565     peer_list_size += LIST_GROW_STEP;
566   }
567   GNUNET_assert (NULL == peer_list[peer->id]);
568   peer_list[peer->id] = peer;
569 }
570
571
572 /**
573  * Routes message to a host given its host_id
574  *
575  * @param host_id the id of the destination host
576  * @param msg the message to be routed
577  */
578 static void
579 route_message (uint32_t host_id, const struct GNUNET_MessageHeader *msg)
580 {
581   GNUNET_break (0);
582 }
583
584
585 /**
586  * The  Link Controller forwarding task
587  *
588  * @param cls the LCFContext
589  * @param tc the Task context from scheduler
590  */
591 static void
592 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
593
594
595 /**
596  * Completion callback for host registrations while forwarding Link Controller messages
597  *
598  * @param cls the LCFContext
599  * @param emsg the error message; NULL if host registration is successful
600  */
601 static void
602 lcf_proc_cc (void *cls, const char *emsg)
603 {
604   struct LCFContext *lcf = cls;
605
606   lcf->rhandle = NULL;
607   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
608   switch (lcf->state)
609   {
610   case INIT:
611     if (NULL != emsg)
612     {
613       LOG (GNUNET_ERROR_TYPE_WARNING, 
614            "Host registration failed with message: %s\n", emsg);
615       lcf->state = FINISHED;
616       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
617       return;
618     }
619     lcf->state = DELEGATED_HOST_REGISTERED;
620     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
621     break;
622   default:
623     GNUNET_assert (0);          /* Shouldn't reach here */
624   }  
625 }
626
627
628 /**
629  * The  Link Controller forwarding task
630  *
631  * @param cls the LCFContext
632  * @param tc the Task context from scheduler
633  */
634 static void
635 lcf_proc_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
636 {
637   struct LCFContext *lcf = cls;
638   struct LCFContextQueue *lcfq;
639
640   lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
641   switch (lcf->state)
642   {
643   case INIT:
644     if (GNUNET_NO ==
645         GNUNET_TESTBED_is_host_registered_ (host_list[lcf->delegated_host_id],
646                                             lcf->gateway->controller))
647     {
648       lcf->rhandle =
649         GNUNET_TESTBED_register_host (lcf->gateway->controller,
650                                       host_list[lcf->delegated_host_id],
651                                       lcf_proc_cc, lcf);                                                   
652     }
653     else
654     {
655       lcf->state = DELEGATED_HOST_REGISTERED;
656       lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcf);
657     }
658     break;
659   case DELEGATED_HOST_REGISTERED:
660     GNUNET_TESTBED_controller_link_2 (lcf->gateway->controller,
661                                       host_list[lcf->delegated_host_id],
662                                       host_list[lcf->gateway->host_id],
663                                       lcf->sxcfg, lcf->sxcfg_size,
664                                       lcf->scfg_size,
665                                       lcf->is_subordinate);
666     lcf->state = FINISHED;
667   case FINISHED:   
668     lcfq = lcfq_head;
669     GNUNET_assert (lcfq->lcf == lcf);
670     GNUNET_free (lcf->sxcfg);
671     GNUNET_free (lcf);
672     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
673     GNUNET_free (lcfq);
674     if (NULL != lcfq_head)
675       lcf_proc_task_id = 
676         GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq_head->lcf);
677   }
678 }
679
680
681 /**
682  * Callback for event from slave controllers
683  *
684  * @param cls struct Slave *
685  * @param event information about the event
686  */
687 static void 
688 slave_event_callback(void *cls,
689                      const struct GNUNET_TESTBED_EventInformation *event)
690 {
691   GNUNET_break (0);
692 }
693
694
695
696 /**
697  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_INIT messages
698  *
699  * @param cls NULL
700  * @param client identification of the client
701  * @param message the actual message
702  */
703 static void 
704 handle_init (void *cls,
705              struct GNUNET_SERVER_Client *client,
706              const struct GNUNET_MessageHeader *message)
707 {
708   const struct GNUNET_TESTBED_InitMessage *msg;
709   struct GNUNET_TESTBED_Host *host;
710
711   if (NULL != master_context)
712   {
713     GNUNET_break (0);
714     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
715     return;
716   }
717   msg = (const struct GNUNET_TESTBED_InitMessage *) message;  
718   master_context = GNUNET_malloc (sizeof (struct Context));
719   master_context->client = client;
720   master_context->host_id = ntohl (msg->host_id);
721   host = GNUNET_TESTBED_host_create_with_id (master_context->host_id,
722                                              NULL, NULL, 0);
723   host_list_add (host);
724   master_context->event_mask = GNUNET_ntohll (msg->event_mask);
725   GNUNET_SERVER_client_keep (client);
726   LOG_DEBUG ("Created master context with host ID: %u\n",
727              master_context->host_id);
728   GNUNET_SERVER_receive_done (client, GNUNET_OK);
729 }
730
731
732 /**
733  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
734  *
735  * @param cls NULL
736  * @param client identification of the client
737  * @param message the actual message
738  */
739 static void 
740 handle_add_host (void *cls,
741                  struct GNUNET_SERVER_Client *client,
742                  const struct GNUNET_MessageHeader *message)
743 {
744   struct GNUNET_TESTBED_Host *host;
745   const struct GNUNET_TESTBED_AddHostMessage *msg;
746   struct GNUNET_TESTBED_HostConfirmedMessage *reply;
747   char *username;
748   char *hostname;
749   char *emsg;
750   uint32_t host_id;
751   uint16_t username_length;
752   uint16_t hostname_length;
753   uint16_t reply_size;
754   
755   msg = (const struct GNUNET_TESTBED_AddHostMessage *) message;
756   username_length = ntohs (msg->user_name_length);
757   username_length = (0 == username_length) ? 0 : username_length + 1;
758   username = (char *) &(msg[1]);
759   hostname = username + username_length;
760   if (ntohs (message->size) <=
761       (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length))
762   {
763     GNUNET_break (0);
764     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
765     return;
766   }
767   hostname_length = ntohs (message->size)
768     - (sizeof (struct GNUNET_TESTBED_AddHostMessage) + username_length);
769   if (strlen (hostname) != hostname_length - 1)
770   {
771     GNUNET_break (0);
772     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
773     return;
774   }
775   host_id = ntohl (msg->host_id);
776   LOG_DEBUG ("Received ADDHOST message\n");
777   LOG_DEBUG ("-------host id: %u\n", host_id);
778   if (NULL != hostname) LOG_DEBUG ("-------hostname: %s\n", hostname);
779   if (0 != username_length) LOG_DEBUG ("-------username: %s\n", username);
780   else LOG_DEBUG ("-------username: NULL\n");
781   LOG_DEBUG ("-------ssh port: %u\n", ntohs (msg->ssh_port));
782   host = GNUNET_TESTBED_host_create_with_id (host_id, hostname, username,
783                                              ntohs (msg->ssh_port));
784   GNUNET_SERVER_receive_done (client, GNUNET_OK);
785   reply_size = sizeof (struct GNUNET_TESTBED_HostConfirmedMessage);
786   if (GNUNET_OK != host_list_add (host))
787   {    
788     /* We are unable to add a host */  
789     emsg = "A host exists with given host-id";
790     LOG_DEBUG ("%s: %u", emsg, host_id);
791     GNUNET_TESTBED_host_destroy (host);
792     reply_size += strlen (emsg) + 1;
793     reply = GNUNET_malloc (reply_size);
794     memcpy (&reply[1], emsg, strlen (emsg) + 1);
795   }
796   else
797     reply = GNUNET_malloc (reply_size);  
798   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM);
799   reply->header.size = htons (reply_size);
800   reply->host_id = htonl (host_id);  
801   queue_message (client, (struct GNUNET_MessageHeader *) reply);
802 }
803
804
805 /**
806  * Iterator over hash map entries.
807  *
808  * @param cls closure
809  * @param key current key code
810  * @param value value in the hash map
811  * @return GNUNET_YES if we should continue to
812  *         iterate,
813  *         GNUNET_NO if not.
814  */
815 int ss_exists_iterator (void *cls,
816                         const struct GNUNET_HashCode * key,
817                         void *value)
818 {
819   struct SharedService *queried_ss = cls;
820   struct SharedService *ss = value;
821
822   if (0 == strcmp (ss->name, queried_ss->name))
823     return GNUNET_NO;
824   else
825     return GNUNET_YES;
826 }
827
828
829 /**
830  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST messages
831  *
832  * @param cls NULL
833  * @param client identification of the client
834  * @param message the actual message
835  */
836 static void 
837 handle_configure_shared_service (void *cls,
838                                  struct GNUNET_SERVER_Client *client,
839                                  const struct GNUNET_MessageHeader *message)
840 {
841   const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
842   struct SharedService *ss;
843   char *service_name;
844   struct GNUNET_HashCode hash;
845   uint16_t msg_size;
846   uint16_t service_name_size;
847     
848   msg = (const struct GNUNET_TESTBED_ConfigureSharedServiceMessage *) message;
849   msg_size = ntohs (message->size);
850   if (msg_size <= sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage))
851   {
852     GNUNET_break (0);
853     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
854     return;
855   }
856   service_name_size = msg_size - 
857     sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage);
858   service_name = (char *) &msg[1];
859   if ('\0' != service_name[service_name_size - 1])
860   {
861     GNUNET_break (0);
862     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
863     return;
864   }
865   LOG_DEBUG ("Received service sharing request for %s, with %d peers\n",
866              service_name, ntohl (msg->num_peers));
867   if (ntohl (msg->host_id) != master_context->host_id)
868   {
869     route_message (ntohl (msg->host_id), message);
870     GNUNET_SERVER_receive_done (client, GNUNET_OK);
871     return;
872   }
873   GNUNET_SERVER_receive_done (client, GNUNET_OK);
874   ss = GNUNET_malloc (sizeof (struct SharedService));
875   ss->name = strdup (service_name);
876   ss->num_shared = ntohl (msg->num_peers);
877   GNUNET_CRYPTO_hash (ss->name, service_name_size, &hash);
878   if (GNUNET_SYSERR == 
879       GNUNET_CONTAINER_multihashmap_get_multiple (ss_map, &hash,
880                                                   &ss_exists_iterator, ss))
881   {
882     LOG (GNUNET_ERROR_TYPE_WARNING,
883          "Service %s already configured as a shared service. "
884          "Ignoring service sharing request \n", ss->name);
885     GNUNET_free (ss->name);
886     GNUNET_free (ss);
887     return;
888   }
889   GNUNET_CONTAINER_multihashmap_put (ss_map, &hash, ss,
890                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
891 }
892
893
894 /**
895  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS message
896  *
897  * @param cls NULL
898  * @param client identification of the client
899  * @param message the actual message
900  */
901 static void 
902 handle_link_controllers (void *cls,
903                          struct GNUNET_SERVER_Client *client,
904                          const struct GNUNET_MessageHeader *message)
905 {
906   const struct GNUNET_TESTBED_ControllerLinkMessage *msg;
907   struct GNUNET_CONFIGURATION_Handle *cfg;
908   struct LCFContextQueue *lcfq;
909   struct Route *route;
910   struct Route *new_route;
911   char *config;  
912   uLongf dest_size;
913   size_t config_size;
914   uint32_t delegated_host_id;
915   uint32_t slave_host_id;
916   uint16_t msize;
917    
918   if (NULL == master_context)
919   {
920     GNUNET_break (0);
921     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
922     return;
923   }
924   msize = ntohs (message->size);
925   if (sizeof (struct GNUNET_TESTBED_ControllerLinkMessage) >= msize)
926   {
927     GNUNET_break (0);
928     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
929     return;
930   }
931   msg = (const struct GNUNET_TESTBED_ControllerLinkMessage *) message;
932   delegated_host_id = ntohl (msg->delegated_host_id);
933   if (delegated_host_id == master_context->host_id)
934   {
935     GNUNET_break (0);
936     LOG (GNUNET_ERROR_TYPE_WARNING, "Trying to link ourselves\n");
937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
938     return;
939   }
940   if ((delegated_host_id >= host_list_size) || 
941       (NULL == host_list[delegated_host_id]))
942   {
943     LOG (GNUNET_ERROR_TYPE_WARNING, "Delegated host not registered with us\n");
944     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
945     return;
946   }
947   slave_host_id = ntohl (msg->slave_host_id);
948   if ((slave_host_id >= host_list_size) || (NULL == host_list[slave_host_id]))
949   {
950     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave host not registered with us\n");
951     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
952     return;
953   }
954   if (slave_host_id == delegated_host_id)
955   {
956     LOG (GNUNET_ERROR_TYPE_WARNING, "Slave and delegated host are same\n");
957     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
958     return;
959   }
960   msize -= sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
961   config_size = ntohs (msg->config_size);
962   
963   if (slave_host_id == master_context->host_id) /* Link from us */
964   {
965     struct Slave *slave;
966
967     if ((delegated_host_id < slave_list_size) && 
968         (NULL != slave_list[delegated_host_id])) /* We have already added */
969     {
970       LOG (GNUNET_ERROR_TYPE_WARNING, "Host %u already connected\n",
971            delegated_host_id);
972       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
973       return;
974     }    
975     config = GNUNET_malloc (config_size);
976     dest_size = (uLongf) config_size;    
977     if (Z_OK != uncompress ((Bytef *) config, &dest_size,
978                             (const Bytef *) &msg[1], (uLong) msize))
979     {
980       GNUNET_break (0);           /* Compression error */
981       GNUNET_free (config);
982       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
983       return;
984     }
985     if (config_size == dest_size)
986     {
987       LOG (GNUNET_ERROR_TYPE_WARNING, "Uncompressed config size mismatch\n");
988       GNUNET_free (config);
989       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
990     }
991     cfg = GNUNET_CONFIGURATION_create (); /* Free here or in lcfcontext */
992     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
993                                                        GNUNET_NO))
994     {
995       GNUNET_break (0);           /* Configuration parsing error */
996       GNUNET_free (config);
997       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
998       return;
999     }
1000     GNUNET_free (config);
1001     if ((delegated_host_id < slave_list_size) &&
1002         (NULL != slave_list[delegated_host_id]))
1003     {
1004       GNUNET_break (0);           /* Configuration parsing error */
1005       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1006       return;
1007     }
1008     slave = GNUNET_malloc (sizeof (struct Slave));
1009     slave->host_id = delegated_host_id;
1010     slave_list_add (slave);
1011     if (1 == msg->is_subordinate)
1012     {
1013       slave->controller_proc =
1014         GNUNET_TESTBED_controller_start (host_list[delegated_host_id]);
1015     }
1016     slave->controller =
1017       GNUNET_TESTBED_controller_connect (cfg, host_list[delegated_host_id],
1018                                          master_context->event_mask,
1019                                          &slave_event_callback, slave);
1020     GNUNET_CONFIGURATION_destroy (cfg);
1021     new_route = GNUNET_malloc (sizeof (struct Route));
1022     new_route->dest = delegated_host_id;
1023     new_route->thru = master_context->host_id;
1024     route_list_add (new_route);
1025     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1026     return;
1027   }
1028
1029   /* Route the request */
1030   if (slave_host_id >= route_list_size)
1031   {
1032     LOG (GNUNET_ERROR_TYPE_WARNING, "No route towards slave host");
1033     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1034     return;
1035   }
1036   while (NULL != (route = route_list[slave_host_id]))
1037   {
1038     if (route->thru == master_context->host_id)
1039       break;
1040     slave_host_id = route->thru;
1041   }
1042   GNUNET_assert (NULL != route); /* because we add routes carefully */
1043   GNUNET_assert (route->dest < slave_list_size);
1044   GNUNET_assert (NULL != slave_list[route->dest]);  
1045   lcfq = GNUNET_malloc (sizeof (struct LCFContextQueue));
1046   lcfq->lcf = GNUNET_malloc (sizeof (struct LCFContext));
1047   lcfq->lcf->delegated_host_id = delegated_host_id;
1048   lcfq->lcf->is_subordinate =
1049     (1 == msg->is_subordinate) ? GNUNET_YES : GNUNET_NO;
1050   lcfq->lcf->state = INIT;
1051   lcfq->lcf->gateway = slave_list[route->dest];
1052   lcfq->lcf->sxcfg_size = msize;
1053   lcfq->lcf->sxcfg = GNUNET_malloc (msize);
1054   lcfq->lcf->scfg_size = config_size;
1055   (void) memcpy (lcfq->lcf->sxcfg, &msg[1], msize);
1056   if (NULL == lcfq_head)
1057   {
1058     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1059     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1060     lcf_proc_task_id = GNUNET_SCHEDULER_add_now (&lcf_proc_task, lcfq);
1061   }
1062   else
1063     GNUNET_CONTAINER_DLL_insert_tail (lcfq_head, lcfq_tail, lcfq);
1064   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1065   new_route = GNUNET_malloc (sizeof (struct Route));
1066   new_route->dest = delegated_host_id;
1067   new_route->thru = route->dest;
1068   route_list_add (new_route);
1069 }
1070
1071
1072 /**
1073  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER messages
1074  *
1075  * @param cls NULL
1076  * @param client identification of the client
1077  * @param message the actual message
1078  */
1079 static void 
1080 handle_peer_create (void *cls,
1081                     struct GNUNET_SERVER_Client *client,
1082                     const struct GNUNET_MessageHeader *message)
1083 {
1084   const struct GNUNET_TESTBED_PeerCreateMessage *msg;
1085   struct GNUNET_CONFIGURATION_Handle *cfg;
1086   char *config;
1087   size_t dest_size;
1088   int ret;
1089   uint32_t config_size;
1090   uint16_t msize;
1091   
1092
1093   msize = ntohs (message->size);
1094   if (msize <= sizeof (struct GNUNET_TESTBED_PeerCreateMessage))
1095   {
1096     GNUNET_break (0);           /* We need configuration */
1097     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1098     return;
1099   }
1100   msg = (const struct GNUNET_TESTBED_PeerCreateMessage *) message;
1101   if (ntohl (msg->host_id) == master_context->host_id)
1102   {
1103     struct Peer *peer;
1104     char *emsg;
1105     
1106     /* We are responsible for this peer */
1107     msize -= sizeof (struct GNUNET_TESTBED_PeerCreateMessage);
1108     config_size = ntohl (msg->config_size);    
1109     config = GNUNET_malloc (config_size);
1110     dest_size = config_size;
1111     if (Z_OK != (ret = uncompress ((Bytef *) config, (uLongf *) &dest_size,
1112                                    (const Bytef *) &msg[1], (uLong) msize)))
1113     {
1114       GNUNET_break (0);           /* uncompression error */
1115       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1116       return;
1117     }
1118     if (config_size != dest_size)
1119     {
1120       GNUNET_break (0);/* Uncompressed config size mismatch */
1121       GNUNET_free (config);
1122       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1123       return;
1124     }
1125     cfg = GNUNET_CONFIGURATION_create ();
1126     if (GNUNET_OK != GNUNET_CONFIGURATION_deserialize (cfg, config, config_size,
1127                                                        GNUNET_NO))
1128     {
1129       GNUNET_break (0);           /* Configuration parsing error */
1130       GNUNET_free (config);
1131       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1132       return;
1133     }
1134     GNUNET_free (config);
1135     peer = GNUNET_malloc (sizeof (struct Peer));
1136     peer->cfg = cfg;
1137     peer->id = ntohl (msg->peer_id);
1138     LOG_DEBUG ("Creating peer with id: %u\n", peer->id);
1139     peer->peer = GNUNET_TESTING_peer_configure (test_system, peer->cfg,
1140                                                 peer->id,
1141                                                 NULL /* Peer id */,
1142                                                 &emsg);
1143     if (NULL == peer->peer)
1144     {
1145       LOG (GNUNET_ERROR_TYPE_WARNING, "Configuring peer failed: %s\n", emsg);
1146       GNUNET_free (emsg);
1147       GNUNET_break (0);
1148       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1149       return;
1150     }
1151     peer_list_add (peer);
1152     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1153     return;
1154   }
1155
1156   /* Forward the peer to other host */
1157   GNUNET_break (0);
1158   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1159 }
1160
1161
1162 /**
1163  * Message handler for GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER messages
1164  *
1165  * @param cls NULL
1166  * @param client identification of the client
1167  * @param message the actual message
1168  */
1169 static void 
1170 handle_peer_destroy (void *cls,
1171                      struct GNUNET_SERVER_Client *client,
1172                      const struct GNUNET_MessageHeader *message)
1173 {
1174   const struct GNUNET_TESTBED_PeerDestroyMessage *msg;
1175   struct GNUNET_TESTBED_GenericOperationSuccessEventMessage *reply;
1176   uint32_t peer_id;
1177   uint32_t id;
1178   uint16_t reply_size;
1179   
1180   msg = (const struct GNUNET_TESTBED_PeerDestroyMessage *) message;
1181   peer_id = ntohl (msg->peer_id);
1182   LOG_DEBUG ("Received peer destory on peer: %u and operation id: %ul\n",
1183              peer_id, GNUNET_ntohll (msg->operation_id));
1184   if ((peer_list_size <= peer_id) || (NULL == peer_list[peer_id]))
1185   {
1186     GNUNET_break (0);
1187     /* Reply with failure event message */
1188   }  
1189   GNUNET_TESTING_peer_destroy (peer_list[peer_id]->peer);
1190   GNUNET_CONFIGURATION_destroy (peer_list[peer_id]->cfg);
1191   GNUNET_free (peer_list[peer_id]);
1192   peer_list[peer_id] = NULL;
1193   for (id = 0; id < LIST_GROW_STEP; id++)
1194   {
1195     if (((peer_id + id >= peer_list_size) ||
1196          (NULL != peer_list[peer_id])))
1197       break;
1198   }
1199   if (LIST_GROW_STEP == id)
1200   {
1201     peer_list_size -= LIST_GROW_STEP;
1202     peer_list = GNUNET_realloc (peer_list, peer_list_size);
1203   }
1204   reply_size = 
1205     sizeof (struct GNUNET_TESTBED_GenericOperationSuccessEventMessage);
1206   reply = GNUNET_malloc (reply_size);
1207   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS);
1208   reply->header.size = htons (reply_size);
1209   reply->operation_id = msg->operation_id;
1210   queue_message (client, (struct GNUNET_MessageHeader *) reply);
1211   
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 static int 
1226 ss_map_free_iterator (void *cls,
1227                       const struct GNUNET_HashCode * key, void *value)
1228 {
1229   struct SharedService *ss = value;
1230
1231   GNUNET_assert (GNUNET_YES ==
1232                  GNUNET_CONTAINER_multihashmap_remove (ss_map, key, value));
1233   GNUNET_free (ss->name);
1234   GNUNET_free (ss);
1235   return GNUNET_YES;
1236 }
1237
1238
1239 /**
1240  * Task to clean up and shutdown nicely
1241  *
1242  * @param cls NULL
1243  * @param tc the TaskContext from scheduler
1244  */
1245 static void
1246 shutdown_task (void *cls,
1247                const struct GNUNET_SCHEDULER_TaskContext *tc)
1248 {
1249   struct LCFContextQueue *lcfq;
1250   uint32_t id;
1251
1252   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
1253   GNUNET_SCHEDULER_shutdown ();
1254   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down testbed service\n");
1255   (void) GNUNET_CONTAINER_multihashmap_iterate (ss_map, &ss_map_free_iterator,
1256                                                 NULL);
1257   GNUNET_CONTAINER_multihashmap_destroy (ss_map);
1258   GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
1259   if (NULL != fh)
1260   {
1261     GNUNET_DISK_file_close (fh);
1262     fh = NULL;
1263   }
1264   if (NULL != lcfq_head)
1265   {
1266     if (GNUNET_SCHEDULER_NO_TASK != lcf_proc_task_id)
1267     {
1268       GNUNET_SCHEDULER_cancel (lcf_proc_task_id);
1269       lcf_proc_task_id = GNUNET_SCHEDULER_NO_TASK;
1270     }
1271     if (NULL != lcfq_head->lcf->rhandle)
1272       GNUNET_TESTBED_cancel_registration (lcfq_head->lcf->rhandle);
1273   }
1274   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == lcf_proc_task_id);
1275   for (lcfq = lcfq_head; NULL != lcfq; lcfq = lcfq_head)
1276   {
1277     GNUNET_free (lcfq->lcf->sxcfg);
1278     GNUNET_free (lcfq->lcf);
1279     GNUNET_CONTAINER_DLL_remove (lcfq_head, lcfq_tail, lcfq);
1280     GNUNET_free (lcfq);
1281   }
1282   /* Clear peer list */
1283   for (id = 0; id < peer_list_size; id++)
1284     if (NULL != peer_list[id])
1285     {
1286       GNUNET_TESTING_peer_destroy (peer_list[id]->peer);
1287       GNUNET_CONFIGURATION_destroy (peer_list[id]->cfg);
1288       GNUNET_free (peer_list[id]);
1289     }
1290   GNUNET_free_non_null (peer_list);
1291   /* Clear host list */
1292   for (id = 0; id < host_list_size; id++)
1293     if (NULL != host_list[id])
1294       GNUNET_TESTBED_host_destroy (host_list[id]);
1295   GNUNET_free_non_null (host_list);
1296   /* Clear route list */
1297   for (id = 0; id < route_list_size; id++)
1298     if (NULL != route_list[id])
1299       GNUNET_free (route_list[id]);
1300   GNUNET_free_non_null (route_list);
1301   /* Clear slave_list */
1302   for (id = 0; id < slave_list_size; id++)
1303     if (NULL != slave_list[id])
1304     {
1305       GNUNET_assert (NULL != slave_list[id]->controller);
1306       GNUNET_TESTBED_controller_disconnect (slave_list[id]->controller);
1307       if (NULL != slave_list[id]->controller_proc)
1308         GNUNET_TESTBED_controller_stop (slave_list[id]->controller_proc);
1309     }
1310   GNUNET_free_non_null (master_context);
1311 }
1312
1313
1314 /**
1315  * Callback for client disconnect
1316  *
1317  * @param cls NULL
1318  * @param client the client which has disconnected
1319  */
1320 static void
1321 client_disconnect_cb (void *cls, struct GNUNET_SERVER_Client *client)
1322 {
1323   if (NULL == master_context)
1324     return;
1325   if (client == master_context->client)
1326   {
1327     LOG (GNUNET_ERROR_TYPE_DEBUG, "Master client disconnected\n");
1328     GNUNET_SERVER_client_drop (client);
1329     /* should not be needed as we're terminated by failure to read
1330        from stdin, but if stdin fails for some reason, this shouldn't 
1331        hurt for now --- might need to revise this later if we ever
1332        decide that master connections might be temporarily down 
1333        for some reason */
1334     GNUNET_SCHEDULER_shutdown ();
1335   }
1336 }
1337
1338
1339 /**
1340  * Testbed setup
1341  *
1342  * @param cls closure
1343  * @param server the initialized server
1344  * @param cfg configuration to use
1345  */
1346 static void 
1347 testbed_run (void *cls,
1348              struct GNUNET_SERVER_Handle *server,
1349              const struct GNUNET_CONFIGURATION_Handle *cfg)
1350 {
1351   static const struct GNUNET_SERVER_MessageHandler message_handlers[] =
1352     {
1353       {&handle_init, NULL, GNUNET_MESSAGE_TYPE_TESTBED_INIT,
1354        sizeof (struct GNUNET_TESTBED_InitMessage)},
1355       {&handle_add_host, NULL, GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST, 0},
1356       {&handle_configure_shared_service, NULL,
1357        GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE, 0},
1358       {&handle_link_controllers, NULL,
1359        GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS, 0},
1360       {&handle_peer_create, NULL, GNUNET_MESSAGE_TYPE_TESTBED_CREATEPEER, 0},
1361       {&handle_peer_destroy, NULL, GNUNET_MESSAGE_TYPE_TESTBED_DESTROYPEER,
1362        sizeof (struct GNUNET_TESTBED_PeerDestroyMessage)},
1363       {NULL}
1364     };
1365
1366   GNUNET_SERVER_add_handlers (server,
1367                               message_handlers);
1368   GNUNET_SERVER_disconnect_notify (server,
1369                                    &client_disconnect_cb,
1370                                    NULL);
1371   ss_map = GNUNET_CONTAINER_multihashmap_create (5);
1372   test_system = GNUNET_TESTING_system_create ("testbed_peers", NULL);
1373   
1374   fh = GNUNET_DISK_get_handle_from_native (stdin);
1375   if (NULL == fh)
1376     shutdown_task_id = 
1377       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,                                  
1378                                     &shutdown_task,
1379                                     NULL);
1380   else
1381     shutdown_task_id = 
1382       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1383                                       fh,
1384                                       &shutdown_task,
1385                                       NULL);
1386   LOG_DEBUG ("Testbed startup complete\n");
1387 }
1388
1389
1390 /**
1391  * The starting point of execution
1392  */
1393 int main (int argc, char *const *argv)
1394 {
1395   return
1396     (GNUNET_OK ==
1397      GNUNET_SERVICE_run (argc,
1398                          argv,
1399                          "testbed",
1400                          GNUNET_SERVICE_OPTION_NONE,
1401                          &testbed_run,
1402                          NULL)) ? 0 : 1;
1403 }