88fe5521a23052c46e172a10ddd6fd68a99a2fa6
[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   LIVING               = 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 /**
390  * Check if peer is already in peer array.
391  */
392   int
393 in_arr (const struct GNUNET_PeerIdentity *array,
394         unsigned int arr_size,
395         const struct GNUNET_PeerIdentity *peer)
396 {
397   GNUNET_assert (NULL != peer);
398
399   if (0 == arr_size)
400     return GNUNET_NO;
401
402   GNUNET_assert (NULL != array);
403
404   unsigned int i;
405
406   i = 0;
407   while (0 != GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer) &&
408          i < arr_size)
409     i++;
410
411   if (i == arr_size)
412     return GNUNET_NO;
413   else
414     return GNUNET_YES;
415 }
416
417 /**
418  * Remove peer from list.
419  */
420   void
421 rem_from_list (struct GNUNET_PeerIdentity *peer_list,
422                unsigned int *list_size,
423                const struct GNUNET_PeerIdentity *peer)
424 {
425   unsigned int i;
426
427   for ( i = 0 ; i < *list_size ; i++ )
428   {
429     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&peer_list[i], peer))
430     {
431       if (i < *list_size -1)
432       { /* Not at the last entry -- shift peers left */
433         memcpy (&peer_list[i], &peer_list[i +1],
434                 (*list_size - i -1) * sizeof (struct GNUNET_PeerIdentity));
435       }
436       /* Remove last entry (should be now useless PeerID) */
437       GNUNET_array_grow (peer_list, *list_size, *list_size -1);
438     }
439   }
440 }
441
442 /**
443  * Get random peer from the given list but don't return one from the @a ignore_list.
444  */
445   struct GNUNET_PeerIdentity *
446 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
447                            uint32_t list_size,
448                            const struct GNUNET_PeerIdentity *ignore_list,
449                            uint32_t ignore_size)
450 {
451   uint32_t r_index;
452   uint32_t tmp_size;
453   struct GNUNET_PeerIdentity *tmp_peer_list;
454   struct GNUNET_PeerIdentity *peer;
455
456   GNUNET_assert (NULL != peer_list);
457   if (0 == list_size)
458     return NULL;
459
460   tmp_size = 0;
461   tmp_peer_list = NULL;
462   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
463   memcpy (tmp_peer_list,
464           peer_list,
465           list_size * sizeof (struct GNUNET_PeerIdentity));
466   peer = GNUNET_new (struct GNUNET_PeerIdentity);
467
468   /**;
469    * Choose the r_index of the peer we want to return
470    * at random from the interval of the gossip list
471    */
472   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
473                                       tmp_size);
474   *peer = tmp_peer_list[r_index];
475
476   while (in_arr (ignore_list, ignore_size, peer))
477   {
478     rem_from_list (tmp_peer_list, &tmp_size, peer);
479
480     if (0 == tmp_size)
481     {
482       GNUNET_free (peer);
483       return NULL;
484     }
485
486     /**;
487      * Choose the r_index of the peer we want to return
488      * at random from the interval of the gossip list
489      */
490     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
491                                         tmp_size);
492     *peer = tmp_peer_list[r_index];
493   }
494
495
496   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
497
498   return peer;
499 }
500
501
502 /**
503  * Get the context of a peer. If not existing, create.
504  */
505   struct PeerContext *
506 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
507               const struct GNUNET_PeerIdentity *peer)
508 {
509   struct PeerContext *ctx;
510
511   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
512   {
513     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
514   }
515   else
516   {
517     ctx = GNUNET_new (struct PeerContext);
518     ctx->peer_flags = 0;
519     ctx->mq = NULL;
520     ctx->send_channel = NULL;
521     ctx->recv_channel = NULL;
522     ctx->outstanding_ops = NULL;
523     ctx->num_outstanding_ops = 0;
524     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
525                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
526   }
527   return ctx;
528 }
529
530
531 /**
532  * Put random peer from sampler into the gossip list as history update.
533  */
534   void
535 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
536 {
537   GNUNET_assert (1 == num_peers);
538
539   if (gossip_list_size < sampler_size_est_need)
540     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
541
542   if (0 < num_hist_update_tasks)
543     num_hist_update_tasks--;
544 }
545
546
547 /**
548  * Callback that is called when a channel was effectively established.
549  * This is given to ntfy_tmt_rdy and called when the channel was
550  * successfully established.
551  */
552 static size_t
553 peer_is_live (void *cls, size_t size, void *buf)
554 {
555   struct PeerContext *ctx = cls;
556   struct GNUNET_PeerIdentity *peer;
557   struct PeerContext *peer_ctx;
558
559   //if (NULL == buf ||
560   //    0 == size)
561   // TODO check
562
563   ctx->is_live_task = NULL;
564   peer = &ctx->peer_id;
565   peer_ctx = get_peer_ctx (peer_map, peer);
566   peer_ctx->peer_flags |= LIVING;
567
568   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
569
570   if (0 != peer_ctx->num_outstanding_ops)
571   { /* Call outstanding operations */
572     unsigned int i;
573
574     for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
575       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
576     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
577   }
578
579   //if (NULL != peer_ctx->is_live_task)
580   //{
581   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
582   //  peer_ctx->is_live_task = NULL; // needed?
583   //}
584   return 0;
585 }
586
587
588 /**
589  * Get the channel of a peer. If not existing, create.
590  */
591   struct GNUNET_CADET_Channel *
592 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
593              const struct GNUNET_PeerIdentity *peer)
594 {
595   struct PeerContext *ctx;
596
597   ctx = get_peer_ctx (peer_map, peer);
598   if (NULL == ctx->send_channel)
599   {
600     ctx->send_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
601                                                      GNUNET_RPS_CADET_PORT,
602                                                      GNUNET_CADET_OPTION_RELIABLE);
603
604     if (NULL == ctx->recv_channel)
605     {
606       ctx->peer_id = *peer;
607       ctx->is_live_task =
608           GNUNET_CADET_notify_transmit_ready (ctx->send_channel, GNUNET_NO,
609                                               GNUNET_TIME_UNIT_FOREVER_REL,
610                                               sizeof (struct GNUNET_MessageHeader),
611                                               peer_is_live, ctx);
612     }
613
614     // do I have to explicitly put it in the peer_map?
615     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
616                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
617   }
618   return ctx->send_channel;
619 }
620
621
622 /**
623  * Get the message queue of a specific peer.
624  *
625  * If we already have a message queue open to this client,
626  * simply return it, otherways create one.
627  */
628   struct GNUNET_MQ_Handle *
629 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
630         const struct GNUNET_PeerIdentity *peer_id)
631 {
632   struct PeerContext *ctx;
633
634   ctx = get_peer_ctx (peer_map, peer_id);
635   if (NULL == ctx->mq)
636   {
637     (void) get_channel (peer_map, peer_id);
638     ctx->mq = GNUNET_CADET_mq_create (ctx->send_channel);
639     //do I have to explicitly put it in the peer_map?
640     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
641                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
642   }
643   return ctx->mq;
644 }
645
646
647 /**
648  * Sum all time relatives of an array.
649   */
650   struct GNUNET_TIME_Relative
651 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
652 {
653   struct GNUNET_TIME_Relative sum;
654   uint32_t i;
655
656   sum = GNUNET_TIME_UNIT_ZERO;
657   for ( i = 0 ; i < arr_size ; i++ )
658   {
659     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
660   }
661   return sum;
662 }
663
664
665 /**
666  * Compute the average of given time relatives.
667  */
668   struct GNUNET_TIME_Relative
669 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
670 {
671   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
672 }
673
674
675 /**
676  * Insert PeerID in #pull_list
677  *
678  * Called once we know a peer is live.
679  */
680   void
681 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
682 {
683   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
684     GNUNET_array_append (pull_list, pull_list_size, *peer);
685 }
686
687 /**
688  * Check whether #insert_in_pull_list was already scheduled
689  */
690   int
691 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
692 {
693   unsigned int i;
694
695   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
696     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
697       return GNUNET_YES;
698   return GNUNET_NO;
699 }
700
701
702 /**
703  * Insert PeerID in #gossip_list
704  *
705  * Called once we know a peer is live.
706  */
707   void
708 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
709 {
710   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
711     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
712 }
713
714 /**
715  * Check whether #insert_in_pull_list was already scheduled
716  */
717   int
718 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
719 {
720   unsigned int i;
721
722   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
723     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
724       return GNUNET_YES;
725   return GNUNET_NO;
726 }
727
728
729 /**
730  * Update sampler with given PeerID.
731  */
732   void
733 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
734 {
735   RPS_sampler_update (prot_sampler,   peer);
736   RPS_sampler_update (client_sampler, peer);
737 }
738
739
740 /**
741  * Check whether #insert_in_sampler was already scheduled
742  */
743 static int
744 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
745 {
746   unsigned int i;
747
748   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
749     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
750       return GNUNET_YES;
751   return GNUNET_NO;
752 }
753
754
755 /**
756  * Wrapper around #RPS_sampler_resize()
757  *
758  * If we do not have enough sampler elements, double current sampler size
759  * If we have more than enough sampler elements, halv current sampler size
760  */
761 static void
762 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
763 {
764   unsigned int sampler_size;
765
766   // TODO statistics
767   // TODO respect the min, max
768   sampler_size = RPS_sampler_get_size (sampler);
769   if (sampler_size > new_size * 4)
770   { /* Shrinking */
771     RPS_sampler_resize (sampler, sampler_size / 2);
772   }
773   else if (sampler_size < new_size)
774   { /* Growing */
775     RPS_sampler_resize (sampler, sampler_size * 2);
776   }
777   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
778 }
779
780
781 /**
782  * Wrapper around #RPS_sampler_resize() resizing the client sampler
783  */
784 static void
785 client_resize_wrapper ()
786 {
787   uint32_t bigger_size;
788   unsigned int sampler_size;
789
790   // TODO statistics
791
792   sampler_size = RPS_sampler_get_size (client_sampler);
793
794   if (sampler_size_est_need > sampler_size_client_need)
795     bigger_size = sampler_size_est_need;
796   else
797     bigger_size = sampler_size_client_need;
798
799   // TODO respect the min, max
800   resize_wrapper (client_sampler, bigger_size);
801   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
802 }
803
804
805 /**
806  * Estimate request rate
807  *
808  * Called every time we receive a request from the client.
809  */
810   void
811 est_request_rate()
812 {
813   struct GNUNET_TIME_Relative max_round_duration;
814
815   if (request_deltas_size > req_counter)
816     req_counter++;
817   if ( 1 < req_counter)
818   {
819     /* Shift last request deltas to the right */
820     memcpy (&request_deltas[1],
821         request_deltas,
822         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
823
824     /* Add current delta to beginning */
825     request_deltas[0] =
826         GNUNET_TIME_absolute_get_difference (last_request,
827                                              GNUNET_TIME_absolute_get ());
828     request_rate = T_relative_avg (request_deltas, req_counter);
829
830     /* Compute the duration a round will maximally take */
831     max_round_duration =
832         GNUNET_TIME_relative_add (round_interval,
833                                   GNUNET_TIME_relative_divide (round_interval, 2));
834
835     /* Set the estimated size the sampler has to have to
836      * satisfy the current client request rate */
837     sampler_size_client_need =
838         max_round_duration.rel_value_us / request_rate.rel_value_us;
839
840     /* Resize the sampler */
841     client_resize_wrapper ();
842   }
843   last_request = GNUNET_TIME_absolute_get ();
844 }
845
846
847 /***********************************************************************
848  * /Util functions
849 ***********************************************************************/
850
851
852
853
854
855 /**
856  * Function called by NSE.
857  *
858  * Updates sizes of sampler list and gossip list and adapt those lists
859  * accordingly.
860  */
861   void
862 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
863               double logestimate, double std_dev)
864 {
865   double estimate;
866   //double scale; // TODO this might go gloabal/config
867
868   LOG (GNUNET_ERROR_TYPE_DEBUG,
869        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
870        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
871   //scale = .01;
872   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
873   // GNUNET_NSE_log_estimate_to_n (logestimate);
874   estimate = pow (estimate, 1.0 / 3);
875   // TODO add if std_dev is a number
876   // estimate += (std_dev * scale);
877   if (2 < ceil (estimate))
878   {
879     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
880     sampler_size_est_need = estimate;
881   } else
882     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
883
884   /* If the NSE has changed adapt the lists accordingly */
885   resize_wrapper (prot_sampler, sampler_size_est_need);
886   client_resize_wrapper ();
887 }
888
889
890 /**
891  * Callback called once the requested PeerIDs are ready.
892  *
893  * Sends those to the requesting client.
894  */
895 void client_respond (void *cls,
896     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
897 {
898   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
899   struct GNUNET_MQ_Envelope *ev;
900   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
901   struct GNUNET_SERVER_Client *client;
902   uint32_t size_needed;
903   struct client_ctx *cli_ctx;
904
905   client = (struct GNUNET_SERVER_Client *) cls;
906
907   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
908                 num_peers * sizeof (struct GNUNET_PeerIdentity);
909
910   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
911
912   ev = GNUNET_MQ_msg_extra (out_msg,
913                             num_peers * sizeof (struct GNUNET_PeerIdentity),
914                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
915   out_msg->num_peers = htonl (num_peers);
916
917   memcpy (&out_msg[1],
918       ids,
919       num_peers * sizeof (struct GNUNET_PeerIdentity));
920   GNUNET_free (ids);
921
922   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
923   if ( NULL == cli_ctx ) {
924     cli_ctx = GNUNET_new (struct client_ctx);
925     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
926     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
927   }
928
929   GNUNET_MQ_send (cli_ctx->mq, ev);
930 }
931
932
933 /**
934  * Handle RPS request from the client.
935  *
936  * @param cls closure
937  * @param client identification of the client
938  * @param message the actual message
939  */
940 static void
941 handle_client_request (void *cls,
942             struct GNUNET_SERVER_Client *client,
943             const struct GNUNET_MessageHeader *message)
944 {
945   struct GNUNET_RPS_CS_RequestMessage *msg;
946   uint32_t num_peers;
947   uint32_t size_needed;
948   uint32_t i;
949
950   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
951
952   num_peers = ntohl (msg->num_peers);
953   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
954                 num_peers * sizeof (struct GNUNET_PeerIdentity);
955
956   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
957   {
958     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
959     return;
960   }
961
962   for (i = 0 ; i < num_peers ; i++)
963     est_request_rate();
964
965   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
966
967   RPS_sampler_get_n_rand_peers (client_sampler, client_respond,
968                                 client, num_peers, GNUNET_YES);
969
970   GNUNET_SERVER_receive_done (client,
971                               GNUNET_OK);
972 }
973
974
975 /**
976  * Handle seed from the client.
977  *
978  * @param cls closure
979  * @param client identification of the client
980  * @param message the actual message
981  */
982   static void
983 handle_client_seed (void *cls,
984             struct GNUNET_SERVER_Client *client,
985             const struct GNUNET_MessageHeader *message)
986 {
987   struct GNUNET_RPS_CS_SeedMessage *in_msg;
988   struct GNUNET_PeerIdentity *peers;
989   uint32_t i;
990
991   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) < ntohs (message->size))
992   {
993     GNUNET_break_op (0);
994     GNUNET_SERVER_receive_done (client,
995               GNUNET_SYSERR);
996   }
997   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
998   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
999       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1000   {
1001     GNUNET_break_op (0);
1002     GNUNET_SERVER_receive_done (client,
1003               GNUNET_SYSERR);
1004   }
1005
1006   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1007   peers = (struct GNUNET_PeerIdentity *) &message[1];
1008
1009   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
1010     RPS_sampler_update (prot_sampler,   &peers[i]);
1011     RPS_sampler_update (client_sampler, &peers[i]);
1012
1013   GNUNET_SERVER_receive_done (client,
1014                               GNUNET_OK);
1015 }
1016
1017
1018 /**
1019  * Handle a PUSH message from another peer.
1020  *
1021  * Check the proof of work and store the PeerID
1022  * in the temporary list for pushed PeerIDs.
1023  *
1024  * @param cls Closure
1025  * @param channel The channel the PUSH was received over
1026  * @param channel_ctx The context associated with this channel
1027  * @param msg The message header
1028  */
1029 static int
1030 handle_peer_push (void *cls,
1031     struct GNUNET_CADET_Channel *channel,
1032     void **channel_ctx,
1033     const struct GNUNET_MessageHeader *msg)
1034 {
1035   const struct GNUNET_PeerIdentity *peer;
1036
1037   // (check the proof of work)
1038
1039   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1040   // FIXME wait for cadet to change this function
1041   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1042
1043   /* Add the sending peer to the push_list */
1044   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
1045     GNUNET_array_append (push_list, push_list_size, *peer);
1046
1047   return GNUNET_OK;
1048 }
1049
1050 /**
1051  * Handle PULL REQUEST request message from another peer.
1052  *
1053  * Reply with the gossip list of PeerIDs.
1054  *
1055  * @param cls Closure
1056  * @param channel The channel the PUSH was received over
1057  * @param channel_ctx The context associated with this channel
1058  * @param msg The message header
1059  */
1060 static int
1061 handle_peer_pull_request (void *cls,
1062     struct GNUNET_CADET_Channel *channel,
1063     void **channel_ctx,
1064     const struct GNUNET_MessageHeader *msg)
1065 {
1066   struct GNUNET_PeerIdentity *peer;
1067   uint32_t send_size;
1068   struct GNUNET_MQ_Handle *mq;
1069   struct GNUNET_MQ_Envelope *ev;
1070   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1071
1072
1073   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel,
1074                                                                        GNUNET_CADET_OPTION_PEER);
1075   // FIXME wait for cadet to change this function
1076
1077   /* Compute actual size */
1078   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1079               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1080
1081   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1082     /* Compute number of peers to send
1083      * If too long, simply truncate */
1084     send_size = (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1085                  sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1086                  sizeof (struct GNUNET_PeerIdentity);
1087   else
1088     send_size = gossip_list_size;
1089
1090   LOG (GNUNET_ERROR_TYPE_DEBUG,
1091       "PULL REQUEST from peer %s received, going to send %u peers\n",
1092       GNUNET_i2s (peer), send_size);
1093
1094   mq = get_mq (peer_map, peer);
1095
1096   ev = GNUNET_MQ_msg_extra (out_msg,
1097                            send_size * sizeof (struct GNUNET_PeerIdentity),
1098                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1099   //out_msg->num_peers = htonl (gossip_list_size);
1100   out_msg->num_peers = htonl (send_size);
1101   memcpy (&out_msg[1], gossip_list,
1102          send_size * sizeof (struct GNUNET_PeerIdentity));
1103
1104   GNUNET_MQ_send (mq, ev);
1105
1106   return GNUNET_OK;
1107 }
1108
1109 /**
1110  * Handle PULL REPLY message from another peer.
1111  *
1112  * Check whether we sent a corresponding request and
1113  * whether this reply is the first one.
1114  *
1115  * @param cls Closure
1116  * @param channel The channel the PUSH was received over
1117  * @param channel_ctx The context associated with this channel
1118  * @param msg The message header
1119  */
1120   static int
1121 handle_peer_pull_reply (void *cls,
1122     struct GNUNET_CADET_Channel *channel,
1123     void **channel_ctx,
1124     const struct GNUNET_MessageHeader *msg)
1125 {
1126   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1127
1128   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1129   struct GNUNET_PeerIdentity *peers;
1130   struct PeerContext *peer_ctx;
1131   struct GNUNET_PeerIdentity *sender;
1132   struct PeerContext *sender_ctx;
1133   struct PeerOutstandingOp out_op;
1134   uint32_t i;
1135
1136   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1137   {
1138     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
1139     return GNUNET_SYSERR;
1140   }
1141   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1142   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1143   {
1144     LOG (GNUNET_ERROR_TYPE_ERROR, "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1145         ntohl (in_msg->num_peers),
1146         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity));
1147     GNUNET_break_op (0);
1148     return GNUNET_SYSERR;
1149   }
1150
1151   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1152       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1153        // Guess simply casting isn't the nicest way...
1154        // FIXME wait for cadet to change this function
1155   sender_ctx = get_peer_ctx (peer_map, sender);
1156
1157   if (0 == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1158   {
1159     GNUNET_break_op (0);
1160     return GNUNET_OK;
1161   }
1162
1163   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1164   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
1165   {
1166     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1167     if ((0 != (peer_ctx->peer_flags && LIVING)) ||
1168         NULL != peer_ctx->recv_channel)
1169     {
1170       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
1171         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1172     }
1173     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1174     {
1175       out_op.op = insert_in_pull_list;
1176       out_op.op_cls = NULL;
1177       GNUNET_array_append (peer_ctx->outstanding_ops,
1178                            peer_ctx->num_outstanding_ops,
1179                            out_op);
1180     }
1181   }
1182
1183   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1184   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1185
1186   return GNUNET_OK;
1187 }
1188
1189
1190 /**
1191  * Send out PUSHes and PULLs.
1192  *
1193  * This is executed regylary.
1194  */
1195 static void
1196 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1197 {
1198   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1199
1200   uint32_t i;
1201   unsigned int *permut;
1202   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1203   struct GNUNET_MQ_Envelope *ev;
1204   struct GNUNET_PeerIdentity peer;
1205   struct GNUNET_PeerIdentity *tmp_peer;
1206   struct GNUNET_MQ_Handle *mq;
1207
1208   LOG (GNUNET_ERROR_TYPE_DEBUG,
1209        "Printing gossip list:\n");
1210   for (i = 0 ; i < gossip_list_size ; i++)
1211     LOG (GNUNET_ERROR_TYPE_DEBUG,
1212          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1213   // TODO log lists, ...
1214
1215   /* Would it make sense to have one shuffeled gossip list and then
1216    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1217    * use the rest to update sampler?
1218    * in essence get random peers with consumption */
1219
1220   /* Send PUSHes */
1221   if (0 < gossip_list_size)
1222   {
1223     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1224                                            (unsigned int) gossip_list_size);
1225     n_peers = ceil (alpha * gossip_list_size);
1226     LOG (GNUNET_ERROR_TYPE_DEBUG,
1227          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1228          n_peers, alpha, gossip_list_size);
1229     for (i = 0 ; i < n_peers ; i++)
1230     {
1231       peer = gossip_list[permut[i]];
1232       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1233       { // FIXME if this fails schedule/loop this for later
1234         LOG (GNUNET_ERROR_TYPE_DEBUG,
1235              "Sending PUSH to peer %s of gossiped list.\n",
1236              GNUNET_i2s (&peer));
1237
1238         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1239         mq = get_mq (peer_map, &peer);
1240         GNUNET_MQ_send (mq, ev);
1241       }
1242     }
1243     GNUNET_free (permut);
1244   }
1245
1246
1247   /* Send PULL requests */
1248   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1249   n_peers = ceil (beta * gossip_list_size);
1250   LOG (GNUNET_ERROR_TYPE_DEBUG,
1251        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1252        n_peers, beta, gossip_list_size);
1253   for (i = 0 ; i < n_peers ; i++)
1254   {
1255     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1256         pending_pull_reply_list, pending_pull_reply_list_size);
1257     if (NULL != tmp_peer)
1258     {
1259       peer = *tmp_peer;
1260       GNUNET_free (tmp_peer);
1261
1262       GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, peer);
1263
1264       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1265       { // FIXME if this fails schedule/loop this for later
1266         LOG (GNUNET_ERROR_TYPE_DEBUG,
1267              "Sending PULL request to peer %s of gossiped list.\n",
1268              GNUNET_i2s (&peer));
1269
1270         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1271         mq = get_mq (peer_map, &peer);
1272         GNUNET_MQ_send (mq, ev);
1273       }
1274     }
1275   }
1276
1277
1278   /* Update gossip list */
1279   uint32_t r_index;
1280
1281   if ( push_list_size <= alpha * gossip_list_size &&
1282        push_list_size != 0 &&
1283        pull_list_size != 0 )
1284   {
1285     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1286
1287     uint32_t first_border;
1288     uint32_t second_border;
1289
1290     first_border  =                ceil (alpha * sampler_size_est_need);
1291     second_border = first_border + ceil (beta  * sampler_size_est_need);
1292
1293     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1294
1295     for (i = 0 ; i < first_border ; i++)
1296     { // TODO use RPS_sampler_get_n_rand_peers
1297       /* Update gossip list with peers received through PUSHes */
1298       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1299                                        push_list_size);
1300       gossip_list[i] = push_list[r_index];
1301       // TODO change the peer_flags accordingly
1302     }
1303
1304     for (i = first_border ; i < second_border ; i++)
1305     {
1306       /* Update gossip list with peers received through PULLs */
1307       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1308                                        pull_list_size);
1309       gossip_list[i] = pull_list[r_index];
1310       // TODO change the peer_flags accordingly
1311     }
1312
1313     for (i = second_border ; i < sampler_size_est_need ; i++)
1314     {
1315       /* Update gossip list with peers from history */
1316       RPS_sampler_get_n_rand_peers (prot_sampler, hist_update, NULL, 1, GNUNET_NO);
1317       num_hist_update_tasks++;
1318       // TODO change the peer_flags accordingly
1319     }
1320
1321   }
1322   else
1323   {
1324     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1325   }
1326   // TODO independent of that also get some peers from CADET_get_peers()?
1327
1328
1329   /* Update samplers */
1330
1331   for ( i = 0 ; i < push_list_size ; i++ )
1332   {
1333     RPS_sampler_update (prot_sampler,   &push_list[i]);
1334     RPS_sampler_update (client_sampler, &push_list[i]);
1335     // TODO set in_flag?
1336   }
1337
1338   for ( i = 0 ; i < pull_list_size ; i++ )
1339   {
1340     RPS_sampler_update (prot_sampler,   &push_list[i]);
1341     RPS_sampler_update (client_sampler, &push_list[i]);
1342     // TODO set in_flag?
1343   }
1344
1345
1346   /* Empty push/pull lists */
1347   GNUNET_array_grow (push_list, push_list_size, 0);
1348   GNUNET_array_grow (pull_list, pull_list_size, 0);
1349
1350   struct GNUNET_TIME_Relative time_next_round;
1351   struct GNUNET_TIME_Relative half_round_interval;
1352   unsigned int rand_delay;
1353
1354   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1355   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1356   do
1357   {
1358   /*
1359    * Compute random value between (0 and 1) * round_interval
1360    * via multiplying round_interval with a 'fraction' (0 to value)/value
1361    */
1362   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1363   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
1364   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
1365   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
1366   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1367
1368   /* Schedule next round */
1369   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1370   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1371 }
1372
1373
1374 /**
1375  * Open a connection to given peer and store channel and mq.
1376  */
1377   void
1378 insertCB (void *cls, struct RPS_Sampler *sampler,
1379           const struct GNUNET_PeerIdentity *id)
1380 {
1381   // We open a channel to be notified when this peer goes down.
1382   (void) get_channel (peer_map, id);
1383 }
1384
1385
1386 /**
1387  * Close the connection to given peer and delete channel and mq
1388  * if the peer is not anymore in the sampler.
1389  */
1390   void
1391 removeCB (void *cls, struct RPS_Sampler *sampler,
1392           const struct GNUNET_PeerIdentity *id)
1393 {
1394   size_t s;
1395   struct PeerContext *ctx;
1396
1397   s = RPS_sampler_count_id (sampler, id);
1398   if ( 1 >= s )
1399   {
1400     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
1401     {
1402       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
1403       if (NULL != ctx->send_channel)
1404       {
1405         if (NULL != ctx->mq)
1406         {
1407           GNUNET_MQ_destroy (ctx->mq);
1408         }
1409         // may already be freed at shutdown of cadet
1410         //GNUNET_CADET_channel_destroy (ctx->send_channel);
1411       }
1412       // TODO cleanup peer
1413       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
1414     }
1415   }
1416 }
1417
1418 static void
1419 rps_start (struct GNUNET_SERVER_Handle *server);
1420
1421 /**
1422  * This is called from GNUNET_CADET_get_peers().
1423  *
1424  * It is called on every peer(ID) that cadet somehow has contact with.
1425  * We use those to initialise the sampler.
1426  */
1427 void
1428 init_peer_cb (void *cls,
1429               const struct GNUNET_PeerIdentity *peer,
1430               int tunnel, // "Do we have a tunnel towards this peer?"
1431               unsigned int n_paths, // "Number of known paths towards this peer"
1432               unsigned int best_path) // "How long is the best path?
1433                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1434 {
1435   struct GNUNET_SERVER_Handle *server;
1436   struct PeerOutstandingOp out_op;
1437   struct PeerContext *peer_ctx;
1438
1439   server = (struct GNUNET_SERVER_Handle *) cls;
1440   if ( NULL != peer )
1441   {
1442     LOG (GNUNET_ERROR_TYPE_DEBUG,
1443         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1444         GNUNET_i2s (peer), peer, gossip_list_size);
1445
1446     // maybe create a function for that
1447     peer_ctx = get_peer_ctx (peer_map, peer);
1448     // FIXME this peer might already be marked as LIVE
1449     if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1450     {
1451       out_op.op = insert_in_sampler;
1452       out_op.op_cls = NULL;
1453       GNUNET_array_append (peer_ctx->outstanding_ops,
1454                            peer_ctx->num_outstanding_ops,
1455                            out_op);
1456     }
1457
1458     if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1459     {
1460       out_op.op = insert_in_gossip_list;
1461       out_op.op_cls = NULL;
1462       GNUNET_array_append (peer_ctx->outstanding_ops,
1463                            peer_ctx->num_outstanding_ops,
1464                            out_op);
1465     }
1466
1467     /* Trigger livelyness test on peer */
1468     (void) get_channel (peer_map, peer);
1469
1470     // send push/pull to each of those peers?
1471   }
1472   else
1473     rps_start (server);
1474 }
1475
1476
1477 /**
1478  * Callback used to clean the multipeermap.
1479  */
1480   int
1481 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1482 {
1483   struct PeerContext *peer_ctx;
1484   const struct GNUNET_CADET_Channel *ch = (const struct GNUNET_CADET_Channel *) cls;
1485   struct GNUNET_CADET_Channel *recv;
1486   struct GNUNET_CADET_Channel *send;
1487
1488   peer_ctx = (struct PeerContext *) value;
1489
1490   if (0 != peer_ctx->num_outstanding_ops)
1491     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
1492
1493   if (NULL != peer_ctx->mq)
1494     GNUNET_MQ_destroy (peer_ctx->mq);
1495
1496   if (NULL != peer_ctx->is_live_task)
1497   {
1498     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1499     peer_ctx->is_live_task = NULL;
1500   }
1501
1502   send = peer_ctx->send_channel;
1503   peer_ctx->send_channel = NULL;
1504   recv = peer_ctx->send_channel;
1505   peer_ctx->recv_channel = NULL;
1506
1507   if (NULL  != send
1508       && ch != send)
1509   {
1510     GNUNET_CADET_channel_destroy (send);
1511   }
1512
1513   if (NULL  != recv
1514       && ch != recv)
1515   {
1516     GNUNET_CADET_channel_destroy (recv);
1517   }
1518
1519   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1520     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1521   else
1522     GNUNET_free (peer_ctx);
1523
1524   return GNUNET_YES;
1525 }
1526
1527
1528 /**
1529  * Task run during shutdown.
1530  *
1531  * @param cls unused
1532  * @param tc unused
1533  */
1534 static void
1535 shutdown_task (void *cls,
1536                const struct GNUNET_SCHEDULER_TaskContext *tc)
1537 {
1538   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1539
1540   if ( NULL != do_round_task )
1541   {
1542     GNUNET_SCHEDULER_cancel (do_round_task);
1543     do_round_task = NULL;
1544   }
1545
1546
1547   {
1548   if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1549     LOG (GNUNET_ERROR_TYPE_WARNING,
1550         "Iterating over peers to disconnect from them was cancelled\n");
1551   }
1552
1553   GNUNET_NSE_disconnect (nse);
1554   GNUNET_CADET_disconnect (cadet_handle);
1555   RPS_sampler_destroy (prot_sampler);
1556   RPS_sampler_destroy (client_sampler);
1557   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
1558   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1559   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1560   GNUNET_array_grow (push_list, push_list_size, 0);
1561   GNUNET_array_grow (pull_list, pull_list_size, 0);
1562 }
1563
1564
1565 /**
1566  * A client disconnected.  Remove all of its data structure entries.
1567  *
1568  * @param cls closure, NULL
1569  * @param client identification of the client
1570  */
1571 static void
1572 handle_client_disconnect (void *cls,
1573                           struct GNUNET_SERVER_Client * client)
1574 {
1575 }
1576
1577
1578 /**
1579  * Handle the channel a peer opens to us.
1580  *
1581  * @param cls The closure
1582  * @param channel The channel the peer wants to establish
1583  * @param initiator The peer's peer ID
1584  * @param port The port the channel is being established over
1585  * @param options Further options
1586  */
1587   static void *
1588 handle_inbound_channel (void *cls,
1589                         struct GNUNET_CADET_Channel *channel,
1590                         const struct GNUNET_PeerIdentity *initiator,
1591                         uint32_t port,
1592                         enum GNUNET_CADET_ChannelOption options)
1593 {
1594   struct PeerContext *ctx;
1595
1596   LOG (GNUNET_ERROR_TYPE_DEBUG,
1597       "New channel was established to us (Peer %s).\n",
1598       GNUNET_i2s (initiator));
1599
1600   GNUNET_assert (NULL != channel);
1601
1602   // we might not even store the recv_channel
1603
1604   ctx = get_peer_ctx (peer_map, initiator);
1605   if (NULL != ctx->recv_channel)
1606   {
1607     ctx->recv_channel = channel;
1608   }
1609
1610   ctx->peer_flags |= LIVING;
1611
1612   //ctx->peer_flags = IN_OTHER_GOSSIP_LIST;
1613   ctx->mq = NULL;
1614
1615   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
1616       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1617
1618   return NULL; // TODO
1619 }
1620
1621
1622 /**
1623  * This is called when a remote peer destroys a channel.
1624  *
1625  * @param cls The closure
1626  * @param channel The channel being closed
1627  * @param channel_ctx The context associated with this channel
1628  */
1629   static void
1630 cleanup_channel (void *cls,
1631                 const struct GNUNET_CADET_Channel *channel,
1632                 void *channel_ctx)
1633 {
1634   struct GNUNET_PeerIdentity *peer;
1635   struct PeerContext *peer_ctx;
1636
1637   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1638       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1639        // Guess simply casting isn't the nicest way...
1640        // FIXME wait for cadet to change this function
1641   LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up channel to peer %s\n",
1642        GNUNET_i2s (peer));
1643
1644   RPS_sampler_reinitialise_by_value (prot_sampler,   peer);
1645   RPS_sampler_reinitialise_by_value (client_sampler, peer);
1646
1647   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1648   {
1649     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1650
1651     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
1652       return;
1653
1654     /* Somwewhat {ab,re}use the iterator function */
1655     /* Cast to void is ok, because it's used as void in peer_remove_cb */
1656     (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
1657   }
1658 }
1659
1660
1661 /**
1662  * Actually start the service.
1663  */
1664   static void
1665 rps_start (struct GNUNET_SERVER_Handle *server)
1666 {
1667   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1668     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1669       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1670     {&handle_client_seed,    NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1671     {NULL, NULL, 0, 0}
1672   };
1673
1674   GNUNET_SERVER_add_handlers (server, handlers);
1675   GNUNET_SERVER_disconnect_notify (server,
1676                                    &handle_client_disconnect,
1677                                    NULL);
1678   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1679
1680
1681   num_hist_update_tasks = 0;
1682
1683   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1684   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1685
1686   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1687                                 &shutdown_task,
1688                                 NULL);
1689 }
1690
1691
1692 /**
1693  * Process statistics requests.
1694  *
1695  * @param cls closure
1696  * @param server the initialized server
1697  * @param c configuration to use
1698  */
1699   static void
1700 run (void *cls,
1701      struct GNUNET_SERVER_Handle *server,
1702      const struct GNUNET_CONFIGURATION_Handle *c)
1703 {
1704   // TODO check what this does -- copied from gnunet-boss
1705   // - seems to work as expected
1706   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1707   cfg = c;
1708
1709
1710   /* Get own ID */
1711   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
1712   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1713               "STARTING SERVICE (rps) for peer [%s]\n",
1714               GNUNET_i2s (&own_identity));
1715
1716
1717   /* Get time interval from the configuration */
1718   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1719                                                         "ROUNDINTERVAL",
1720                                                         &round_interval))
1721   {
1722     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1723     GNUNET_SCHEDULER_shutdown ();
1724     return;
1725   }
1726
1727   /* Get initial size of sampler/gossip list from the configuration */
1728   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1729                                                          "INITSIZE",
1730                                                          (long long unsigned int *) &sampler_size_est_need))
1731   {
1732     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1733     GNUNET_SCHEDULER_shutdown ();
1734     return;
1735   }
1736   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
1737
1738
1739   gossip_list = NULL;
1740
1741
1742   /* connect to NSE */
1743   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
1744   // TODO check whether that was successful
1745   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1746
1747
1748   alpha = 0.45;
1749   beta  = 0.45;
1750
1751   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
1752
1753
1754   /* Initialise cadet */
1755   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1756     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
1757       sizeof (struct GNUNET_MessageHeader)},
1758     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
1759       sizeof (struct GNUNET_MessageHeader)},
1760     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1761     {NULL, 0, 0}
1762   };
1763
1764   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1765   cadet_handle = GNUNET_CADET_connect (cfg,
1766                                        cls,
1767                                        &handle_inbound_channel,
1768                                        &cleanup_channel,
1769                                        cadet_handlers,
1770                                        ports);
1771   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1772
1773
1774   /* Initialise sampler */
1775   struct GNUNET_TIME_Relative half_round_interval;
1776   struct GNUNET_TIME_Relative  max_round_interval;
1777
1778   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
1779   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
1780
1781   prot_sampler =   RPS_sampler_init (sampler_size_est_need, max_round_interval,
1782       insertCB, NULL, removeCB, NULL);
1783   client_sampler = RPS_sampler_init (sampler_size_est_need, max_round_interval,
1784       insertCB, NULL, removeCB, NULL);
1785
1786   /* Initialise push and pull maps */
1787   push_list = NULL;
1788   push_list_size = 0;
1789   pull_list = NULL;
1790   pull_list_size = 0;
1791   pending_pull_reply_list = NULL;
1792   pending_pull_reply_list_size = 0;
1793
1794
1795   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1796   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, server);
1797
1798   // TODO send push/pull to each of those peers?
1799 }
1800
1801
1802 /**
1803  * The main function for the rps service.
1804  *
1805  * @param argc number of arguments from the command line
1806  * @param argv command line arguments
1807  * @return 0 ok, 1 on error
1808  */
1809   int
1810 main (int argc, char *const *argv)
1811 {
1812   return (GNUNET_OK ==
1813           GNUNET_SERVICE_run (argc,
1814                               argv,
1815                               "rps",
1816                               GNUNET_SERVICE_OPTION_NONE,
1817                               &run, NULL)) ? 0 : 1;
1818 }
1819
1820 /* end of gnunet-service-rps.c */