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