57fecb136f3ac4955b28e7f03e646fd9e3965e7a
[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  * Check if peer is already in peer array.
267  */
268   int
269 in_arr (const struct GNUNET_PeerIdentity *array,
270         unsigned int arr_size,
271         const struct GNUNET_PeerIdentity *peer)
272 {
273   GNUNET_assert (NULL != peer);
274
275   if (0 == arr_size)
276     return GNUNET_NO;
277
278   GNUNET_assert (NULL != array);
279
280   unsigned int i;
281
282   i = 0;
283   while (0 != GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer) &&
284          i < arr_size)
285     i++;
286
287   if (i == arr_size)
288     return GNUNET_NO;
289   else
290     return GNUNET_YES;
291 }
292
293
294 /**
295  * Get random peer from the gossip list.
296  */
297   struct GNUNET_PeerIdentity *
298 get_rand_peer(const struct GNUNET_PeerIdentity *peer_list, unsigned int list_size)
299 {
300   uint64_t r_index;
301   struct GNUNET_PeerIdentity *peer;
302
303   peer = GNUNET_new(struct GNUNET_PeerIdentity);
304   // FIXME if we have only NULL in gossip list this will block
305   // but then we might have a problem nevertheless
306
307   do
308   {
309
310     /**;
311      * Choose the r_index of the peer we want to return
312      * at random from the interval of the gossip list
313      */
314     r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
315                                      list_size);
316
317     *peer = peer_list[r_index];
318   } while (NULL == peer);
319
320   return peer;
321 }
322
323
324 /**
325  * Get the context of a peer. If not existing, create.
326  */
327   struct peer_context *
328 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
329 {
330   struct peer_context *ctx;
331
332   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
333   {
334     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
335   }
336   else
337   {
338     ctx = GNUNET_new (struct peer_context);
339     ctx->in_flags = 0;
340     ctx->mq = NULL;
341     ctx->to_channel = NULL;
342     ctx->from_channel = NULL;
343     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
344   }
345   return ctx;
346 }
347
348
349 /**
350  * Get the channel of a peer. If not existing, create.
351  */
352   struct GNUNET_CADET_Channel *
353 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
354 {
355   struct peer_context *ctx;
356
357   ctx = get_peer_ctx (peer_map, peer);
358   if (NULL == ctx->to_channel)
359   {
360     ctx->to_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
361                                                    GNUNET_RPS_CADET_PORT,
362                                                    GNUNET_CADET_OPTION_RELIABLE);
363     // do I have to explicitly put it in the peer_map?
364     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
365                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
366   }
367   return ctx->to_channel;
368 }
369
370
371 /**
372  * Get the message queue of a specific peer.
373  *
374  * If we already have a message queue open to this client,
375  * simply return it, otherways create one.
376  */
377   struct GNUNET_MQ_Handle *
378 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer_id)
379 {
380   struct peer_context *ctx;
381
382   ctx = get_peer_ctx (peer_map, peer_id);
383   if (NULL == ctx->mq)
384   {
385     (void) get_channel (peer_map, peer_id);
386     ctx->mq = GNUNET_CADET_mq_create (ctx->to_channel);
387     //do I have to explicitly put it in the peer_map?
388     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
389                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
390   }
391   return ctx->mq;
392 }
393
394
395 /***********************************************************************
396  * /Util functions
397 ***********************************************************************/
398
399 /**
400  * Function called by NSE.
401  *
402  * Updates sizes of sampler list and gossip list and adapt those lists
403  * accordingly.
404  */
405   void
406 nse_callback(void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
407 {
408   double estimate;
409   unsigned int old_est;
410   //double scale; // TODO this might go gloabal/config
411
412   old_est = est_size;
413
414   LOG (GNUNET_ERROR_TYPE_DEBUG,
415       "Received a ns estimate - logest: %f, std_dev: %f (old_est: %f)\n",
416       logestimate, std_dev, old_est);
417   //scale = .01;
418   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
419   // GNUNET_NSE_log_estimate_to_n (logestimate);
420   estimate = pow (estimate, 1./3);
421   // TODO add if std_dev is a number
422   // estimate += (std_dev * scale);
423   if ( 0 < estimate ) {
424     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
425     est_size = estimate;
426   } else
427     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
428
429   /* If the NSE has changed adapt the lists accordingly */
430   // TODO respect the request rate, min, max
431   if (old_est > est_size*4)
432   { /* Shrinking */
433     RPS_sampler_resize (old_est/2);
434   }
435   else if (old_est < est_size)
436   { /* Growing */
437     if (est_size < old_est*2)
438       RPS_sampler_resize (old_est*2);
439     else
440       RPS_sampler_resize (est_size);
441   }
442 }
443
444 /**
445  * Handle RPS request from the client.
446  *
447  * @param cls closure
448  * @param client identification of the client
449  * @param message the actual message
450  */
451 static void
452 // TODO rename
453 handle_cs_request (void *cls,
454             struct GNUNET_SERVER_Client *client,
455             const struct GNUNET_MessageHeader *message)
456 {
457   LOG(GNUNET_ERROR_TYPE_DEBUG, "Client requested (a) random peer(s).\n");
458
459   struct GNUNET_RPS_CS_RequestMessage *msg;
460   //unsigned int n_arr[sampler_list->size];// =
461     //GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
462   //struct GNUNET_MQ_Handle *mq;
463   struct client_ctx *cli_ctx;
464   struct GNUNET_MQ_Envelope *ev;
465   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
466   uint64_t num_peers;
467   const struct GNUNET_PeerIdentity *peers;
468   //uint64_t i;
469
470   // TODO check message size
471   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
472   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
473   if ( NULL == cli_ctx ) {
474     cli_ctx = GNUNET_new(struct client_ctx);
475     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
476     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
477   }
478   
479   // How many peers do we give back?
480   // Wait until we have enough random peers?
481
482   num_peers = GNUNET_ntohll (msg->num_peers);
483
484   ev = GNUNET_MQ_msg_extra (out_msg,
485                             num_peers * sizeof (struct GNUNET_PeerIdentity),
486                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
487   out_msg->num_peers = msg->num_peers; // No conversion between network and network order
488
489   //&out_msg[1] = RPS_sampler_get_n_rand_peers (num_peers);
490   peers = RPS_sampler_get_n_rand_peers (num_peers);
491   memcpy(&out_msg[1],
492       peers,
493       num_peers * sizeof (struct GNUNET_PeerIdentity));
494   
495   GNUNET_MQ_send (cli_ctx->mq, ev);
496   //GNUNET_MQ_destroy(mq);
497
498   GNUNET_SERVER_receive_done (client,
499                               GNUNET_OK);
500 }
501
502 /**
503  * Handle a PUSH message from another peer.
504  *
505  * Check the proof of work and store the PeerID
506  * in the temporary list for pushed PeerIDs.
507  *
508  * @param cls Closure
509  * @param channel The channel the PUSH was received over
510  * @param channel_ctx The context associated with this channel
511  * @param msg The message header
512  */
513 static int
514 handle_peer_push (void *cls,
515     struct GNUNET_CADET_Channel *channel,
516     void **channel_ctx,
517     const struct GNUNET_MessageHeader *msg)
518 {
519   const struct GNUNET_PeerIdentity *peer;
520
521   // (check the proof of work) 
522   
523   // TODO accept empty message
524   if (ntohs(msg->size) != sizeof (struct GNUNET_RPS_P2P_PushMessage))
525   {
526     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
527     return GNUNET_SYSERR;
528   }
529
530   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
531   // FIXME wait for cadet to change this function
532   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
533   
534   /* Add the sending peer to the push_list */
535   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
536     GNUNET_array_append (push_list, push_list_size, *peer);
537
538   return GNUNET_OK;
539 }
540
541 /**
542  * Handle PULL REQUEST request message from another peer.
543  *
544  * Reply with the gossip list of PeerIDs.
545  *
546  * @param cls Closure
547  * @param channel The channel the PUSH was received over
548  * @param channel_ctx The context associated with this channel
549  * @param msg The message header
550  */
551 static int
552 handle_peer_pull_request (void *cls,
553     struct GNUNET_CADET_Channel *channel,
554     void **channel_ctx,
555     const struct GNUNET_MessageHeader *msg)
556 {
557   struct GNUNET_PeerIdentity *peer;
558   struct GNUNET_MQ_Handle *mq;
559   struct GNUNET_MQ_Envelope *ev;
560   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
561
562   // assert that msg->size is 0
563
564   // TODO accept empty message
565   if (ntohs(msg->size) != sizeof (struct GNUNET_RPS_P2P_PullRequestMessage))
566   {
567     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
568     return GNUNET_SYSERR;
569   }
570
571   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
572   // FIXME wait for cadet to change this function
573   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REQUEST from peer %s received\n", GNUNET_i2s (peer));
574
575   mq = get_mq (peer_map, peer);
576
577   ev = GNUNET_MQ_msg_extra (out_msg,
578                            gossip_list_size * sizeof (struct GNUNET_PeerIdentity),
579                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
580   out_msg->num_peers = GNUNET_htonll (gossip_list_size);
581   memcpy (&out_msg[1], gossip_list,
582          gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
583
584   GNUNET_MQ_send (mq, ev);
585
586   return GNUNET_OK;
587 }
588
589 /**
590  * Handle PULL REPLY message from another peer.
591  *
592  * Check whether we sent a corresponding request and
593  * whether this reply is the first one.
594  *
595  * @param cls Closure
596  * @param channel The channel the PUSH was received over
597  * @param channel_ctx The context associated with this channel
598  * @param msg The message header
599  */
600 static int
601 handle_peer_pull_reply (void *cls,
602     struct GNUNET_CADET_Channel *channel,
603     void **channel_ctx,
604     const struct GNUNET_MessageHeader *msg)
605 {
606   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
607
608   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
609   struct GNUNET_PeerIdentity *peers;
610   uint64_t i;
611
612   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) < ntohs (msg->size))
613   {
614     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
615     return GNUNET_SYSERR;
616   }
617   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
618   if (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) / sizeof (struct GNUNET_PeerIdentity) != GNUNET_ntohll (in_msg->num_peers))
619   {
620     GNUNET_break_op (0);
621     return GNUNET_SYSERR;
622   }
623
624   // TODO check that we sent a request and that it is the first reply
625
626   peers = (struct GNUNET_PeerIdentity *) &msg[1];
627   for ( i = 0 ; i < GNUNET_ntohll (in_msg->num_peers) ; i++ )
628   {
629     if (GNUNET_NO == in_arr(pull_list, pull_list_size, &peers[i]))
630       GNUNET_array_append (pull_list, pull_list_size, peers[i]);
631   }
632
633   // TODO check that id is valid - whether it is reachable
634
635   return GNUNET_OK;
636 }
637
638
639 /**
640  * Send out PUSHes and PULLs.
641  *
642  * This is executed regylary.
643  */
644 static void
645 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
646 {
647   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
648
649   uint64_t i;
650   //unsigned int *n_arr;
651   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
652   struct GNUNET_RPS_P2P_PushMessage        *push_msg;
653   struct GNUNET_RPS_P2P_PullRequestMessage *pull_msg; // FIXME Send empty message
654   struct GNUNET_MQ_Envelope *ev;
655   const struct GNUNET_PeerIdentity *peer;
656   struct GNUNET_MQ_Handle *mq;
657
658   // TODO print lists, ...
659   // TODO randomise and spread calls herein over time
660
661
662   /* Would it make sense to have one shuffeled gossip list and then
663    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
664    * use the rest to update sampler?
665    * in essence get random peers with consumption */
666
667   /* Send PUSHes */
668   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
669   n_peers = round (alpha * gossip_list_size);
670   if (0 == n_peers)
671     n_peers = 1;
672   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %u (%f * %u) peers.\n",
673       n_peers, alpha, gossip_list_size);
674   for ( i = 0 ; i < n_peers ; i++ )
675   {
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 PUSH to peer %s of gossiped list.\n", GNUNET_i2s (peer));
680
681       ev = GNUNET_MQ_msg (push_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
682       push_msg = NULL;
683       // FIXME sometimes it returns a pointer to a freed mq
684       mq = get_mq (peer_map, peer);
685       GNUNET_MQ_send (mq, ev);
686     }
687   }
688
689
690   /* Send PULL requests */
691   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
692   n_peers = round (beta * gossip_list_size);
693   if (0 == n_peers)
694     n_peers = 1;
695   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %u (%f * %u) peers.\n",
696       n_peers, beta, gossip_list_size);
697   for ( i = 0 ; i < n_peers ; i++ )
698   {
699     peer = get_rand_peer (gossip_list, gossip_list_size);
700     if (own_identity != peer)
701     { // FIXME if this fails schedule/loop this for later
702       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s (peer));
703
704       ev = GNUNET_MQ_msg (pull_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
705       pull_msg = NULL;
706       mq = get_mq (peer_map, peer);
707       GNUNET_MQ_send (mq, ev);
708     }
709   }
710
711
712   /* Update gossip list */
713   uint64_t r_index;
714
715   if ( push_list_size <= alpha * gossip_list_size &&
716        push_list_size != 0 &&
717        pull_list_size != 0 )
718   {
719     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list. ()\n");
720
721     uint64_t first_border;
722     uint64_t second_border;
723     
724     GNUNET_array_grow(gossip_list, gossip_list_size, est_size);
725
726     first_border = round(alpha * gossip_list_size);
727     for ( i = 0 ; i < first_border ; i++ )
728     { // TODO use RPS_sampler_get_n_rand_peers
729       /* Update gossip list with peers received through PUSHes */
730       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
731                                        push_list_size);
732       gossip_list[i] = push_list[r_index];
733       // TODO change the in_flags accordingly
734     }
735
736     second_border = first_border + round(beta * gossip_list_size);
737     for ( i = first_border ; i < second_border ; i++ )
738     {
739       /* Update gossip list with peers received through PULLs */
740       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
741                                        pull_list_size);
742       gossip_list[i] = pull_list[r_index];
743       // TODO change the in_flags accordingly
744     }
745
746     for ( i = second_border ; i < gossip_list_size ; i++ )
747     {
748       /* Update gossip list with peers from history */
749       peer = RPS_sampler_get_n_rand_peers (1),
750       gossip_list[i] = *peer;
751       // TODO change the in_flags accordingly
752     }
753
754   }
755   else
756   {
757     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
758   }
759   // TODO independent of that also get some peers from CADET_get_peers()?
760
761
762   /* Update samplers */
763
764   for ( i = 0 ; i < push_list_size ; i++ )
765   {
766     RPS_sampler_update_list (&push_list[i]);
767     // TODO set in_flag?
768   }
769
770   for ( i = 0 ; i < pull_list_size ; i++ )
771   {
772     RPS_sampler_update_list (&pull_list[i]);
773     // TODO set in_flag?
774   }
775
776
777   /* Empty push/pull lists */
778   GNUNET_array_grow (push_list, push_list_size, 0);
779   GNUNET_array_grow (pull_list, pull_list_size, 0);
780
781   struct GNUNET_TIME_Relative time_next_round;
782   struct GNUNET_TIME_Relative half_round_interval;
783   unsigned int rand_delay;
784   
785   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
786   do
787   {
788   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
789   time_next_round = GNUNET_TIME_relative_multiply (time_next_round, rand_delay);
790   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
791   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
792   } while (GNUNET_TIME_FOREVER_REL != time_next_round);
793
794   /* Schedule next round */
795   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
796   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
797 }
798
799
800 /**
801  * Open a connection to given peer and store channel and mq.
802  */
803   void
804 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
805 {
806   // We open a channel to be notified when this peer goes down.
807   (void) get_channel (peer_map, id);
808 }
809
810
811 /**
812  * Close the connection to given peer and delete channel and mq.
813  */
814   void
815 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
816 {
817   size_t s;
818   struct peer_context *ctx;
819
820   s = RPS_sampler_count_id (id);
821   if ( 1 >= s )
822   {
823     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
824     {
825       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
826       if (NULL != ctx->to_channel)
827       {
828         if (NULL != ctx->mq)
829         {
830           GNUNET_MQ_destroy (ctx->mq);
831         }
832         // may already be freed at shutdown of cadet
833         //GNUNET_CADET_channel_destroy (ctx->to_channel);
834       }
835       // TODO cleanup peer
836       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
837     }
838   }
839 }
840
841 static void
842 rps_start (struct GNUNET_SERVER_Handle *server);
843
844 /**
845  * This is called from GNUNET_CADET_get_peers().
846  *
847  * It is called on every peer(ID) that cadet somehow has contact with.
848  * We use those to initialise the sampler.
849  */
850 void
851 init_peer_cb (void *cls,
852               const struct GNUNET_PeerIdentity *peer,
853               int tunnel, // "Do we have a tunnel towards this peer?"
854               unsigned int n_paths, // "Number of known paths towards this peer"
855               unsigned int best_path) // "How long is the best path?
856                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
857 {
858   struct init_peer_cls *ipc;
859
860   ipc = (struct init_peer_cls *) cls;
861   if ( NULL != peer )
862   {
863     LOG (GNUNET_ERROR_TYPE_DEBUG,
864         "Got %" PRIX32 ". peer %s (at %p) from CADET (gossip_list_size: %u)\n",
865         ipc->i, GNUNET_i2s (peer), peer, gossip_list_size);
866     RPS_sampler_update_list (peer);
867     (void) get_peer_ctx (peer_map, peer); // unneeded? -> insertCB
868
869     if (ipc->i < gossip_list_size)
870     {
871       gossip_list[ipc->i] = *peer; // FIXME sometimes we're writing to invalid space here
872                                    // not sure whether fixed
873       ipc->i++;
874     }
875
876     // send push/pull to each of those peers?
877   }
878   else
879   {
880     if (ipc->i < gossip_list_size)
881     {
882       memcpy(&gossip_list[ipc->i],
883           RPS_sampler_get_n_rand_peers (1),
884           (gossip_list_size - ipc->i) * sizeof(struct GNUNET_PeerIdentity));
885     }
886     rps_start (ipc->server);
887     GNUNET_free (ipc);
888   }
889 }
890
891
892 /**
893  * Task run during shutdown.
894  *
895  * @param cls unused
896  * @param tc unused
897  */
898 static void
899 shutdown_task (void *cls,
900                const struct GNUNET_SCHEDULER_TaskContext *tc)
901 {
902   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
903
904   if ( NULL != do_round_task )
905   {
906     GNUNET_SCHEDULER_cancel (do_round_task);
907     do_round_task = NULL;
908   }
909
910   GNUNET_NSE_disconnect(nse);
911   GNUNET_CADET_disconnect(cadet_handle);
912   GNUNET_free(own_identity);
913   RPS_sampler_destroy();
914   GNUNET_array_grow(gossip_list, gossip_list_size, 0);
915   GNUNET_array_grow(push_list, push_list_size, 0);
916   GNUNET_array_grow(pull_list, pull_list_size, 0);
917 }
918
919
920 /**
921  * A client disconnected.  Remove all of its data structure entries.
922  *
923  * @param cls closure, NULL
924  * @param client identification of the client
925  */
926 static void
927 handle_client_disconnect (void *cls,
928                           struct GNUNET_SERVER_Client * client)
929 {
930 }
931
932 /**
933  * Handle the channel a peer opens to us.
934  *
935  * @param cls The closure
936  * @param channel The channel the peer wants to establish
937  * @param initiator The peer's peer ID
938  * @param port The port the channel is being established over
939  * @param options Further options
940  */
941   static void *
942 handle_inbound_channel (void *cls,
943                         struct GNUNET_CADET_Channel *channel,
944                         const struct GNUNET_PeerIdentity *initiator,
945                         uint32_t port,
946                         enum GNUNET_CADET_ChannelOption options)
947 {
948   struct peer_context *ctx;
949
950   LOG(GNUNET_ERROR_TYPE_DEBUG, "New channel was established to us (Peer %s).\n", GNUNET_i2s(initiator));
951
952   GNUNET_assert( NULL != channel );
953
954   // we might not even store the from_channel
955
956   ctx = get_peer_ctx(peer_map, initiator);
957   if (NULL != ctx->from_channel)
958   {
959     ctx->from_channel = channel;
960   }
961
962   // FIXME there might already be an established channel
963
964   //ctx->in_flags = in_other_gossip_list;
965   ctx->mq = NULL; // TODO create mq?
966
967   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
968       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
969   return NULL; // TODO
970 }
971
972 /**
973  * This is called when a remote peer destroys a channel.
974  *
975  * @param cls The closure
976  * @param channel The channel being closed
977  * @param channel_ctx The context associated with this channel
978  */
979 static void
980 cleanup_channel(void *cls,
981                 const struct GNUNET_CADET_Channel *channel,
982                 void *channel_ctx)
983 {
984   struct GNUNET_PeerIdentity *peer;
985   LOG(GNUNET_ERROR_TYPE_DEBUG, "Channel to remote peer was destroyed.\n");
986
987   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
988       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
989        // Guess simply casting isn't the nicest way...
990        // FIXME wait for cadet to change this function
991   RPS_sampler_reinitialise_by_value (peer);
992 }
993
994 /**
995  * Actually start the service.
996  */
997 static void
998 rps_start (struct GNUNET_SERVER_Handle *server)
999 {
1000   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1001     {&handle_cs_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1002       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1003     {NULL, NULL, 0, 0}
1004   };
1005
1006   GNUNET_SERVER_add_handlers (server, handlers);
1007   GNUNET_SERVER_disconnect_notify (server,
1008                                    &handle_client_disconnect,
1009                                    NULL);
1010   LOG(GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1011
1012
1013   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1014   LOG(GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1015
1016   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1017                                 &shutdown_task,
1018                                 NULL);
1019 }
1020
1021
1022 /**
1023  * Process statistics requests.
1024  *
1025  * @param cls closure
1026  * @param server the initialized server
1027  * @param c configuration to use
1028  */
1029 static void
1030 run (void *cls,
1031      struct GNUNET_SERVER_Handle *server,
1032      const struct GNUNET_CONFIGURATION_Handle *c)
1033 {
1034   // TODO check what this does -- copied from gnunet-boss
1035   // - seems to work as expected
1036   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1037
1038   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1039
1040   struct init_peer_cls *ipc;
1041
1042   cfg = c;
1043
1044
1045   /* Get own ID */
1046   own_identity = GNUNET_new (struct GNUNET_PeerIdentity);
1047   GNUNET_CRYPTO_get_peer_identity (cfg, own_identity); // TODO check return value
1048   GNUNET_assert (NULL != own_identity);
1049   LOG (GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s(own_identity), own_identity);
1050
1051
1052   /* Get time interval from the configuration */
1053   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1054                                                         "ROUNDINTERVAL",
1055                                                         &round_interval))
1056   {
1057     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1058     GNUNET_SCHEDULER_shutdown();
1059     return;
1060   }
1061
1062   /* Get initial size of sampler/gossip list from the configuration */
1063   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1064                                                          "INITSIZE",
1065                                                          (long long unsigned int *) &est_size))
1066   {
1067     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1068     GNUNET_SCHEDULER_shutdown ();
1069     return;
1070   }
1071   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", est_size);
1072
1073   //gossip_list_size = est_size; // TODO rename est_size
1074
1075   gossip_list = NULL;
1076   GNUNET_array_grow (gossip_list, gossip_list_size, est_size);
1077
1078
1079   /* connect to NSE */
1080   nse = GNUNET_NSE_connect(cfg, nse_callback, NULL);
1081   // TODO check whether that was successful
1082   // TODO disconnect on shutdown
1083   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1084
1085
1086   alpha = 0.45;
1087   beta  = 0.45;
1088   // TODO initialise thresholds - ?
1089
1090   /* Get alpha from the configuration */
1091   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1092                                                          "ALPHA",
1093                                                          &alpha))
1094   {
1095     LOG(GNUNET_ERROR_TYPE_DEBUG, "No ALPHA specified in the config\n");
1096   }
1097   LOG(GNUNET_ERROR_TYPE_DEBUG, "ALPHA is %f\n", alpha);
1098  
1099   /* Get beta from the configuration */
1100   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1101                                                          "BETA",
1102                                                          &beta))
1103   {
1104     LOG (GNUNET_ERROR_TYPE_DEBUG, "No BETA specified in the config\n");
1105   }
1106   LOG (GNUNET_ERROR_TYPE_DEBUG, "BETA is %f\n", beta);
1107
1108   // TODO check that alpha + beta < 1
1109
1110   peer_map = GNUNET_CONTAINER_multipeermap_create (est_size, GNUNET_NO);
1111
1112
1113   /* Initialise cadet */
1114   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1115     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        , 0},
1116     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST, 0},
1117     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1118     {NULL, 0, 0}
1119   };
1120
1121   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1122   cadet_handle = GNUNET_CADET_connect (cfg,
1123                                     cls,
1124                                     &handle_inbound_channel,
1125                                     &cleanup_channel,
1126                                     cadet_handlers,
1127                                     ports);
1128   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1129
1130
1131   /* Initialise sampler */
1132   RPS_sampler_init (est_size, own_identity, insertCB, NULL, removeCB, NULL);
1133
1134   /* Initialise push and pull maps */
1135   push_list = NULL;
1136   push_list_size = 0;
1137   pull_list = NULL;
1138   pull_list_size = 0;
1139
1140
1141   ipc = GNUNET_new (struct init_peer_cls);
1142   ipc->server = server;
1143   ipc->i = 0;
1144   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1145   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, ipc);
1146
1147   // TODO send push/pull to each of those peers?
1148 }
1149
1150
1151 /**
1152  * The main function for the rps service.
1153  *
1154  * @param argc number of arguments from the command line
1155  * @param argv command line arguments
1156  * @return 0 ok, 1 on error
1157  */
1158 int
1159 main (int argc, char *const *argv)
1160 {
1161   return (GNUNET_OK ==
1162           GNUNET_SERVICE_run (argc,
1163                               argv,
1164                               "rps",
1165                               GNUNET_SERVICE_OPTION_NONE,
1166                               &run, NULL)) ? 0 : 1;
1167 }
1168
1169 /* end of gnunet-service-rps.c */