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