-fix coverity
[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 #include "rps-test_util.h"
32
33 #include "gnunet-service-rps_sampler.h"
34
35 #include <math.h>
36 #include <inttypes.h>
37
38 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
39
40 // TODO modify @brief in every file
41
42 // TODO check for overflows
43
44 // TODO align message structs
45
46 // TODO connect to friends
47
48 // TODO store peers somewhere persistent
49
50 // TODO blacklist? (-> mal peer detection on top of brahms)
51
52 // TODO API request_cancel
53
54 // hist_size_init, hist_size_max
55
56 /**
57  * Our configuration.
58  */
59 static const struct GNUNET_CONFIGURATION_Handle *cfg;
60
61 /**
62  * Our own identity.
63  */
64 static struct GNUNET_PeerIdentity own_identity;
65
66
67   struct GNUNET_PeerIdentity *
68 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
69                            const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
70
71
72 /***********************************************************************
73  * Housekeeping with peers
74 ***********************************************************************/
75
76 /**
77  * Struct used to store the context of a connected client.
78  */
79 struct ClientContext
80 {
81   /**
82    * The message queue to communicate with the client.
83    */
84   struct GNUNET_MQ_Handle *mq;
85 };
86
87 /**
88  * Used to keep track in what lists single peerIDs are.
89  */
90 enum PeerFlags
91 {
92   PULL_REPLY_PENDING   = 0x01,
93   IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
94   IN_OWN_SAMPLER_LIST  = 0x04, // unneeded?
95   IN_OWN_GOSSIP_LIST   = 0x08, // unneeded?
96
97   /**
98    * We set this bit when we can be sure the other peer is/was live.
99    */
100   VALID                = 0x10,
101
102   /**
103    * We set this bit when we are going to destroy the channel to this peer.
104    * When cleanup_channel is called, we know that we wanted to destroy it.
105    * Otherwise the channel to the other peer was destroyed.
106    */
107   TO_DESTROY           = 0x20,
108 };
109
110
111 /**
112  * Functions of this type can be used to be stored at a peer for later execution.
113  */
114 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
115
116 /**
117  * Outstanding operation on peer consisting of callback and closure
118  */
119 struct PeerOutstandingOp
120 {
121   /**
122    * Callback
123    */
124   PeerOp op;
125
126   /**
127    * Closure
128    */
129   void *op_cls;
130 };
131
132
133 /**
134  * Struct used to keep track of other peer's status
135  *
136  * This is stored in a multipeermap.
137  */
138 struct PeerContext
139 {
140   /**
141    * In own gossip/sampler list, in other's gossip/sampler list
142    */
143   uint32_t peer_flags;
144
145   /**
146    * Message queue open to client
147    */
148   struct GNUNET_MQ_Handle *mq;
149
150   /**
151    * Channel open to client.
152    */
153   struct GNUNET_CADET_Channel *send_channel;
154
155   /**
156    * Channel open from client.
157    */
158   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
159
160   /**
161    * Array of outstanding operations on this peer.
162    */
163   struct PeerOutstandingOp *outstanding_ops;
164
165   /**
166    * Number of outstanding operations.
167    */
168   unsigned int num_outstanding_ops;
169   //size_t num_outstanding_ops;
170
171   /**
172    * Handle to the callback given to cadet_ntfy_tmt_rdy()
173    *
174    * To be canceled on shutdown.
175    */
176   struct GNUNET_CADET_TransmitHandle *is_live_task;
177
178   /**
179    * Identity of the peer
180    */
181   struct GNUNET_PeerIdentity peer_id;
182
183   /**
184    * This is pobably followed by 'statistical' data (when we first saw
185    * him, how did we get his ID, how many pushes (in a timeinterval),
186    * ...)
187    */
188 };
189
190 /***********************************************************************
191  * /Housekeeping with peers
192 ***********************************************************************/
193
194
195
196
197
198 /***********************************************************************
199  * Globals
200 ***********************************************************************/
201
202 /**
203  * Sampler used for the Brahms protocol itself.
204  */
205 static struct RPS_Sampler *prot_sampler;
206
207 /**
208  * Sampler used for the clients.
209  */
210 static struct RPS_Sampler *client_sampler;
211
212 /**
213  * Set of all peers to keep track of them.
214  */
215 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
216
217
218 /**
219  * The gossiped list of peers.
220  */
221 static struct GNUNET_PeerIdentity *gossip_list;
222
223 /**
224  * Size of the gossiped list
225  */
226 //static unsigned int gossip_list_size;
227 static uint32_t gossip_list_size;
228
229 /**
230  * Name to log view (gossip_list) to
231  */
232 static char *file_name_view_log;
233
234
235 /**
236  * The size of sampler we need to be able to satisfy the client's need of
237  * random peers.
238  */
239 static unsigned int sampler_size_client_need;
240
241 /**
242  * The size of sampler we need to be able to satisfy the Brahms protocol's
243  * need of random peers.
244  *
245  * This is directly taken as the #gossip_list_size on update of the
246  * #gossip_list
247  *
248  * This is one minimum size the sampler grows to.
249  */
250 static unsigned int sampler_size_est_need;
251
252
253 /**
254  * Percentage of total peer number in the gossip list
255  * to send random PUSHes to
256  */
257 static float alpha;
258
259 /**
260  * Percentage of total peer number in the gossip list
261  * to send random PULLs to
262  */
263 static float beta;
264
265 /**
266  * The percentage gamma of history updates.
267  * Simply 1 - alpha - beta
268  */
269
270
271 /**
272  * Identifier for the main task that runs periodically.
273  */
274 static struct GNUNET_SCHEDULER_Task *do_round_task;
275
276 /**
277  * Time inverval the do_round task runs in.
278  */
279 static struct GNUNET_TIME_Relative round_interval;
280
281
282
283 /**
284  * List to store peers received through pushes temporary.
285  *
286  * TODO -> multipeermap
287  */
288 static struct GNUNET_PeerIdentity *push_list;
289
290 /**
291  * Size of the push_list;
292  */
293 static unsigned int push_list_size;
294 //size_t push_list_size;
295
296 /**
297  * List to store peers received through pulls temporary.
298  *
299  * TODO -> multipeermap
300  */
301 static struct GNUNET_PeerIdentity *pull_list;
302
303 /**
304  * Size of the pull_list;
305  */
306 static unsigned int pull_list_size;
307 //size_t pull_list_size;
308
309
310 /**
311  * Handler to NSE.
312  */
313 static struct GNUNET_NSE_Handle *nse;
314
315 /**
316  * Handler to CADET.
317  */
318 static struct GNUNET_CADET_Handle *cadet_handle;
319
320
321 /**
322  * Request counter.
323  *
324  * Only needed in the beginning to check how many of the 64 deltas
325  * we already have
326  */
327 static unsigned int req_counter;
328
329 /**
330  * Time of the last request we received.
331  *
332  * Used to compute the expected request rate.
333  */
334 static struct GNUNET_TIME_Absolute last_request;
335
336 /**
337  * Size of #request_deltas.
338  */
339 #define REQUEST_DELTAS_SIZE 64
340 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
341
342 /**
343  * Last 64 deltas between requests
344  */
345 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
346
347 /**
348  * The prediction of the rate of requests
349  */
350 static struct GNUNET_TIME_Relative  request_rate;
351
352
353 /**
354  * List with the peers we sent requests to.
355  */
356 struct GNUNET_PeerIdentity *pending_pull_reply_list;
357
358 /**
359  * Size of #pending_pull_reply_list.
360  */
361 uint32_t pending_pull_reply_list_size;
362
363
364 /**
365  * Number of history update tasks.
366  */
367 uint32_t num_hist_update_tasks;
368
369
370 /**
371  * Closure used to pass the client and the id to the callback
372  * that replies to a client's request
373  */
374 struct ReplyCls
375 {
376   /**
377    * The identifier of the request
378    */
379   uint32_t id;
380
381   /**
382    * The client handle to send the reply to
383    */
384   struct GNUNET_SERVER_Client *client;
385 };
386
387
388 #ifdef ENABLE_MALICIOUS
389 /**
390  * Type of malicious peer
391  *
392  * 0 Don't act malicious at all - Default
393  * 1 Try to maximise representation
394  * 2 Try to partition the network
395  * 3 Combined attack
396  */
397 uint32_t mal_type = 0;
398
399 /**
400  * Other malicious peers
401  */
402 static struct GNUNET_PeerIdentity *mal_peers = NULL;
403
404 /**
405  * Hashmap of malicious peers used as set.
406  * Used to more efficiently check whether we know that peer.
407  */
408 static struct GNUNET_CONTAINER_MultiPeerMap *mal_peer_set = NULL;
409
410 /**
411  * Number of other malicious peers
412  */
413 static uint32_t num_mal_peers = 0;
414
415
416 /**
417  * If type is 2 This struct is used to store the attacked peers in a DLL
418  */
419 struct AttackedPeer
420 {
421   /**
422    * DLL
423    */
424   struct AttackedPeer *next;
425   struct AttackedPeer *prev;
426
427   /**
428    * PeerID
429    */
430   struct GNUNET_PeerIdentity peer_id;
431 };
432
433 /**
434  * If type is 2 this is the DLL of attacked peers
435  */
436 static struct AttackedPeer *att_peers_head = NULL;
437 static struct AttackedPeer *att_peers_tail = NULL;
438
439 /**
440  * This index is used to point to an attacked peer to
441  * implement the round-robin-ish way to select attacked peers.
442  */
443 static struct AttackedPeer *att_peer_index = NULL;
444
445 /**
446  * Hashmap of attacked peers used as set.
447  * Used to more efficiently check whether we know that peer.
448  */
449 static struct GNUNET_CONTAINER_MultiPeerMap *att_peer_set = NULL;
450
451 /**
452  * Number of attacked peers
453  */
454 static uint32_t num_attacked_peers = 0;
455
456
457 /**
458  * If type is 1 this is the attacked peer
459  */
460 static struct GNUNET_PeerIdentity attacked_peer;
461
462 /**
463  * The limit of PUSHes we can send in one round.
464  * This is an assumption of the Brahms protocol and either implemented
465  * via proof of work
466  * or
467  * assumend to be the bandwidth limitation.
468  */
469 static uint32_t push_limit = 10000;
470 #endif /* ENABLE_MALICIOUS */
471
472
473 /***********************************************************************
474  * /Globals
475 ***********************************************************************/
476
477
478
479
480
481
482 /***********************************************************************
483  * Util functions
484 ***********************************************************************/
485
486 /**
487  * Set a peer flag of given peer context.
488  */
489 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
490
491 /**
492  * Get peer flag of given peer context.
493  */
494 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
495
496 /**
497  * Unset flag of given peer context.
498  */
499 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
500
501 /**
502  * Clean the send channel of a peer
503  */
504 void
505 peer_clean (const struct GNUNET_PeerIdentity *peer);
506
507
508 /**
509  * Check if peer is already in peer array.
510  */
511   int
512 in_arr (const struct GNUNET_PeerIdentity *array,
513         unsigned int arr_size,
514         const struct GNUNET_PeerIdentity *peer)
515 {
516   GNUNET_assert (NULL != peer);
517
518   if (0 == arr_size)
519     return GNUNET_NO;
520
521   GNUNET_assert (NULL != array);
522
523   unsigned int i;
524
525   for (i = 0; i < arr_size ; i++)
526     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
527       return GNUNET_YES;
528   return GNUNET_NO;
529 }
530
531
532 /**
533  * Print peerlist to log.
534  */
535 void
536 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
537 {
538   unsigned int i;
539
540   LOG (GNUNET_ERROR_TYPE_DEBUG,
541        "Printing peer list of length %u at %p:\n",
542        len,
543        list);
544   for (i = 0 ; i < len ; i++)
545   {
546     LOG (GNUNET_ERROR_TYPE_DEBUG,
547          "%u. peer: %s\n",
548          i, GNUNET_i2s (&list[i]));
549   }
550 }
551
552
553 /**
554  * Remove peer from list.
555  */
556   void
557 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
558                unsigned int *list_size,
559                const struct GNUNET_PeerIdentity *peer)
560 {
561   unsigned int i;
562   struct GNUNET_PeerIdentity *tmp;
563
564   tmp = *peer_list;
565
566   LOG (GNUNET_ERROR_TYPE_DEBUG,
567        "Removing peer %s from list at %p\n",
568        GNUNET_i2s (peer),
569        tmp);
570
571   for ( i = 0 ; i < *list_size ; i++ )
572   {
573     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
574     {
575       if (i < *list_size -1)
576       { /* Not at the last entry -- shift peers left */
577         memcpy (&tmp[i], &tmp[i +1],
578                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
579       }
580       /* Remove last entry (should be now useless PeerID) */
581       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
582     }
583   }
584   *peer_list = tmp;
585 }
586
587 /**
588  * Get random peer from the given list but don't return one from the @a ignore_list.
589  */
590   struct GNUNET_PeerIdentity *
591 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
592                            uint32_t list_size,
593                            const struct GNUNET_PeerIdentity *ignore_list,
594                            uint32_t ignore_size)
595 {
596   uint32_t r_index;
597   uint32_t tmp_size;
598   struct GNUNET_PeerIdentity *tmp_peer_list;
599   struct GNUNET_PeerIdentity *peer;
600
601   GNUNET_assert (NULL != peer_list);
602   if (0 == list_size)
603     return NULL;
604
605   tmp_size = 0;
606   tmp_peer_list = NULL;
607   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
608   memcpy (tmp_peer_list,
609           peer_list,
610           list_size * sizeof (struct GNUNET_PeerIdentity));
611   peer = GNUNET_new (struct GNUNET_PeerIdentity);
612
613   /**;
614    * Choose the r_index of the peer we want to return
615    * at random from the interval of the gossip list
616    */
617   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
618                                       tmp_size);
619   *peer = tmp_peer_list[r_index];
620
621   while (in_arr (ignore_list, ignore_size, peer))
622   {
623     rem_from_list (&tmp_peer_list, &tmp_size, peer);
624
625     print_peer_list (tmp_peer_list, tmp_size);
626
627     if (0 == tmp_size)
628     {
629       GNUNET_free (peer);
630       return NULL;
631     }
632
633     /**;
634      * Choose the r_index of the peer we want to return
635      * at random from the interval of the gossip list
636      */
637     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
638                                         tmp_size);
639     *peer = tmp_peer_list[r_index];
640   }
641
642
643   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
644
645   return peer;
646 }
647
648
649 /**
650  * Get the context of a peer. If not existing, create.
651  */
652   struct PeerContext *
653 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
654               const struct GNUNET_PeerIdentity *peer)
655 {
656   struct PeerContext *ctx;
657
658   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
659   {
660     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
661   }
662   else
663   {
664     ctx = GNUNET_new (struct PeerContext);
665     ctx->peer_flags = 0;
666     ctx->mq = NULL;
667     ctx->send_channel = NULL;
668     ctx->recv_channel = NULL;
669     ctx->outstanding_ops = NULL;
670     ctx->num_outstanding_ops = 0;
671     ctx->is_live_task = NULL;
672     ctx->peer_id = *peer;
673     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
674                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
675   }
676   return ctx;
677 }
678
679
680 /**
681  * Put random peer from sampler into the gossip list as history update.
682  */
683   void
684 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
685 {
686   GNUNET_assert (1 == num_peers);
687
688   if (gossip_list_size < sampler_size_est_need)
689   {
690     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
691     to_file (file_name_view_log,
692              "+%s\t(hist)",
693              GNUNET_i2s_full (ids));
694   }
695
696   if (0 < num_hist_update_tasks)
697     num_hist_update_tasks--;
698 }
699
700
701 /**
702  * Set the peer flag to living and call the outstanding operations on this peer.
703  */
704 static size_t
705 peer_is_live (struct PeerContext *peer_ctx)
706 {
707   struct GNUNET_PeerIdentity *peer;
708
709   /* Cancle is_live_task if still scheduled */
710   if (NULL != peer_ctx->is_live_task)
711   {
712     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
713     peer_ctx->is_live_task = NULL;
714   }
715
716   peer = &peer_ctx->peer_id;
717   set_peer_flag (peer_ctx, VALID);
718
719   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
720
721   if (0 < peer_ctx->num_outstanding_ops)
722   { /* Call outstanding operations */
723     unsigned int i;
724
725     for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
726       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
727     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
728   }
729
730   return 0;
731 }
732
733
734 /**
735  * Callback that is called when a channel was effectively established.
736  * This is given to ntfy_tmt_rdy and called when the channel was
737  * successfully established.
738  */
739 static size_t
740 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
741 {
742   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
743
744   peer_ctx->is_live_task = NULL;
745   LOG (GNUNET_ERROR_TYPE_DEBUG,
746        "Set ->is_live_task = NULL for peer %s\n",
747        GNUNET_i2s (&peer_ctx->peer_id));
748
749   if (NULL != buf
750       && 0 != size)
751   {
752     peer_is_live (peer_ctx);
753   }
754   else
755   {
756     LOG (GNUNET_ERROR_TYPE_WARNING,
757          "Problems establishing a connection to peer %s in order to check liveliness\n",
758          GNUNET_i2s (&peer_ctx->peer_id));
759     // TODO reschedule? cleanup?
760   }
761
762   //if (NULL != peer_ctx->is_live_task)
763   //{
764   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
765   //       "Trying to cancle is_live_task for peer %s\n",
766   //       GNUNET_i2s (&peer_ctx->peer_id));
767   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
768   //  peer_ctx->is_live_task = NULL;
769   //}
770
771   return 0;
772 }
773
774
775 /**
776  * Get the channel of a peer. If not existing, create.
777  */
778   struct GNUNET_CADET_Channel *
779 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
780              const struct GNUNET_PeerIdentity *peer)
781 {
782   struct PeerContext *peer_ctx;
783
784   peer_ctx = get_peer_ctx (peer_map, peer);
785
786   if (NULL == peer_ctx->send_channel)
787   {
788     LOG (GNUNET_ERROR_TYPE_DEBUG,
789          "Trying to establish channel to peer %s\n",
790          GNUNET_i2s (peer));
791
792     peer_ctx->send_channel =
793       GNUNET_CADET_channel_create (cadet_handle,
794                                    NULL,
795                                    peer,
796                                    GNUNET_RPS_CADET_PORT,
797                                    GNUNET_CADET_OPTION_RELIABLE);
798
799     // do I have to explicitly put it in the peer_map?
800     (void) GNUNET_CONTAINER_multipeermap_put
801       (peer_map,
802        peer,
803        peer_ctx,
804        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
805   }
806   return peer_ctx->send_channel;
807 }
808
809
810 /**
811  * Get the message queue of a specific peer.
812  *
813  * If we already have a message queue open to this client,
814  * simply return it, otherways create one.
815  */
816   struct GNUNET_MQ_Handle *
817 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
818         const struct GNUNET_PeerIdentity *peer_id)
819 {
820   struct PeerContext *peer_ctx;
821
822   peer_ctx = get_peer_ctx (peer_map, peer_id);
823
824   GNUNET_assert (NULL == peer_ctx->is_live_task);
825
826   if (NULL == peer_ctx->mq)
827   {
828     (void) get_channel (peer_map, peer_id);
829     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
830     //do I have to explicitly put it in the peer_map?
831     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
832                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
833   }
834   return peer_ctx->mq;
835 }
836
837
838 /**
839  * Issue check whether peer is live
840  *
841  * @param peer_ctx the context of the peer
842  */
843 void
844 check_peer_live (struct PeerContext *peer_ctx)
845 {
846   (void) get_channel (peer_map, &peer_ctx->peer_id);
847   LOG (GNUNET_ERROR_TYPE_DEBUG,
848        "Get informed about peer %s getting live\n",
849        GNUNET_i2s (&peer_ctx->peer_id));
850   if (NULL == peer_ctx->is_live_task)
851   {
852     peer_ctx->is_live_task =
853         GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
854                                             GNUNET_NO,
855                                             GNUNET_TIME_UNIT_FOREVER_REL,
856                                             sizeof (struct GNUNET_MessageHeader),
857                                             cadet_ntfy_tmt_rdy_cb,
858                                             peer_ctx);
859   }
860   else
861   {
862     LOG (GNUNET_ERROR_TYPE_DEBUG,
863          "Already waiting for notification\n");
864   }
865 }
866
867
868 /**
869  * Sum all time relatives of an array.
870   */
871   struct GNUNET_TIME_Relative
872 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
873 {
874   struct GNUNET_TIME_Relative sum;
875   uint32_t i;
876
877   sum = GNUNET_TIME_UNIT_ZERO;
878   for ( i = 0 ; i < arr_size ; i++ )
879   {
880     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
881   }
882   return sum;
883 }
884
885
886 /**
887  * Compute the average of given time relatives.
888  */
889   struct GNUNET_TIME_Relative
890 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
891 {
892   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
893 }
894
895
896 /**
897  * Insert PeerID in #pull_list
898  *
899  * Called once we know a peer is live.
900  */
901   void
902 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
903 {
904   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
905     GNUNET_array_append (pull_list, pull_list_size, *peer);
906
907   peer_clean (peer);
908 }
909
910 /**
911  * Check whether #insert_in_pull_list was already scheduled
912  */
913   int
914 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
915 {
916   unsigned int i;
917
918   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
919     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
920       return GNUNET_YES;
921   return GNUNET_NO;
922 }
923
924
925 /**
926  * Insert PeerID in #gossip_list
927  *
928  * Called once we know a peer is live.
929  */
930   void
931 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
932 {
933   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
934   {
935     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
936     to_file (file_name_view_log,
937              "+%s\t(ins in gossip list)",
938              GNUNET_i2s_full (peer));
939   }
940
941   (void) get_channel (peer_map, peer);
942 }
943
944 /**
945  * Check whether #insert_in_gossip_list was already scheduled
946  */
947   int
948 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
949 {
950   unsigned int i;
951
952   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
953     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
954       return GNUNET_YES;
955   return GNUNET_NO;
956 }
957
958
959 /**
960  * Update sampler with given PeerID.
961  */
962   void
963 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
964 {
965   LOG (GNUNET_ERROR_TYPE_DEBUG,
966        "Updating samplers with peer %s from insert_in_sampler()\n",
967        GNUNET_i2s (peer));
968   RPS_sampler_update (prot_sampler,   peer);
969   RPS_sampler_update (client_sampler, peer);
970 }
971
972
973 /**
974  * Check whether #insert_in_sampler was already scheduled
975  */
976 static int
977 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
978 {
979   unsigned int i;
980
981   for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
982     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
983       return GNUNET_YES;
984   return GNUNET_NO;
985 }
986
987
988 /**
989  * Wrapper around #RPS_sampler_resize()
990  *
991  * If we do not have enough sampler elements, double current sampler size
992  * If we have more than enough sampler elements, halv current sampler size
993  */
994 static void
995 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
996 {
997   unsigned int sampler_size;
998
999   // TODO statistics
1000   // TODO respect the min, max
1001   sampler_size = RPS_sampler_get_size (sampler);
1002   if (sampler_size > new_size * 4)
1003   { /* Shrinking */
1004     RPS_sampler_resize (sampler, sampler_size / 2);
1005   }
1006   else if (sampler_size < new_size)
1007   { /* Growing */
1008     RPS_sampler_resize (sampler, sampler_size * 2);
1009   }
1010   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
1011 }
1012
1013
1014 /**
1015  * Wrapper around #RPS_sampler_resize() resizing the client sampler
1016  */
1017 static void
1018 client_resize_wrapper ()
1019 {
1020   uint32_t bigger_size;
1021   unsigned int sampler_size;
1022
1023   // TODO statistics
1024
1025   sampler_size = RPS_sampler_get_size (client_sampler);
1026
1027   if (sampler_size_est_need > sampler_size_client_need)
1028     bigger_size = sampler_size_est_need;
1029   else
1030     bigger_size = sampler_size_client_need;
1031
1032   // TODO respect the min, max
1033   resize_wrapper (client_sampler, bigger_size);
1034   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
1035 }
1036
1037
1038 /**
1039  * Estimate request rate
1040  *
1041  * Called every time we receive a request from the client.
1042  */
1043   void
1044 est_request_rate()
1045 {
1046   struct GNUNET_TIME_Relative max_round_duration;
1047
1048   if (request_deltas_size > req_counter)
1049     req_counter++;
1050   if ( 1 < req_counter)
1051   {
1052     /* Shift last request deltas to the right */
1053     memcpy (&request_deltas[1],
1054         request_deltas,
1055         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
1056
1057     /* Add current delta to beginning */
1058     request_deltas[0] =
1059         GNUNET_TIME_absolute_get_difference (last_request,
1060                                              GNUNET_TIME_absolute_get ());
1061     request_rate = T_relative_avg (request_deltas, req_counter);
1062
1063     /* Compute the duration a round will maximally take */
1064     max_round_duration =
1065         GNUNET_TIME_relative_add (round_interval,
1066                                   GNUNET_TIME_relative_divide (round_interval, 2));
1067
1068     /* Set the estimated size the sampler has to have to
1069      * satisfy the current client request rate */
1070     sampler_size_client_need =
1071         max_round_duration.rel_value_us / request_rate.rel_value_us;
1072
1073     /* Resize the sampler */
1074     client_resize_wrapper ();
1075   }
1076   last_request = GNUNET_TIME_absolute_get ();
1077 }
1078
1079
1080 /**
1081  * Add all peers in @a peer_array to @a peer_map used as set.
1082  *
1083  * @param peer_array array containing the peers
1084  * @param num_peers number of peers in @peer_array
1085  * @param peer_map the peermap to use as set
1086  */
1087 static void
1088 add_peer_array_to_set (const struct GNUNET_PeerIdentity *peer_array,
1089                        unsigned int num_peers,
1090                        struct GNUNET_CONTAINER_MultiPeerMap *peer_map)
1091 {
1092   unsigned int i;
1093   if (NULL == peer_map)
1094     LOG (GNUNET_ERROR_TYPE_WARNING,
1095          "Trying to add peers to an empty peermap.\n");
1096     return;
1097
1098   for (i = 0 ; i < num_peers ; i++)
1099   {
1100     GNUNET_CONTAINER_multipeermap_put (peer_map,
1101                                        &peer_array[i],
1102                                        NULL,
1103                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1104   }
1105 }
1106
1107
1108 /**
1109  * Send a PULL REPLY to @a peer_id
1110  *
1111  * @param peer_id the peer to send the reply to.
1112  * @param peer_ids the peers to send to @a peer_id
1113  * @param num_peer_ids the number of peers to send to @a peer_id
1114  */
1115 static void
1116 send_pull_reply (const struct GNUNET_PeerIdentity *peer_id,
1117                  const struct GNUNET_PeerIdentity *peer_ids,
1118                  unsigned int num_peer_ids)
1119 {
1120   uint32_t send_size;
1121   struct GNUNET_MQ_Handle *mq;
1122   struct GNUNET_MQ_Envelope *ev;
1123   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1124
1125   /* Compute actual size */
1126   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1127               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
1128
1129   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1130     /* Compute number of peers to send
1131      * If too long, simply truncate */
1132     // TODO select random ones via permutation
1133     //      or even better: do good protocol design
1134     send_size =
1135       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1136        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1137        sizeof (struct GNUNET_PeerIdentity);
1138   else
1139     send_size = num_peer_ids;
1140
1141   LOG (GNUNET_ERROR_TYPE_DEBUG,
1142       "PULL REQUEST from peer %s received, going to send %u peers\n",
1143       GNUNET_i2s (peer_id), send_size);
1144
1145   mq = get_mq (peer_map, peer_id);
1146
1147   ev = GNUNET_MQ_msg_extra (out_msg,
1148                             send_size * sizeof (struct GNUNET_PeerIdentity),
1149                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1150   out_msg->num_peers = htonl (send_size);
1151   memcpy (&out_msg[1], peer_ids,
1152          send_size * sizeof (struct GNUNET_PeerIdentity));
1153
1154   GNUNET_MQ_send (mq, ev);
1155 }
1156
1157
1158 /**
1159  * This function is called on new peer_ids from 'external' sources
1160  * (client seed, cadet get_peers(), ...)
1161  *
1162  * @param peer_id the new peer_id
1163  */
1164 static void
1165 new_peer_id (const struct GNUNET_PeerIdentity *peer_id)
1166 {
1167   struct PeerOutstandingOp out_op;
1168   struct PeerContext *peer_ctx;
1169
1170   if (NULL != peer_id
1171       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer_id))
1172   {
1173     LOG (GNUNET_ERROR_TYPE_DEBUG,
1174         "Got peer_id %s (at %p, gossip_list_size: %u)\n",
1175         GNUNET_i2s (peer_id),
1176         peer_id,
1177         gossip_list_size);
1178
1179     peer_ctx = get_peer_ctx (peer_map, peer_id);
1180     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1181     {
1182       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1183       {
1184         out_op.op = insert_in_sampler;
1185         out_op.op_cls = NULL;
1186         GNUNET_array_append (peer_ctx->outstanding_ops,
1187                              peer_ctx->num_outstanding_ops,
1188                              out_op);
1189       }
1190
1191       if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1192       {
1193         out_op.op = insert_in_gossip_list;
1194         out_op.op_cls = NULL;
1195         GNUNET_array_append (peer_ctx->outstanding_ops,
1196                              peer_ctx->num_outstanding_ops,
1197                              out_op);
1198       }
1199
1200       /* Trigger livelyness test on peer */
1201       check_peer_live (peer_ctx);
1202     }
1203     // else...?
1204
1205     // send push/pull to each of those peers?
1206   }
1207 }
1208
1209
1210 /***********************************************************************
1211  * /Util functions
1212 ***********************************************************************/
1213
1214
1215
1216
1217
1218 /**
1219  * Function called by NSE.
1220  *
1221  * Updates sizes of sampler list and gossip list and adapt those lists
1222  * accordingly.
1223  */
1224   void
1225 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1226               double logestimate, double std_dev)
1227 {
1228   double estimate;
1229   //double scale; // TODO this might go gloabal/config
1230
1231   LOG (GNUNET_ERROR_TYPE_DEBUG,
1232        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1233        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1234   //scale = .01;
1235   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1236   // GNUNET_NSE_log_estimate_to_n (logestimate);
1237   estimate = pow (estimate, 1.0 / 3);
1238   // TODO add if std_dev is a number
1239   // estimate += (std_dev * scale);
1240   if (2 < ceil (estimate))
1241   {
1242     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1243     sampler_size_est_need = estimate;
1244   } else
1245     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1246
1247   /* If the NSE has changed adapt the lists accordingly */
1248   resize_wrapper (prot_sampler, sampler_size_est_need);
1249   client_resize_wrapper ();
1250 }
1251
1252
1253 /**
1254  * Callback called once the requested PeerIDs are ready.
1255  *
1256  * Sends those to the requesting client.
1257  */
1258 void client_respond (void *cls,
1259     struct GNUNET_PeerIdentity *peer_ids, uint32_t num_peers)
1260 {
1261   struct GNUNET_MQ_Envelope *ev;
1262   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1263   struct ReplyCls *reply_cls = (struct ReplyCls *) cls;
1264   uint32_t size_needed;
1265   struct ClientContext *cli_ctx;
1266
1267   LOG (GNUNET_ERROR_TYPE_DEBUG,
1268        "sampler returned %" PRIu32 " peers\n",
1269        num_peers);
1270
1271   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1272                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1273
1274   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1275
1276   ev = GNUNET_MQ_msg_extra (out_msg,
1277                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1278                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1279   out_msg->num_peers = htonl (num_peers);
1280   out_msg->id = htonl (reply_cls->id);
1281
1282   memcpy (&out_msg[1],
1283           peer_ids,
1284           num_peers * sizeof (struct GNUNET_PeerIdentity));
1285   GNUNET_free (peer_ids);
1286
1287   cli_ctx = GNUNET_SERVER_client_get_user_context (reply_cls->client, struct ClientContext);
1288   if (NULL == cli_ctx) {
1289     cli_ctx = GNUNET_new (struct ClientContext);
1290     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (reply_cls->client);
1291     GNUNET_SERVER_client_set_user_context (reply_cls->client, cli_ctx);
1292   }
1293
1294   GNUNET_free (reply_cls);
1295
1296   GNUNET_MQ_send (cli_ctx->mq, ev);
1297 }
1298
1299
1300 /**
1301  * Handle RPS request from the client.
1302  *
1303  * @param cls closure
1304  * @param client identification of the client
1305  * @param message the actual message
1306  */
1307 static void
1308 handle_client_request (void *cls,
1309                        struct GNUNET_SERVER_Client *client,
1310                        const struct GNUNET_MessageHeader *message)
1311 {
1312   struct GNUNET_RPS_CS_RequestMessage *msg;
1313   uint32_t num_peers;
1314   uint32_t size_needed;
1315   struct ReplyCls *reply_cls;
1316   uint32_t i;
1317
1318   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1319
1320   num_peers = ntohl (msg->num_peers);
1321   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1322                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1323
1324   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1325   {
1326     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1327     return;
1328   }
1329
1330   for (i = 0 ; i < num_peers ; i++)
1331     est_request_rate();
1332
1333   LOG (GNUNET_ERROR_TYPE_DEBUG,
1334        "Client requested %" PRIu32 " random peer(s).\n",
1335        num_peers);
1336
1337   reply_cls = GNUNET_new (struct ReplyCls);
1338   reply_cls->id = ntohl (msg->id);
1339   reply_cls->client = client;
1340
1341   RPS_sampler_get_n_rand_peers (client_sampler,
1342                                 client_respond,
1343                                 reply_cls,
1344                                 num_peers);
1345
1346   GNUNET_SERVER_receive_done (client,
1347                               GNUNET_OK);
1348 }
1349
1350
1351 /**
1352  * Handle seed from the client.
1353  *
1354  * @param cls closure
1355  * @param client identification of the client
1356  * @param message the actual message
1357  */
1358   static void
1359 handle_client_seed (void *cls,
1360                     struct GNUNET_SERVER_Client *client,
1361                     const struct GNUNET_MessageHeader *message)
1362 {
1363   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1364   struct GNUNET_PeerIdentity *peers;
1365   uint32_t num_peers;
1366   uint32_t i;
1367
1368   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1369   {
1370     GNUNET_break_op (0);
1371     GNUNET_SERVER_receive_done (client,
1372                                 GNUNET_SYSERR);
1373   }
1374
1375   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1376   num_peers = ntohl (in_msg->num_peers);
1377   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1378   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1379   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1380
1381   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1382       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1383   {
1384     GNUNET_break_op (0);
1385     GNUNET_SERVER_receive_done (client,
1386                                 GNUNET_SYSERR);
1387   }
1388
1389   LOG (GNUNET_ERROR_TYPE_DEBUG,
1390        "Client seeded peers:\n");
1391   print_peer_list (peers, num_peers);
1392
1393   for (i = 0 ; i < num_peers ; i++)
1394   {
1395     LOG (GNUNET_ERROR_TYPE_DEBUG,
1396          "Updating samplers with seed %" PRIu32 ": %s\n",
1397          i,
1398          GNUNET_i2s (&peers[i]));
1399
1400     new_peer_id (&peers[i]);
1401
1402     //RPS_sampler_update (prot_sampler,   &peers[i]);
1403     //RPS_sampler_update (client_sampler, &peers[i]);
1404   }
1405
1406   ////GNUNET_free (peers);
1407
1408   GNUNET_SERVER_receive_done (client,
1409                                                 GNUNET_OK);
1410 }
1411
1412
1413 /**
1414  * Handle a PUSH message from another peer.
1415  *
1416  * Check the proof of work and store the PeerID
1417  * in the temporary list for pushed PeerIDs.
1418  *
1419  * @param cls Closure
1420  * @param channel The channel the PUSH was received over
1421  * @param channel_ctx The context associated with this channel
1422  * @param msg The message header
1423  */
1424 static int
1425 handle_peer_push (void *cls,
1426     struct GNUNET_CADET_Channel *channel,
1427     void **channel_ctx,
1428     const struct GNUNET_MessageHeader *msg)
1429 {
1430   const struct GNUNET_PeerIdentity *peer;
1431
1432   // (check the proof of work)
1433
1434   peer = (const struct GNUNET_PeerIdentity *)
1435     GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1436   // FIXME wait for cadet to change this function
1437
1438   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1439
1440   #ifdef ENABLE_MALICIOUS
1441   struct AttackedPeer *tmp_att_peer;
1442
1443   tmp_att_peer = GNUNET_new (struct AttackedPeer);
1444   memcpy (&tmp_att_peer->peer_id, peer, sizeof (struct GNUNET_PeerIdentity));
1445   if (1 == mal_type
1446       || 3 == mal_type)
1447   { /* Try to maximise representation */
1448     if (NULL == att_peer_set)
1449       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
1450     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1451                                                              peer))
1452     {
1453       GNUNET_CONTAINER_DLL_insert (att_peers_head,
1454                                    att_peers_tail,
1455                                    tmp_att_peer);
1456       add_peer_array_to_set (peer, 1, att_peer_set);
1457     }
1458     return GNUNET_OK;
1459   }
1460
1461
1462   else if (2 == mal_type)
1463   { /* We attack one single well-known peer - simply ignore */
1464     return GNUNET_OK;
1465   }
1466   else
1467   {
1468     GNUNET_free (tmp_att_peer);
1469   }
1470
1471   #endif /* ENABLE_MALICIOUS */
1472
1473   /* Add the sending peer to the push_list */
1474   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1475     GNUNET_array_append (push_list, push_list_size, *peer);
1476
1477   return GNUNET_OK;
1478 }
1479
1480
1481 /**
1482  * Handle PULL REQUEST request message from another peer.
1483  *
1484  * Reply with the gossip list of PeerIDs.
1485  *
1486  * @param cls Closure
1487  * @param channel The channel the PUSH was received over
1488  * @param channel_ctx The context associated with this channel
1489  * @param msg The message header
1490  */
1491 static int
1492 handle_peer_pull_request (void *cls,
1493     struct GNUNET_CADET_Channel *channel,
1494     void **channel_ctx,
1495     const struct GNUNET_MessageHeader *msg)
1496 {
1497   struct GNUNET_PeerIdentity *peer;
1498
1499   peer = (struct GNUNET_PeerIdentity *)
1500     GNUNET_CADET_channel_get_info (channel,
1501                                    GNUNET_CADET_OPTION_PEER);
1502   // FIXME wait for cadet to change this function
1503
1504   #ifdef ENABLE_MALICIOUS
1505   if (1 == mal_type
1506       || 3 == mal_type)
1507   { /* Try to maximise representation */
1508     send_pull_reply (peer, mal_peers, num_mal_peers);
1509     return GNUNET_OK;
1510   }
1511
1512   else if (2 == mal_type)
1513   { /* Try to partition network */
1514     if (GNUNET_YES == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
1515     {
1516       send_pull_reply (peer, mal_peers, num_mal_peers);
1517     }
1518     return GNUNET_OK;
1519   }
1520   #endif /* ENABLE_MALICIOUS */
1521
1522   send_pull_reply (peer, gossip_list, gossip_list_size);
1523
1524   return GNUNET_OK;
1525 }
1526
1527
1528 /**
1529  * Handle PULL REPLY message from another peer.
1530  *
1531  * Check whether we sent a corresponding request and
1532  * whether this reply is the first one.
1533  *
1534  * @param cls Closure
1535  * @param channel The channel the PUSH was received over
1536  * @param channel_ctx The context associated with this channel
1537  * @param msg The message header
1538  */
1539   static int
1540 handle_peer_pull_reply (void *cls,
1541                         struct GNUNET_CADET_Channel *channel,
1542                         void **channel_ctx,
1543                         const struct GNUNET_MessageHeader *msg)
1544 {
1545   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1546   struct GNUNET_PeerIdentity *peers;
1547   struct PeerContext *peer_ctx;
1548   struct GNUNET_PeerIdentity *sender;
1549   struct PeerContext *sender_ctx;
1550   struct PeerOutstandingOp out_op;
1551   uint32_t i;
1552 #ifdef ENABLE_MALICIOUS
1553   struct AttackedPeer *tmp_att_peer;
1554 #endif /* ENABLE_MALICIOUS */
1555
1556   /* Check for protocol violation */
1557   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1558   {
1559     GNUNET_break_op (0);
1560     return GNUNET_SYSERR;
1561   }
1562
1563   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1564   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1565       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1566   {
1567     LOG (GNUNET_ERROR_TYPE_ERROR,
1568         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1569         ntohl (in_msg->num_peers),
1570         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1571             sizeof (struct GNUNET_PeerIdentity));
1572     GNUNET_break_op (0);
1573     return GNUNET_SYSERR;
1574   }
1575
1576   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1577       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1578        // Guess simply casting isn't the nicest way...
1579        // FIXME wait for cadet to change this function
1580   sender_ctx = get_peer_ctx (peer_map, sender);
1581
1582   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1583   {
1584     GNUNET_break_op (0);
1585     return GNUNET_OK;
1586   }
1587
1588
1589   #ifdef ENABLE_MALICIOUS
1590   // We shouldn't even receive pull replies as we're not sending
1591   if (2 == mal_type)
1592     return GNUNET_OK;
1593   #endif /* ENABLE_MALICIOUS */
1594
1595   /* Do actual logic */
1596   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1597
1598   LOG (GNUNET_ERROR_TYPE_DEBUG,
1599        "PULL REPLY received, got following peers:\n");
1600
1601   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1602   {
1603     LOG (GNUNET_ERROR_TYPE_DEBUG,
1604          "%u. %s\n",
1605          i,
1606          GNUNET_i2s (&peers[i]));
1607
1608     #ifdef ENABLE_MALICIOUS
1609     if (1 == mal_type
1610         || 3 == mal_type)
1611     { /* Add attacked peer to local list */
1612       // TODO check if we sent a request and this was the first reply
1613       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1614                                                                &peers[i])
1615           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
1616                                                                   &peers[i])
1617           && GNUNET_NO == GNUNET_CRYPTO_cmp_peer_identity (&peers[i],
1618                                                            &own_identity))
1619       {
1620         tmp_att_peer = GNUNET_new (struct AttackedPeer);
1621         tmp_att_peer->peer_id = peers[i];
1622         GNUNET_CONTAINER_DLL_insert (att_peers_head,
1623                                      att_peers_tail,
1624                                      tmp_att_peer);
1625         add_peer_array_to_set (&peers[i], 1, att_peer_set);
1626       }
1627       continue;
1628     }
1629     #endif /* ENABLE_MALICIOUS */
1630     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1631     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1632         || NULL != peer_ctx->send_channel
1633         || NULL != peer_ctx->recv_channel)
1634     {
1635       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1636           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1637         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1638     }
1639     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1640     {
1641       out_op.op = insert_in_pull_list;
1642       out_op.op_cls = NULL;
1643       GNUNET_array_append (peer_ctx->outstanding_ops,
1644                            peer_ctx->num_outstanding_ops,
1645                            out_op);
1646       check_peer_live (peer_ctx);
1647     }
1648   }
1649
1650   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1651   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1652
1653   return GNUNET_OK;
1654 }
1655
1656
1657 /**
1658  * Compute a random delay.
1659  * A uniformly distributed value between mean + spread and mean - spread.
1660  *
1661  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1662  * It would return a random value between 2 and 6 min.
1663  *
1664  * @param mean the mean
1665  * @param spread the inverse amount of deviation from the mean
1666  */
1667 static struct GNUNET_TIME_Relative
1668 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1669 {
1670   struct GNUNET_TIME_Relative half_interval;
1671   struct GNUNET_TIME_Relative ret;
1672   unsigned int rand_delay;
1673   unsigned int max_rand_delay;
1674
1675   if (0 == spread)
1676   {
1677     LOG (GNUNET_ERROR_TYPE_WARNING,
1678          "Not accepting spread of 0\n");
1679     GNUNET_break (0);
1680   }
1681
1682   /* Compute random time value between spread * mean and spread * mean */
1683   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1684
1685   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1686   /**
1687    * Compute random value between (0 and 1) * round_interval
1688    * via multiplying round_interval with a 'fraction' (0 to value)/value
1689    */
1690   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1691   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1692   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1693   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1694
1695   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1696     LOG (GNUNET_ERROR_TYPE_WARNING,
1697          "Returning FOREVER_REL\n");
1698
1699   return ret;
1700 }
1701
1702
1703 /**
1704  * Send single pull request
1705  *
1706  * @param peer_id the peer to send the pull request to.
1707  */
1708 static void
1709 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1710 {
1711   struct GNUNET_MQ_Envelope *ev;
1712   struct GNUNET_MQ_Handle *mq;
1713
1714   LOG (GNUNET_ERROR_TYPE_DEBUG,
1715        "Sending PULL request to peer %s of gossiped list.\n",
1716        GNUNET_i2s (peer_id));
1717
1718   GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer_id);
1719
1720   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1721   mq = get_mq (peer_map, peer_id);
1722   GNUNET_MQ_send (mq, ev);
1723 }
1724
1725
1726 /**
1727  * Send single push
1728  *
1729  * @param peer_id the peer to send the push to.
1730  */
1731 static void
1732 send_push (struct GNUNET_PeerIdentity *peer_id)
1733 {
1734   struct GNUNET_MQ_Envelope *ev;
1735   struct GNUNET_MQ_Handle *mq;
1736
1737   LOG (GNUNET_ERROR_TYPE_DEBUG,
1738        "Sending PUSH to peer %s of gossiped list.\n",
1739        GNUNET_i2s (peer_id));
1740
1741   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1742   mq = get_mq (peer_map, peer_id);
1743   GNUNET_MQ_send (mq, ev);
1744 }
1745
1746
1747 static void
1748 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1749
1750 static void
1751 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1752
1753
1754 #ifdef ENABLE_MALICIOUS
1755 /**
1756  * Turn RPS service to act malicious.
1757  *
1758  * @param cls Closure
1759  * @param channel The channel the PUSH was received over
1760  * @param channel_ctx The context associated with this channel
1761  * @param msg The message header
1762  */
1763   static void
1764 handle_client_act_malicious (void *cls,
1765                              struct GNUNET_SERVER_Client *client,
1766                              const struct GNUNET_MessageHeader *msg)
1767 {
1768   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1769   struct GNUNET_PeerIdentity *peers;
1770   uint32_t num_mal_peers_sent;
1771   uint32_t num_mal_peers_old;
1772
1773   /* Check for protocol violation */
1774   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1775   {
1776     GNUNET_break_op (0);
1777   }
1778
1779   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1780   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1781       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1782   {
1783     LOG (GNUNET_ERROR_TYPE_ERROR,
1784         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1785         ntohl (in_msg->num_peers),
1786         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1787             sizeof (struct GNUNET_PeerIdentity));
1788     GNUNET_break_op (0);
1789   }
1790
1791
1792   /* Do actual logic */
1793   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1794   mal_type = ntohl (in_msg->type);
1795
1796   LOG (GNUNET_ERROR_TYPE_DEBUG,
1797        "Now acting malicious type %" PRIu32 "\n",
1798        mal_type);
1799
1800   if (1 == mal_type)
1801   { /* Try to maximise representation */
1802     /* Add other malicious peers to those we already know */
1803
1804     num_mal_peers_sent = ntohl (in_msg->num_peers);
1805     num_mal_peers_old = num_mal_peers;
1806     GNUNET_array_grow (mal_peers,
1807                        num_mal_peers,
1808                        num_mal_peers + num_mal_peers_sent);
1809     memcpy (&mal_peers[num_mal_peers_old],
1810             peers,
1811             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1812
1813     /* Add all mal peers to mal_peer_set */
1814     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
1815                            num_mal_peers_sent,
1816                            mal_peer_set);
1817
1818     /* Substitute do_round () with do_mal_round () */
1819     GNUNET_SCHEDULER_cancel (do_round_task);
1820     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1821   }
1822
1823   else if (2 == mal_type
1824            || 3 == mal_type)
1825   { /* Try to partition the network */
1826     /* Add other malicious peers to those we already know */
1827     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
1828     num_mal_peers_old = num_mal_peers;
1829     GNUNET_array_grow (mal_peers,
1830                        num_mal_peers,
1831                        num_mal_peers + num_mal_peers_sent);
1832     memcpy (&mal_peers[num_mal_peers_old],
1833             peers,
1834             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1835
1836     /* Add all mal peers to mal_peer_set */
1837     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
1838                            num_mal_peers_sent,
1839                            mal_peer_set);
1840
1841     /* Store the one attacked peer */
1842     memcpy (&attacked_peer,
1843             &in_msg->attacked_peer,
1844             sizeof (struct GNUNET_PeerIdentity));
1845
1846     LOG (GNUNET_ERROR_TYPE_DEBUG,
1847          "Attacked peer is %s\n",
1848          GNUNET_i2s (&attacked_peer));
1849
1850     /* Substitute do_round () with do_mal_round () */
1851     GNUNET_SCHEDULER_cancel (do_round_task);
1852     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1853   }
1854   else if (0 == mal_type)
1855   { /* Stop acting malicious */
1856     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
1857
1858     /* Substitute do_mal_round () with do_round () */
1859     GNUNET_SCHEDULER_cancel (do_round_task);
1860     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1861   }
1862   else
1863   {
1864     GNUNET_break (0);
1865   }
1866
1867   GNUNET_SERVER_receive_done (client,   GNUNET_OK);
1868 }
1869
1870
1871 /**
1872  * Send out PUSHes and PULLs maliciously.
1873  *
1874  * This is executed regylary.
1875  */
1876 static void
1877 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1878 {
1879   uint32_t num_pushes;
1880   uint32_t i;
1881   struct GNUNET_TIME_Relative time_next_round;
1882   struct AttackedPeer *tmp_att_peer;
1883
1884   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously.\n");
1885
1886   /* Do malicious actions */
1887   if (1 == mal_type)
1888   { /* Try to maximise representation */
1889
1890     /* The maximum of pushes we're going to send this round */
1891     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
1892                                          num_attacked_peers),
1893                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1894
1895     LOG (GNUNET_ERROR_TYPE_DEBUG,
1896          "Going to send %" PRIu32 " pushes\n",
1897          num_pushes);
1898
1899     /* Send PUSHes to attacked peers */
1900     for (i = 0 ; i < num_pushes ; i++)
1901     {
1902       if (att_peers_tail == att_peer_index)
1903         att_peer_index = att_peers_head;
1904       else
1905         att_peer_index = att_peer_index->next;
1906
1907       send_push (&att_peer_index->peer_id);
1908     }
1909
1910     /* Send PULLs to some peers to learn about additional peers to attack */
1911     tmp_att_peer = att_peer_index;
1912     for (i = 0 ; i < num_pushes * alpha ; i++)
1913     {
1914       if (att_peers_tail == tmp_att_peer)
1915         tmp_att_peer = att_peers_head;
1916       else
1917         att_peer_index = tmp_att_peer->next;
1918
1919       send_pull_request (&tmp_att_peer->peer_id);
1920     }
1921   }
1922
1923
1924   else if (2 == mal_type)
1925   { /**
1926      * Try to partition the network
1927      * Send as many pushes to the attacked peer as possible
1928      * That is one push per round as it will ignore more.
1929      */
1930       send_push (&attacked_peer);
1931   }
1932
1933
1934   if (3 == mal_type)
1935   { /* Combined attack */
1936
1937     /* The maximum of pushes we're going to send this round */
1938     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
1939                                          num_attacked_peers),
1940                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1941
1942     LOG (GNUNET_ERROR_TYPE_DEBUG,
1943          "Going to send %" PRIu32 " pushes\n",
1944          num_pushes);
1945
1946     /* Send PUSHes to attacked peers */
1947     send_push (&attacked_peer);
1948
1949     for (i = 0 ; i < num_pushes ; i++)
1950     {
1951       if (att_peers_tail == att_peer_index)
1952         att_peer_index = att_peers_head;
1953       else
1954         att_peer_index = att_peer_index->next;
1955
1956       send_push (&att_peer_index->peer_id);
1957     }
1958
1959     /* Send PULLs to some peers to learn about additional peers to attack */
1960     tmp_att_peer = att_peer_index;
1961     for (i = 0 ; i < num_pushes * alpha ; i++)
1962     {
1963       if (att_peers_tail == tmp_att_peer)
1964         tmp_att_peer = att_peers_head;
1965       else
1966         att_peer_index = tmp_att_peer->next;
1967
1968       send_pull_request (&tmp_att_peer->peer_id);
1969     }
1970   }
1971
1972   /* Schedule next round */
1973   time_next_round = compute_rand_delay (round_interval, 2);
1974
1975   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
1976   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
1977   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1978 }
1979 #endif /* ENABLE_MALICIOUS */
1980
1981
1982 /**
1983  * Send out PUSHes and PULLs, possibly update #gossip_list, samplers.
1984  *
1985  * This is executed regylary.
1986  */
1987 static void
1988 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1989 {
1990   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
1991
1992   uint32_t i;
1993   unsigned int *permut;
1994   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1995   struct GNUNET_PeerIdentity peer;
1996   struct GNUNET_PeerIdentity *tmp_peer;
1997
1998   LOG (GNUNET_ERROR_TYPE_DEBUG,
1999        "Printing gossip list:\n");
2000   for (i = 0 ; i < gossip_list_size ; i++)
2001   {
2002     LOG (GNUNET_ERROR_TYPE_DEBUG,
2003          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
2004     to_file (file_name_view_log,
2005              "=%s\t(do round)",
2006              GNUNET_i2s_full (&gossip_list[i]));
2007   }
2008   // TODO log lists, ...
2009
2010   /* Would it make sense to have one shuffeled gossip list and then
2011    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
2012    * use the rest to update sampler?
2013    * in essence get random peers with consumption */
2014
2015   /* Send PUSHes */
2016   if (0 < gossip_list_size)
2017   {
2018     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2019                                            (unsigned int) gossip_list_size);
2020     n_peers = ceil (alpha * gossip_list_size);
2021     LOG (GNUNET_ERROR_TYPE_DEBUG,
2022          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
2023          n_peers, alpha, gossip_list_size);
2024     for (i = 0 ; i < n_peers ; i++)
2025     {
2026       peer = gossip_list[permut[i]];
2027       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
2028       { // FIXME if this fails schedule/loop this for later
2029         send_push (&peer);
2030       }
2031     }
2032     GNUNET_free (permut);
2033   }
2034
2035
2036   /* Send PULL requests */
2037   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
2038   n_peers = ceil (beta * gossip_list_size);
2039   LOG (GNUNET_ERROR_TYPE_DEBUG,
2040        "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
2041        n_peers, beta, gossip_list_size);
2042   for (i = 0 ; i < n_peers ; i++)
2043   {
2044     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
2045         pending_pull_reply_list, pending_pull_reply_list_size);
2046     if (NULL != tmp_peer)
2047     {
2048       peer = *tmp_peer;
2049       GNUNET_free (tmp_peer);
2050
2051       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
2052       {
2053         send_pull_request (&peer);
2054       }
2055     }
2056   }
2057
2058
2059   /* Update gossip list */
2060   /* TODO see how many peers are in push-/pull- list! */
2061
2062   if (push_list_size <= alpha * gossip_list_size
2063       && push_list_size > 0
2064       && pull_list_size > 0)
2065   {
2066     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
2067
2068     uint32_t first_border;
2069     uint32_t second_border;
2070     uint32_t r_index;
2071     uint32_t peers_to_clean_size;
2072     struct GNUNET_PeerIdentity *peers_to_clean;
2073
2074     peers_to_clean = NULL;
2075     peers_to_clean_size = 0;
2076     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
2077     memcpy (peers_to_clean,
2078             gossip_list,
2079             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
2080
2081     first_border  =                ceil (alpha * sampler_size_est_need);
2082     second_border = first_border + ceil (beta  * sampler_size_est_need);
2083
2084     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
2085
2086     to_file (file_name_view_log,
2087              "--- emptied ---");
2088
2089     for (i = 0 ; i < first_border ; i++)
2090     {/* Update gossip list with peers received through PUSHes */
2091       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
2092                                           push_list_size);
2093       gossip_list[i] = push_list[r_index];
2094       to_file (file_name_view_log,
2095                "+%s't(push list)",
2096                GNUNET_i2s_full (&gossip_list[i]));
2097       // TODO change the peer_flags accordingly
2098     }
2099
2100     for (i = first_border ; i < second_border ; i++)
2101     {/* Update gossip list with peers received through PULLs */
2102       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
2103                                           pull_list_size);
2104       gossip_list[i] = pull_list[r_index];
2105       to_file (file_name_view_log,
2106                "+%s\t(pull list)",
2107                GNUNET_i2s_full (&gossip_list[i]));
2108       // TODO change the peer_flags accordingly
2109     }
2110
2111     for (i = second_border ; i < sampler_size_est_need ; i++)
2112     {/* Update gossip list with peers from history */
2113       RPS_sampler_get_n_rand_peers (prot_sampler,
2114                                     hist_update,
2115                                     NULL,
2116                                     1);
2117       num_hist_update_tasks++;
2118       // TODO change the peer_flags accordingly
2119     }
2120
2121     for (i = 0 ; i < gossip_list_size ; i++)
2122       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
2123
2124     for (i = 0 ; i < peers_to_clean_size ; i++)
2125     {
2126       peer_clean (&peers_to_clean[i]);
2127       /* to_file (file_name_view_log,
2128                "-%s",
2129                GNUNET_i2s_full (&peers_to_clean[i])); */
2130     }
2131
2132     GNUNET_free (peers_to_clean);
2133   }
2134   else
2135   {
2136     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
2137   }
2138   // TODO independent of that also get some peers from CADET_get_peers()?
2139
2140   LOG (GNUNET_ERROR_TYPE_DEBUG,
2141        "Received %u pushes and %u pulls last round (alpha (%.2f) * gossip_list_size (%u) = %.2f)\n",
2142        push_list_size,
2143        pull_list_size,
2144        alpha,
2145        gossip_list_size,
2146        alpha * gossip_list_size);
2147
2148   /* Update samplers */
2149   for ( i = 0 ; i < push_list_size ; i++ )
2150   {
2151     LOG (GNUNET_ERROR_TYPE_DEBUG,
2152          "Updating with peer %s from push list\n",
2153          GNUNET_i2s (&push_list[i]));
2154     RPS_sampler_update (prot_sampler,   &push_list[i]);
2155     RPS_sampler_update (client_sampler, &push_list[i]);
2156     // TODO set in_flag?
2157   }
2158
2159   for ( i = 0 ; i < pull_list_size ; i++ )
2160   {
2161     LOG (GNUNET_ERROR_TYPE_DEBUG,
2162          "Updating with peer %s from pull list\n",
2163          GNUNET_i2s (&pull_list[i]));
2164     RPS_sampler_update (prot_sampler,   &pull_list[i]);
2165     RPS_sampler_update (client_sampler, &pull_list[i]);
2166     // TODO set in_flag?
2167   }
2168
2169
2170   /* Empty push/pull lists */
2171   GNUNET_array_grow (push_list, push_list_size, 0);
2172   GNUNET_array_grow (pull_list, pull_list_size, 0);
2173
2174   struct GNUNET_TIME_Relative time_next_round;
2175
2176   time_next_round = compute_rand_delay (round_interval, 2);
2177
2178   /* Schedule next round */
2179   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
2180   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
2181   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2182 }
2183
2184
2185 static void
2186 rps_start (struct GNUNET_SERVER_Handle *server);
2187
2188
2189 /**
2190  * This is called from GNUNET_CADET_get_peers().
2191  *
2192  * It is called on every peer(ID) that cadet somehow has contact with.
2193  * We use those to initialise the sampler.
2194  */
2195 void
2196 init_peer_cb (void *cls,
2197               const struct GNUNET_PeerIdentity *peer,
2198               int tunnel, // "Do we have a tunnel towards this peer?"
2199               unsigned int n_paths, // "Number of known paths towards this peer"
2200               unsigned int best_path) // "How long is the best path?
2201                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
2202 {
2203   if (NULL != peer)
2204   {
2205     LOG (GNUNET_ERROR_TYPE_DEBUG,
2206          "Got peer_id %s from cadet\n",
2207          GNUNET_i2s (peer));
2208     new_peer_id (peer);
2209   }
2210 }
2211
2212
2213 /**
2214  * Clean the send channel of a peer
2215  */
2216 void
2217 peer_clean (const struct GNUNET_PeerIdentity *peer)
2218 {
2219   struct PeerContext *peer_ctx;
2220   struct GNUNET_CADET_Channel *channel;
2221
2222   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
2223       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2224   {
2225     peer_ctx = get_peer_ctx (peer_map, peer);
2226     if (NULL != peer_ctx->send_channel)
2227     {
2228       channel = peer_ctx->send_channel;
2229       peer_ctx->send_channel = NULL;
2230       GNUNET_CADET_channel_destroy (channel);
2231     }
2232   }
2233 }
2234
2235
2236 /**
2237  * Callback used to remove peers from the multipeermap.
2238  */
2239   int
2240 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
2241 {
2242   struct PeerContext *peer_ctx;
2243   const struct GNUNET_CADET_Channel *channel =
2244     (const struct GNUNET_CADET_Channel *) cls;
2245   struct GNUNET_CADET_Channel *recv;
2246   struct GNUNET_CADET_Channel *send;
2247
2248   peer_ctx = (struct PeerContext *) value;
2249
2250   LOG (GNUNET_ERROR_TYPE_DEBUG,
2251        "Going to clean peer %s\n",
2252        GNUNET_i2s (&peer_ctx->peer_id));
2253
2254   /* If operations are still scheduled for this peer cancel those */
2255   if (0 != peer_ctx->num_outstanding_ops)
2256     GNUNET_array_grow (peer_ctx->outstanding_ops,
2257                        peer_ctx->num_outstanding_ops,
2258                        0);
2259
2260   /* If we are still waiting for notification whether this peer is live 
2261    * cancel the according task */
2262   if (NULL != peer_ctx->is_live_task)
2263   {
2264   LOG (GNUNET_ERROR_TYPE_DEBUG,
2265        "Trying to cancle is_live_task for peer %s\n",
2266        GNUNET_i2s (key));
2267     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
2268     peer_ctx->is_live_task = NULL;
2269   }
2270
2271
2272   recv = peer_ctx->recv_channel;
2273   peer_ctx->recv_channel = NULL;
2274   if (NULL != recv
2275       && channel != recv)
2276   {
2277     GNUNET_CADET_channel_destroy (recv);
2278   }
2279
2280   /* If there is still a mq destroy it */
2281   if (NULL != peer_ctx->mq)
2282   {
2283     GNUNET_MQ_destroy (peer_ctx->mq);
2284     peer_ctx->mq = NULL;
2285   }
2286
2287   /* Remove the send_channel
2288    * The peer map entry should be removed
2289    * from the callback #cleanup_channel */
2290   send = peer_ctx->send_channel;
2291   peer_ctx->send_channel = NULL;
2292   if (NULL != send
2293       && channel != send)
2294   {
2295     set_peer_flag (peer_ctx, TO_DESTROY);
2296     GNUNET_CADET_channel_destroy (send);
2297   }
2298   else
2299   { /* If there is no channel we have to remove it now */
2300     if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2301       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
2302     else
2303       GNUNET_free (peer_ctx);
2304   }
2305
2306   return GNUNET_YES;
2307 }
2308
2309
2310 /**
2311  * Task run during shutdown.
2312  *
2313  * @param cls unused
2314  * @param tc unused
2315  */
2316 static void
2317 shutdown_task (void *cls,
2318                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2319 {
2320
2321   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
2322
2323   if (NULL != do_round_task)
2324   {
2325     GNUNET_SCHEDULER_cancel (do_round_task);
2326     do_round_task = NULL;
2327   }
2328
2329
2330   {
2331   if (GNUNET_SYSERR ==
2332         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
2333     LOG (GNUNET_ERROR_TYPE_WARNING,
2334         "Iterating over peers to disconnect from them was cancelled\n");
2335   }
2336
2337   GNUNET_NSE_disconnect (nse);
2338   RPS_sampler_destroy (prot_sampler);
2339   RPS_sampler_destroy (client_sampler);
2340   LOG (GNUNET_ERROR_TYPE_DEBUG,
2341        "Size of the peermap: %u\n",
2342        GNUNET_CONTAINER_multipeermap_size (peer_map));
2343   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2344   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2345   GNUNET_CADET_disconnect (cadet_handle);
2346   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
2347   GNUNET_array_grow (push_list, push_list_size, 0);
2348   GNUNET_array_grow (pull_list, pull_list_size, 0);
2349   #ifdef ENABLE_MALICIOUS
2350   struct AttackedPeer *tmp_att_peer;
2351   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2352   if (NULL != mal_peer_set)
2353     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
2354   if (NULL != att_peer_set)
2355     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
2356   while (NULL != att_peers_head)
2357   {
2358     tmp_att_peer = att_peers_head;
2359     GNUNET_CONTAINER_DLL_remove (att_peers_head, att_peers_tail, tmp_att_peer);
2360   }
2361   #endif /* ENABLE_MALICIOUS */
2362 }
2363
2364
2365 /**
2366  * A client disconnected.  Remove all of its data structure entries.
2367  *
2368  * @param cls closure, NULL
2369  * @param client identification of the client
2370  */
2371 static void
2372 handle_client_disconnect (void *cls,
2373                           struct GNUNET_SERVER_Client * client)
2374 {
2375 }
2376
2377
2378 /**
2379  * Handle the channel a peer opens to us.
2380  *
2381  * @param cls The closure
2382  * @param channel The channel the peer wants to establish
2383  * @param initiator The peer's peer ID
2384  * @param port The port the channel is being established over
2385  * @param options Further options
2386  */
2387   static void *
2388 handle_inbound_channel (void *cls,
2389                         struct GNUNET_CADET_Channel *channel,
2390                         const struct GNUNET_PeerIdentity *initiator,
2391                         uint32_t port,
2392                         enum GNUNET_CADET_ChannelOption options)
2393 {
2394   struct PeerContext *peer_ctx;
2395   struct GNUNET_PeerIdentity peer;
2396
2397   peer = *initiator;
2398   LOG (GNUNET_ERROR_TYPE_DEBUG,
2399       "New channel was established to us (Peer %s).\n",
2400       GNUNET_i2s (&peer));
2401
2402   GNUNET_assert (NULL != channel);
2403
2404   // we might not even store the recv_channel
2405
2406   peer_ctx = get_peer_ctx (peer_map, &peer);
2407   // FIXME what do we do if a channel is established twice?
2408   //       overwrite? Clean old channel? ...?
2409   //if (NULL != peer_ctx->recv_channel)
2410   //{
2411   //  peer_ctx->recv_channel = channel;
2412   //}
2413   peer_ctx->recv_channel = channel;
2414
2415   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
2416       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
2417
2418   peer_is_live (peer_ctx);
2419
2420   return NULL; // TODO
2421 }
2422
2423
2424 /**
2425  * This is called when a remote peer destroys a channel.
2426  *
2427  * @param cls The closure
2428  * @param channel The channel being closed
2429  * @param channel_ctx The context associated with this channel
2430  */
2431   static void
2432 cleanup_channel (void *cls,
2433                 const struct GNUNET_CADET_Channel *channel,
2434                 void *channel_ctx)
2435 {
2436   struct GNUNET_PeerIdentity *peer;
2437   struct PeerContext *peer_ctx;
2438
2439   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2440       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2441        // Guess simply casting isn't the nicest way...
2442        // FIXME wait for cadet to change this function
2443
2444   //if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2445   //{
2446     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2447
2448     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2449       return;
2450
2451
2452     if (channel == peer_ctx->send_channel)
2453     { /* Something (but us) killd the channel */
2454       LOG (GNUNET_ERROR_TYPE_DEBUG,
2455            "send channel (%s) was destroyed - cleaning up\n",
2456            GNUNET_i2s (peer));
2457
2458       rem_from_list (&gossip_list,
2459                      &gossip_list_size,
2460                      peer);
2461       rem_from_list (&pending_pull_reply_list,
2462                      &pending_pull_reply_list_size,
2463                      peer);
2464       to_file (file_name_view_log,
2465                "-%s\t(cleanup channel, other peer)",
2466                GNUNET_i2s_full (peer));
2467
2468       peer_ctx->send_channel = NULL;
2469       /* Somwewhat {ab,re}use the iterator function */
2470       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2471       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2472
2473       //if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2474       //  LOG (GNUNET_ERROR_TYPE_WARNING, "Removing peer from peer_map failed\n");
2475       //else
2476       //  GNUNET_free (peer_ctx);
2477     }
2478     else if (channel == peer_ctx->recv_channel)
2479     { /* Other peer doesn't want to send us messages anymore */
2480       LOG (GNUNET_ERROR_TYPE_DEBUG,
2481            "Peer %s destroyed recv channel - cleaning up channel\n",
2482            GNUNET_i2s (peer));
2483       peer_ctx->recv_channel = NULL;
2484     }
2485     else if (NULL == peer_ctx->send_channel &&
2486              get_peer_flag (peer_ctx, TO_DESTROY))
2487     { /* We closed the channel to that peer */
2488       LOG (GNUNET_ERROR_TYPE_DEBUG,
2489            "send channel (%s) was destroyed by us - cleaning up\n",
2490            GNUNET_i2s (peer));
2491
2492       rem_from_list (&gossip_list,
2493                      &gossip_list_size,
2494                      peer);
2495       rem_from_list (&pending_pull_reply_list,
2496                      &pending_pull_reply_list_size,
2497                      peer);
2498       to_file (file_name_view_log,
2499                "-%s\t(cleanup channel, ourself)",
2500                GNUNET_i2s_full (peer));
2501
2502       /* Somwewhat {ab,re}use the iterator function */
2503       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2504       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2505     }
2506     else
2507     {
2508       LOG (GNUNET_ERROR_TYPE_WARNING,
2509            "unknown channel (%s) was destroyed\n",
2510            GNUNET_i2s (peer));
2511     }
2512   //}
2513 }
2514
2515
2516 /**
2517  * Actually start the service.
2518  */
2519   static void
2520 rps_start (struct GNUNET_SERVER_Handle *server)
2521 {
2522   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2523     {&handle_client_request,     NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2524       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2525     {&handle_client_seed,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2526     #ifdef ENABLE_MALICIOUS
2527     {&handle_client_act_malicious, NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2528     #endif /* ENABLE_MALICIOUS */
2529     {NULL, NULL, 0, 0}
2530   };
2531
2532   GNUNET_SERVER_add_handlers (server, handlers);
2533   GNUNET_SERVER_disconnect_notify (server,
2534                                    &handle_client_disconnect,
2535                                    NULL);
2536   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
2537
2538
2539   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2540   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2541
2542   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2543                                                         &shutdown_task,
2544                                                         NULL);
2545 }
2546
2547
2548 /**
2549  * Process statistics requests.
2550  *
2551  * @param cls closure
2552  * @param server the initialized server
2553  * @param c configuration to use
2554  */
2555   static void
2556 run (void *cls,
2557      struct GNUNET_SERVER_Handle *server,
2558      const struct GNUNET_CONFIGURATION_Handle *c)
2559 {
2560   int size;
2561   int out_size;
2562
2563   // TODO check what this does -- copied from gnunet-boss
2564   // - seems to work as expected
2565   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2566   cfg = c;
2567
2568
2569   /* Get own ID */
2570   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2571   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2572               "STARTING SERVICE (rps) for peer [%s]\n",
2573               GNUNET_i2s (&own_identity));
2574   #ifdef ENABLE_MALICIOUS
2575   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2576               "Malicious execution compiled in.\n");
2577   #endif /* ENABLE_MALICIOUS */
2578
2579
2580
2581   /* Get time interval from the configuration */
2582   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2583                                                         "ROUNDINTERVAL",
2584                                                         &round_interval))
2585   {
2586     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
2587     GNUNET_SCHEDULER_shutdown ();
2588     return;
2589   }
2590
2591   /* Get initial size of sampler/gossip list from the configuration */
2592   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
2593                                                          "INITSIZE",
2594                                                          (long long unsigned int *) &sampler_size_est_need))
2595   {
2596     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
2597     GNUNET_SCHEDULER_shutdown ();
2598     return;
2599   }
2600   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2601
2602
2603   gossip_list = NULL;
2604   gossip_list_size = 0;
2605
2606   /* file_name_view_log */
2607   if (GNUNET_OK != GNUNET_DISK_directory_create ("/tmp/rps/"))
2608   {
2609     LOG (GNUNET_ERROR_TYPE_WARNING,
2610          "Failed to create directory /tmp/rps/\n");
2611   }
2612
2613   size = (14 + strlen (GNUNET_i2s_full (&own_identity)) + 1) * sizeof (char);
2614   file_name_view_log = GNUNET_malloc (size);
2615   out_size = GNUNET_snprintf (file_name_view_log,
2616                               size,
2617                               "/tmp/rps/view-%s",
2618                               GNUNET_i2s_full (&own_identity));
2619   if (size < out_size ||
2620       0 > out_size)
2621   {
2622     LOG (GNUNET_ERROR_TYPE_WARNING,
2623          "Failed to write string to buffer (size: %i, out_size: %i)\n",
2624          size,
2625          out_size);
2626   }
2627
2628
2629   /* connect to NSE */
2630   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2631
2632
2633   alpha = 0.45;
2634   beta  = 0.45;
2635
2636   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2637
2638
2639   /* Initialise cadet */
2640   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2641     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2642       sizeof (struct GNUNET_MessageHeader)},
2643     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2644       sizeof (struct GNUNET_MessageHeader)},
2645     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2646     {NULL, 0, 0}
2647   };
2648
2649   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2650   cadet_handle = GNUNET_CADET_connect (cfg,
2651                                        cls,
2652                                        &handle_inbound_channel,
2653                                        &cleanup_channel,
2654                                        cadet_handlers,
2655                                        ports);
2656
2657
2658   /* Initialise sampler */
2659   struct GNUNET_TIME_Relative half_round_interval;
2660   struct GNUNET_TIME_Relative  max_round_interval;
2661
2662   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2663   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2664
2665   prot_sampler =   RPS_sampler_init     (sampler_size_est_need, max_round_interval);
2666   client_sampler = RPS_sampler_mod_init (sampler_size_est_need, max_round_interval);
2667
2668   /* Initialise push and pull maps */
2669   push_list = NULL;
2670   push_list_size = 0;
2671   pull_list = NULL;
2672   pull_list_size = 0;
2673   pending_pull_reply_list = NULL;
2674   pending_pull_reply_list_size = 0;
2675
2676
2677   num_hist_update_tasks = 0;
2678
2679
2680   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2681   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2682   // TODO send push/pull to each of those peers?
2683
2684
2685   rps_start (server);
2686 }
2687
2688
2689 /**
2690  * The main function for the rps service.
2691  *
2692  * @param argc number of arguments from the command line
2693  * @param argv command line arguments
2694  * @return 0 ok, 1 on error
2695  */
2696   int
2697 main (int argc, char *const *argv)
2698 {
2699   return (GNUNET_OK ==
2700           GNUNET_SERVICE_run (argc,
2701                               argv,
2702                               "rps",
2703                               GNUNET_SERVICE_OPTION_NONE,
2704                               &run, NULL)) ? 0 : 1;
2705 }
2706
2707 /* end of gnunet-service-rps.c */