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