- check for validity of peers
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      Copyright (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 check for overflows
42
43 // TODO align message structs
44
45 // (TODO api -- possibility of getting weak random peer immideately)
46
47 // TODO malicious peer
48
49 // TODO connect to friends
50
51 // TODO store peers somewhere
52
53 // TODO ignore list?
54
55 // hist_size_init, hist_size_max
56
57 /**
58  * Our configuration.
59  */
60 static const struct GNUNET_CONFIGURATION_Handle *cfg;
61
62 /**
63  * Our own identity.
64  */
65 static struct GNUNET_PeerIdentity own_identity;
66
67
68   struct GNUNET_PeerIdentity *
69 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
70                            const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
71
72
73 /***********************************************************************
74  * Housekeeping with peers
75 ***********************************************************************/
76
77 /**
78  * Struct used to store the context of a connected client.
79  */
80 struct client_ctx
81 {
82   /**
83    * The message queue to communicate with the client.
84    */
85   struct GNUNET_MQ_Handle *mq;
86 };
87
88 /**
89  * Used to keep track in what lists single peerIDs are.
90  */
91 enum PeerFlags
92 {
93   PULL_REPLY_PENDING   = 0x01,
94   IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
95   IN_OWN_SAMPLER_LIST  = 0x04, // unneeded?
96   IN_OWN_GOSSIP_LIST   = 0x08, // unneeded?
97
98   /**
99    * We set this bit when we can be sure the other peer is/was live.
100    */
101   VALID                = 0x10
102 };
103
104
105 /**
106  * Functions of this type can be used to be stored at a peer for later execution.
107  */
108 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
109
110 /**
111  * Outstanding operation on peer consisting of callback and closure
112  */
113 struct PeerOutstandingOp
114 {
115   /**
116    * Callback
117    */
118   PeerOp op;
119
120   /**
121    * Closure
122    */
123   void *op_cls;
124 };
125
126
127 /**
128  * Struct used to keep track of other peer's status
129  *
130  * This is stored in a multipeermap.
131  */
132 struct PeerContext
133 {
134   /**
135    * In own gossip/sampler list, in other's gossip/sampler list
136    */
137   uint32_t peer_flags;
138
139   /**
140    * Message queue open to client
141    */
142   struct GNUNET_MQ_Handle *mq;
143
144   /**
145    * Channel open to client.
146    */
147   struct GNUNET_CADET_Channel *send_channel;
148
149   /**
150    * Channel open from client.
151    */
152   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
153
154   /**
155    * Array of outstanding operations on this peer.
156    */
157   struct PeerOutstandingOp *outstanding_ops;
158
159   /**
160    * Number of outstanding operations.
161    */
162   unsigned int num_outstanding_ops;
163   //size_t num_outstanding_ops;
164
165   /**
166    * Handle to the callback given to cadet_ntfy_tmt_rdy()
167    *
168    * To be canceled on shutdown.
169    */
170   struct GNUNET_CADET_TransmitHandle *is_live_task;
171
172   /**
173    * Identity of the peer
174    */
175   struct GNUNET_PeerIdentity peer_id;
176
177   /**
178    * This is pobably followed by 'statistical' data (when we first saw
179    * him, how did we get his ID, how many pushes (in a timeinterval),
180    * ...)
181    */
182 };
183
184 /***********************************************************************
185  * /Housekeeping with peers
186 ***********************************************************************/
187
188
189
190
191
192 /***********************************************************************
193  * Globals
194 ***********************************************************************/
195
196 /**
197  * Sampler used for the Brahms protocol itself.
198  */
199 static struct RPS_Sampler *prot_sampler;
200
201 /**
202  * Sampler used for the clients.
203  */
204 static struct RPS_Sampler *client_sampler;
205
206 /**
207  * Set of all peers to keep track of them.
208  */
209 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
210
211
212 /**
213  * The gossiped list of peers.
214  */
215 static struct GNUNET_PeerIdentity *gossip_list;
216
217 /**
218  * Size of the gossiped list
219  */
220 //static unsigned int gossip_list_size;
221 static uint32_t gossip_list_size;
222
223
224 /**
225  * The size of sampler we need to be able to satisfy the client's need of
226  * random peers.
227  */
228 static unsigned int sampler_size_client_need;
229
230 /**
231  * The size of sampler we need to be able to satisfy the Brahms protocol's
232  * need of random peers.
233  *
234  * This is directly taken as the #gossip_list_size on update of the
235  * #gossip_list
236  *
237  * This is one minimum size the sampler grows to.
238  */
239 static unsigned int sampler_size_est_need;
240
241
242 /**
243  * Percentage of total peer number in the gossip list
244  * to send random PUSHes to
245  */
246 static float alpha;
247
248 /**
249  * Percentage of total peer number in the gossip list
250  * to send random PULLs to
251  */
252 static float beta;
253
254 /**
255  * The percentage gamma of history updates.
256  * Simply 1 - alpha - beta
257  */
258
259
260 /**
261  * Identifier for the main task that runs periodically.
262  */
263 static struct GNUNET_SCHEDULER_Task *do_round_task;
264
265 /**
266  * Time inverval the do_round task runs in.
267  */
268 static struct GNUNET_TIME_Relative round_interval;
269
270
271
272 /**
273  * List to store peers received through pushes temporary.
274  *
275  * TODO -> multipeermap
276  */
277 static struct GNUNET_PeerIdentity *push_list;
278
279 /**
280  * Size of the push_list;
281  */
282 static unsigned int push_list_size;
283 //size_t push_list_size;
284
285 /**
286  * List to store peers received through pulls temporary.
287  *
288  * TODO -> multipeermap
289  */
290 static struct GNUNET_PeerIdentity *pull_list;
291
292 /**
293  * Size of the pull_list;
294  */
295 static unsigned int pull_list_size;
296 //size_t pull_list_size;
297
298
299 /**
300  * Handler to NSE.
301  */
302 static struct GNUNET_NSE_Handle *nse;
303
304 /**
305  * Handler to CADET.
306  */
307 static struct GNUNET_CADET_Handle *cadet_handle;
308
309
310 /**
311  * Request counter.
312  *
313  * Only needed in the beginning to check how many of the 64 deltas
314  * we already have
315  */
316 static unsigned int req_counter;
317
318 /**
319  * Time of the last request we received.
320  *
321  * Used to compute the expected request rate.
322  */
323 static struct GNUNET_TIME_Absolute last_request;
324
325 /**
326  * Size of #request_deltas.
327  */
328 #define REQUEST_DELTAS_SIZE 64
329 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
330
331 /**
332  * Last 64 deltas between requests
333  */
334 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
335
336 /**
337  * The prediction of the rate of requests
338  */
339 static struct GNUNET_TIME_Relative  request_rate;
340
341
342 /**
343  * List with the peers we sent requests to.
344  */
345 struct GNUNET_PeerIdentity *pending_pull_reply_list;
346
347 /**
348  * Size of #pending_pull_reply_list.
349  */
350 uint32_t pending_pull_reply_list_size;
351
352
353 /**
354  * Number of history update tasks.
355  */
356 uint32_t num_hist_update_tasks;
357
358
359 /***********************************************************************
360  * /Globals
361 ***********************************************************************/
362
363
364
365
366
367
368 /***********************************************************************
369  * Util functions
370 ***********************************************************************/
371
372 /**
373  * Set a peer flag of given peer context.
374  */
375 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
376
377 /**
378  * Get peer flag of given peer context.
379  */
380 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
381
382 /**
383  * Unset flag of given peer context.
384  */
385 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
386
387
388 /**
389  * Clean the send channel of a peer
390  */
391 void
392 peer_clean (const struct GNUNET_PeerIdentity *peer);
393
394
395 /**
396  * Check if peer is already in peer array.
397  */
398   int
399 in_arr (const struct GNUNET_PeerIdentity *array,
400         unsigned int arr_size,
401         const struct GNUNET_PeerIdentity *peer)
402 {
403   GNUNET_assert (NULL != peer);
404
405   if (0 == arr_size)
406     return GNUNET_NO;
407
408   GNUNET_assert (NULL != array);
409
410   unsigned int i;
411
412   for (i = 0; i < arr_size ; i++)
413     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
414       return GNUNET_YES;
415   return GNUNET_NO;
416 }
417
418
419 /**
420  * Print peerlist to log.
421  */
422 void
423 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
424 {
425   unsigned int i;
426
427   LOG (GNUNET_ERROR_TYPE_DEBUG,
428        "Printing peer list of length %u at %p:\n",
429        len,
430        list);
431   for (i = 0 ; i < len ; i++)
432   {
433     LOG (GNUNET_ERROR_TYPE_DEBUG,
434          "%u. peer: %s\n",
435          i, GNUNET_i2s (&list[i]));
436   }
437 }
438
439
440 /**
441  * Remove peer from list.
442  */
443   void
444 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
445                unsigned int *list_size,
446                const struct GNUNET_PeerIdentity *peer)
447 {
448   unsigned int i;
449   struct GNUNET_PeerIdentity *tmp;
450
451   tmp = *peer_list;
452
453   LOG (GNUNET_ERROR_TYPE_DEBUG,
454        "Removing peer %s from list at %p\n",
455        GNUNET_i2s (peer),
456        tmp);
457   print_peer_list (tmp, *list_size);
458
459   for ( i = 0 ; i < *list_size ; i++ )
460   {
461     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
462     {
463       if (i < *list_size -1)
464       { /* Not at the last entry -- shift peers left */
465         memcpy (&tmp[i], &tmp[i +1],
466                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
467       }
468       /* Remove last entry (should be now useless PeerID) */
469       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
470     }
471   }
472   *peer_list = tmp;
473 }
474
475 /**
476  * Get random peer from the given list but don't return one from the @a ignore_list.
477  */
478   struct GNUNET_PeerIdentity *
479 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
480                            uint32_t list_size,
481                            const struct GNUNET_PeerIdentity *ignore_list,
482                            uint32_t ignore_size)
483 {
484   uint32_t r_index;
485   uint32_t tmp_size;
486   struct GNUNET_PeerIdentity *tmp_peer_list;
487   struct GNUNET_PeerIdentity *peer;
488
489   GNUNET_assert (NULL != peer_list);
490   if (0 == list_size)
491     return NULL;
492
493   tmp_size = 0;
494   tmp_peer_list = NULL;
495   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
496   memcpy (tmp_peer_list,
497           peer_list,
498           list_size * sizeof (struct GNUNET_PeerIdentity));
499   peer = GNUNET_new (struct GNUNET_PeerIdentity);
500
501   /**;
502    * Choose the r_index of the peer we want to return
503    * at random from the interval of the gossip list
504    */
505   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
506                                       tmp_size);
507   *peer = tmp_peer_list[r_index];
508
509   while (in_arr (ignore_list, ignore_size, peer))
510   {
511     rem_from_list (&tmp_peer_list, &tmp_size, peer);
512
513     print_peer_list (tmp_peer_list, tmp_size);
514
515     if (0 == tmp_size)
516     {
517       GNUNET_free (peer);
518       return NULL;
519     }
520
521     /**;
522      * Choose the r_index of the peer we want to return
523      * at random from the interval of the gossip list
524      */
525     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
526                                         tmp_size);
527     *peer = tmp_peer_list[r_index];
528   }
529
530
531   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
532
533   return peer;
534 }
535
536
537 /**
538  * Get the context of a peer. If not existing, create.
539  */
540   struct PeerContext *
541 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
542               const struct GNUNET_PeerIdentity *peer)
543 {
544   struct PeerContext *ctx;
545
546   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
547   {
548     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
549   }
550   else
551   {
552     ctx = GNUNET_new (struct PeerContext);
553     ctx->peer_flags = 0;
554     ctx->mq = NULL;
555     ctx->send_channel = NULL;
556     ctx->recv_channel = NULL;
557     ctx->outstanding_ops = NULL;
558     ctx->num_outstanding_ops = 0;
559     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
560                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
561   }
562   return ctx;
563 }
564
565
566 /**
567  * Put random peer from sampler into the gossip list as history update.
568  */
569   void
570 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
571 {
572   GNUNET_assert (1 == num_peers);
573
574   if (gossip_list_size < sampler_size_est_need)
575     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
576
577   if (0 < num_hist_update_tasks)
578     num_hist_update_tasks--;
579 }
580
581
582 /**
583  * Set the peer flag to living and call the outstanding operations on this peer.
584  */
585 static size_t
586 peer_is_live (struct PeerContext *peer_ctx)
587 {
588   struct GNUNET_PeerIdentity *peer;
589
590   peer = &peer_ctx->peer_id;
591   set_peer_flag (peer_ctx, VALID);
592
593   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
594
595   if (0 != peer_ctx->num_outstanding_ops)
596   { /* Call outstanding operations */
597     unsigned int i;
598
599     for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
600       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
601     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
602   }
603
604   return 0;
605 }
606
607
608 /**
609  * Callback that is called when a channel was effectively established.
610  * This is given to ntfy_tmt_rdy and called when the channel was
611  * successfully established.
612  */
613 static size_t
614 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
615 {
616   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
617
618   if (NULL != buf
619       && 0 != size)
620     peer_is_live (peer_ctx);
621
622   //if (NULL != peer_ctx->is_live_task)
623   //{
624   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
625   //       "Trying to cancle is_live_task for peer %s\n",
626   //       GNUNET_i2s (&peer_ctx->peer_id));
627   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
628   //  peer_ctx->is_live_task = NULL;
629   //}
630   peer_ctx->is_live_task = NULL;
631
632   return 0;
633 }
634
635
636 /**
637  * Get the channel of a peer. If not existing, create.
638  */
639   struct GNUNET_CADET_Channel *
640 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
641              const struct GNUNET_PeerIdentity *peer)
642 {
643   struct PeerContext *ctx;
644
645   LOG (GNUNET_ERROR_TYPE_DEBUG,
646        "Trying to establish channel to peer %s\n",
647        GNUNET_i2s (peer));
648
649   ctx = get_peer_ctx (peer_map, peer);
650   if (NULL == ctx->send_channel)
651   {
652     ctx->send_channel = GNUNET_CADET_channel_create (cadet_handle,
653                                                      NULL,
654                                                      peer,
655                                                      GNUNET_RPS_CADET_PORT,
656                                                      GNUNET_CADET_OPTION_RELIABLE);
657
658     /* If we don't know whether peer is live,
659      * get notified when we know it is live. */
660     if (GNUNET_YES != get_peer_flag (ctx, VALID)
661         && NULL == ctx->recv_channel
662         && NULL == ctx->is_live_task)
663     {
664       ctx->peer_id = *peer;
665       LOG (GNUNET_ERROR_TYPE_DEBUG,
666            "Get informed about peer %s getting live\n",
667            GNUNET_i2s (peer));
668       ctx->is_live_task =
669           GNUNET_CADET_notify_transmit_ready (ctx->send_channel,
670                                               GNUNET_NO,
671                                               GNUNET_TIME_UNIT_FOREVER_REL,
672                                               sizeof (struct GNUNET_MessageHeader),
673                                               cadet_ntfy_tmt_rdy_cb,
674                                               ctx);
675     }
676     // FIXME check whether this is NULL
677
678     // do I have to explicitly put it in the peer_map?
679     (void) GNUNET_CONTAINER_multipeermap_put
680       (peer_map,
681        peer,
682        ctx,
683        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
684   }
685   return ctx->send_channel;
686 }
687
688
689 /**
690  * Get the message queue of a specific peer.
691  *
692  * If we already have a message queue open to this client,
693  * simply return it, otherways create one.
694  */
695   struct GNUNET_MQ_Handle *
696 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
697         const struct GNUNET_PeerIdentity *peer_id)
698 {
699   struct PeerContext *peer_ctx;
700
701   peer_ctx = get_peer_ctx (peer_map, peer_id);
702
703   GNUNET_assert (NULL == peer_ctx->is_live_task);
704
705   if (NULL == peer_ctx->mq)
706   {
707     (void) get_channel (peer_map, peer_id);
708     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
709     //do I have to explicitly put it in the peer_map?
710     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
711                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
712   }
713   return peer_ctx->mq;
714 }
715
716
717 /**
718  * Sum all time relatives of an array.
719   */
720   struct GNUNET_TIME_Relative
721 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
722 {
723   struct GNUNET_TIME_Relative sum;
724   uint32_t i;
725
726   sum = GNUNET_TIME_UNIT_ZERO;
727   for ( i = 0 ; i < arr_size ; i++ )
728   {
729     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
730   }
731   return sum;
732 }
733
734
735 /**
736  * Compute the average of given time relatives.
737  */
738   struct GNUNET_TIME_Relative
739 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
740 {
741   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
742 }
743
744
745 /**
746  * Insert PeerID in #pull_list
747  *
748  * Called once we know a peer is live.
749  */
750   void
751 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
752 {
753   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
754     GNUNET_array_append (pull_list, pull_list_size, *peer);
755
756   peer_clean (peer);
757 }
758
759 /**
760  * Check whether #insert_in_pull_list was already scheduled
761  */
762   int
763 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
764 {
765   unsigned int i;
766
767   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
768     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
769       return GNUNET_YES;
770   return GNUNET_NO;
771 }
772
773
774 /**
775  * Insert PeerID in #gossip_list
776  *
777  * Called once we know a peer is live.
778  */
779   void
780 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
781 {
782   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
783     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
784
785   (void) get_channel (peer_map, peer);
786 }
787
788 /**
789  * Check whether #insert_in_pull_list was already scheduled
790  */
791   int
792 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
793 {
794   unsigned int i;
795
796   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
797     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
798       return GNUNET_YES;
799   return GNUNET_NO;
800 }
801
802
803 /**
804  * Update sampler with given PeerID.
805  */
806   void
807 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
808 {
809   RPS_sampler_update (prot_sampler,   peer);
810   RPS_sampler_update (client_sampler, peer);
811 }
812
813
814 /**
815  * Check whether #insert_in_sampler was already scheduled
816  */
817 static int
818 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
819 {
820   unsigned int i;
821
822   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
823     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
824       return GNUNET_YES;
825   return GNUNET_NO;
826 }
827
828
829 /**
830  * Wrapper around #RPS_sampler_resize()
831  *
832  * If we do not have enough sampler elements, double current sampler size
833  * If we have more than enough sampler elements, halv current sampler size
834  */
835 static void
836 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
837 {
838   unsigned int sampler_size;
839
840   // TODO statistics
841   // TODO respect the min, max
842   sampler_size = RPS_sampler_get_size (sampler);
843   if (sampler_size > new_size * 4)
844   { /* Shrinking */
845     RPS_sampler_resize (sampler, sampler_size / 2);
846   }
847   else if (sampler_size < new_size)
848   { /* Growing */
849     RPS_sampler_resize (sampler, sampler_size * 2);
850   }
851   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
852 }
853
854
855 /**
856  * Wrapper around #RPS_sampler_resize() resizing the client sampler
857  */
858 static void
859 client_resize_wrapper ()
860 {
861   uint32_t bigger_size;
862   unsigned int sampler_size;
863
864   // TODO statistics
865
866   sampler_size = RPS_sampler_get_size (client_sampler);
867
868   if (sampler_size_est_need > sampler_size_client_need)
869     bigger_size = sampler_size_est_need;
870   else
871     bigger_size = sampler_size_client_need;
872
873   // TODO respect the min, max
874   resize_wrapper (client_sampler, bigger_size);
875   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
876 }
877
878
879 /**
880  * Estimate request rate
881  *
882  * Called every time we receive a request from the client.
883  */
884   void
885 est_request_rate()
886 {
887   struct GNUNET_TIME_Relative max_round_duration;
888
889   if (request_deltas_size > req_counter)
890     req_counter++;
891   if ( 1 < req_counter)
892   {
893     /* Shift last request deltas to the right */
894     memcpy (&request_deltas[1],
895         request_deltas,
896         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
897
898     /* Add current delta to beginning */
899     request_deltas[0] =
900         GNUNET_TIME_absolute_get_difference (last_request,
901                                              GNUNET_TIME_absolute_get ());
902     request_rate = T_relative_avg (request_deltas, req_counter);
903
904     /* Compute the duration a round will maximally take */
905     max_round_duration =
906         GNUNET_TIME_relative_add (round_interval,
907                                   GNUNET_TIME_relative_divide (round_interval, 2));
908
909     /* Set the estimated size the sampler has to have to
910      * satisfy the current client request rate */
911     sampler_size_client_need =
912         max_round_duration.rel_value_us / request_rate.rel_value_us;
913
914     /* Resize the sampler */
915     client_resize_wrapper ();
916   }
917   last_request = GNUNET_TIME_absolute_get ();
918 }
919
920
921 /***********************************************************************
922  * /Util functions
923 ***********************************************************************/
924
925
926
927
928
929 /**
930  * Function called by NSE.
931  *
932  * Updates sizes of sampler list and gossip list and adapt those lists
933  * accordingly.
934  */
935   void
936 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
937               double logestimate, double std_dev)
938 {
939   double estimate;
940   //double scale; // TODO this might go gloabal/config
941
942   LOG (GNUNET_ERROR_TYPE_DEBUG,
943        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
944        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
945   //scale = .01;
946   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
947   // GNUNET_NSE_log_estimate_to_n (logestimate);
948   estimate = pow (estimate, 1.0 / 3);
949   // TODO add if std_dev is a number
950   // estimate += (std_dev * scale);
951   if (2 < ceil (estimate))
952   {
953     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
954     sampler_size_est_need = estimate;
955   } else
956     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
957
958   /* If the NSE has changed adapt the lists accordingly */
959   resize_wrapper (prot_sampler, sampler_size_est_need);
960   client_resize_wrapper ();
961 }
962
963
964 /**
965  * Callback called once the requested PeerIDs are ready.
966  *
967  * Sends those to the requesting client.
968  */
969 void client_respond (void *cls,
970     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
971 {
972   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
973   struct GNUNET_MQ_Envelope *ev;
974   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
975   struct GNUNET_SERVER_Client *client;
976   uint32_t size_needed;
977   struct client_ctx *cli_ctx;
978
979   client = (struct GNUNET_SERVER_Client *) cls;
980
981   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
982                 num_peers * sizeof (struct GNUNET_PeerIdentity);
983
984   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
985
986   ev = GNUNET_MQ_msg_extra (out_msg,
987                             num_peers * sizeof (struct GNUNET_PeerIdentity),
988                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
989   out_msg->num_peers = htonl (num_peers);
990
991   memcpy (&out_msg[1],
992       ids,
993       num_peers * sizeof (struct GNUNET_PeerIdentity));
994   GNUNET_free (ids);
995
996   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
997   if ( NULL == cli_ctx ) {
998     cli_ctx = GNUNET_new (struct client_ctx);
999     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
1000     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
1001   }
1002
1003   GNUNET_MQ_send (cli_ctx->mq, ev);
1004 }
1005
1006
1007 /**
1008  * Handle RPS request from the client.
1009  *
1010  * @param cls closure
1011  * @param client identification of the client
1012  * @param message the actual message
1013  */
1014 static void
1015 handle_client_request (void *cls,
1016             struct GNUNET_SERVER_Client *client,
1017             const struct GNUNET_MessageHeader *message)
1018 {
1019   struct GNUNET_RPS_CS_RequestMessage *msg;
1020   uint32_t num_peers;
1021   uint32_t size_needed;
1022   uint32_t i;
1023
1024   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1025
1026   num_peers = ntohl (msg->num_peers);
1027   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1028                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1029
1030   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1031   {
1032     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1033     return;
1034   }
1035
1036   for (i = 0 ; i < num_peers ; i++)
1037     est_request_rate();
1038
1039   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
1040
1041   RPS_sampler_get_n_rand_peers (client_sampler, client_respond,
1042                                 client, num_peers, GNUNET_YES);
1043
1044   GNUNET_SERVER_receive_done (client,
1045                               GNUNET_OK);
1046 }
1047
1048
1049 /**
1050  * Handle seed from the client.
1051  *
1052  * @param cls closure
1053  * @param client identification of the client
1054  * @param message the actual message
1055  */
1056   static void
1057 handle_client_seed (void *cls,
1058             struct GNUNET_SERVER_Client *client,
1059             const struct GNUNET_MessageHeader *message)
1060 {
1061   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1062   struct GNUNET_PeerIdentity *peers;
1063   uint32_t i;
1064
1065   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) < ntohs (message->size))
1066   {
1067     GNUNET_break_op (0);
1068     GNUNET_SERVER_receive_done (client,
1069               GNUNET_SYSERR);
1070   }
1071   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1072   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1073       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1074   {
1075     GNUNET_break_op (0);
1076     GNUNET_SERVER_receive_done (client,
1077               GNUNET_SYSERR);
1078   }
1079
1080   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1081   peers = (struct GNUNET_PeerIdentity *) &message[1];
1082
1083   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
1084     RPS_sampler_update (prot_sampler,   &peers[i]);
1085     RPS_sampler_update (client_sampler, &peers[i]);
1086
1087   GNUNET_SERVER_receive_done (client,
1088                               GNUNET_OK);
1089 }
1090
1091
1092 /**
1093  * Handle a PUSH message from another peer.
1094  *
1095  * Check the proof of work and store the PeerID
1096  * in the temporary list for pushed PeerIDs.
1097  *
1098  * @param cls Closure
1099  * @param channel The channel the PUSH was received over
1100  * @param channel_ctx The context associated with this channel
1101  * @param msg The message header
1102  */
1103 static int
1104 handle_peer_push (void *cls,
1105     struct GNUNET_CADET_Channel *channel,
1106     void **channel_ctx,
1107     const struct GNUNET_MessageHeader *msg)
1108 {
1109   const struct GNUNET_PeerIdentity *peer;
1110
1111   // (check the proof of work)
1112
1113   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1114   // FIXME wait for cadet to change this function
1115   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1116
1117   /* Add the sending peer to the push_list */
1118   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
1119     GNUNET_array_append (push_list, push_list_size, *peer);
1120
1121   return GNUNET_OK;
1122 }
1123
1124 /**
1125  * Handle PULL REQUEST request message from another peer.
1126  *
1127  * Reply with the gossip list of PeerIDs.
1128  *
1129  * @param cls Closure
1130  * @param channel The channel the PUSH was received over
1131  * @param channel_ctx The context associated with this channel
1132  * @param msg The message header
1133  */
1134 static int
1135 handle_peer_pull_request (void *cls,
1136     struct GNUNET_CADET_Channel *channel,
1137     void **channel_ctx,
1138     const struct GNUNET_MessageHeader *msg)
1139 {
1140   struct GNUNET_PeerIdentity *peer;
1141   uint32_t send_size;
1142   struct GNUNET_MQ_Handle *mq;
1143   struct GNUNET_MQ_Envelope *ev;
1144   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1145
1146
1147   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel,
1148                                                                        GNUNET_CADET_OPTION_PEER);
1149   // FIXME wait for cadet to change this function
1150
1151   /* Compute actual size */
1152   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1153               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1154
1155   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1156     /* Compute number of peers to send
1157      * If too long, simply truncate */
1158     send_size =
1159       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1160        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1161        sizeof (struct GNUNET_PeerIdentity);
1162   else
1163     send_size = gossip_list_size;
1164
1165   LOG (GNUNET_ERROR_TYPE_DEBUG,
1166       "PULL REQUEST from peer %s received, going to send %u peers\n",
1167       GNUNET_i2s (peer), send_size);
1168
1169   mq = get_mq (peer_map, peer);
1170
1171   ev = GNUNET_MQ_msg_extra (out_msg,
1172                            send_size * sizeof (struct GNUNET_PeerIdentity),
1173                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1174   //out_msg->num_peers = htonl (gossip_list_size);
1175   out_msg->num_peers = htonl (send_size);
1176   memcpy (&out_msg[1], gossip_list,
1177          send_size * sizeof (struct GNUNET_PeerIdentity));
1178
1179   GNUNET_MQ_send (mq, ev);
1180
1181   return GNUNET_OK;
1182 }
1183
1184 /**
1185  * Handle PULL REPLY message from another peer.
1186  *
1187  * Check whether we sent a corresponding request and
1188  * whether this reply is the first one.
1189  *
1190  * @param cls Closure
1191  * @param channel The channel the PUSH was received over
1192  * @param channel_ctx The context associated with this channel
1193  * @param msg The message header
1194  */
1195   static int
1196 handle_peer_pull_reply (void *cls,
1197     struct GNUNET_CADET_Channel *channel,
1198     void **channel_ctx,
1199     const struct GNUNET_MessageHeader *msg)
1200 {
1201   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1202
1203   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1204   struct GNUNET_PeerIdentity *peers;
1205   struct PeerContext *peer_ctx;
1206   struct GNUNET_PeerIdentity *sender;
1207   struct PeerContext *sender_ctx;
1208   struct PeerOutstandingOp out_op;
1209   uint32_t i;
1210
1211   /* Check for protocol violation */
1212   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1213   {
1214     GNUNET_break_op (0);
1215     return GNUNET_SYSERR;
1216   }
1217   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1218   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1219       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1220   {
1221     LOG (GNUNET_ERROR_TYPE_ERROR,
1222         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1223         ntohl (in_msg->num_peers),
1224         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1225             sizeof (struct GNUNET_PeerIdentity));
1226     GNUNET_break_op (0);
1227     return GNUNET_SYSERR;
1228   }
1229
1230   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1231       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1232        // Guess simply casting isn't the nicest way...
1233        // FIXME wait for cadet to change this function
1234   sender_ctx = get_peer_ctx (peer_map, sender);
1235
1236   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1237   {
1238     GNUNET_break_op (0);
1239     return GNUNET_OK;
1240   }
1241
1242   /* Do actual logic */
1243   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1244   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1245   {
1246     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1247     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1248         || NULL != peer_ctx->send_channel
1249         || NULL != peer_ctx->recv_channel)
1250     {
1251       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1252           && GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1253         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1254     }
1255     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1256     {
1257       out_op.op = insert_in_pull_list;
1258       out_op.op_cls = NULL;
1259       GNUNET_array_append (peer_ctx->outstanding_ops,
1260                            peer_ctx->num_outstanding_ops,
1261                            out_op);
1262     }
1263   }
1264
1265   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1266   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1267
1268   return GNUNET_OK;
1269 }
1270
1271
1272 /**
1273  * Send out PUSHes and PULLs.
1274  *
1275  * This is executed regylary.
1276  */
1277 static void
1278 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1279 {
1280   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1281
1282   uint32_t i;
1283   unsigned int *permut;
1284   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1285   struct GNUNET_MQ_Envelope *ev;
1286   struct GNUNET_PeerIdentity peer;
1287   struct GNUNET_PeerIdentity *tmp_peer;
1288   struct GNUNET_MQ_Handle *mq;
1289
1290   LOG (GNUNET_ERROR_TYPE_DEBUG,
1291        "Printing gossip list:\n");
1292   for (i = 0 ; i < gossip_list_size ; i++)
1293     LOG (GNUNET_ERROR_TYPE_DEBUG,
1294          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1295   // TODO log lists, ...
1296
1297   /* Would it make sense to have one shuffeled gossip list and then
1298    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1299    * use the rest to update sampler?
1300    * in essence get random peers with consumption */
1301
1302   /* Send PUSHes */
1303   if (0 < gossip_list_size)
1304   {
1305     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1306                                            (unsigned int) gossip_list_size);
1307     n_peers = ceil (alpha * gossip_list_size);
1308     LOG (GNUNET_ERROR_TYPE_DEBUG,
1309          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1310          n_peers, alpha, gossip_list_size);
1311     for (i = 0 ; i < n_peers ; i++)
1312     {
1313       peer = gossip_list[permut[i]];
1314       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1315       { // FIXME if this fails schedule/loop this for later
1316         LOG (GNUNET_ERROR_TYPE_DEBUG,
1317              "Sending PUSH to peer %s of gossiped list.\n",
1318              GNUNET_i2s (&peer));
1319
1320         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1321         mq = get_mq (peer_map, &peer);
1322         GNUNET_MQ_send (mq, ev);
1323       }
1324     }
1325     GNUNET_free (permut);
1326   }
1327
1328
1329   /* Send PULL requests */
1330   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1331   n_peers = ceil (beta * gossip_list_size);
1332   LOG (GNUNET_ERROR_TYPE_DEBUG,
1333        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1334        n_peers, beta, gossip_list_size);
1335   for (i = 0 ; i < n_peers ; i++)
1336   {
1337     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1338         pending_pull_reply_list, pending_pull_reply_list_size);
1339     if (NULL != tmp_peer)
1340     {
1341       peer = *tmp_peer;
1342       GNUNET_free (tmp_peer);
1343
1344       GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, peer);
1345
1346       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1347       { // FIXME if this fails schedule/loop this for later
1348         LOG (GNUNET_ERROR_TYPE_DEBUG,
1349              "Sending PULL request to peer %s of gossiped list.\n",
1350              GNUNET_i2s (&peer));
1351
1352         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1353         mq = get_mq (peer_map, &peer);
1354         GNUNET_MQ_send (mq, ev);
1355       }
1356     }
1357   }
1358
1359
1360   /* Update gossip list */
1361
1362   if ( push_list_size <= alpha * gossip_list_size &&
1363        push_list_size != 0 &&
1364        pull_list_size != 0 )
1365   {
1366     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1367
1368     uint32_t first_border;
1369     uint32_t second_border;
1370     uint32_t r_index;
1371     uint32_t peers_to_clean_size;
1372     struct GNUNET_PeerIdentity *peers_to_clean;
1373
1374     peers_to_clean = NULL;
1375     peers_to_clean_size = 0;
1376     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
1377     memcpy (peers_to_clean,
1378             gossip_list,
1379             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
1380
1381     first_border  =                ceil (alpha * sampler_size_est_need);
1382     second_border = first_border + ceil (beta  * sampler_size_est_need);
1383
1384     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1385
1386     for (i = 0 ; i < first_border ; i++)
1387     { // TODO use RPS_sampler_get_n_rand_peers
1388       /* Update gossip list with peers received through PUSHes */
1389       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1390                                        push_list_size);
1391       gossip_list[i] = push_list[r_index];
1392       // TODO change the peer_flags accordingly
1393     }
1394
1395     for (i = first_border ; i < second_border ; i++)
1396     {
1397       /* Update gossip list with peers received through PULLs */
1398       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1399                                        pull_list_size);
1400       gossip_list[i] = pull_list[r_index];
1401       // TODO change the peer_flags accordingly
1402     }
1403
1404     for (i = second_border ; i < sampler_size_est_need ; i++)
1405     {
1406       /* Update gossip list with peers from history */
1407       RPS_sampler_get_n_rand_peers (prot_sampler, hist_update, NULL, 1, GNUNET_NO);
1408       num_hist_update_tasks++;
1409       // TODO change the peer_flags accordingly
1410     }
1411
1412     for (i = 0 ; i < gossip_list_size ; i++)
1413       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
1414
1415     for (i = 0 ; i < peers_to_clean_size ; i++)
1416       peer_clean (&peers_to_clean[i]);
1417
1418     GNUNET_free (peers_to_clean);
1419   }
1420   else
1421   {
1422     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1423   }
1424   // TODO independent of that also get some peers from CADET_get_peers()?
1425
1426
1427   /* Update samplers */
1428   for ( i = 0 ; i < push_list_size ; i++ )
1429   {
1430     RPS_sampler_update (prot_sampler,   &push_list[i]);
1431     RPS_sampler_update (client_sampler, &push_list[i]);
1432     // TODO set in_flag?
1433   }
1434
1435   for ( i = 0 ; i < pull_list_size ; i++ )
1436   {
1437     RPS_sampler_update (prot_sampler,   &push_list[i]);
1438     RPS_sampler_update (client_sampler, &push_list[i]);
1439     // TODO set in_flag?
1440   }
1441
1442
1443   /* Empty push/pull lists */
1444   GNUNET_array_grow (push_list, push_list_size, 0);
1445   GNUNET_array_grow (pull_list, pull_list_size, 0);
1446
1447   struct GNUNET_TIME_Relative time_next_round;
1448   struct GNUNET_TIME_Relative half_round_interval;
1449   unsigned int rand_delay;
1450
1451
1452   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1453   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1454   do
1455   {
1456   /*
1457    * Compute random value between (0 and 1) * round_interval
1458    * via multiplying round_interval with a 'fraction' (0 to value)/value
1459    */
1460   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1461   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
1462   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
1463   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
1464   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1465
1466   /* Schedule next round */
1467   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1468   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1469 }
1470
1471
1472 static void
1473 rps_start (struct GNUNET_SERVER_Handle *server);
1474
1475
1476 /**
1477  * This is called from GNUNET_CADET_get_peers().
1478  *
1479  * It is called on every peer(ID) that cadet somehow has contact with.
1480  * We use those to initialise the sampler.
1481  */
1482 void
1483 init_peer_cb (void *cls,
1484               const struct GNUNET_PeerIdentity *peer,
1485               int tunnel, // "Do we have a tunnel towards this peer?"
1486               unsigned int n_paths, // "Number of known paths towards this peer"
1487               unsigned int best_path) // "How long is the best path?
1488                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1489 {
1490   struct GNUNET_SERVER_Handle *server;
1491   struct PeerOutstandingOp out_op;
1492   struct PeerContext *peer_ctx;
1493
1494   server = (struct GNUNET_SERVER_Handle *) cls;
1495   if (NULL != peer
1496       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer))
1497   {
1498     LOG (GNUNET_ERROR_TYPE_DEBUG,
1499         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1500         GNUNET_i2s (peer), peer, gossip_list_size);
1501
1502     // maybe create a function for that
1503     peer_ctx = get_peer_ctx (peer_map, peer);
1504     // FIXME this peer might already be marked as LIVE
1505     if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1506     {
1507       out_op.op = insert_in_sampler;
1508       out_op.op_cls = NULL;
1509       GNUNET_array_append (peer_ctx->outstanding_ops,
1510                            peer_ctx->num_outstanding_ops,
1511                            out_op);
1512     }
1513
1514     if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1515     {
1516       out_op.op = insert_in_gossip_list;
1517       out_op.op_cls = NULL;
1518       GNUNET_array_append (peer_ctx->outstanding_ops,
1519                            peer_ctx->num_outstanding_ops,
1520                            out_op);
1521     }
1522
1523     /* Trigger livelyness test on peer */
1524     (void) get_channel (peer_map, peer);
1525
1526     // send push/pull to each of those peers?
1527   }
1528   else if (NULL == peer)
1529     rps_start (server);
1530 }
1531
1532
1533 /**
1534  * Clean the send channel of a peer
1535  */
1536 void
1537 peer_clean (const struct GNUNET_PeerIdentity *peer)
1538 {
1539   struct PeerContext *peer_ctx;
1540   struct GNUNET_CADET_Channel *channel;
1541
1542   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
1543       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1544   {
1545     peer_ctx = get_peer_ctx (peer_map, peer);
1546     if (NULL != peer_ctx->send_channel)
1547     {
1548       channel = peer_ctx->send_channel;
1549       peer_ctx->send_channel = NULL;
1550       GNUNET_CADET_channel_destroy (channel);
1551     }
1552   }
1553 }
1554
1555
1556 /**
1557  * Callback used to remove peers from the multipeermap.
1558  */
1559   int
1560 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1561 {
1562   struct PeerContext *peer_ctx;
1563   const struct GNUNET_CADET_Channel *channel =
1564     (const struct GNUNET_CADET_Channel *) cls;
1565   struct GNUNET_CADET_Channel *recv;
1566   struct GNUNET_CADET_Channel *send;
1567
1568   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, value))
1569   {
1570     peer_ctx = (struct PeerContext *) value;
1571
1572     if (0 != peer_ctx->num_outstanding_ops)
1573       GNUNET_array_grow (peer_ctx->outstanding_ops,
1574                          peer_ctx->num_outstanding_ops,
1575                          0);
1576
1577     if (NULL != peer_ctx->mq)
1578       GNUNET_MQ_destroy (peer_ctx->mq);
1579
1580     if (NULL != peer_ctx->is_live_task)
1581     {
1582     LOG (GNUNET_ERROR_TYPE_DEBUG,
1583          "Trying to cancle is_live_task for peer %s\n",
1584          GNUNET_i2s (key));
1585       GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1586       peer_ctx->is_live_task = NULL;
1587     }
1588
1589     send = peer_ctx->send_channel;
1590     peer_ctx->send_channel = NULL;
1591     recv = peer_ctx->send_channel;
1592     peer_ctx->recv_channel = NULL;
1593
1594     if (NULL != send
1595         && channel != send)
1596     {
1597       GNUNET_CADET_channel_destroy (send);
1598     }
1599
1600     if (NULL != recv
1601         && channel != recv)
1602     {
1603       GNUNET_CADET_channel_destroy (recv);
1604     }
1605
1606     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1607       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1608     else
1609       GNUNET_free (peer_ctx);
1610   }
1611
1612   return GNUNET_YES;
1613 }
1614
1615
1616 /**
1617  * Task run during shutdown.
1618  *
1619  * @param cls unused
1620  * @param tc unused
1621  */
1622 static void
1623 shutdown_task (void *cls,
1624                const struct GNUNET_SCHEDULER_TaskContext *tc)
1625 {
1626   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1627
1628   if ( NULL != do_round_task )
1629   {
1630     GNUNET_SCHEDULER_cancel (do_round_task);
1631     do_round_task = NULL;
1632   }
1633
1634
1635   {
1636   if (GNUNET_SYSERR ==
1637         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1638     LOG (GNUNET_ERROR_TYPE_WARNING,
1639         "Iterating over peers to disconnect from them was cancelled\n");
1640   }
1641
1642   GNUNET_NSE_disconnect (nse);
1643   GNUNET_CADET_disconnect (cadet_handle);
1644   RPS_sampler_destroy (prot_sampler);
1645   RPS_sampler_destroy (client_sampler);
1646   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
1647   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1648   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1649   GNUNET_array_grow (push_list, push_list_size, 0);
1650   GNUNET_array_grow (pull_list, pull_list_size, 0);
1651 }
1652
1653
1654 /**
1655  * A client disconnected.  Remove all of its data structure entries.
1656  *
1657  * @param cls closure, NULL
1658  * @param client identification of the client
1659  */
1660 static void
1661 handle_client_disconnect (void *cls,
1662                           struct GNUNET_SERVER_Client * client)
1663 {
1664 }
1665
1666
1667 /**
1668  * Handle the channel a peer opens to us.
1669  *
1670  * @param cls The closure
1671  * @param channel The channel the peer wants to establish
1672  * @param initiator The peer's peer ID
1673  * @param port The port the channel is being established over
1674  * @param options Further options
1675  */
1676   static void *
1677 handle_inbound_channel (void *cls,
1678                         struct GNUNET_CADET_Channel *channel,
1679                         const struct GNUNET_PeerIdentity *initiator,
1680                         uint32_t port,
1681                         enum GNUNET_CADET_ChannelOption options)
1682 {
1683   struct PeerContext *peer_ctx;
1684
1685   LOG (GNUNET_ERROR_TYPE_DEBUG,
1686       "New channel was established to us (Peer %s).\n",
1687       GNUNET_i2s (initiator));
1688
1689   GNUNET_assert (NULL != channel);
1690
1691   // we might not even store the recv_channel
1692
1693   peer_ctx = get_peer_ctx (peer_map, initiator);
1694   // FIXME what do we do if a channel is established twice?
1695   //       overwrite? Clean old channel? ...?
1696   //if (NULL != peer_ctx->recv_channel)
1697   //{
1698   //  peer_ctx->recv_channel = channel;
1699   //}
1700   peer_ctx->recv_channel = channel;
1701
1702   peer_ctx->mq = NULL;
1703
1704   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, peer_ctx,
1705       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1706
1707   peer_is_live (peer_ctx);
1708
1709   return NULL; // TODO
1710 }
1711
1712
1713 /**
1714  * This is called when a remote peer destroys a channel.
1715  *
1716  * @param cls The closure
1717  * @param channel The channel being closed
1718  * @param channel_ctx The context associated with this channel
1719  */
1720   static void
1721 cleanup_channel (void *cls,
1722                 const struct GNUNET_CADET_Channel *channel,
1723                 void *channel_ctx)
1724 {
1725   struct GNUNET_PeerIdentity *peer;
1726   struct PeerContext *peer_ctx;
1727
1728   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1729       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1730        // Guess simply casting isn't the nicest way...
1731        // FIXME wait for cadet to change this function
1732   LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up channel to peer %s\n",
1733        GNUNET_i2s (peer));
1734
1735   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1736   {
1737     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1738
1739     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
1740       return;
1741
1742     if (channel == peer_ctx->send_channel)
1743     { /* Peer probably went down */
1744       rem_from_list (&gossip_list, &gossip_list_size, peer);
1745       rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, peer);
1746
1747       /* Somwewhat {ab,re}use the iterator function */
1748       /* Cast to void is ok, because it's used as void in peer_remove_cb */
1749       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
1750     }
1751     else
1752       peer_ctx->recv_channel = NULL;
1753   }
1754 }
1755
1756
1757 /**
1758  * Actually start the service.
1759  */
1760   static void
1761 rps_start (struct GNUNET_SERVER_Handle *server)
1762 {
1763   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1764     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1765       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1766     {&handle_client_seed,    NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1767     {NULL, NULL, 0, 0}
1768   };
1769
1770   GNUNET_SERVER_add_handlers (server, handlers);
1771   GNUNET_SERVER_disconnect_notify (server,
1772                                    &handle_client_disconnect,
1773                                    NULL);
1774   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1775
1776
1777   num_hist_update_tasks = 0;
1778
1779   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1780   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1781
1782   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1783                                 &shutdown_task,
1784                                 NULL);
1785 }
1786
1787
1788 /**
1789  * Process statistics requests.
1790  *
1791  * @param cls closure
1792  * @param server the initialized server
1793  * @param c configuration to use
1794  */
1795   static void
1796 run (void *cls,
1797      struct GNUNET_SERVER_Handle *server,
1798      const struct GNUNET_CONFIGURATION_Handle *c)
1799 {
1800   // TODO check what this does -- copied from gnunet-boss
1801   // - seems to work as expected
1802   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1803   cfg = c;
1804
1805
1806   /* Get own ID */
1807   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
1808   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1809               "STARTING SERVICE (rps) for peer [%s]\n",
1810               GNUNET_i2s (&own_identity));
1811
1812
1813   /* Get time interval from the configuration */
1814   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1815                                                         "ROUNDINTERVAL",
1816                                                         &round_interval))
1817   {
1818     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1819     GNUNET_SCHEDULER_shutdown ();
1820     return;
1821   }
1822
1823   /* Get initial size of sampler/gossip list from the configuration */
1824   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1825                                                          "INITSIZE",
1826                                                          (long long unsigned int *) &sampler_size_est_need))
1827   {
1828     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1829     GNUNET_SCHEDULER_shutdown ();
1830     return;
1831   }
1832   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
1833
1834
1835   gossip_list = NULL;
1836
1837
1838   /* connect to NSE */
1839   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
1840   // TODO check whether that was successful
1841   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1842
1843
1844   alpha = 0.45;
1845   beta  = 0.45;
1846
1847   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
1848
1849
1850   /* Initialise cadet */
1851   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1852     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
1853       sizeof (struct GNUNET_MessageHeader)},
1854     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
1855       sizeof (struct GNUNET_MessageHeader)},
1856     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1857     {NULL, 0, 0}
1858   };
1859
1860   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1861   cadet_handle = GNUNET_CADET_connect (cfg,
1862                                        cls,
1863                                        &handle_inbound_channel,
1864                                        &cleanup_channel,
1865                                        cadet_handlers,
1866                                        ports);
1867   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1868
1869
1870   /* Initialise sampler */
1871   struct GNUNET_TIME_Relative half_round_interval;
1872   struct GNUNET_TIME_Relative  max_round_interval;
1873
1874   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
1875   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
1876
1877   prot_sampler =   RPS_sampler_init (sampler_size_est_need, max_round_interval);
1878   client_sampler = RPS_sampler_init (sampler_size_est_need, max_round_interval);
1879
1880   /* Initialise push and pull maps */
1881   push_list = NULL;
1882   push_list_size = 0;
1883   pull_list = NULL;
1884   pull_list_size = 0;
1885   pending_pull_reply_list = NULL;
1886   pending_pull_reply_list_size = 0;
1887
1888
1889   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1890   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, server);
1891
1892   // TODO send push/pull to each of those peers?
1893 }
1894
1895
1896 /**
1897  * The main function for the rps service.
1898  *
1899  * @param argc number of arguments from the command line
1900  * @param argv command line arguments
1901  * @return 0 ok, 1 on error
1902  */
1903   int
1904 main (int argc, char *const *argv)
1905 {
1906   return (GNUNET_OK ==
1907           GNUNET_SERVICE_run (argc,
1908                               argv,
1909                               "rps",
1910                               GNUNET_SERVICE_OPTION_NONE,
1911                               &run, NULL)) ? 0 : 1;
1912 }
1913
1914 /* end of gnunet-service-rps.c */