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