130fef535088e8e390ac4a4492cae801ca71ffee
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      (C)
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 3, 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 rps/gnunet-service-rps.c
23  * @brief rps service implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_cadet_service.h"
29 #include "gnunet_nse_service.h"
30 #include "rps.h"
31
32 #include "gnunet-service-rps_sampler.h"
33
34 #include <math.h>
35 #include <inttypes.h>
36
37 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
38
39 // TODO modify @brief in every file
40
41 // TODO take care that messages are not longer than 64k
42
43 // TODO check for overflows
44
45 // TODO align message structs
46
47 // (TODO api -- possibility of getting weak random peer immideately)
48
49 // TODO malicious peer
50
51 // TODO Change API to accept initialisation peers
52
53 // TODO Change API to accept good peers 'friends'
54
55 // TODO store peers somewhere
56
57 // TODO check that every id we get is valid - is it reachable?
58
59 // hist_size_init, hist_size_max
60
61 /**
62  * Our configuration.
63  */
64 static const struct GNUNET_CONFIGURATION_Handle *cfg;
65
66 /**
67  * Our own identity.
68  */
69 static struct GNUNET_PeerIdentity *own_identity;
70
71 /**
72  * Closure to the callback cadet calls on each peer it passes to us
73  */
74 struct init_peer_cls
75 {
76   /**
77    * The server handle to later listen to client requests
78    */
79   struct GNUNET_SERVER_Handle *server;
80
81   /**
82    * Counts how many peers cadet already passed to us
83    */
84   uint32_t i;
85 };
86
87
88   struct GNUNET_PeerIdentity *
89 get_rand_peer (const struct GNUNET_PeerIdentity *peer_list, unsigned int size);
90
91
92 /***********************************************************************
93  * Housekeeping with peers
94 ***********************************************************************/
95
96 /**
97  * Struct used to store the context of a connected client.
98  */
99 struct client_ctx
100 {
101   /**
102    * The message queue to communicate with the client.
103    */
104   struct GNUNET_MQ_Handle *mq;
105 };
106
107 /**
108  * Used to keep track in what lists single peerIDs are.
109  */
110 enum in_list_flag // probably unneeded
111 {
112   in_other_sampler_list = 0x1,
113   in_other_gossip_list  = 0x2, // unneeded?
114   in_own_sampler_list   = 0x4,
115   in_own_gossip_list    = 0x8 // unneeded?
116 };
117
118 /**
119  * Struct used to keep track of other peer's status
120  *
121  * This is stored in a multipeermap.
122  */
123 struct peer_context
124 {
125   /**
126    * In own gossip/sampler list, in other's gossip/sampler list
127    */
128   uint32_t in_flags; // unneeded?
129
130   /**
131    * Message queue open to client
132    */
133   struct GNUNET_MQ_Handle *mq;
134
135   /**
136    * Channel open to client.
137    */
138   struct GNUNET_CADET_Channel *to_channel;
139
140   /**
141    * Channel open from client.
142    */
143   struct GNUNET_CADET_Channel *from_channel; // unneeded
144
145   /**
146    * This is pobably followed by 'statistical' data (when we first saw
147    * him, how did we get his ID, how many pushes (in a timeinterval),
148    * ...)
149    */
150 };
151
152 /***********************************************************************
153  * /Housekeeping with peers
154 ***********************************************************************/
155
156 /**
157  * Set of all peers to keep track of them.
158  */
159 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
160
161
162 /**
163  * The gossiped list of peers.
164  */
165 static struct GNUNET_PeerIdentity *gossip_list;
166
167 /**
168  * Size of the gossiped list
169  */
170 static unsigned int gossip_list_size;
171
172
173 /**
174  * The estimated size of the network.
175  *
176  * Influenced by the stdev.
177  */
178 static unsigned int est_size;
179 //size_t est_size;
180
181
182 /**
183  * Percentage of total peer number in the gossip list
184  * to send random PUSHes to
185  *
186  * TODO do not read from configuration
187  */
188 static float alpha;
189
190 /**
191  * Percentage of total peer number in the gossip list
192  * to send random PULLs to
193  *
194  * TODO do not read from configuration
195  */
196 static float beta;
197
198 /**
199  * The percentage gamma of history updates.
200  * Simply 1 - alpha - beta
201  */
202
203
204
205
206 /**
207  * Identifier for the main task that runs periodically.
208  */
209 static struct GNUNET_SCHEDULER_Task * do_round_task;
210
211 /**
212  * Time inverval the do_round task runs in.
213  */
214 static struct GNUNET_TIME_Relative round_interval;
215
216
217
218 /**
219  * List to store peers received through pushes temporary.
220  *
221  * TODO -> multipeermap
222  */
223 static struct GNUNET_PeerIdentity *push_list;
224
225 /**
226  * Size of the push_list;
227  */
228 static unsigned int push_list_size;
229 //size_t push_list_size;
230
231 /**
232  * List to store peers received through pulls temporary.
233  *
234  * TODO -> multipeermap
235  */
236 static struct GNUNET_PeerIdentity *pull_list;
237
238 /**
239  * Size of the pull_list;
240  */
241 static unsigned int pull_list_size;
242 //size_t pull_list_size;
243
244
245 /**
246  * Handler to NSE.
247  */
248 static struct GNUNET_NSE_Handle *nse;
249
250 /**
251  * Handler to CADET.
252  */
253 static struct GNUNET_CADET_Handle *cadet_handle;
254
255 /**
256  * Global counter
257  */
258 uint64_t g_i = 0;
259
260
261 /***********************************************************************
262  * Util functions
263 ***********************************************************************/
264
265 /**
266  * Get random peer from the gossip list.
267  */
268   struct GNUNET_PeerIdentity *
269 get_rand_peer(const struct GNUNET_PeerIdentity *peer_list, unsigned int list_size)
270 {
271   uint64_t r_index;
272   struct GNUNET_PeerIdentity *peer;
273
274   peer = GNUNET_new(struct GNUNET_PeerIdentity);
275   // FIXME if we have only NULL in gossip list this will block
276   // but then we might have a problem nevertheless
277
278   do
279   {
280
281     /**;
282      * Choose the r_index of the peer we want to return
283      * at random from the interval of the gossip list
284      */
285     r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
286                                      list_size);
287
288     *peer = peer_list[r_index];
289   } while (NULL == peer);
290
291   return peer;
292 }
293
294
295 /**
296  * Get the context of a peer. If not existing, create.
297  */
298   struct peer_context *
299 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
300 {
301   struct peer_context *ctx;
302
303   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
304   {
305     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
306   }
307   else
308   {
309     ctx = GNUNET_new (struct peer_context);
310     ctx->in_flags = 0;
311     ctx->mq = NULL;
312     ctx->to_channel = NULL;
313     ctx->from_channel = NULL;
314     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
315   }
316   return ctx;
317 }
318
319
320 /**
321  * Get the channel of a peer. If not existing, create.
322  */
323   struct GNUNET_CADET_Channel *
324 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
325 {
326   struct peer_context *ctx;
327
328   ctx = get_peer_ctx (peer_map, peer);
329   if (NULL == ctx->to_channel)
330   {
331     ctx->to_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
332                                                    GNUNET_RPS_CADET_PORT,
333                                                    GNUNET_CADET_OPTION_RELIABLE);
334     // do I have to explicitly put it in the peer_map?
335     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
336                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
337   }
338   return ctx->to_channel;
339 }
340
341
342 /**
343  * Get the message queue of a specific peer.
344  *
345  * If we already have a message queue open to this client,
346  * simply return it, otherways create one.
347  */
348   struct GNUNET_MQ_Handle *
349 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer_id)
350 {
351   struct peer_context *ctx;
352
353   ctx = get_peer_ctx (peer_map, peer_id);
354   if (NULL == ctx->mq)
355   {
356     (void) get_channel (peer_map, peer_id);
357     ctx->mq = GNUNET_CADET_mq_create (ctx->to_channel);
358     //do I have to explicitly put it in the peer_map?
359     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
360                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
361   }
362   return ctx->mq;
363 }
364
365
366 /***********************************************************************
367  * /Util functions
368 ***********************************************************************/
369
370 /**
371  * Function called by NSE.
372  *
373  * Updates sizes of sampler list and gossip list and adapt those lists
374  * accordingly.
375  */
376   void
377 nse_callback(void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
378 {
379   double estimate;
380   unsigned int old_est;
381   //double scale; // TODO this might go gloabal/config
382
383   old_est = est_size;
384
385   LOG (GNUNET_ERROR_TYPE_DEBUG,
386       "Received a ns estimate - logest: %f, std_dev: %f (old_est: %f)\n",
387       logestimate, std_dev, old_est);
388   //scale = .01;
389   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
390   // GNUNET_NSE_log_estimate_to_n (logestimate);
391   estimate = pow (estimate, 1./3);
392   // TODO add if std_dev is a number
393   // estimate += (std_dev * scale);
394   if ( 0 < estimate ) {
395     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
396     est_size = estimate;
397   } else
398     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
399
400   /* If the NSE has changed adapt the lists accordingly */
401   // TODO respect the request rate, min, max
402   if (old_est > est_size*4)
403   { /* Shrinking */
404     RPS_sampler_resize (old_est/2);
405   }
406   else if (old_est < est_size)
407   { /* Growing */
408     if (est_size < old_est*2)
409       RPS_sampler_resize (old_est*2);
410     else
411       RPS_sampler_resize (est_size);
412   }
413 }
414
415 /**
416  * Handle RPS request from the client.
417  *
418  * @param cls closure
419  * @param client identification of the client
420  * @param message the actual message
421  */
422 static void
423 // TODO rename
424 handle_cs_request (void *cls,
425             struct GNUNET_SERVER_Client *client,
426             const struct GNUNET_MessageHeader *message)
427 {
428   LOG(GNUNET_ERROR_TYPE_DEBUG, "Client requested (a) random peer(s).\n");
429
430   struct GNUNET_RPS_CS_RequestMessage *msg;
431   //unsigned int n_arr[sampler_list->size];// =
432     //GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
433   //struct GNUNET_MQ_Handle *mq;
434   struct client_ctx *cli_ctx;
435   struct GNUNET_MQ_Envelope *ev;
436   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
437   uint64_t num_peers;
438   const struct GNUNET_PeerIdentity *peers;
439   //uint64_t i;
440
441   // TODO check message size
442   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
443   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
444   if ( NULL == cli_ctx ) {
445     cli_ctx = GNUNET_new(struct client_ctx);
446     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
447     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
448   }
449   
450   // How many peers do we give back?
451   // Wait until we have enough random peers?
452
453   num_peers = GNUNET_ntohll (msg->num_peers);
454
455   ev = GNUNET_MQ_msg_extra (out_msg,
456                             num_peers * sizeof (struct GNUNET_PeerIdentity),
457                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
458   out_msg->num_peers = msg->num_peers; // No conversion between network and network order
459
460   //&out_msg[1] = RPS_sampler_get_n_rand_peers (num_peers);
461   peers = RPS_sampler_get_n_rand_peers (num_peers);
462   memcpy(&out_msg[1],
463       peers,
464       num_peers * sizeof (struct GNUNET_PeerIdentity));
465   
466   GNUNET_MQ_send (cli_ctx->mq, ev);
467   //GNUNET_MQ_destroy(mq);
468
469   GNUNET_SERVER_receive_done (client,
470                               GNUNET_OK);
471 }
472
473 /**
474  * Handle a PUSH message from another peer.
475  *
476  * Check the proof of work and store the PeerID
477  * in the temporary list for pushed PeerIDs.
478  *
479  * @param cls Closure
480  * @param channel The channel the PUSH was received over
481  * @param channel_ctx The context associated with this channel
482  * @param msg The message header
483  */
484 static int
485 handle_peer_push (void *cls,
486     struct GNUNET_CADET_Channel *channel,
487     void **channel_ctx,
488     const struct GNUNET_MessageHeader *msg)
489 {
490   const struct GNUNET_PeerIdentity *peer;
491
492   // (check the proof of work) 
493   
494   // TODO accept empty message
495   if (ntohs(msg->size) != sizeof (struct GNUNET_RPS_P2P_PushMessage))
496   {
497     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
498     return GNUNET_SYSERR;
499   }
500
501   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
502   // FIXME wait for cadet to change this function
503   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
504   
505   /* Add the sending peer to the push_list */
506   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding peer to push_list of size %u\n", push_list_size);
507   GNUNET_array_append (push_list, push_list_size, *peer);
508   LOG (GNUNET_ERROR_TYPE_DEBUG, "Size of push_list is now %u\n", push_list_size);
509
510   return GNUNET_OK;
511 }
512
513 /**
514  * Handle PULL REQUEST request message from another peer.
515  *
516  * Reply with the gossip list of PeerIDs.
517  *
518  * @param cls Closure
519  * @param channel The channel the PUSH was received over
520  * @param channel_ctx The context associated with this channel
521  * @param msg The message header
522  */
523 static int
524 handle_peer_pull_request (void *cls,
525     struct GNUNET_CADET_Channel *channel,
526     void **channel_ctx,
527     const struct GNUNET_MessageHeader *msg)
528 {
529   struct GNUNET_PeerIdentity *peer;
530   struct GNUNET_MQ_Handle *mq;
531   struct GNUNET_MQ_Envelope *ev;
532   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
533
534   // assert that msg->size is 0
535
536   // TODO accept empty message
537   if (ntohs(msg->size) != sizeof (struct GNUNET_RPS_P2P_PullRequestMessage))
538   {
539     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
540     return GNUNET_SYSERR;
541   }
542
543   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
544   // FIXME wait for cadet to change this function
545   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REQUEST from peer %s received\n", GNUNET_i2s (peer));
546
547   mq = get_mq (peer_map, peer);
548
549   ev = GNUNET_MQ_msg_extra (out_msg,
550                            gossip_list_size * sizeof (struct GNUNET_PeerIdentity),
551                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
552   out_msg->num_peers = GNUNET_htonll (gossip_list_size);
553   memcpy (&out_msg[1], gossip_list,
554          gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
555
556   GNUNET_MQ_send (mq, ev);
557
558   return GNUNET_OK;
559 }
560
561 /**
562  * Handle PULL REPLY message from another peer.
563  *
564  * Check whether we sent a corresponding request and
565  * whether this reply is the first one.
566  *
567  * @param cls Closure
568  * @param channel The channel the PUSH was received over
569  * @param channel_ctx The context associated with this channel
570  * @param msg The message header
571  */
572 static int
573 handle_peer_pull_reply (void *cls,
574     struct GNUNET_CADET_Channel *channel,
575     void **channel_ctx,
576     const struct GNUNET_MessageHeader *msg)
577 {
578   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
579
580   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
581   struct GNUNET_PeerIdentity *peers;
582   uint64_t i;
583
584   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) < ntohs (msg->size))
585   {
586     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
587     return GNUNET_SYSERR;
588   }
589   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
590   if (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) / sizeof (struct GNUNET_PeerIdentity) != GNUNET_ntohll (in_msg->num_peers))
591   {
592     GNUNET_break_op (0);
593     return GNUNET_SYSERR;
594   }
595
596   // TODO check that we sent a request and that it is the first reply
597
598   peers = (struct GNUNET_PeerIdentity *) &msg[1];
599   for ( i = 0 ; i < GNUNET_ntohll (in_msg->num_peers) ; i++ )
600   {
601     GNUNET_array_append (pull_list, pull_list_size, peers[i]);
602   }
603
604   // TODO check that id is valid - whether it is reachable
605
606   return GNUNET_OK;
607 }
608
609
610 /**
611  * Send out PUSHes and PULLs.
612  *
613  * This is executed regylary.
614  */
615 static void
616 do_round(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
617 {
618   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
619
620   uint64_t i;
621   //unsigned int *n_arr;
622   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
623   struct GNUNET_RPS_P2P_PushMessage        *push_msg;
624   struct GNUNET_RPS_P2P_PullRequestMessage *pull_msg; // FIXME Send empty message
625   struct GNUNET_MQ_Envelope *ev;
626   const struct GNUNET_PeerIdentity *peer;
627   struct GNUNET_MQ_Handle *mq;
628
629   // TODO print lists, ...
630   // TODO rendomise and spread calls herein over time
631
632
633   /* Would it make sense to have one shuffeled gossip list and then
634    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
635    * use the rest to update sampler?
636    * in essence get random peers with consumption */
637
638   /* Send PUSHes */
639   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
640   n_peers = round (alpha * gossip_list_size);
641   if (0 == n_peers)
642     n_peers = 1;
643   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %u (%f * %u) peers.\n",
644       n_peers, alpha, gossip_list_size);
645   for ( i = 0 ; i < n_peers ; i++ )
646   { // TODO compute length
647     peer = get_rand_peer (gossip_list, gossip_list_size);
648     if (own_identity != peer)
649     { // FIXME if this fails schedule/loop this for later
650       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s (peer));
651
652       ev = GNUNET_MQ_msg (push_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
653       //ev = GNUNET_MQ_msg_extra();
654       /* TODO Compute proof of work here
655          push_msg; */
656       //push_msg->placeholder = 0;
657       push_msg = NULL;
658       // FIXME sometimes it returns a pointer to a freed mq
659       mq = get_mq (peer_map, peer);
660       GNUNET_MQ_send (mq, ev);
661
662       // modify in_flags of respective peer?
663     }
664   }
665
666
667   /* Send PULL requests */
668   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
669   n_peers = round (beta * gossip_list_size);
670   if (0 == n_peers)
671     n_peers = 1;
672   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %u (%f * %u) peers.\n",
673       n_peers, beta, gossip_list_size);
674   for ( i = 0 ; i < n_peers ; i++ )
675   { // TODO compute length
676     peer = get_rand_peer (gossip_list, gossip_list_size);
677     if (own_identity != peer)
678     { // FIXME if this fails schedule/loop this for later
679       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s (peer));
680
681       ev = GNUNET_MQ_msg (pull_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
682       //pull_msg->placeholder = 0;
683       pull_msg = NULL;
684       mq = get_mq (peer_map, peer);
685       GNUNET_MQ_send (mq, ev);
686       // modify in_flags of respective peer?
687     }
688   }
689
690
691   /* Update gossip list */
692   uint64_t r_index;
693
694   if ( push_list_size <= alpha * gossip_list_size &&
695        push_list_size != 0 &&
696        pull_list_size != 0 )
697   {
698     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list. ()\n");
699
700     uint64_t first_border;
701     uint64_t second_border;
702     
703     GNUNET_array_grow(gossip_list, gossip_list_size, est_size);
704
705     first_border = round(alpha * gossip_list_size);
706     for ( i = 0 ; i < first_border ; i++ )
707     { // TODO use RPS_sampler_get_n_rand_peers
708       /* Update gossip list with peers received through PUSHes */
709       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
710                                        push_list_size);
711       gossip_list[i] = push_list[r_index];
712       // TODO change the in_flags accordingly
713     }
714
715     second_border = first_border + round(beta * gossip_list_size);
716     for ( i = first_border ; i < second_border ; i++ )
717     {
718       /* Update gossip list with peers received through PULLs */
719       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
720                                        pull_list_size);
721       gossip_list[i] = pull_list[r_index];
722       // TODO change the in_flags accordingly
723     }
724
725     for ( i = second_border ; i < gossip_list_size ; i++ )
726     {
727       /* Update gossip list with peers from history */
728       peer = RPS_sampler_get_n_rand_peers (1),
729       gossip_list[i] = *peer;
730       // TODO change the in_flags accordingly
731     }
732
733   }
734   else
735   {
736     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
737   }
738   // TODO independent of that also get some peers from CADET_get_peers()?
739
740
741   /* Update samplers */
742
743   for ( i = 0 ; i < push_list_size ; i++ )
744   {
745     RPS_sampler_update_list (&push_list[i]);
746     // TODO set in_flag?
747   }
748
749   for ( i = 0 ; i < pull_list_size ; i++ )
750   {
751     RPS_sampler_update_list (&pull_list[i]);
752     // TODO set in_flag?
753   }
754
755
756   /* Empty push/pull lists */
757   GNUNET_array_grow (push_list, push_list_size, 0);
758   GNUNET_array_grow (pull_list, pull_list_size, 0);
759
760
761   /* Schedule next round */
762   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
763   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
764 }
765
766
767 /**
768  * Open a connection to given peer and store channel and mq.
769  */
770   void
771 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
772 {
773   // We open a channel to be notified when this peer goes down.
774   (void) get_channel (peer_map, id);
775 }
776
777
778 /**
779  * Close the connection to given peer and delete channel and mq.
780  */
781   void
782 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
783 {
784   size_t s;
785   struct peer_context *ctx;
786
787   s = RPS_sampler_count_id (id);
788   if ( 1 >= s )
789   {
790     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
791     {
792       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
793       if (NULL != ctx->to_channel)
794       {
795         if (NULL != ctx->mq)
796         {
797           GNUNET_MQ_destroy (ctx->mq);
798         }
799         // may already be freed at shutdown of cadet
800         //GNUNET_CADET_channel_destroy (ctx->to_channel);
801       }
802       // TODO cleanup peer
803       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
804     }
805   }
806 }
807
808 static void
809 rps_start (struct GNUNET_SERVER_Handle *server);
810
811 /**
812  * This is called from GNUNET_CADET_get_peers().
813  *
814  * It is called on every peer(ID) that cadet somehow has contact with.
815  * We use those to initialise the sampler.
816  */
817 void
818 init_peer_cb (void *cls,
819               const struct GNUNET_PeerIdentity *peer,
820               int tunnel, // "Do we have a tunnel towards this peer?"
821               unsigned int n_paths, // "Number of known paths towards this peer"
822               unsigned int best_path) // "How long is the best path?
823                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
824 {
825   struct init_peer_cls *ipc;
826
827   ipc = (struct init_peer_cls *) cls;
828   if ( NULL != peer )
829   {
830     LOG (GNUNET_ERROR_TYPE_DEBUG,
831         "Got %" PRIX32 ". peer %s (at %p) from CADET (gossip_list_size: %u)\n",
832         ipc->i, GNUNET_i2s (peer), peer, gossip_list_size);
833     RPS_sampler_update_list (peer);
834     (void) get_peer_ctx (peer_map, peer); // unneeded? -> insertCB
835
836     if (ipc->i < gossip_list_size)
837     {
838       gossip_list[ipc->i] = *peer; // FIXME sometimes we're writing to invalid space here
839                                    // not sure whether fixed
840       ipc->i++;
841     }
842
843     // send push/pull to each of those peers?
844   }
845   else
846   {
847     if (ipc->i < gossip_list_size)
848     {
849       memcpy(&gossip_list[ipc->i],
850           RPS_sampler_get_n_rand_peers (1),
851           (gossip_list_size - ipc->i) * sizeof(struct GNUNET_PeerIdentity));
852     }
853     rps_start (ipc->server);
854     GNUNET_free (ipc);
855   }
856 }
857
858
859 /**
860  * Task run during shutdown.
861  *
862  * @param cls unused
863  * @param tc unused
864  */
865 static void
866 shutdown_task (void *cls,
867                const struct GNUNET_SCHEDULER_TaskContext *tc)
868 {
869   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
870
871   if ( NULL != do_round_task )
872   {
873     GNUNET_SCHEDULER_cancel (do_round_task);
874     do_round_task = NULL;
875   }
876
877   GNUNET_NSE_disconnect(nse);
878   GNUNET_CADET_disconnect(cadet_handle);
879   GNUNET_free(own_identity);
880   RPS_sampler_destroy();
881   GNUNET_array_grow(gossip_list, gossip_list_size, 0);
882   GNUNET_array_grow(push_list, push_list_size, 0);
883   GNUNET_array_grow(pull_list, pull_list_size, 0);
884 }
885
886
887 /**
888  * A client disconnected.  Remove all of its data structure entries.
889  *
890  * @param cls closure, NULL
891  * @param client identification of the client
892  */
893 static void
894 handle_client_disconnect (void *cls,
895                           struct GNUNET_SERVER_Client * client)
896 {
897 }
898
899 /**
900  * Handle the channel a peer opens to us.
901  *
902  * @param cls The closure
903  * @param channel The channel the peer wants to establish
904  * @param initiator The peer's peer ID
905  * @param port The port the channel is being established over
906  * @param options Further options
907  */
908   static void *
909 handle_inbound_channel (void *cls,
910                         struct GNUNET_CADET_Channel *channel,
911                         const struct GNUNET_PeerIdentity *initiator,
912                         uint32_t port,
913                         enum GNUNET_CADET_ChannelOption options)
914 {
915   struct peer_context *ctx;
916
917   LOG(GNUNET_ERROR_TYPE_DEBUG, "New channel was established to us (Peer %s).\n", GNUNET_i2s(initiator));
918
919   GNUNET_assert( NULL != channel );
920
921   // we might not even store the from_channel
922
923   ctx = get_peer_ctx(peer_map, initiator);
924   if (NULL != ctx->from_channel)
925   {
926     ctx->from_channel = channel;
927   }
928
929   // FIXME there might already be an established channel
930
931   //ctx->in_flags = in_other_gossip_list;
932   ctx->mq = NULL; // TODO create mq?
933
934   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
935       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
936   return NULL; // TODO
937 }
938
939 /**
940  * This is called when a remote peer destroys a channel.
941  *
942  * @param cls The closure
943  * @param channel The channel being closed
944  * @param channel_ctx The context associated with this channel
945  */
946 static void
947 cleanup_channel(void *cls,
948                 const struct GNUNET_CADET_Channel *channel,
949                 void *channel_ctx)
950 {
951   struct GNUNET_PeerIdentity *peer;
952   LOG(GNUNET_ERROR_TYPE_DEBUG, "Channel to remote peer was destroyed.\n");
953
954   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
955       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
956        // Guess simply casting isn't the nicest way...
957        // FIXME wait for cadet to change this function
958   RPS_sampler_reinitialise_by_value (peer);
959 }
960
961 /**
962  * Actually start the service.
963  */
964 static void
965 rps_start (struct GNUNET_SERVER_Handle *server)
966 {
967   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
968     {&handle_cs_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
969       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
970     {NULL, NULL, 0, 0}
971   };
972
973   GNUNET_SERVER_add_handlers (server, handlers);
974   GNUNET_SERVER_disconnect_notify (server,
975                                    &handle_client_disconnect,
976                                    NULL);
977   LOG(GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
978
979
980   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
981   LOG(GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
982
983   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
984                                 &shutdown_task,
985                                 NULL);
986 }
987
988
989 /**
990  * Process statistics requests.
991  *
992  * @param cls closure
993  * @param server the initialized server
994  * @param c configuration to use
995  */
996 static void
997 run (void *cls,
998      struct GNUNET_SERVER_Handle *server,
999      const struct GNUNET_CONFIGURATION_Handle *c)
1000 {
1001   // TODO check what this does -- copied from gnunet-boss
1002   // - seems to work as expected
1003   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1004
1005   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1006
1007   struct init_peer_cls *ipc;
1008
1009   cfg = c;
1010
1011
1012   /* Get own ID */
1013   own_identity = GNUNET_new (struct GNUNET_PeerIdentity);
1014   GNUNET_CRYPTO_get_peer_identity (cfg, own_identity); // TODO check return value
1015   GNUNET_assert (NULL != own_identity);
1016   LOG (GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s(own_identity), own_identity);
1017
1018
1019   /* Get time interval from the configuration */
1020   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1021                                                         "ROUNDINTERVAL",
1022                                                         &round_interval))
1023   {
1024     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1025     GNUNET_SCHEDULER_shutdown();
1026     return;
1027   }
1028
1029   /* Get initial size of sampler/gossip list from the configuration */
1030   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1031                                                          "INITSIZE",
1032                                                          (long long unsigned int *) &est_size))
1033   {
1034     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1035     GNUNET_SCHEDULER_shutdown ();
1036     return;
1037   }
1038   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", est_size);
1039
1040   //gossip_list_size = est_size; // TODO rename est_size
1041
1042   gossip_list = NULL;
1043   GNUNET_array_grow (gossip_list, gossip_list_size, est_size);
1044
1045
1046   /* connect to NSE */
1047   nse = GNUNET_NSE_connect(cfg, nse_callback, NULL);
1048   // TODO check whether that was successful
1049   // TODO disconnect on shutdown
1050   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1051
1052
1053   alpha = 0.45;
1054   beta  = 0.45;
1055   // TODO initialise thresholds - ?
1056
1057   /* Get alpha from the configuration */
1058   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1059                                                          "ALPHA",
1060                                                          &alpha))
1061   {
1062     LOG(GNUNET_ERROR_TYPE_DEBUG, "No ALPHA specified in the config\n");
1063   }
1064   LOG(GNUNET_ERROR_TYPE_DEBUG, "ALPHA is %f\n", alpha);
1065  
1066   /* Get beta from the configuration */
1067   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1068                                                          "BETA",
1069                                                          &beta))
1070   {
1071     LOG (GNUNET_ERROR_TYPE_DEBUG, "No BETA specified in the config\n");
1072   }
1073   LOG (GNUNET_ERROR_TYPE_DEBUG, "BETA is %f\n", beta);
1074
1075   // TODO check that alpha + beta < 1
1076
1077   peer_map = GNUNET_CONTAINER_multipeermap_create (est_size, GNUNET_NO);
1078
1079
1080   /* Initialise cadet */
1081   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1082     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        , 0},
1083     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST, 0},
1084     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1085     {NULL, 0, 0}
1086   };
1087
1088   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1089   cadet_handle = GNUNET_CADET_connect (cfg,
1090                                     cls,
1091                                     &handle_inbound_channel,
1092                                     &cleanup_channel,
1093                                     cadet_handlers,
1094                                     ports);
1095   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1096
1097
1098   /* Initialise sampler */
1099   RPS_sampler_init (est_size, own_identity, insertCB, NULL, removeCB, NULL);
1100
1101   /* Initialise push and pull maps */
1102   push_list = NULL;
1103   push_list_size = 0;
1104   pull_list = NULL;
1105   pull_list_size = 0;
1106
1107
1108   ipc = GNUNET_new (struct init_peer_cls);
1109   ipc->server = server;
1110   ipc->i = 0;
1111   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1112   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, ipc);
1113
1114   // TODO send push/pull to each of those peers?
1115 }
1116
1117
1118 /**
1119  * The main function for the rps service.
1120  *
1121  * @param argc number of arguments from the command line
1122  * @param argv command line arguments
1123  * @return 0 ok, 1 on error
1124  */
1125 int
1126 main (int argc, char *const *argv)
1127 {
1128   return (GNUNET_OK ==
1129           GNUNET_SERVICE_run (argc,
1130                               argv,
1131                               "rps",
1132                               GNUNET_SERVICE_OPTION_NONE,
1133                               &run, NULL)) ? 0 : 1;
1134 }
1135
1136 /* end of gnunet-service-rps.c */