86b5d7443108354e3e55aecd104bcd325c36fe09
[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 // TODO ignore list
60
61 // hist_size_init, hist_size_max
62
63 /**
64  * Our configuration.
65  */
66 static const struct GNUNET_CONFIGURATION_Handle *cfg;
67
68 /**
69  * Our own identity.
70  */
71 static struct GNUNET_PeerIdentity *own_identity;
72
73 /**
74  * Closure to the callback cadet calls on each peer it passes to us
75  */
76 struct init_peer_cls
77 {
78   /**
79    * The server handle to later listen to client requests
80    */
81   struct GNUNET_SERVER_Handle *server;
82
83   /**
84    * Counts how many peers cadet already passed to us
85    */
86   uint32_t i;
87 };
88
89
90   struct GNUNET_PeerIdentity *
91 get_rand_peer (const struct GNUNET_PeerIdentity *peer_list, unsigned int size);
92
93
94 /***********************************************************************
95  * Housekeeping with peers
96 ***********************************************************************/
97
98 /**
99  * Struct used to store the context of a connected client.
100  */
101 struct client_ctx
102 {
103   /**
104    * The message queue to communicate with the client.
105    */
106   struct GNUNET_MQ_Handle *mq;
107 };
108
109 /**
110  * Used to keep track in what lists single peerIDs are.
111  */
112 enum in_list_flag // probably unneeded
113 {
114   in_other_sampler_list = 0x1,
115   in_other_gossip_list  = 0x2, // unneeded?
116   in_own_sampler_list   = 0x4,
117   in_own_gossip_list    = 0x8 // unneeded?
118 };
119
120 /**
121  * Struct used to keep track of other peer's status
122  *
123  * This is stored in a multipeermap.
124  */
125 struct PeerContext
126 {
127   /**
128    * In own gossip/sampler list, in other's gossip/sampler list
129    */
130   uint32_t in_flags; // unneeded?
131
132   /**
133    * Message queue open to client
134    */
135   struct GNUNET_MQ_Handle *mq;
136
137   /**
138    * Channel open to client.
139    */
140   struct GNUNET_CADET_Channel *to_channel;
141
142   /**
143    * Channel open from client.
144    */
145   struct GNUNET_CADET_Channel *from_channel; // unneeded
146
147   /**
148    * This is pobably followed by 'statistical' data (when we first saw
149    * him, how did we get his ID, how many pushes (in a timeinterval),
150    * ...)
151    */
152 };
153
154 /***********************************************************************
155  * /Housekeeping with peers
156 ***********************************************************************/
157
158 /***********************************************************************
159  * Globals
160 ***********************************************************************/
161
162 /**
163  * Set of all peers to keep track of them.
164  */
165 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
166
167
168 /**
169  * The gossiped list of peers.
170  */
171 static struct GNUNET_PeerIdentity *gossip_list;
172
173 /**
174  * Size of the gossiped list
175  */
176 //static unsigned int gossip_list_size;
177 static uint32_t gossip_list_size;
178
179
180 /**
181  * The actual size of the sampler
182  */
183 static unsigned int sampler_size;
184 //size_t sampler_size;
185
186 /**
187  * The size of sampler we need to be able to satisfy the client's need of
188  * random peers.
189  */
190 static unsigned int sampler_size_client_need;
191
192 /**
193  * The size of sampler we need to be able to satisfy the Brahms protocol's
194  * need of random peers.
195  *
196  * This is directly taken as the #gossip_list_size on update of the
197  * #gossip_list
198  *
199  * This is one minimum size the sampler grows to.
200  */
201 static unsigned int sampler_size_est_need;
202
203
204 /**
205  * Percentage of total peer number in the gossip list
206  * to send random PUSHes to
207  *
208  * TODO do not read from configuration
209  */
210 static float alpha;
211
212 /**
213  * Percentage of total peer number in the gossip list
214  * to send random PULLs to
215  *
216  * TODO do not read from configuration
217  */
218 static float beta;
219
220 /**
221  * The percentage gamma of history updates.
222  * Simply 1 - alpha - beta
223  */
224
225
226 /**
227  * Identifier for the main task that runs periodically.
228  */
229 static struct GNUNET_SCHEDULER_Task *do_round_task;
230
231 /**
232  * Time inverval the do_round task runs in.
233  */
234 static struct GNUNET_TIME_Relative round_interval;
235
236
237
238 /**
239  * List to store peers received through pushes temporary.
240  *
241  * TODO -> multipeermap
242  */
243 static struct GNUNET_PeerIdentity *push_list;
244
245 /**
246  * Size of the push_list;
247  */
248 static unsigned int push_list_size;
249 //size_t push_list_size;
250
251 /**
252  * List to store peers received through pulls temporary.
253  *
254  * TODO -> multipeermap
255  */
256 static struct GNUNET_PeerIdentity *pull_list;
257
258 /**
259  * Size of the pull_list;
260  */
261 static unsigned int pull_list_size;
262 //size_t pull_list_size;
263
264
265 /**
266  * Handler to NSE.
267  */
268 static struct GNUNET_NSE_Handle *nse;
269
270 /**
271  * Handler to CADET.
272  */
273 static struct GNUNET_CADET_Handle *cadet_handle;
274
275
276 /**
277  * Request counter.
278  *
279  * Only needed in the beginning to check how many of the 64 deltas
280  * we already have
281  */
282 static unsigned int req_counter;
283
284 /**
285  * Time of the last request we received.
286  *
287  * Used to compute the expected request rate.
288  */
289 static struct GNUNET_TIME_Absolute last_request;
290
291 /**
292  * Size of #request_deltas.
293  */
294 #define REQUEST_DELTAS_SIZE 64
295 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
296
297 /**
298  * Last 64 deltas between requests
299  */
300 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
301
302 /**
303  * The prediction of the rate of requests
304  */
305 static struct GNUNET_TIME_Relative  request_rate;
306
307
308 /***********************************************************************
309  * /Globals
310 ***********************************************************************/
311
312
313 /***********************************************************************
314  * Util functions
315 ***********************************************************************/
316
317 /**
318  * Check if peer is already in peer array.
319  */
320   int
321 in_arr (const struct GNUNET_PeerIdentity *array,
322         unsigned int arr_size,
323         const struct GNUNET_PeerIdentity *peer)
324 {
325   GNUNET_assert (NULL != peer);
326
327   if (0 == arr_size)
328     return GNUNET_NO;
329
330   GNUNET_assert (NULL != array);
331
332   unsigned int i;
333
334   i = 0;
335   while (0 != GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer) &&
336          i < arr_size)
337     i++;
338
339   if (i == arr_size)
340     return GNUNET_NO;
341   else
342     return GNUNET_YES;
343 }
344
345
346 /**
347  * Get random peer from the gossip list.
348  */
349   struct GNUNET_PeerIdentity *
350 get_rand_peer (const struct GNUNET_PeerIdentity *peer_list, unsigned int list_size)
351 {
352   uint32_t r_index;
353   struct GNUNET_PeerIdentity *peer;
354
355   peer = GNUNET_new (struct GNUNET_PeerIdentity);
356   // FIXME if we have only NULL in gossip list this will block
357   // but then we might have a problem nevertheless
358
359   do
360   {
361
362     /**;
363      * Choose the r_index of the peer we want to return
364      * at random from the interval of the gossip list
365      */
366     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
367                                      list_size);
368
369     *peer = peer_list[r_index];
370   } while (NULL == peer);
371
372   return peer;
373 }
374
375
376 /**
377  * Get the context of a peer. If not existing, create.
378  */
379   struct PeerContext *
380 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
381 {
382   struct PeerContext *ctx;
383
384   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
385   {
386     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
387   }
388   else
389   {
390     ctx = GNUNET_new (struct PeerContext);
391     ctx->in_flags = 0;
392     ctx->mq = NULL;
393     ctx->to_channel = NULL;
394     ctx->from_channel = NULL;
395     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
396   }
397   return ctx;
398 }
399
400
401 /**
402  * Get the channel of a peer. If not existing, create.
403  */
404   struct GNUNET_CADET_Channel *
405 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
406 {
407   struct PeerContext *ctx;
408
409   ctx = get_peer_ctx (peer_map, peer);
410   if (NULL == ctx->to_channel)
411   {
412     ctx->to_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
413                                                    GNUNET_RPS_CADET_PORT,
414                                                    GNUNET_CADET_OPTION_RELIABLE);
415     // do I have to explicitly put it in the peer_map?
416     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
417                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
418   }
419   return ctx->to_channel;
420 }
421
422
423 /**
424  * Get the message queue of a specific peer.
425  *
426  * If we already have a message queue open to this client,
427  * simply return it, otherways create one.
428  */
429   struct GNUNET_MQ_Handle *
430 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer_id)
431 {
432   struct PeerContext *ctx;
433
434   ctx = get_peer_ctx (peer_map, peer_id);
435   if (NULL == ctx->mq)
436   {
437     (void) get_channel (peer_map, peer_id);
438     ctx->mq = GNUNET_CADET_mq_create (ctx->to_channel);
439     //do I have to explicitly put it in the peer_map?
440     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
441                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
442   }
443   return ctx->mq;
444 }
445
446
447 /**
448  * Sum all time relatives of an array.
449   */
450   struct GNUNET_TIME_Relative
451 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
452 {
453   struct GNUNET_TIME_Relative sum;
454   uint32_t i;
455
456   sum = GNUNET_TIME_UNIT_ZERO;
457   for ( i = 0 ; i < arr_size ; i++ )
458   {
459     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
460   }
461   return sum;
462 }
463
464
465 /**
466  * Compute the average of given time relatives.
467  */
468   struct GNUNET_TIME_Relative
469 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
470 {
471   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size); // FIXME find a way to devide that by arr_size
472 }
473
474
475 /***********************************************************************
476  * /Util functions
477 ***********************************************************************/
478
479 /**
480  * Wrapper around _sampler_resize()
481  */
482   void
483 resize_wrapper ()
484 {
485   uint32_t bigger_size;
486
487   // TODO statistics
488
489   if (sampler_size_est_need > sampler_size_client_need)
490     bigger_size = sampler_size_client_need;
491   else
492     bigger_size = sampler_size_est_need;
493
494   // TODO respect the request rate, min, max
495   if (sampler_size > bigger_size*4)
496   { /* Shrinking */
497     RPS_sampler_resize (sampler_size/2);
498   }
499   else if (sampler_size < bigger_size)
500   { /* Growing */
501     RPS_sampler_resize (sampler_size*2);
502   }
503 }
504
505
506 /**
507  * Function called by NSE.
508  *
509  * Updates sizes of sampler list and gossip list and adapt those lists
510  * accordingly.
511  */
512   void
513 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
514 {
515   double estimate;
516   //double scale; // TODO this might go gloabal/config
517
518   LOG (GNUNET_ERROR_TYPE_DEBUG,
519       "Received a ns estimate - logest: %f, std_dev: %f (old_size: %f)\n",
520       logestimate, std_dev, sampler_size);
521   //scale = .01;
522   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
523   // GNUNET_NSE_log_estimate_to_n (logestimate);
524   estimate = pow (estimate, 1./3);
525   // TODO add if std_dev is a number
526   // estimate += (std_dev * scale);
527   if ( 0 < estimate ) {
528     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
529     sampler_size_est_need = estimate;
530   } else
531     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
532
533   /* If the NSE has changed adapt the lists accordingly */
534   resize_wrapper ();
535 }
536
537
538 /**
539  * Callback called once the requested PeerIDs are ready.
540  *
541  * Sends those to the requesting client.
542  */
543 void client_respond (void *cls,
544     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
545 {
546   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
547   struct GNUNET_MQ_Envelope *ev;
548   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
549   struct GNUNET_SERVER_Client *client;
550   struct client_ctx *cli_ctx;
551
552   client = (struct GNUNET_SERVER_Client *) cls;
553
554   ev = GNUNET_MQ_msg_extra (out_msg,
555                             num_peers * sizeof (struct GNUNET_PeerIdentity),
556                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
557   out_msg->num_peers = htonl (num_peers);
558
559   memcpy (&out_msg[1],
560       ids,
561       num_peers * sizeof (struct GNUNET_PeerIdentity));
562   GNUNET_free (ids);
563   
564   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
565   if ( NULL == cli_ctx ) {
566     cli_ctx = GNUNET_new (struct client_ctx);
567     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
568     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
569   }
570   
571   GNUNET_MQ_send (cli_ctx->mq, ev);
572 }
573
574
575 /**
576  * Handle RPS request from the client.
577  *
578  * @param cls closure
579  * @param client identification of the client
580  * @param message the actual message
581  */
582 static void
583 handle_client_request (void *cls,
584             struct GNUNET_SERVER_Client *client,
585             const struct GNUNET_MessageHeader *message)
586 {
587   struct GNUNET_RPS_CS_RequestMessage *msg;
588   uint32_t num_peers;
589   struct GNUNET_TIME_Relative max_round_duration;
590
591
592   /* Estimate request rate */
593   if (request_deltas_size > req_counter)
594     req_counter++;
595   if ( 1 < req_counter)
596   {
597     /* Shift last request deltas to the right */
598     memcpy (&request_deltas[1],
599         request_deltas,
600         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
601     /* Add current delta to beginning */
602     request_deltas[0] = GNUNET_TIME_absolute_get_difference (last_request,
603         GNUNET_TIME_absolute_get ());
604     request_rate = T_relative_avg (request_deltas, req_counter);
605
606     max_round_duration = GNUNET_TIME_relative_add (round_interval,
607         GNUNET_TIME_relative_divide (round_interval, 2));
608     sampler_size_client_need = max_round_duration.rel_value_us / request_rate.rel_value_us;
609
610     resize_wrapper ();
611   }
612   last_request = GNUNET_TIME_absolute_get ();
613
614
615   // TODO check message size
616   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
617
618   num_peers = ntohl (msg->num_peers);
619
620   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
621
622   RPS_sampler_get_n_rand_peers (client_respond, client, num_peers);
623
624   GNUNET_SERVER_receive_done (client,
625                               GNUNET_OK);
626 }
627
628
629 /**
630  * Handle seed from the client.
631  *
632  * @param cls closure
633  * @param client identification of the client
634  * @param message the actual message
635  */
636   static void
637 handle_client_seed (void *cls,
638             struct GNUNET_SERVER_Client *client,
639             const struct GNUNET_MessageHeader *message)
640 {
641   struct GNUNET_RPS_CS_SeedMessage *in_msg;
642   struct GNUNET_PeerIdentity *peers;
643   uint32_t i;
644
645   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) < ntohs (message->size))
646   {
647     GNUNET_break_op (0);
648     GNUNET_SERVER_receive_done (client,
649               GNUNET_SYSERR);
650   }
651   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
652   if (ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage) /
653       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
654   {
655     GNUNET_break_op (0);
656     GNUNET_SERVER_receive_done (client,
657               GNUNET_SYSERR);
658   }
659
660   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
661   peers = (struct GNUNET_PeerIdentity *) &message[1];
662
663   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
664     RPS_sampler_update_list (&peers[i]);
665
666   GNUNET_SERVER_receive_done (client,
667                               GNUNET_OK);
668 }
669
670
671 /**
672  * Handle a PUSH message from another peer.
673  *
674  * Check the proof of work and store the PeerID
675  * in the temporary list for pushed PeerIDs.
676  *
677  * @param cls Closure
678  * @param channel The channel the PUSH was received over
679  * @param channel_ctx The context associated with this channel
680  * @param msg The message header
681  */
682 static int
683 handle_peer_push (void *cls,
684     struct GNUNET_CADET_Channel *channel,
685     void **channel_ctx,
686     const struct GNUNET_MessageHeader *msg)
687 {
688   const struct GNUNET_PeerIdentity *peer;
689
690   // (check the proof of work) 
691   
692   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
693   // FIXME wait for cadet to change this function
694   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
695   
696   /* Add the sending peer to the push_list */
697   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
698     GNUNET_array_append (push_list, push_list_size, *peer);
699
700   return GNUNET_OK;
701 }
702
703 /**
704  * Handle PULL REQUEST request message from another peer.
705  *
706  * Reply with the gossip list of PeerIDs.
707  *
708  * @param cls Closure
709  * @param channel The channel the PUSH was received over
710  * @param channel_ctx The context associated with this channel
711  * @param msg The message header
712  */
713 static int
714 handle_peer_pull_request (void *cls,
715     struct GNUNET_CADET_Channel *channel,
716     void **channel_ctx,
717     const struct GNUNET_MessageHeader *msg)
718 {
719   struct GNUNET_PeerIdentity *peer;
720   struct GNUNET_MQ_Handle *mq;
721   struct GNUNET_MQ_Envelope *ev;
722   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
723
724
725   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
726   // FIXME wait for cadet to change this function
727   LOG (GNUNET_ERROR_TYPE_DEBUG,
728       "PULL REQUEST from peer %s received, going to send %u peers\n",
729       GNUNET_i2s (peer), gossip_list_size);
730
731   mq = get_mq (peer_map, peer);
732
733   ev = GNUNET_MQ_msg_extra (out_msg,
734                            gossip_list_size * sizeof (struct GNUNET_PeerIdentity),
735                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
736   //out_msg->num_peers = htonl (gossip_list_size);
737   out_msg->num_peers = htonl (gossip_list_size);
738   memcpy (&out_msg[1], gossip_list,
739          gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
740
741   GNUNET_MQ_send (mq, ev);
742
743   return GNUNET_OK;
744 }
745
746 /**
747  * Handle PULL REPLY message from another peer.
748  *
749  * Check whether we sent a corresponding request and
750  * whether this reply is the first one.
751  *
752  * @param cls Closure
753  * @param channel The channel the PUSH was received over
754  * @param channel_ctx The context associated with this channel
755  * @param msg The message header
756  */
757 static int
758 handle_peer_pull_reply (void *cls,
759     struct GNUNET_CADET_Channel *channel,
760     void **channel_ctx,
761     const struct GNUNET_MessageHeader *msg)
762 {
763   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
764
765   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
766   struct GNUNET_PeerIdentity *peers;
767   uint32_t i;
768
769   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
770   {
771     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
772     return GNUNET_SYSERR;
773   }
774   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
775   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
776   {
777     LOG (GNUNET_ERROR_TYPE_ERROR, "message says it sends %" PRIu64 " peers, have space for %i peers\n",
778         ntohl (in_msg->num_peers),
779         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity));
780     GNUNET_break_op (0);
781     return GNUNET_SYSERR;
782   }
783
784   // TODO check that we sent a request and that it is the first reply
785
786   peers = (struct GNUNET_PeerIdentity *) &msg[1];
787   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
788   {
789     if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
790       GNUNET_array_append (pull_list, pull_list_size, peers[i]);
791   }
792
793   // TODO check that id is valid - whether it is reachable
794
795   return GNUNET_OK;
796 }
797
798
799 /**
800  * Send out PUSHes and PULLs.
801  *
802  * This is executed regylary.
803  */
804 static void
805 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
806 {
807   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
808
809   uint32_t i;
810   //unsigned int *n_arr;
811   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
812   struct GNUNET_MQ_Envelope *ev;
813   const struct GNUNET_PeerIdentity *peer;
814   struct GNUNET_MQ_Handle *mq;
815
816   // TODO log lists, ...
817
818
819   /* Would it make sense to have one shuffeled gossip list and then
820    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
821    * use the rest to update sampler?
822    * in essence get random peers with consumption */
823
824   /* Send PUSHes */
825   //n_arr = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
826   n_peers = round (alpha * gossip_list_size);
827   if (0 == n_peers)
828     n_peers = 1;
829   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %u (%f * %u) peers.\n",
830       n_peers, alpha, gossip_list_size);
831   for ( i = 0 ; i < n_peers ; i++ )
832   {
833     peer = get_rand_peer (gossip_list, gossip_list_size);
834     if (own_identity != peer)
835     { // FIXME if this fails schedule/loop this for later
836       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s (peer));
837
838       ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
839       // FIXME sometimes it returns a pointer to a freed mq
840       mq = get_mq (peer_map, peer);
841       GNUNET_MQ_send (mq, ev);
842     }
843   }
844
845
846   /* Send PULL requests */
847   //n_arr = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
848   n_peers = round (beta * gossip_list_size);
849   if (0 == n_peers)
850     n_peers = 1;
851   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %u (%f * %u) peers.\n",
852       n_peers, beta, gossip_list_size);
853   for ( i = 0 ; i < n_peers ; i++ )
854   {
855     peer = get_rand_peer (gossip_list, gossip_list_size);
856     if (own_identity != peer)
857     { // FIXME if this fails schedule/loop this for later
858       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s (peer));
859
860       ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
861       //pull_msg = NULL;
862       mq = get_mq (peer_map, peer);
863       GNUNET_MQ_send (mq, ev);
864     }
865   }
866
867
868   /* Update gossip list */
869   uint32_t r_index;
870
871   if ( push_list_size <= alpha * gossip_list_size &&
872        push_list_size != 0 &&
873        pull_list_size != 0 )
874   {
875     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list. ()\n");
876
877     uint32_t first_border;
878     uint32_t second_border;
879     
880     GNUNET_array_grow (gossip_list, gossip_list_size, sampler_size_est_need);
881
882     first_border = round (alpha * gossip_list_size);
883     for ( i = 0 ; i < first_border ; i++ )
884     { // TODO use RPS_sampler_get_n_rand_peers
885       /* Update gossip list with peers received through PUSHes */
886       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
887                                        push_list_size);
888       gossip_list[i] = push_list[r_index];
889       // TODO change the in_flags accordingly
890     }
891
892     second_border = first_border + round (beta * gossip_list_size);
893     for ( i = first_border ; i < second_border ; i++ )
894     {
895       /* Update gossip list with peers received through PULLs */
896       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
897                                        pull_list_size);
898       gossip_list[i] = pull_list[r_index];
899       // TODO change the in_flags accordingly
900     }
901
902     for ( i = second_border ; i < gossip_list_size ; i++ )
903     {
904       /* Update gossip list with peers from history */
905       peer = RPS_sampler_get_n_rand_peers_ (1);
906       gossip_list[i] = *peer;
907       // TODO change the in_flags accordingly
908     }
909
910   }
911   else
912   {
913     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
914   }
915   // TODO independent of that also get some peers from CADET_get_peers()?
916
917
918   /* Update samplers */
919
920   for ( i = 0 ; i < push_list_size ; i++ )
921   {
922     RPS_sampler_update_list (&push_list[i]);
923     // TODO set in_flag?
924   }
925
926   for ( i = 0 ; i < pull_list_size ; i++ )
927   {
928     RPS_sampler_update_list (&pull_list[i]);
929     // TODO set in_flag?
930   }
931
932
933   /* Empty push/pull lists */
934   GNUNET_array_grow (push_list, push_list_size, 0);
935   GNUNET_array_grow (pull_list, pull_list_size, 0);
936
937   struct GNUNET_TIME_Relative time_next_round;
938   struct GNUNET_TIME_Relative half_round_interval;
939   unsigned int rand_delay;
940
941   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
942   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
943   do
944   {
945   /*
946    * Compute random value between (0 and 1) * round_interval
947    * via multiplying round_interval with a 'fraction' (0 to value)/value
948    */
949   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
950   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
951   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
952   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
953   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
954
955   /* Schedule next round */
956   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
957   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
958 }
959
960
961 /**
962  * Open a connection to given peer and store channel and mq.
963  */
964   void
965 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
966 {
967   // We open a channel to be notified when this peer goes down.
968   (void) get_channel (peer_map, id);
969 }
970
971
972 /**
973  * Close the connection to given peer and delete channel and mq.
974  */
975   void
976 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
977 {
978   size_t s;
979   struct PeerContext *ctx;
980
981   s = RPS_sampler_count_id (id);
982   if ( 1 >= s )
983   {
984     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
985     {
986       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
987       if (NULL != ctx->to_channel)
988       {
989         if (NULL != ctx->mq)
990         {
991           GNUNET_MQ_destroy (ctx->mq);
992         }
993         // may already be freed at shutdown of cadet
994         //GNUNET_CADET_channel_destroy (ctx->to_channel);
995       }
996       // TODO cleanup peer
997       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
998     }
999   }
1000 }
1001
1002 static void
1003 rps_start (struct GNUNET_SERVER_Handle *server);
1004
1005 /**
1006  * This is called from GNUNET_CADET_get_peers().
1007  *
1008  * It is called on every peer(ID) that cadet somehow has contact with.
1009  * We use those to initialise the sampler.
1010  */
1011 void
1012 init_peer_cb (void *cls,
1013               const struct GNUNET_PeerIdentity *peer,
1014               int tunnel, // "Do we have a tunnel towards this peer?"
1015               unsigned int n_paths, // "Number of known paths towards this peer"
1016               unsigned int best_path) // "How long is the best path?
1017                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1018 {
1019   struct init_peer_cls *ipc;
1020
1021   ipc = (struct init_peer_cls *) cls;
1022   if ( NULL != peer )
1023   {
1024     LOG (GNUNET_ERROR_TYPE_DEBUG,
1025         "Got %" PRIX32 ". peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1026         ipc->i, GNUNET_i2s (peer), peer, gossip_list_size);
1027     RPS_sampler_update_list (peer);
1028     (void) get_peer_ctx (peer_map, peer); // unneeded? -> insertCB
1029
1030     if (ipc->i < gossip_list_size)
1031     {
1032       gossip_list[ipc->i] = *peer; // FIXME sometimes we're writing to invalid space here
1033                                    // not sure whether fixed
1034       ipc->i++;
1035     }
1036
1037     // send push/pull to each of those peers?
1038   }
1039   else
1040   {
1041     if (ipc->i < gossip_list_size)
1042     {
1043       memcpy (&gossip_list[ipc->i],
1044           RPS_sampler_get_n_rand_peers_ (1),
1045           (gossip_list_size - ipc->i) * sizeof (struct GNUNET_PeerIdentity));
1046     }
1047     rps_start (ipc->server);
1048     GNUNET_free (ipc);
1049   }
1050 }
1051
1052
1053 /**
1054  * Callback used to clean the multipeermap.
1055  */
1056   int
1057 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1058 {
1059   struct PeerContext *peer_ctx;
1060
1061   peer_ctx = (struct PeerContext *) value;
1062
1063   if ( NULL != peer_ctx->mq)
1064     GNUNET_MQ_destroy (peer_ctx->mq);
1065
1066   if ( NULL != peer_ctx->to_channel)
1067     GNUNET_CADET_channel_destroy (peer_ctx->to_channel);
1068   
1069   if ( NULL != peer_ctx->from_channel)
1070     GNUNET_CADET_channel_destroy (peer_ctx->from_channel);
1071
1072   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1073     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1074   
1075   return GNUNET_YES;
1076 }
1077
1078
1079 /**
1080  * Task run during shutdown.
1081  *
1082  * @param cls unused
1083  * @param tc unused
1084  */
1085 static void
1086 shutdown_task (void *cls,
1087                const struct GNUNET_SCHEDULER_TaskContext *tc)
1088 {
1089   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1090
1091   if ( NULL != do_round_task )
1092   {
1093     GNUNET_SCHEDULER_cancel (do_round_task);
1094     do_round_task = NULL;
1095   }
1096
1097   
1098   if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1099     LOG (GNUNET_ERROR_TYPE_WARNING,
1100         "Iterating over peers to disconnect from them was cancelled\n");
1101
1102   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1103
1104   GNUNET_NSE_disconnect (nse);
1105   GNUNET_CADET_disconnect (cadet_handle);
1106   GNUNET_free (own_identity);
1107   RPS_sampler_destroy ();
1108   GNUNET_array_grow (request_deltas, request_deltas_size, 0);
1109   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1110   GNUNET_array_grow (push_list, push_list_size, 0);
1111   GNUNET_array_grow (pull_list, pull_list_size, 0);
1112 }
1113
1114
1115 /**
1116  * A client disconnected.  Remove all of its data structure entries.
1117  *
1118  * @param cls closure, NULL
1119  * @param client identification of the client
1120  */
1121 static void
1122 handle_client_disconnect (void *cls,
1123                           struct GNUNET_SERVER_Client * client)
1124 {
1125 }
1126
1127 /**
1128  * Handle the channel a peer opens to us.
1129  *
1130  * @param cls The closure
1131  * @param channel The channel the peer wants to establish
1132  * @param initiator The peer's peer ID
1133  * @param port The port the channel is being established over
1134  * @param options Further options
1135  */
1136   static void *
1137 handle_inbound_channel (void *cls,
1138                         struct GNUNET_CADET_Channel *channel,
1139                         const struct GNUNET_PeerIdentity *initiator,
1140                         uint32_t port,
1141                         enum GNUNET_CADET_ChannelOption options)
1142 {
1143   struct PeerContext *ctx;
1144
1145   LOG (GNUNET_ERROR_TYPE_DEBUG, "New channel was established to us (Peer %s).\n", GNUNET_i2s (initiator));
1146
1147   GNUNET_assert ( NULL != channel );
1148
1149   // we might not even store the from_channel
1150
1151   ctx = get_peer_ctx (peer_map, initiator);
1152   if (NULL != ctx->from_channel)
1153   {
1154     ctx->from_channel = channel;
1155   }
1156
1157   // FIXME there might already be an established channel
1158
1159   //ctx->in_flags = in_other_gossip_list;
1160   ctx->mq = NULL; // TODO create mq?
1161
1162   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
1163       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1164   return NULL; // TODO
1165 }
1166
1167 /**
1168  * This is called when a remote peer destroys a channel.
1169  *
1170  * @param cls The closure
1171  * @param channel The channel being closed
1172  * @param channel_ctx The context associated with this channel
1173  */
1174 static void
1175 cleanup_channel (void *cls,
1176                 const struct GNUNET_CADET_Channel *channel,
1177                 void *channel_ctx)
1178 {
1179   struct GNUNET_PeerIdentity *peer;
1180   struct PeerContext *peer_ctx;
1181
1182   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel to remote peer was destroyed.\n");
1183
1184   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1185       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1186        // Guess simply casting isn't the nicest way...
1187        // FIXME wait for cadet to change this function
1188   RPS_sampler_reinitialise_by_value (peer);
1189
1190   peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1191   /* Somwewhat {ab,re}use the iterator function */
1192   (void) peer_remove_cb (peer, peer, peer_ctx);
1193 }
1194
1195 /**
1196  * Actually start the service.
1197  */
1198 static void
1199 rps_start (struct GNUNET_SERVER_Handle *server)
1200 {
1201   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1202     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1203       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1204     {&handle_client_seed,    NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1205     {NULL, NULL, 0, 0}
1206   };
1207
1208   GNUNET_SERVER_add_handlers (server, handlers);
1209   GNUNET_SERVER_disconnect_notify (server,
1210                                    &handle_client_disconnect,
1211                                    NULL);
1212   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1213
1214
1215   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1216   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1217
1218   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1219                                 &shutdown_task,
1220                                 NULL);
1221 }
1222
1223
1224 /**
1225  * Process statistics requests.
1226  *
1227  * @param cls closure
1228  * @param server the initialized server
1229  * @param c configuration to use
1230  */
1231 static void
1232 run (void *cls,
1233      struct GNUNET_SERVER_Handle *server,
1234      const struct GNUNET_CONFIGURATION_Handle *c)
1235 {
1236   // TODO check what this does -- copied from gnunet-boss
1237   // - seems to work as expected
1238   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1239
1240   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1241
1242   struct init_peer_cls *ipc;
1243
1244   cfg = c;
1245
1246
1247   /* Get own ID */
1248   own_identity = GNUNET_new (struct GNUNET_PeerIdentity);
1249   GNUNET_CRYPTO_get_peer_identity (cfg, own_identity); // TODO check return value
1250   GNUNET_assert (NULL != own_identity);
1251   LOG (GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s (own_identity), own_identity);
1252
1253
1254   /* Get time interval from the configuration */
1255   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1256                                                         "ROUNDINTERVAL",
1257                                                         &round_interval))
1258   {
1259     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1260     GNUNET_SCHEDULER_shutdown ();
1261     return;
1262   }
1263
1264   /* Get initial size of sampler/gossip list from the configuration */
1265   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1266                                                          "INITSIZE",
1267                                                          (long long unsigned int *) &sampler_size_est_need))
1268   {
1269     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1270     GNUNET_SCHEDULER_shutdown ();
1271     return;
1272   }
1273   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
1274
1275   //gossip_list_size = sampler_size; // TODO rename sampler_size
1276
1277   gossip_list = NULL;
1278   GNUNET_array_grow (gossip_list, gossip_list_size, sampler_size_est_need);
1279
1280
1281   /* connect to NSE */
1282   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
1283   // TODO check whether that was successful
1284   // TODO disconnect on shutdown
1285   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1286
1287
1288   alpha = 0.45;
1289   beta  = 0.45;
1290   // TODO initialise thresholds - ?
1291
1292   /* Get alpha from the configuration */
1293   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1294                                                          "ALPHA",
1295                                                          &alpha))
1296   {
1297     LOG (GNUNET_ERROR_TYPE_DEBUG, "No ALPHA specified in the config\n");
1298   }
1299   LOG (GNUNET_ERROR_TYPE_DEBUG, "ALPHA is %f\n", alpha);
1300  
1301   /* Get beta from the configuration */
1302   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1303                                                          "BETA",
1304                                                          &beta))
1305   {
1306     LOG (GNUNET_ERROR_TYPE_DEBUG, "No BETA specified in the config\n");
1307   }
1308   LOG (GNUNET_ERROR_TYPE_DEBUG, "BETA is %f\n", beta);
1309
1310   // TODO check that alpha + beta < 1
1311
1312   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
1313
1314
1315   /* Initialise cadet */
1316   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1317     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
1318       sizeof (struct GNUNET_MessageHeader)},
1319     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
1320       sizeof (struct GNUNET_MessageHeader)},
1321     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1322     {NULL, 0, 0}
1323   };
1324
1325   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1326   cadet_handle = GNUNET_CADET_connect (cfg,
1327                                     cls,
1328                                     &handle_inbound_channel,
1329                                     &cleanup_channel,
1330                                     cadet_handlers,
1331                                     ports);
1332   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1333
1334
1335   /* Initialise sampler */
1336   struct GNUNET_TIME_Relative half_round_interval;
1337   struct GNUNET_TIME_Relative  max_round_interval;
1338
1339   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
1340   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
1341
1342   RPS_sampler_init (sampler_size_est_need, own_identity, max_round_interval,
1343       insertCB, NULL, removeCB, NULL);
1344   sampler_size = sampler_size_est_need;
1345
1346   /* Initialise push and pull maps */
1347   push_list = NULL;
1348   push_list_size = 0;
1349   pull_list = NULL;
1350   pull_list_size = 0;
1351
1352
1353   ipc = GNUNET_new (struct init_peer_cls);
1354   ipc->server = server;
1355   ipc->i = 0;
1356   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1357   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, ipc);
1358
1359   // TODO send push/pull to each of those peers?
1360 }
1361
1362
1363 /**
1364  * The main function for the rps service.
1365  *
1366  * @param argc number of arguments from the command line
1367  * @param argv command line arguments
1368  * @return 0 ok, 1 on error
1369  */
1370 int
1371 main (int argc, char *const *argv)
1372 {
1373   return (GNUNET_OK ==
1374           GNUNET_SERVICE_run (argc,
1375                               argv,
1376                               "rps",
1377                               GNUNET_SERVICE_OPTION_NONE,
1378                               &run, NULL)) ? 0 : 1;
1379 }
1380
1381 /* end of gnunet-service-rps.c */