-malicious push handling
[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 #ifdef ENABLE_MALICIOUS
360 /**
361  * Type of malicious peer
362  *
363  * 0 Don't act malicious at all - Default
364  * 1 Try to maximise representation
365  * 2 Try to partition the network
366  */
367 uint32_t mal_type = 0;
368
369 /**
370  * Other malicious peers
371  */
372 static struct GNUNET_PeerIdentity *mal_peers = NULL;
373
374 /**
375  * Number of other malicious peers
376  */
377 static uint32_t num_mal_peers = 0;
378
379
380 /**
381  * If type is 2 This struct is used to store the attacked peers in a DLL
382  */
383 struct AttackedPeer
384 {
385   /**
386    * DLL
387    */
388   struct AttackedPeer *next;
389   struct AttackedPeer *prev;
390
391   /**
392    * PeerID
393    */
394   struct GNUNET_PeerIdentity peer_id;
395 };
396
397 /**
398  * If type is 2 this is the DLL of attacked peers
399  */
400 static struct AttackedPeer *att_peers_head = NULL;
401 static struct AttackedPeer *att_peers_tail = NULL;
402
403 /**
404  * This index is used to point to an attacked peer to
405  * implement the round-robin-ish way to select attacked peers.
406  */
407 static struct AttackedPeer *att_peer_index = NULL;
408
409 /**
410  * Number of attacked peers
411  */
412 static uint32_t num_attacked_peers = 0;
413
414
415 /**
416  * If type is 1 this is the attacked peer
417  */
418 static struct GNUNET_PeerIdentity attacked_peer;
419
420 /**
421  * The limit of PUSHes we can send in one round.
422  * This is an assumption of the Brahms protocol and either implemented
423  * via proof of work
424  * or
425  * assumend to be the bandwidth limitation.
426  */
427 static uint32_t push_limit = 10000;
428 #endif /* ENABLE_MALICIOUS */
429
430
431 /***********************************************************************
432  * /Globals
433 ***********************************************************************/
434
435
436
437
438
439
440 /***********************************************************************
441  * Util functions
442 ***********************************************************************/
443
444 /**
445  * Set a peer flag of given peer context.
446  */
447 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
448
449 /**
450  * Get peer flag of given peer context.
451  */
452 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
453
454 /**
455  * Unset flag of given peer context.
456  */
457 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
458
459 /**
460  * Compute the minimum of two ints
461  */
462 #define min(x, y) ((x < y) ? x : y)
463
464 /**
465  * Clean the send channel of a peer
466  */
467 void
468 peer_clean (const struct GNUNET_PeerIdentity *peer);
469
470
471 /**
472  * Check if peer is already in peer array.
473  */
474   int
475 in_arr (const struct GNUNET_PeerIdentity *array,
476         unsigned int arr_size,
477         const struct GNUNET_PeerIdentity *peer)
478 {
479   GNUNET_assert (NULL != peer);
480
481   if (0 == arr_size)
482     return GNUNET_NO;
483
484   GNUNET_assert (NULL != array);
485
486   unsigned int i;
487
488   for (i = 0; i < arr_size ; i++)
489     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
490       return GNUNET_YES;
491   return GNUNET_NO;
492 }
493
494
495 /**
496  * Print peerlist to log.
497  */
498 void
499 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
500 {
501   unsigned int i;
502
503   LOG (GNUNET_ERROR_TYPE_DEBUG,
504        "Printing peer list of length %u at %p:\n",
505        len,
506        list);
507   for (i = 0 ; i < len ; i++)
508   {
509     LOG (GNUNET_ERROR_TYPE_DEBUG,
510          "%u. peer: %s\n",
511          i, GNUNET_i2s (&list[i]));
512   }
513 }
514
515
516 /**
517  * Remove peer from list.
518  */
519   void
520 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
521                unsigned int *list_size,
522                const struct GNUNET_PeerIdentity *peer)
523 {
524   unsigned int i;
525   struct GNUNET_PeerIdentity *tmp;
526
527   tmp = *peer_list;
528
529   LOG (GNUNET_ERROR_TYPE_DEBUG,
530        "Removing peer %s from list at %p\n",
531        GNUNET_i2s (peer),
532        tmp);
533
534   for ( i = 0 ; i < *list_size ; i++ )
535   {
536     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
537     {
538       if (i < *list_size -1)
539       { /* Not at the last entry -- shift peers left */
540         memcpy (&tmp[i], &tmp[i +1],
541                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
542       }
543       /* Remove last entry (should be now useless PeerID) */
544       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
545     }
546   }
547   *peer_list = tmp;
548 }
549
550 /**
551  * Get random peer from the given list but don't return one from the @a ignore_list.
552  */
553   struct GNUNET_PeerIdentity *
554 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
555                            uint32_t list_size,
556                            const struct GNUNET_PeerIdentity *ignore_list,
557                            uint32_t ignore_size)
558 {
559   uint32_t r_index;
560   uint32_t tmp_size;
561   struct GNUNET_PeerIdentity *tmp_peer_list;
562   struct GNUNET_PeerIdentity *peer;
563
564   GNUNET_assert (NULL != peer_list);
565   if (0 == list_size)
566     return NULL;
567
568   tmp_size = 0;
569   tmp_peer_list = NULL;
570   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
571   memcpy (tmp_peer_list,
572           peer_list,
573           list_size * sizeof (struct GNUNET_PeerIdentity));
574   peer = GNUNET_new (struct GNUNET_PeerIdentity);
575
576   /**;
577    * Choose the r_index of the peer we want to return
578    * at random from the interval of the gossip list
579    */
580   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
581                                       tmp_size);
582   *peer = tmp_peer_list[r_index];
583
584   while (in_arr (ignore_list, ignore_size, peer))
585   {
586     rem_from_list (&tmp_peer_list, &tmp_size, peer);
587
588     print_peer_list (tmp_peer_list, tmp_size);
589
590     if (0 == tmp_size)
591     {
592       GNUNET_free (peer);
593       return NULL;
594     }
595
596     /**;
597      * Choose the r_index of the peer we want to return
598      * at random from the interval of the gossip list
599      */
600     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
601                                         tmp_size);
602     *peer = tmp_peer_list[r_index];
603   }
604
605
606   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
607
608   return peer;
609 }
610
611
612 /**
613  * Get the context of a peer. If not existing, create.
614  */
615   struct PeerContext *
616 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
617               const struct GNUNET_PeerIdentity *peer)
618 {
619   struct PeerContext *ctx;
620
621   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
622   {
623     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
624   }
625   else
626   {
627     ctx = GNUNET_new (struct PeerContext);
628     ctx->peer_flags = 0;
629     ctx->mq = NULL;
630     ctx->send_channel = NULL;
631     ctx->recv_channel = NULL;
632     ctx->outstanding_ops = NULL;
633     ctx->num_outstanding_ops = 0;
634     ctx->is_live_task = NULL;
635     ctx->peer_id = *peer;
636     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
637                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
638   }
639   return ctx;
640 }
641
642
643 /**
644  * Put random peer from sampler into the gossip list as history update.
645  */
646   void
647 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
648 {
649   GNUNET_assert (1 == num_peers);
650
651   if (gossip_list_size < sampler_size_est_need)
652     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
653
654   if (0 < num_hist_update_tasks)
655     num_hist_update_tasks--;
656 }
657
658
659 /**
660  * Set the peer flag to living and call the outstanding operations on this peer.
661  */
662 static size_t
663 peer_is_live (struct PeerContext *peer_ctx)
664 {
665   struct GNUNET_PeerIdentity *peer;
666
667   /* Cancle is_live_task if still scheduled */
668   if (NULL != peer_ctx->is_live_task)
669   {
670     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
671     peer_ctx->is_live_task = NULL;
672   }
673
674   peer = &peer_ctx->peer_id;
675   set_peer_flag (peer_ctx, VALID);
676
677   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
678
679   if (0 < peer_ctx->num_outstanding_ops)
680   { /* Call outstanding operations */
681     unsigned int i;
682
683     for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
684       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
685     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
686   }
687
688   return 0;
689 }
690
691
692 /**
693  * Callback that is called when a channel was effectively established.
694  * This is given to ntfy_tmt_rdy and called when the channel was
695  * successfully established.
696  */
697 static size_t
698 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
699 {
700   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
701
702   peer_ctx->is_live_task = NULL;
703   LOG (GNUNET_ERROR_TYPE_DEBUG,
704        "Set ->is_live_task = NULL for peer %s\n",
705        GNUNET_i2s (&peer_ctx->peer_id));
706
707   if (NULL != buf
708       && 0 != size)
709   {
710     peer_is_live (peer_ctx);
711   }
712   else
713   {
714     LOG (GNUNET_ERROR_TYPE_WARNING,
715          "Problems establishing a connection to peer %s in order to check liveliness\n",
716          GNUNET_i2s (&peer_ctx->peer_id));
717     // TODO reschedule? cleanup?
718   }
719
720   //if (NULL != peer_ctx->is_live_task)
721   //{
722   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
723   //       "Trying to cancle is_live_task for peer %s\n",
724   //       GNUNET_i2s (&peer_ctx->peer_id));
725   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
726   //  peer_ctx->is_live_task = NULL;
727   //}
728
729   return 0;
730 }
731
732
733 /**
734  * Get the channel of a peer. If not existing, create.
735  */
736   struct GNUNET_CADET_Channel *
737 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
738              const struct GNUNET_PeerIdentity *peer)
739 {
740   struct PeerContext *peer_ctx;
741
742   peer_ctx = get_peer_ctx (peer_map, peer);
743
744   GNUNET_assert (NULL == peer_ctx->is_live_task);
745
746   if (NULL == peer_ctx->send_channel)
747   {
748     LOG (GNUNET_ERROR_TYPE_DEBUG,
749          "Trying to establish channel to peer %s\n",
750          GNUNET_i2s (peer));
751
752     peer_ctx->send_channel =
753       GNUNET_CADET_channel_create (cadet_handle,
754                                    NULL,
755                                    peer,
756                                    GNUNET_RPS_CADET_PORT,
757                                    GNUNET_CADET_OPTION_RELIABLE);
758
759     // do I have to explicitly put it in the peer_map?
760     (void) GNUNET_CONTAINER_multipeermap_put
761       (peer_map,
762        peer,
763        peer_ctx,
764        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
765   }
766   return peer_ctx->send_channel;
767 }
768
769
770 /**
771  * Get the message queue of a specific peer.
772  *
773  * If we already have a message queue open to this client,
774  * simply return it, otherways create one.
775  */
776   struct GNUNET_MQ_Handle *
777 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
778         const struct GNUNET_PeerIdentity *peer_id)
779 {
780   struct PeerContext *peer_ctx;
781
782   peer_ctx = get_peer_ctx (peer_map, peer_id);
783
784   GNUNET_assert (NULL == peer_ctx->is_live_task);
785
786   if (NULL == peer_ctx->mq)
787   {
788     (void) get_channel (peer_map, peer_id);
789     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
790     //do I have to explicitly put it in the peer_map?
791     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
792                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
793   }
794   return peer_ctx->mq;
795 }
796
797
798 /**
799  * Issue check whether peer is live
800  *
801  * @param peer_ctx the context of the peer
802  */
803 void
804 check_peer_live (struct PeerContext *peer_ctx)
805 {
806   (void) get_channel (peer_map, &peer_ctx->peer_id);
807   LOG (GNUNET_ERROR_TYPE_DEBUG,
808        "Get informed about peer %s getting live\n",
809        GNUNET_i2s (&peer_ctx->peer_id));
810   if (NULL == peer_ctx->is_live_task)
811   {
812     peer_ctx->is_live_task =
813         GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
814                                             GNUNET_NO,
815                                             GNUNET_TIME_UNIT_FOREVER_REL,
816                                             sizeof (struct GNUNET_MessageHeader),
817                                             cadet_ntfy_tmt_rdy_cb,
818                                             peer_ctx);
819   }
820   else
821   {
822     LOG (GNUNET_ERROR_TYPE_DEBUG,
823          "Already waiting for notification\n");
824   }
825 }
826
827
828 /**
829  * Sum all time relatives of an array.
830   */
831   struct GNUNET_TIME_Relative
832 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
833 {
834   struct GNUNET_TIME_Relative sum;
835   uint32_t i;
836
837   sum = GNUNET_TIME_UNIT_ZERO;
838   for ( i = 0 ; i < arr_size ; i++ )
839   {
840     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
841   }
842   return sum;
843 }
844
845
846 /**
847  * Compute the average of given time relatives.
848  */
849   struct GNUNET_TIME_Relative
850 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
851 {
852   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
853 }
854
855
856 /**
857  * Insert PeerID in #pull_list
858  *
859  * Called once we know a peer is live.
860  */
861   void
862 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
863 {
864   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
865     GNUNET_array_append (pull_list, pull_list_size, *peer);
866
867   peer_clean (peer);
868 }
869
870 /**
871  * Check whether #insert_in_pull_list was already scheduled
872  */
873   int
874 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
875 {
876   unsigned int i;
877
878   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
879     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
880       return GNUNET_YES;
881   return GNUNET_NO;
882 }
883
884
885 /**
886  * Insert PeerID in #gossip_list
887  *
888  * Called once we know a peer is live.
889  */
890   void
891 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
892 {
893   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
894     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
895
896   (void) get_channel (peer_map, peer);
897 }
898
899 /**
900  * Check whether #insert_in_gossip_list was already scheduled
901  */
902   int
903 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
904 {
905   unsigned int i;
906
907   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
908     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
909       return GNUNET_YES;
910   return GNUNET_NO;
911 }
912
913
914 /**
915  * Update sampler with given PeerID.
916  */
917   void
918 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
919 {
920   LOG (GNUNET_ERROR_TYPE_DEBUG,
921        "Updating samplers with peer %s from insert_in_sampler()\n",
922        GNUNET_i2s (peer));
923   RPS_sampler_update (prot_sampler,   peer);
924   RPS_sampler_update (client_sampler, peer);
925 }
926
927
928 /**
929  * Check whether #insert_in_sampler was already scheduled
930  */
931 static int
932 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
933 {
934   unsigned int i;
935
936   for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
937     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
938       return GNUNET_YES;
939   return GNUNET_NO;
940 }
941
942
943 /**
944  * Wrapper around #RPS_sampler_resize()
945  *
946  * If we do not have enough sampler elements, double current sampler size
947  * If we have more than enough sampler elements, halv current sampler size
948  */
949 static void
950 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
951 {
952   unsigned int sampler_size;
953
954   // TODO statistics
955   // TODO respect the min, max
956   sampler_size = RPS_sampler_get_size (sampler);
957   if (sampler_size > new_size * 4)
958   { /* Shrinking */
959     RPS_sampler_resize (sampler, sampler_size / 2);
960   }
961   else if (sampler_size < new_size)
962   { /* Growing */
963     RPS_sampler_resize (sampler, sampler_size * 2);
964   }
965   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
966 }
967
968
969 /**
970  * Wrapper around #RPS_sampler_resize() resizing the client sampler
971  */
972 static void
973 client_resize_wrapper ()
974 {
975   uint32_t bigger_size;
976   unsigned int sampler_size;
977
978   // TODO statistics
979
980   sampler_size = RPS_sampler_get_size (client_sampler);
981
982   if (sampler_size_est_need > sampler_size_client_need)
983     bigger_size = sampler_size_est_need;
984   else
985     bigger_size = sampler_size_client_need;
986
987   // TODO respect the min, max
988   resize_wrapper (client_sampler, bigger_size);
989   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
990 }
991
992
993 /**
994  * Estimate request rate
995  *
996  * Called every time we receive a request from the client.
997  */
998   void
999 est_request_rate()
1000 {
1001   struct GNUNET_TIME_Relative max_round_duration;
1002
1003   if (request_deltas_size > req_counter)
1004     req_counter++;
1005   if ( 1 < req_counter)
1006   {
1007     /* Shift last request deltas to the right */
1008     memcpy (&request_deltas[1],
1009         request_deltas,
1010         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
1011
1012     /* Add current delta to beginning */
1013     request_deltas[0] =
1014         GNUNET_TIME_absolute_get_difference (last_request,
1015                                              GNUNET_TIME_absolute_get ());
1016     request_rate = T_relative_avg (request_deltas, req_counter);
1017
1018     /* Compute the duration a round will maximally take */
1019     max_round_duration =
1020         GNUNET_TIME_relative_add (round_interval,
1021                                   GNUNET_TIME_relative_divide (round_interval, 2));
1022
1023     /* Set the estimated size the sampler has to have to
1024      * satisfy the current client request rate */
1025     sampler_size_client_need =
1026         max_round_duration.rel_value_us / request_rate.rel_value_us;
1027
1028     /* Resize the sampler */
1029     client_resize_wrapper ();
1030   }
1031   last_request = GNUNET_TIME_absolute_get ();
1032 }
1033
1034
1035 /***********************************************************************
1036  * /Util functions
1037 ***********************************************************************/
1038
1039
1040
1041
1042
1043 /**
1044  * Function called by NSE.
1045  *
1046  * Updates sizes of sampler list and gossip list and adapt those lists
1047  * accordingly.
1048  */
1049   void
1050 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1051               double logestimate, double std_dev)
1052 {
1053   double estimate;
1054   //double scale; // TODO this might go gloabal/config
1055
1056   LOG (GNUNET_ERROR_TYPE_DEBUG,
1057        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1058        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1059   //scale = .01;
1060   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1061   // GNUNET_NSE_log_estimate_to_n (logestimate);
1062   estimate = pow (estimate, 1.0 / 3);
1063   // TODO add if std_dev is a number
1064   // estimate += (std_dev * scale);
1065   if (2 < ceil (estimate))
1066   {
1067     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1068     sampler_size_est_need = estimate;
1069   } else
1070     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1071
1072   /* If the NSE has changed adapt the lists accordingly */
1073   resize_wrapper (prot_sampler, sampler_size_est_need);
1074   client_resize_wrapper ();
1075 }
1076
1077
1078 /**
1079  * Callback called once the requested PeerIDs are ready.
1080  *
1081  * Sends those to the requesting client.
1082  */
1083 void client_respond (void *cls,
1084     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
1085 {
1086   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
1087   struct GNUNET_MQ_Envelope *ev;
1088   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1089   struct GNUNET_SERVER_Client *client;
1090   uint32_t size_needed;
1091   struct client_ctx *cli_ctx;
1092
1093   client = (struct GNUNET_SERVER_Client *) cls;
1094
1095   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1096                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1097
1098   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1099
1100   ev = GNUNET_MQ_msg_extra (out_msg,
1101                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1102                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1103   out_msg->num_peers = htonl (num_peers);
1104
1105   memcpy (&out_msg[1],
1106       ids,
1107       num_peers * sizeof (struct GNUNET_PeerIdentity));
1108   GNUNET_free (ids);
1109
1110   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
1111   if (NULL == cli_ctx) {
1112     cli_ctx = GNUNET_new (struct client_ctx);
1113     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
1114     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
1115   }
1116
1117   GNUNET_MQ_send (cli_ctx->mq, ev);
1118 }
1119
1120
1121 /**
1122  * Handle RPS request from the client.
1123  *
1124  * @param cls closure
1125  * @param client identification of the client
1126  * @param message the actual message
1127  */
1128 static void
1129 handle_client_request (void *cls,
1130             struct GNUNET_SERVER_Client *client,
1131             const struct GNUNET_MessageHeader *message)
1132 {
1133   struct GNUNET_RPS_CS_RequestMessage *msg;
1134   uint32_t num_peers;
1135   uint32_t size_needed;
1136   uint32_t i;
1137
1138   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1139
1140   num_peers = ntohl (msg->num_peers);
1141   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1142                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1143
1144   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1145   {
1146     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1147     return;
1148   }
1149
1150   for (i = 0 ; i < num_peers ; i++)
1151     est_request_rate();
1152
1153   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
1154
1155   RPS_sampler_get_n_rand_peers (client_sampler, client_respond,
1156                                 client, num_peers, GNUNET_YES);
1157
1158   GNUNET_SERVER_receive_done (client,
1159                               GNUNET_OK);
1160 }
1161
1162
1163 /**
1164  * Handle seed from the client.
1165  *
1166  * @param cls closure
1167  * @param client identification of the client
1168  * @param message the actual message
1169  */
1170   static void
1171 handle_client_seed (void *cls,
1172                     struct GNUNET_SERVER_Client *client,
1173                     const struct GNUNET_MessageHeader *message)
1174 {
1175   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1176   struct GNUNET_PeerIdentity *peers;
1177   uint32_t num_peers;
1178   uint32_t i;
1179
1180   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1181   {
1182     GNUNET_break_op (0);
1183     GNUNET_SERVER_receive_done (client,
1184                                 GNUNET_SYSERR);
1185   }
1186
1187   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1188   num_peers = ntohl (in_msg->num_peers);
1189   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1190   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1191   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1192
1193   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1194       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1195   {
1196     GNUNET_break_op (0);
1197     GNUNET_SERVER_receive_done (client,
1198                                 GNUNET_SYSERR);
1199   }
1200
1201   LOG (GNUNET_ERROR_TYPE_DEBUG,
1202        "Client seeded peers:\n");
1203   print_peer_list (peers, num_peers);
1204
1205   // TODO check for validity of ids
1206
1207   for (i = 0 ; i < num_peers ; i++)
1208   {
1209     LOG (GNUNET_ERROR_TYPE_DEBUG,
1210          "Updating samplers with seed %" PRIX32 ": %s\n",
1211          i,
1212          GNUNET_i2s (&peers[i]));
1213
1214     RPS_sampler_update (prot_sampler,   &peers[i]);
1215     RPS_sampler_update (client_sampler, &peers[i]);
1216   }
1217
1218   //GNUNET_free (peers);
1219
1220   GNUNET_SERVER_receive_done (client,
1221                                                 GNUNET_OK);
1222 }
1223
1224
1225 /**
1226  * Handle a PUSH message from another peer.
1227  *
1228  * Check the proof of work and store the PeerID
1229  * in the temporary list for pushed PeerIDs.
1230  *
1231  * @param cls Closure
1232  * @param channel The channel the PUSH was received over
1233  * @param channel_ctx The context associated with this channel
1234  * @param msg The message header
1235  */
1236 static int
1237 handle_peer_push (void *cls,
1238     struct GNUNET_CADET_Channel *channel,
1239     void **channel_ctx,
1240     const struct GNUNET_MessageHeader *msg)
1241 {
1242   const struct GNUNET_PeerIdentity *peer;
1243
1244   // (check the proof of work)
1245
1246   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1247   // FIXME wait for cadet to change this function
1248   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1249
1250   #ifdef ENABLE_MALICIOUS
1251   struct AttackedPeer *tmp_att_peer;
1252
1253   tmp_att_peer = GNUNET_new (struct AttackedPeer);
1254   memcpy (&tmp_att_peer->peer_id, peer, sizeof (struct GNUNET_PeerIdentity));
1255   if (1 == mal_type)
1256   { /* Try to maximise representation */
1257     // TODO Check whether we already have that peer
1258     GNUNET_CONTAINER_DLL_insert (att_peers_head, att_peers_tail, tmp_att_peer);
1259     return GNUNET_OK;
1260   }
1261
1262
1263   else if (2 == mal_type)
1264   { /* We attack one single well-known peer - simply ignore */
1265     return GNUNET_OK;
1266   }
1267
1268   #endif /* ENABLE_MALICIOUS */
1269
1270   /* Add the sending peer to the push_list */
1271   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1272     GNUNET_array_append (push_list, push_list_size, *peer);
1273
1274   return GNUNET_OK;
1275 }
1276
1277
1278 /**
1279  * Handle PULL REQUEST request message from another peer.
1280  *
1281  * Reply with the gossip list of PeerIDs.
1282  *
1283  * @param cls Closure
1284  * @param channel The channel the PUSH was received over
1285  * @param channel_ctx The context associated with this channel
1286  * @param msg The message header
1287  */
1288 static int
1289 handle_peer_pull_request (void *cls,
1290     struct GNUNET_CADET_Channel *channel,
1291     void **channel_ctx,
1292     const struct GNUNET_MessageHeader *msg)
1293 {
1294   struct GNUNET_PeerIdentity *peer;
1295   uint32_t send_size;
1296   struct GNUNET_MQ_Handle *mq;
1297   struct GNUNET_MQ_Envelope *ev;
1298   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1299
1300
1301   peer = (struct GNUNET_PeerIdentity *)
1302     GNUNET_CADET_channel_get_info (channel,
1303                                    GNUNET_CADET_OPTION_PEER);
1304   // FIXME wait for cadet to change this function
1305
1306   /* Compute actual size */
1307   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1308               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1309
1310   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1311     /* Compute number of peers to send
1312      * If too long, simply truncate */
1313   // TODO select random ones via permutation
1314     send_size =
1315       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1316        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1317        sizeof (struct GNUNET_PeerIdentity);
1318   else
1319     send_size = gossip_list_size;
1320
1321   LOG (GNUNET_ERROR_TYPE_DEBUG,
1322       "PULL REQUEST from peer %s received, going to send %u peers\n",
1323       GNUNET_i2s (peer), send_size);
1324
1325   mq = get_mq (peer_map, peer);
1326
1327   ev = GNUNET_MQ_msg_extra (out_msg,
1328                            send_size * sizeof (struct GNUNET_PeerIdentity),
1329                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1330   //out_msg->num_peers = htonl (gossip_list_size);
1331   out_msg->num_peers = htonl (send_size);
1332   memcpy (&out_msg[1], gossip_list,
1333          send_size * sizeof (struct GNUNET_PeerIdentity));
1334
1335   GNUNET_MQ_send (mq, ev);
1336
1337   return GNUNET_OK;
1338 }
1339
1340
1341 /**
1342  * Handle PULL REPLY message from another peer.
1343  *
1344  * Check whether we sent a corresponding request and
1345  * whether this reply is the first one.
1346  *
1347  * @param cls Closure
1348  * @param channel The channel the PUSH was received over
1349  * @param channel_ctx The context associated with this channel
1350  * @param msg The message header
1351  */
1352   static int
1353 handle_peer_pull_reply (void *cls,
1354                         struct GNUNET_CADET_Channel *channel,
1355                         void **channel_ctx,
1356                         const struct GNUNET_MessageHeader *msg)
1357 {
1358   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1359
1360   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1361   struct GNUNET_PeerIdentity *peers;
1362   struct PeerContext *peer_ctx;
1363   struct GNUNET_PeerIdentity *sender;
1364   struct PeerContext *sender_ctx;
1365   struct PeerOutstandingOp out_op;
1366   uint32_t i;
1367
1368   /* Check for protocol violation */
1369   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1370   {
1371     GNUNET_break_op (0);
1372     return GNUNET_SYSERR;
1373   }
1374
1375   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1376   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1377       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1378   {
1379     LOG (GNUNET_ERROR_TYPE_ERROR,
1380         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1381         ntohl (in_msg->num_peers),
1382         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1383             sizeof (struct GNUNET_PeerIdentity));
1384     GNUNET_break_op (0);
1385     return GNUNET_SYSERR;
1386   }
1387
1388   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1389       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1390        // Guess simply casting isn't the nicest way...
1391        // FIXME wait for cadet to change this function
1392   sender_ctx = get_peer_ctx (peer_map, sender);
1393
1394   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1395   {
1396     GNUNET_break_op (0);
1397     return GNUNET_OK;
1398   }
1399
1400
1401   /* Do actual logic */
1402   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1403   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1404   {
1405     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1406     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1407         || NULL != peer_ctx->send_channel
1408         || NULL != peer_ctx->recv_channel)
1409     {
1410       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1411           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1412         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1413     }
1414     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1415     {
1416       out_op.op = insert_in_pull_list;
1417       out_op.op_cls = NULL;
1418       GNUNET_array_append (peer_ctx->outstanding_ops,
1419                            peer_ctx->num_outstanding_ops,
1420                            out_op);
1421       check_peer_live (peer_ctx);
1422     }
1423   }
1424
1425   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1426   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1427
1428   return GNUNET_OK;
1429 }
1430
1431
1432 /**
1433  * Compute a random delay.
1434  * A uniformly distributed value between mean + spread and mean - spread.
1435  *
1436  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1437  * It would return a random value between 2 and 6 min.
1438  *
1439  * @param mean the mean
1440  * @param spread the inverse amount of deviation from the mean
1441  */
1442 static struct GNUNET_TIME_Relative
1443 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1444 {
1445   struct GNUNET_TIME_Relative half_interval;
1446   struct GNUNET_TIME_Relative ret;
1447   unsigned int rand_delay;
1448   unsigned int max_rand_delay;
1449
1450   if (0 == spread)
1451   {
1452     LOG (GNUNET_ERROR_TYPE_WARNING,
1453          "Not accepting spread of 0\n");
1454     GNUNET_break (0);
1455   }
1456
1457   /* Compute random time value between spread * mean and spread * mean */
1458   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1459
1460   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1461   /**
1462    * Compute random value between (0 and 1) * round_interval
1463    * via multiplying round_interval with a 'fraction' (0 to value)/value
1464    */
1465   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1466   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1467   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1468   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1469
1470   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1471     LOG (GNUNET_ERROR_TYPE_WARNING,
1472          "Returning FOREVER_REL\n");
1473
1474   return ret;
1475 }
1476
1477
1478 /**
1479  * Send single pull request
1480  *
1481  * @param peer_id the peer to send the pull request to.
1482  */
1483 static void
1484 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1485 {
1486   struct GNUNET_MQ_Envelope *ev;
1487   struct GNUNET_MQ_Handle *mq;
1488
1489   LOG (GNUNET_ERROR_TYPE_DEBUG,
1490        "Sending PULL request to peer %s of gossiped list.\n",
1491        GNUNET_i2s (peer_id));
1492
1493   GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer_id);
1494
1495   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1496   mq = get_mq (peer_map, peer_id);
1497   GNUNET_MQ_send (mq, ev);
1498 }
1499
1500
1501 /**
1502  * Send single push
1503  *
1504  * @param peer_id the peer to send the push to.
1505  */
1506 static void
1507 send_push (struct GNUNET_PeerIdentity *peer_id)
1508 {
1509   struct GNUNET_MQ_Envelope *ev;
1510   struct GNUNET_MQ_Handle *mq;
1511
1512   LOG (GNUNET_ERROR_TYPE_DEBUG,
1513        "Sending PUSH to peer %s of gossiped list.\n",
1514        GNUNET_i2s (peer_id));
1515
1516   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1517   mq = get_mq (peer_map, peer_id);
1518   GNUNET_MQ_send (mq, ev);
1519 }
1520
1521
1522 static void
1523 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1524
1525 static void
1526 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1527
1528
1529 #ifdef ENABLE_MALICIOUS
1530 /**
1531  * Turn RPS service to act malicious.
1532  *
1533  * @param cls Closure
1534  * @param channel The channel the PUSH was received over
1535  * @param channel_ctx The context associated with this channel
1536  * @param msg The message header
1537  */
1538   static void
1539 handle_client_act_malicious (void *cls,
1540                              struct GNUNET_SERVER_Client *client,
1541                              const struct GNUNET_MessageHeader *msg)
1542 {
1543   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1544   struct GNUNET_PeerIdentity *peers;
1545   uint32_t num_mal_peers_sent;
1546   uint32_t num_mal_peers_old;
1547
1548   /* Check for protocol violation */
1549   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1550   {
1551     GNUNET_break_op (0);
1552   }
1553
1554   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1555   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1556       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1557   {
1558     LOG (GNUNET_ERROR_TYPE_ERROR,
1559         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1560         ntohl (in_msg->num_peers),
1561         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1562             sizeof (struct GNUNET_PeerIdentity));
1563     GNUNET_break_op (0);
1564   }
1565
1566
1567   /* Do actual logic */
1568   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1569   mal_type = ntohl (in_msg->type);
1570
1571   LOG (GNUNET_ERROR_TYPE_DEBUG,
1572        "Now acting malicious type %" PRIu32 "\n",
1573        mal_type);
1574
1575   if (1 == mal_type)
1576   { /* Try to maximise representation */
1577     /* Add other malicious peers to those we already know */
1578     num_mal_peers_sent = ntohl (in_msg->num_peers);
1579     num_mal_peers_old = num_mal_peers;
1580     GNUNET_array_grow (mal_peers,
1581                        num_mal_peers,
1582                        num_mal_peers + num_mal_peers_sent);
1583     memcpy (&mal_peers[num_mal_peers_old],
1584             peers,
1585             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1586
1587     /* Substitute do_round () with do_mal_round () */
1588     GNUNET_SCHEDULER_cancel (do_round_task);
1589     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1590   }
1591   else if (2 == mal_type)
1592   { /* Try to partition the network */
1593     /* Add other malicious peers to those we already know */
1594     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
1595     num_mal_peers_old = num_mal_peers;
1596     GNUNET_array_grow (mal_peers,
1597                        num_mal_peers,
1598                        num_mal_peers + num_mal_peers_sent);
1599     memcpy (&mal_peers[num_mal_peers_old],
1600             peers,
1601             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1602
1603     /* Store the one attacked peer */
1604     memcpy (&attacked_peer,
1605             &peers[num_mal_peers_sent],
1606             sizeof (struct GNUNET_PeerIdentity));
1607
1608     LOG (GNUNET_ERROR_TYPE_DEBUG,
1609          "Attacked peer is %s\n",
1610          GNUNET_i2s (&attacked_peer));
1611
1612     /* Substitute do_round () with do_mal_round () */
1613     GNUNET_SCHEDULER_cancel (do_round_task);
1614     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1615   }
1616   else if (0 == mal_type)
1617   { /* Stop acting malicious */
1618     num_mal_peers = 0;
1619     GNUNET_free (mal_peers);
1620
1621     /* Substitute do_mal_round () with do_round () */
1622     GNUNET_SCHEDULER_cancel (do_round_task);
1623     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1624   }
1625   else
1626   {
1627     GNUNET_break (0);
1628   }
1629 }
1630
1631
1632 /**
1633  * Send out PUSHes and PULLs maliciously.
1634  *
1635  * This is executed regylary.
1636  */
1637 static void
1638 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1639 {
1640   uint32_t num_pushes;
1641   uint32_t i;
1642   struct GNUNET_TIME_Relative time_next_round;
1643   struct AttackedPeer *tmp_att_peer;
1644   struct AttackedPeer *att_stop_peer;
1645
1646   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously.\n");
1647
1648   /* Do malicious actions */
1649   if (1 == mal_type)
1650   { /* Try to maximise representation */
1651
1652     /* The maximum of pushes we're going to send this round */
1653     num_pushes = min (min (push_limit,
1654                            num_attacked_peers),
1655                        GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1656
1657
1658     /* Send PUSHes to attacked peers */
1659
1660     /* If we see this peer again while iterating over peers
1661      * we can stop iterating, as peers will ignore multiple
1662      * pushes from one peer in one round */
1663     if (att_peers_head == att_peer_index)
1664       att_stop_peer = att_peers_tail;
1665     else
1666       att_peers_tail = att_peer_index->prev;
1667
1668     for (i = 0 ; i < num_pushes ; i++)
1669     {
1670       if (att_peers_tail == att_peer_index)
1671         att_peer_index = att_peers_head;
1672       else if (att_stop_peer == att_peer_index)
1673         break;
1674       else
1675         att_peer_index = att_peer_index->next;
1676
1677       send_push (&att_peer_index->peer_id);
1678     }
1679
1680
1681     /* Send PULLs to some peers to learn about additional peers to attack */
1682
1683     /* If we see this peer again while iterating over peers
1684      * we can stop iterating, as peers will ignore multiple
1685      * pushes from one peer in one round */
1686     tmp_att_peer = att_peer_index;
1687     if (att_peers_head == att_peer_index)
1688       att_stop_peer = att_peers_tail;
1689     else
1690       att_peers_tail = att_peer_index->prev;
1691
1692     for (i = 0 ; i < num_pushes * alpha ; i++)
1693     {
1694       if (att_peers_tail == tmp_att_peer)
1695         tmp_att_peer = att_peers_head;
1696       else if (att_stop_peer == att_peer_index)
1697         break;
1698       else
1699         att_peer_index = tmp_att_peer->next;
1700
1701       send_pull_request (&tmp_att_peer->peer_id);
1702     }
1703   }
1704
1705
1706   else if (2 == mal_type)
1707   { /**
1708      * Try to partition the network
1709      * Send as many pushes to the attacked peer as possible
1710      * That is one push per round as it will ignore more.
1711      */
1712       send_push (&attacked_peer);
1713   }
1714
1715
1716   /* Schedule next round */
1717   time_next_round = compute_rand_delay (round_interval, 2);
1718
1719   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
1720   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
1721   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1722 }
1723 #endif /* ENABLE_MALICIOUS */
1724
1725
1726 /**
1727  * Send out PUSHes and PULLs, possibly update #gossip_list, samplers.
1728  *
1729  * This is executed regylary.
1730  */
1731 static void
1732 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1733 {
1734   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
1735
1736   uint32_t i;
1737   unsigned int *permut;
1738   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1739   struct GNUNET_PeerIdentity peer;
1740   struct GNUNET_PeerIdentity *tmp_peer;
1741
1742   LOG (GNUNET_ERROR_TYPE_DEBUG,
1743        "Printing gossip list:\n");
1744   for (i = 0 ; i < gossip_list_size ; i++)
1745     LOG (GNUNET_ERROR_TYPE_DEBUG,
1746          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1747   // TODO log lists, ...
1748
1749   /* Would it make sense to have one shuffeled gossip list and then
1750    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1751    * use the rest to update sampler?
1752    * in essence get random peers with consumption */
1753
1754   /* Send PUSHes */
1755   if (0 < gossip_list_size)
1756   {
1757     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1758                                            (unsigned int) gossip_list_size);
1759     n_peers = ceil (alpha * gossip_list_size);
1760     LOG (GNUNET_ERROR_TYPE_DEBUG,
1761          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1762          n_peers, alpha, gossip_list_size);
1763     for (i = 0 ; i < n_peers ; i++)
1764     {
1765       peer = gossip_list[permut[i]];
1766       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1767       { // FIXME if this fails schedule/loop this for later
1768         send_push (&peer);
1769       }
1770     }
1771     GNUNET_free (permut);
1772   }
1773
1774
1775   /* Send PULL requests */
1776   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1777   n_peers = ceil (beta * gossip_list_size);
1778   LOG (GNUNET_ERROR_TYPE_DEBUG,
1779        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1780        n_peers, beta, gossip_list_size);
1781   for (i = 0 ; i < n_peers ; i++)
1782   {
1783     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1784         pending_pull_reply_list, pending_pull_reply_list_size);
1785     if (NULL != tmp_peer)
1786     {
1787       peer = *tmp_peer;
1788       GNUNET_free (tmp_peer);
1789
1790       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1791       {
1792         send_pull_request (&peer);
1793       }
1794     }
1795   }
1796
1797
1798   /* Update gossip list */
1799
1800   if ( push_list_size <= alpha * gossip_list_size &&
1801        push_list_size != 0 &&
1802        pull_list_size != 0 )
1803   {
1804     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1805
1806     uint32_t first_border;
1807     uint32_t second_border;
1808     uint32_t r_index;
1809     uint32_t peers_to_clean_size;
1810     struct GNUNET_PeerIdentity *peers_to_clean;
1811
1812     peers_to_clean = NULL;
1813     peers_to_clean_size = 0;
1814     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
1815     memcpy (peers_to_clean,
1816             gossip_list,
1817             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
1818
1819     first_border  =                ceil (alpha * sampler_size_est_need);
1820     second_border = first_border + ceil (beta  * sampler_size_est_need);
1821
1822     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1823
1824     for (i = 0 ; i < first_border ; i++)
1825     { // TODO use RPS_sampler_get_n_rand_peers
1826       /* Update gossip list with peers received through PUSHes */
1827       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1828                                        push_list_size);
1829       gossip_list[i] = push_list[r_index];
1830       // TODO change the peer_flags accordingly
1831     }
1832
1833     for (i = first_border ; i < second_border ; i++)
1834     {
1835       /* Update gossip list with peers received through PULLs */
1836       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1837                                        pull_list_size);
1838       gossip_list[i] = pull_list[r_index];
1839       // TODO change the peer_flags accordingly
1840     }
1841
1842     for (i = second_border ; i < sampler_size_est_need ; i++)
1843     {
1844       /* Update gossip list with peers from history */
1845       RPS_sampler_get_n_rand_peers (prot_sampler, hist_update, NULL, 1, GNUNET_NO);
1846       num_hist_update_tasks++;
1847       // TODO change the peer_flags accordingly
1848     }
1849
1850     for (i = 0 ; i < gossip_list_size ; i++)
1851       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
1852
1853     for (i = 0 ; i < peers_to_clean_size ; i++)
1854       peer_clean (&peers_to_clean[i]);
1855
1856     GNUNET_free (peers_to_clean);
1857   }
1858   else
1859   {
1860     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1861   }
1862   // TODO independent of that also get some peers from CADET_get_peers()?
1863
1864
1865   /* Update samplers */
1866   for ( i = 0 ; i < push_list_size ; i++ )
1867   {
1868     LOG (GNUNET_ERROR_TYPE_DEBUG,
1869          "Updating with peer %s from push list\n",
1870          GNUNET_i2s (&push_list[i]));
1871     RPS_sampler_update (prot_sampler,   &push_list[i]);
1872     RPS_sampler_update (client_sampler, &push_list[i]);
1873     // TODO set in_flag?
1874   }
1875
1876   for ( i = 0 ; i < pull_list_size ; i++ )
1877   {
1878     LOG (GNUNET_ERROR_TYPE_DEBUG,
1879          "Updating with peer %s from pull list\n",
1880          GNUNET_i2s (&pull_list[i]));
1881     RPS_sampler_update (prot_sampler,   &pull_list[i]);
1882     RPS_sampler_update (client_sampler, &pull_list[i]);
1883     // TODO set in_flag?
1884   }
1885
1886
1887   /* Empty push/pull lists */
1888   GNUNET_array_grow (push_list, push_list_size, 0);
1889   GNUNET_array_grow (pull_list, pull_list_size, 0);
1890
1891   struct GNUNET_TIME_Relative time_next_round;
1892
1893   time_next_round = compute_rand_delay (round_interval, 2);
1894
1895   /* Schedule next round */
1896   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1897   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
1898   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1899 }
1900
1901
1902 static void
1903 rps_start (struct GNUNET_SERVER_Handle *server);
1904
1905
1906 /**
1907  * This is called from GNUNET_CADET_get_peers().
1908  *
1909  * It is called on every peer(ID) that cadet somehow has contact with.
1910  * We use those to initialise the sampler.
1911  */
1912 void
1913 init_peer_cb (void *cls,
1914               const struct GNUNET_PeerIdentity *peer,
1915               int tunnel, // "Do we have a tunnel towards this peer?"
1916               unsigned int n_paths, // "Number of known paths towards this peer"
1917               unsigned int best_path) // "How long is the best path?
1918                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1919 {
1920   struct PeerOutstandingOp out_op;
1921   struct PeerContext *peer_ctx;
1922
1923   if (NULL != peer
1924       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer))
1925   {
1926     LOG (GNUNET_ERROR_TYPE_DEBUG,
1927         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1928         GNUNET_i2s (peer), peer, gossip_list_size);
1929
1930     // maybe create a function for that
1931     peer_ctx = get_peer_ctx (peer_map, peer);
1932     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1933     {
1934       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1935       {
1936         out_op.op = insert_in_sampler;
1937         out_op.op_cls = NULL;
1938         GNUNET_array_append (peer_ctx->outstanding_ops,
1939                              peer_ctx->num_outstanding_ops,
1940                              out_op);
1941       }
1942
1943       if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1944       {
1945         out_op.op = insert_in_gossip_list;
1946         out_op.op_cls = NULL;
1947         GNUNET_array_append (peer_ctx->outstanding_ops,
1948                              peer_ctx->num_outstanding_ops,
1949                              out_op);
1950       }
1951
1952       /* Trigger livelyness test on peer */
1953       check_peer_live (peer_ctx);
1954     }
1955
1956     // send push/pull to each of those peers?
1957   }
1958 }
1959
1960
1961 /**
1962  * Clean the send channel of a peer
1963  */
1964 void
1965 peer_clean (const struct GNUNET_PeerIdentity *peer)
1966 {
1967   struct PeerContext *peer_ctx;
1968   struct GNUNET_CADET_Channel *channel;
1969
1970   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
1971       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1972   {
1973     peer_ctx = get_peer_ctx (peer_map, peer);
1974     if (NULL != peer_ctx->send_channel)
1975     {
1976       channel = peer_ctx->send_channel;
1977       peer_ctx->send_channel = NULL;
1978       GNUNET_CADET_channel_destroy (channel);
1979     }
1980   }
1981 }
1982
1983
1984 /**
1985  * Callback used to remove peers from the multipeermap.
1986  */
1987   int
1988 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1989 {
1990   struct PeerContext *peer_ctx;
1991   const struct GNUNET_CADET_Channel *channel =
1992     (const struct GNUNET_CADET_Channel *) cls;
1993   struct GNUNET_CADET_Channel *recv;
1994   struct GNUNET_CADET_Channel *send;
1995
1996   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, value))
1997   {
1998     peer_ctx = (struct PeerContext *) value;
1999
2000     if (0 != peer_ctx->num_outstanding_ops)
2001       GNUNET_array_grow (peer_ctx->outstanding_ops,
2002                          peer_ctx->num_outstanding_ops,
2003                          0);
2004
2005     if (NULL != peer_ctx->mq)
2006     {
2007       GNUNET_MQ_destroy (peer_ctx->mq);
2008       peer_ctx->mq = NULL;
2009     }
2010
2011
2012     if (NULL != peer_ctx->is_live_task)
2013     {
2014     LOG (GNUNET_ERROR_TYPE_DEBUG,
2015          "Trying to cancle is_live_task for peer %s\n",
2016          GNUNET_i2s (key));
2017       GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
2018       peer_ctx->is_live_task = NULL;
2019     }
2020
2021     send = peer_ctx->send_channel;
2022     peer_ctx->send_channel = NULL;
2023     if (NULL != send
2024         && channel != send)
2025     {
2026       GNUNET_CADET_channel_destroy (send);
2027     }
2028
2029     recv = peer_ctx->send_channel;
2030     peer_ctx->recv_channel = NULL;
2031     if (NULL != recv
2032         && channel != recv)
2033     {
2034       GNUNET_CADET_channel_destroy (recv);
2035     }
2036
2037     if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2038       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
2039     else
2040       GNUNET_free (peer_ctx);
2041   }
2042
2043   return GNUNET_YES;
2044 }
2045
2046
2047 /**
2048  * Task run during shutdown.
2049  *
2050  * @param cls unused
2051  * @param tc unused
2052  */
2053 static void
2054 shutdown_task (void *cls,
2055                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2056 {
2057   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
2058
2059   if (NULL != do_round_task)
2060   {
2061     GNUNET_SCHEDULER_cancel (do_round_task);
2062     do_round_task = NULL;
2063   }
2064
2065
2066   {
2067   if (GNUNET_SYSERR ==
2068         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
2069     LOG (GNUNET_ERROR_TYPE_WARNING,
2070         "Iterating over peers to disconnect from them was cancelled\n");
2071   }
2072
2073   GNUNET_NSE_disconnect (nse);
2074   GNUNET_CADET_disconnect (cadet_handle);
2075   RPS_sampler_destroy (prot_sampler);
2076   RPS_sampler_destroy (client_sampler);
2077   LOG (GNUNET_ERROR_TYPE_DEBUG,
2078        "Size of the peermap: %u\n",
2079        GNUNET_CONTAINER_multipeermap_size (peer_map));
2080   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2081   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2082   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
2083   GNUNET_array_grow (push_list, push_list_size, 0);
2084   GNUNET_array_grow (pull_list, pull_list_size, 0);
2085   #ifdef ENABLE_MALICIOUS
2086   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2087   // TODO empty attacked_peers DLL
2088   #endif /* ENABLE_MALICIOUS */
2089 }
2090
2091
2092 /**
2093  * A client disconnected.  Remove all of its data structure entries.
2094  *
2095  * @param cls closure, NULL
2096  * @param client identification of the client
2097  */
2098 static void
2099 handle_client_disconnect (void *cls,
2100                           struct GNUNET_SERVER_Client * client)
2101 {
2102 }
2103
2104
2105 /**
2106  * Handle the channel a peer opens to us.
2107  *
2108  * @param cls The closure
2109  * @param channel The channel the peer wants to establish
2110  * @param initiator The peer's peer ID
2111  * @param port The port the channel is being established over
2112  * @param options Further options
2113  */
2114   static void *
2115 handle_inbound_channel (void *cls,
2116                         struct GNUNET_CADET_Channel *channel,
2117                         const struct GNUNET_PeerIdentity *initiator,
2118                         uint32_t port,
2119                         enum GNUNET_CADET_ChannelOption options)
2120 {
2121   struct PeerContext *peer_ctx;
2122   struct GNUNET_PeerIdentity peer;
2123
2124   peer = *initiator;
2125   LOG (GNUNET_ERROR_TYPE_DEBUG,
2126       "New channel was established to us (Peer %s).\n",
2127       GNUNET_i2s (&peer));
2128
2129   GNUNET_assert (NULL != channel);
2130
2131   // we might not even store the recv_channel
2132
2133   peer_ctx = get_peer_ctx (peer_map, &peer);
2134   // FIXME what do we do if a channel is established twice?
2135   //       overwrite? Clean old channel? ...?
2136   //if (NULL != peer_ctx->recv_channel)
2137   //{
2138   //  peer_ctx->recv_channel = channel;
2139   //}
2140   peer_ctx->recv_channel = channel;
2141
2142   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
2143       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
2144
2145   peer_is_live (peer_ctx);
2146
2147   return NULL; // TODO
2148 }
2149
2150
2151 /**
2152  * This is called when a remote peer destroys a channel.
2153  *
2154  * @param cls The closure
2155  * @param channel The channel being closed
2156  * @param channel_ctx The context associated with this channel
2157  */
2158   static void
2159 cleanup_channel (void *cls,
2160                 const struct GNUNET_CADET_Channel *channel,
2161                 void *channel_ctx)
2162 {
2163   struct GNUNET_PeerIdentity *peer;
2164   struct PeerContext *peer_ctx;
2165
2166   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2167       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2168        // Guess simply casting isn't the nicest way...
2169        // FIXME wait for cadet to change this function
2170
2171   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2172   {
2173     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2174
2175     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2176       return;
2177
2178     if (channel == peer_ctx->send_channel)
2179     { /* Peer probably went down */
2180       LOG (GNUNET_ERROR_TYPE_DEBUG,
2181            "Peer %s destroyed send channel - probably went down, cleaning up\n",
2182            GNUNET_i2s (peer));
2183       rem_from_list (&gossip_list, &gossip_list_size, peer);
2184       rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, peer);
2185
2186       peer_ctx->send_channel = NULL;
2187       /* Somwewhat {ab,re}use the iterator function */
2188       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2189       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2190     }
2191     else if (channel == peer_ctx->recv_channel)
2192     { /* Other peer doesn't want to send us messages anymore */
2193       LOG (GNUNET_ERROR_TYPE_DEBUG,
2194            "Peer %s destroyed recv channel - cleaning up channel\n",
2195            GNUNET_i2s (peer));
2196       peer_ctx->recv_channel = NULL;
2197     }
2198   }
2199 }
2200
2201
2202 /**
2203  * Actually start the service.
2204  */
2205   static void
2206 rps_start (struct GNUNET_SERVER_Handle *server)
2207 {
2208   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2209     {&handle_client_request,     NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2210       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2211     {&handle_client_seed,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2212     #ifdef ENABLE_MALICIOUS
2213     {&handle_client_act_malicious, NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2214     #endif /* ENABLE_MALICIOUS */
2215     {NULL, NULL, 0, 0}
2216   };
2217
2218   GNUNET_SERVER_add_handlers (server, handlers);
2219   GNUNET_SERVER_disconnect_notify (server,
2220                                    &handle_client_disconnect,
2221                                    NULL);
2222   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
2223
2224
2225   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2226   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2227
2228   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2229                                                         &shutdown_task,
2230                                                         NULL);
2231 }
2232
2233
2234 /**
2235  * Process statistics requests.
2236  *
2237  * @param cls closure
2238  * @param server the initialized server
2239  * @param c configuration to use
2240  */
2241   static void
2242 run (void *cls,
2243      struct GNUNET_SERVER_Handle *server,
2244      const struct GNUNET_CONFIGURATION_Handle *c)
2245 {
2246   // TODO check what this does -- copied from gnunet-boss
2247   // - seems to work as expected
2248   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2249   cfg = c;
2250
2251
2252   /* Get own ID */
2253   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2254   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2255               "STARTING SERVICE (rps) for peer [%s]\n",
2256               GNUNET_i2s (&own_identity));
2257   #ifdef ENABLE_MALICIOUS
2258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2259               "Malicious execution compiled in.\n");
2260   #endif /* ENABLE_MALICIOUS */
2261
2262
2263
2264   /* Get time interval from the configuration */
2265   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2266                                                         "ROUNDINTERVAL",
2267                                                         &round_interval))
2268   {
2269     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
2270     GNUNET_SCHEDULER_shutdown ();
2271     return;
2272   }
2273
2274   /* Get initial size of sampler/gossip list from the configuration */
2275   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
2276                                                          "INITSIZE",
2277                                                          (long long unsigned int *) &sampler_size_est_need))
2278   {
2279     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
2280     GNUNET_SCHEDULER_shutdown ();
2281     return;
2282   }
2283   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2284
2285
2286   gossip_list = NULL;
2287
2288
2289   /* connect to NSE */
2290   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2291   // TODO check whether that was successful
2292   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
2293
2294
2295   alpha = 0.45;
2296   beta  = 0.45;
2297
2298   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2299
2300
2301   /* Initialise cadet */
2302   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2303     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2304       sizeof (struct GNUNET_MessageHeader)},
2305     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2306       sizeof (struct GNUNET_MessageHeader)},
2307     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2308     {NULL, 0, 0}
2309   };
2310
2311   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2312   cadet_handle = GNUNET_CADET_connect (cfg,
2313                                        cls,
2314                                        &handle_inbound_channel,
2315                                        &cleanup_channel,
2316                                        cadet_handlers,
2317                                        ports);
2318   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
2319
2320
2321   /* Initialise sampler */
2322   struct GNUNET_TIME_Relative half_round_interval;
2323   struct GNUNET_TIME_Relative  max_round_interval;
2324
2325   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2326   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2327
2328   prot_sampler =   RPS_sampler_init (sampler_size_est_need, max_round_interval);
2329   client_sampler = RPS_sampler_init (sampler_size_est_need, max_round_interval);
2330
2331   /* Initialise push and pull maps */
2332   push_list = NULL;
2333   push_list_size = 0;
2334   pull_list = NULL;
2335   pull_list_size = 0;
2336   pending_pull_reply_list = NULL;
2337   pending_pull_reply_list_size = 0;
2338
2339
2340   num_hist_update_tasks = 0;
2341
2342
2343   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2344   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2345   // TODO send push/pull to each of those peers?
2346
2347
2348   rps_start (server);
2349 }
2350
2351
2352 /**
2353  * The main function for the rps service.
2354  *
2355  * @param argc number of arguments from the command line
2356  * @param argv command line arguments
2357  * @return 0 ok, 1 on error
2358  */
2359   int
2360 main (int argc, char *const *argv)
2361 {
2362   return (GNUNET_OK ==
2363           GNUNET_SERVICE_run (argc,
2364                               argv,
2365                               "rps",
2366                               GNUNET_SERVICE_OPTION_NONE,
2367                               &run, NULL)) ? 0 : 1;
2368 }
2369
2370 /* end of gnunet-service-rps.c */