-tried to fix channel cleanups
[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     peer_map = GNUNET_CONTAINER_multipeermap_create (num_peers + 1,
1095                                                      GNUNET_NO);
1096   for (i = 0 ; i < num_peers ; i++)
1097   {
1098     GNUNET_CONTAINER_multipeermap_put (peer_map,
1099                                        &peer_array[i],
1100                                        NULL,
1101                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1102   }
1103 }
1104
1105
1106 /**
1107  * Send a PULL REPLY to @a peer_id
1108  *
1109  * @param peer_id the peer to send the reply to.
1110  * @param peer_ids the peers to send to @a peer_id
1111  * @param num_peer_ids the number of peers to send to @a peer_id
1112  */
1113 static void
1114 send_pull_reply (const struct GNUNET_PeerIdentity *peer_id,
1115                  const struct GNUNET_PeerIdentity *peer_ids,
1116                  unsigned int num_peer_ids)
1117 {
1118   uint32_t send_size;
1119   struct GNUNET_MQ_Handle *mq;
1120   struct GNUNET_MQ_Envelope *ev;
1121   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1122
1123   /* Compute actual size */
1124   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1125               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
1126
1127   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1128     /* Compute number of peers to send
1129      * If too long, simply truncate */
1130     // TODO select random ones via permutation
1131     //      or even better: do good protocol design
1132     send_size =
1133       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1134        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1135        sizeof (struct GNUNET_PeerIdentity);
1136   else
1137     send_size = num_peer_ids;
1138
1139   LOG (GNUNET_ERROR_TYPE_DEBUG,
1140       "PULL REQUEST from peer %s received, going to send %u peers\n",
1141       GNUNET_i2s (peer_id), send_size);
1142
1143   mq = get_mq (peer_map, peer_id);
1144
1145   ev = GNUNET_MQ_msg_extra (out_msg,
1146                             send_size * sizeof (struct GNUNET_PeerIdentity),
1147                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1148   out_msg->num_peers = htonl (send_size);
1149   memcpy (&out_msg[1], peer_ids,
1150          send_size * sizeof (struct GNUNET_PeerIdentity));
1151
1152   GNUNET_MQ_send (mq, ev);
1153 }
1154
1155
1156 /**
1157  * This function is called on new peer_ids from 'external' sources
1158  * (client seed, cadet get_peers(), ...)
1159  *
1160  * @param peer_id the new peer_id
1161  */
1162 static void
1163 new_peer_id (const struct GNUNET_PeerIdentity *peer_id)
1164 {
1165   struct PeerOutstandingOp out_op;
1166   struct PeerContext *peer_ctx;
1167
1168   if (NULL != peer_id
1169       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer_id))
1170   {
1171     LOG (GNUNET_ERROR_TYPE_DEBUG,
1172         "Got peer_id %s (at %p, gossip_list_size: %u)\n",
1173         GNUNET_i2s (peer_id),
1174         peer_id,
1175         gossip_list_size);
1176
1177     peer_ctx = get_peer_ctx (peer_map, peer_id);
1178     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1179     {
1180       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1181       {
1182         out_op.op = insert_in_sampler;
1183         out_op.op_cls = NULL;
1184         GNUNET_array_append (peer_ctx->outstanding_ops,
1185                              peer_ctx->num_outstanding_ops,
1186                              out_op);
1187       }
1188
1189       if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1190       {
1191         out_op.op = insert_in_gossip_list;
1192         out_op.op_cls = NULL;
1193         GNUNET_array_append (peer_ctx->outstanding_ops,
1194                              peer_ctx->num_outstanding_ops,
1195                              out_op);
1196       }
1197
1198       /* Trigger livelyness test on peer */
1199       check_peer_live (peer_ctx);
1200     }
1201     // else...?
1202
1203     // send push/pull to each of those peers?
1204   }
1205 }
1206
1207
1208 /***********************************************************************
1209  * /Util functions
1210 ***********************************************************************/
1211
1212
1213
1214
1215
1216 /**
1217  * Function called by NSE.
1218  *
1219  * Updates sizes of sampler list and gossip list and adapt those lists
1220  * accordingly.
1221  */
1222   void
1223 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1224               double logestimate, double std_dev)
1225 {
1226   double estimate;
1227   //double scale; // TODO this might go gloabal/config
1228
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1231        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1232   //scale = .01;
1233   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1234   // GNUNET_NSE_log_estimate_to_n (logestimate);
1235   estimate = pow (estimate, 1.0 / 3);
1236   // TODO add if std_dev is a number
1237   // estimate += (std_dev * scale);
1238   if (2 < ceil (estimate))
1239   {
1240     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1241     sampler_size_est_need = estimate;
1242   } else
1243     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1244
1245   /* If the NSE has changed adapt the lists accordingly */
1246   resize_wrapper (prot_sampler, sampler_size_est_need);
1247   client_resize_wrapper ();
1248 }
1249
1250
1251 /**
1252  * Callback called once the requested PeerIDs are ready.
1253  *
1254  * Sends those to the requesting client.
1255  */
1256 void client_respond (void *cls,
1257     struct GNUNET_PeerIdentity *peer_ids, uint32_t num_peers)
1258 {
1259   struct GNUNET_MQ_Envelope *ev;
1260   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1261   struct ReplyCls *reply_cls = (struct ReplyCls *) cls;
1262   uint32_t size_needed;
1263   struct ClientContext *cli_ctx;
1264
1265   LOG (GNUNET_ERROR_TYPE_DEBUG,
1266        "sampler returned %" PRIu32 " peers\n",
1267        num_peers);
1268
1269   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1270                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1271
1272   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1273
1274   ev = GNUNET_MQ_msg_extra (out_msg,
1275                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1276                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1277   out_msg->num_peers = htonl (num_peers);
1278   out_msg->id = htonl (reply_cls->id);
1279
1280   memcpy (&out_msg[1],
1281           peer_ids,
1282           num_peers * sizeof (struct GNUNET_PeerIdentity));
1283   GNUNET_free (peer_ids);
1284
1285   cli_ctx = GNUNET_SERVER_client_get_user_context (reply_cls->client, struct ClientContext);
1286   if (NULL == cli_ctx) {
1287     cli_ctx = GNUNET_new (struct ClientContext);
1288     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (reply_cls->client);
1289     GNUNET_SERVER_client_set_user_context (reply_cls->client, cli_ctx);
1290   }
1291
1292   GNUNET_free (reply_cls);
1293
1294   GNUNET_MQ_send (cli_ctx->mq, ev);
1295 }
1296
1297
1298 /**
1299  * Handle RPS request from the client.
1300  *
1301  * @param cls closure
1302  * @param client identification of the client
1303  * @param message the actual message
1304  */
1305 static void
1306 handle_client_request (void *cls,
1307                        struct GNUNET_SERVER_Client *client,
1308                        const struct GNUNET_MessageHeader *message)
1309 {
1310   struct GNUNET_RPS_CS_RequestMessage *msg;
1311   uint32_t num_peers;
1312   uint32_t size_needed;
1313   struct ReplyCls *reply_cls;
1314   uint32_t i;
1315
1316   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1317
1318   num_peers = ntohl (msg->num_peers);
1319   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1320                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1321
1322   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1323   {
1324     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1325     return;
1326   }
1327
1328   for (i = 0 ; i < num_peers ; i++)
1329     est_request_rate();
1330
1331   LOG (GNUNET_ERROR_TYPE_DEBUG,
1332        "Client requested %" PRIu32 " random peer(s).\n",
1333        num_peers);
1334
1335   reply_cls = GNUNET_new (struct ReplyCls);
1336   reply_cls->id = ntohl (msg->id);
1337   reply_cls->client = client;
1338
1339   RPS_sampler_get_n_rand_peers (client_sampler,
1340                                 client_respond,
1341                                 reply_cls,
1342                                 num_peers);
1343
1344   GNUNET_SERVER_receive_done (client,
1345                               GNUNET_OK);
1346 }
1347
1348
1349 /**
1350  * Handle seed from the client.
1351  *
1352  * @param cls closure
1353  * @param client identification of the client
1354  * @param message the actual message
1355  */
1356   static void
1357 handle_client_seed (void *cls,
1358                     struct GNUNET_SERVER_Client *client,
1359                     const struct GNUNET_MessageHeader *message)
1360 {
1361   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1362   struct GNUNET_PeerIdentity *peers;
1363   uint32_t num_peers;
1364   uint32_t i;
1365
1366   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1367   {
1368     GNUNET_break_op (0);
1369     GNUNET_SERVER_receive_done (client,
1370                                 GNUNET_SYSERR);
1371   }
1372
1373   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1374   num_peers = ntohl (in_msg->num_peers);
1375   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1376   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1377   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1378
1379   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1380       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1381   {
1382     GNUNET_break_op (0);
1383     GNUNET_SERVER_receive_done (client,
1384                                 GNUNET_SYSERR);
1385   }
1386
1387   LOG (GNUNET_ERROR_TYPE_DEBUG,
1388        "Client seeded peers:\n");
1389   print_peer_list (peers, num_peers);
1390
1391   for (i = 0 ; i < num_peers ; i++)
1392   {
1393     LOG (GNUNET_ERROR_TYPE_DEBUG,
1394          "Updating samplers with seed %" PRIu32 ": %s\n",
1395          i,
1396          GNUNET_i2s (&peers[i]));
1397
1398     new_peer_id (&peers[i]);
1399
1400     //RPS_sampler_update (prot_sampler,   &peers[i]);
1401     //RPS_sampler_update (client_sampler, &peers[i]);
1402   }
1403
1404   ////GNUNET_free (peers);
1405
1406   GNUNET_SERVER_receive_done (client,
1407                                                 GNUNET_OK);
1408 }
1409
1410
1411 /**
1412  * Handle a PUSH message from another peer.
1413  *
1414  * Check the proof of work and store the PeerID
1415  * in the temporary list for pushed PeerIDs.
1416  *
1417  * @param cls Closure
1418  * @param channel The channel the PUSH was received over
1419  * @param channel_ctx The context associated with this channel
1420  * @param msg The message header
1421  */
1422 static int
1423 handle_peer_push (void *cls,
1424     struct GNUNET_CADET_Channel *channel,
1425     void **channel_ctx,
1426     const struct GNUNET_MessageHeader *msg)
1427 {
1428   const struct GNUNET_PeerIdentity *peer;
1429
1430   // (check the proof of work)
1431
1432   peer = (const struct GNUNET_PeerIdentity *)
1433     GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1434   // FIXME wait for cadet to change this function
1435
1436   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1437
1438   #ifdef ENABLE_MALICIOUS
1439   struct AttackedPeer *tmp_att_peer;
1440
1441   tmp_att_peer = GNUNET_new (struct AttackedPeer);
1442   memcpy (&tmp_att_peer->peer_id, peer, sizeof (struct GNUNET_PeerIdentity));
1443   if (1 == mal_type
1444       || 3 == mal_type)
1445   { /* Try to maximise representation */
1446     if (NULL == att_peer_set)
1447       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
1448     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1449                                                              peer))
1450     {
1451       GNUNET_CONTAINER_DLL_insert (att_peers_head,
1452                                    att_peers_tail,
1453                                    tmp_att_peer);
1454       add_peer_array_to_set (peer, 1, att_peer_set);
1455     }
1456     return GNUNET_OK;
1457   }
1458
1459
1460   else if (2 == mal_type)
1461   { /* We attack one single well-known peer - simply ignore */
1462     return GNUNET_OK;
1463   }
1464
1465   #endif /* ENABLE_MALICIOUS */
1466
1467   /* Add the sending peer to the push_list */
1468   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1469     GNUNET_array_append (push_list, push_list_size, *peer);
1470
1471   return GNUNET_OK;
1472 }
1473
1474
1475 /**
1476  * Handle PULL REQUEST request message from another peer.
1477  *
1478  * Reply with the gossip list of PeerIDs.
1479  *
1480  * @param cls Closure
1481  * @param channel The channel the PUSH was received over
1482  * @param channel_ctx The context associated with this channel
1483  * @param msg The message header
1484  */
1485 static int
1486 handle_peer_pull_request (void *cls,
1487     struct GNUNET_CADET_Channel *channel,
1488     void **channel_ctx,
1489     const struct GNUNET_MessageHeader *msg)
1490 {
1491   struct GNUNET_PeerIdentity *peer;
1492
1493   peer = (struct GNUNET_PeerIdentity *)
1494     GNUNET_CADET_channel_get_info (channel,
1495                                    GNUNET_CADET_OPTION_PEER);
1496   // FIXME wait for cadet to change this function
1497
1498   #ifdef ENABLE_MALICIOUS
1499   if (1 == mal_type
1500       || 3 == mal_type)
1501   { /* Try to maximise representation */
1502     send_pull_reply (peer, mal_peers, num_mal_peers);
1503     return GNUNET_OK;
1504   }
1505
1506   else if (2 == mal_type)
1507   { /* Try to partition network */
1508     if (GNUNET_YES == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
1509     {
1510       send_pull_reply (peer, mal_peers, num_mal_peers);
1511     }
1512     return GNUNET_OK;
1513   }
1514   #endif /* ENABLE_MALICIOUS */
1515
1516   send_pull_reply (peer, gossip_list, gossip_list_size);
1517
1518   return GNUNET_OK;
1519 }
1520
1521
1522 /**
1523  * Handle PULL REPLY message from another peer.
1524  *
1525  * Check whether we sent a corresponding request and
1526  * whether this reply is the first one.
1527  *
1528  * @param cls Closure
1529  * @param channel The channel the PUSH was received over
1530  * @param channel_ctx The context associated with this channel
1531  * @param msg The message header
1532  */
1533   static int
1534 handle_peer_pull_reply (void *cls,
1535                         struct GNUNET_CADET_Channel *channel,
1536                         void **channel_ctx,
1537                         const struct GNUNET_MessageHeader *msg)
1538 {
1539   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1540   struct GNUNET_PeerIdentity *peers;
1541   struct PeerContext *peer_ctx;
1542   struct GNUNET_PeerIdentity *sender;
1543   struct PeerContext *sender_ctx;
1544   struct PeerOutstandingOp out_op;
1545   uint32_t i;
1546 #ifdef ENABLE_MALICIOUS
1547   struct AttackedPeer *tmp_att_peer;
1548 #endif /* ENABLE_MALICIOUS */
1549
1550   /* Check for protocol violation */
1551   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1552   {
1553     GNUNET_break_op (0);
1554     return GNUNET_SYSERR;
1555   }
1556
1557   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1558   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1559       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1560   {
1561     LOG (GNUNET_ERROR_TYPE_ERROR,
1562         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1563         ntohl (in_msg->num_peers),
1564         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1565             sizeof (struct GNUNET_PeerIdentity));
1566     GNUNET_break_op (0);
1567     return GNUNET_SYSERR;
1568   }
1569
1570   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1571       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1572        // Guess simply casting isn't the nicest way...
1573        // FIXME wait for cadet to change this function
1574   sender_ctx = get_peer_ctx (peer_map, sender);
1575
1576   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1577   {
1578     GNUNET_break_op (0);
1579     return GNUNET_OK;
1580   }
1581
1582
1583   #ifdef ENABLE_MALICIOUS
1584   // We shouldn't even receive pull replies as we're not sending
1585   if (2 == mal_type)
1586     return GNUNET_OK;
1587   #endif /* ENABLE_MALICIOUS */
1588
1589   /* Do actual logic */
1590   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1591
1592   LOG (GNUNET_ERROR_TYPE_DEBUG,
1593        "PULL REPLY received, got following peers:\n");
1594
1595   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1596   {
1597     LOG (GNUNET_ERROR_TYPE_DEBUG,
1598          "%u. %s\n",
1599          i,
1600          GNUNET_i2s (&peers[i]));
1601
1602     #ifdef ENABLE_MALICIOUS
1603     if (1 == mal_type
1604         || 3 == mal_type)
1605     { /* Add attacked peer to local list */
1606       // TODO check if we sent a request and this was the first reply
1607       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1608                                                                &peers[i])
1609           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
1610                                                                   &peers[i])
1611           && GNUNET_NO == GNUNET_CRYPTO_cmp_peer_identity (&peers[i],
1612                                                            &own_identity))
1613       {
1614         tmp_att_peer = GNUNET_new (struct AttackedPeer);
1615         tmp_att_peer->peer_id = peers[i];
1616         GNUNET_CONTAINER_DLL_insert (att_peers_head,
1617                                      att_peers_tail,
1618                                      tmp_att_peer);
1619         add_peer_array_to_set (&peers[i], 1, att_peer_set);
1620       }
1621       continue;
1622     }
1623     #endif /* ENABLE_MALICIOUS */
1624     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1625     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1626         || NULL != peer_ctx->send_channel
1627         || NULL != peer_ctx->recv_channel)
1628     {
1629       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1630           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1631         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1632     }
1633     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1634     {
1635       out_op.op = insert_in_pull_list;
1636       out_op.op_cls = NULL;
1637       GNUNET_array_append (peer_ctx->outstanding_ops,
1638                            peer_ctx->num_outstanding_ops,
1639                            out_op);
1640       check_peer_live (peer_ctx);
1641     }
1642   }
1643
1644   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1645   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1646
1647   return GNUNET_OK;
1648 }
1649
1650
1651 /**
1652  * Compute a random delay.
1653  * A uniformly distributed value between mean + spread and mean - spread.
1654  *
1655  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1656  * It would return a random value between 2 and 6 min.
1657  *
1658  * @param mean the mean
1659  * @param spread the inverse amount of deviation from the mean
1660  */
1661 static struct GNUNET_TIME_Relative
1662 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1663 {
1664   struct GNUNET_TIME_Relative half_interval;
1665   struct GNUNET_TIME_Relative ret;
1666   unsigned int rand_delay;
1667   unsigned int max_rand_delay;
1668
1669   if (0 == spread)
1670   {
1671     LOG (GNUNET_ERROR_TYPE_WARNING,
1672          "Not accepting spread of 0\n");
1673     GNUNET_break (0);
1674   }
1675
1676   /* Compute random time value between spread * mean and spread * mean */
1677   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1678
1679   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1680   /**
1681    * Compute random value between (0 and 1) * round_interval
1682    * via multiplying round_interval with a 'fraction' (0 to value)/value
1683    */
1684   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1685   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1686   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1687   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1688
1689   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1690     LOG (GNUNET_ERROR_TYPE_WARNING,
1691          "Returning FOREVER_REL\n");
1692
1693   return ret;
1694 }
1695
1696
1697 /**
1698  * Send single pull request
1699  *
1700  * @param peer_id the peer to send the pull request to.
1701  */
1702 static void
1703 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1704 {
1705   struct GNUNET_MQ_Envelope *ev;
1706   struct GNUNET_MQ_Handle *mq;
1707
1708   LOG (GNUNET_ERROR_TYPE_DEBUG,
1709        "Sending PULL request to peer %s of gossiped list.\n",
1710        GNUNET_i2s (peer_id));
1711
1712   GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer_id);
1713
1714   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1715   mq = get_mq (peer_map, peer_id);
1716   GNUNET_MQ_send (mq, ev);
1717 }
1718
1719
1720 /**
1721  * Send single push
1722  *
1723  * @param peer_id the peer to send the push to.
1724  */
1725 static void
1726 send_push (struct GNUNET_PeerIdentity *peer_id)
1727 {
1728   struct GNUNET_MQ_Envelope *ev;
1729   struct GNUNET_MQ_Handle *mq;
1730
1731   LOG (GNUNET_ERROR_TYPE_DEBUG,
1732        "Sending PUSH to peer %s of gossiped list.\n",
1733        GNUNET_i2s (peer_id));
1734
1735   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1736   mq = get_mq (peer_map, peer_id);
1737   GNUNET_MQ_send (mq, ev);
1738 }
1739
1740
1741 static void
1742 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1743
1744 static void
1745 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1746
1747
1748 #ifdef ENABLE_MALICIOUS
1749 /**
1750  * Turn RPS service to act malicious.
1751  *
1752  * @param cls Closure
1753  * @param channel The channel the PUSH was received over
1754  * @param channel_ctx The context associated with this channel
1755  * @param msg The message header
1756  */
1757   static void
1758 handle_client_act_malicious (void *cls,
1759                              struct GNUNET_SERVER_Client *client,
1760                              const struct GNUNET_MessageHeader *msg)
1761 {
1762   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1763   struct GNUNET_PeerIdentity *peers;
1764   uint32_t num_mal_peers_sent;
1765   uint32_t num_mal_peers_old;
1766
1767   /* Check for protocol violation */
1768   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1769   {
1770     GNUNET_break_op (0);
1771   }
1772
1773   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1774   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1775       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1776   {
1777     LOG (GNUNET_ERROR_TYPE_ERROR,
1778         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1779         ntohl (in_msg->num_peers),
1780         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1781             sizeof (struct GNUNET_PeerIdentity));
1782     GNUNET_break_op (0);
1783   }
1784
1785
1786   /* Do actual logic */
1787   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1788   mal_type = ntohl (in_msg->type);
1789
1790   LOG (GNUNET_ERROR_TYPE_DEBUG,
1791        "Now acting malicious type %" PRIu32 "\n",
1792        mal_type);
1793
1794   if (1 == mal_type)
1795   { /* Try to maximise representation */
1796     /* Add other malicious peers to those we already know */
1797
1798     num_mal_peers_sent = ntohl (in_msg->num_peers);
1799     num_mal_peers_old = num_mal_peers;
1800     GNUNET_array_grow (mal_peers,
1801                        num_mal_peers,
1802                        num_mal_peers + num_mal_peers_sent);
1803     memcpy (&mal_peers[num_mal_peers_old],
1804             peers,
1805             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1806
1807     /* Add all mal peers to mal_peer_set */
1808     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
1809                            num_mal_peers_sent,
1810                            mal_peer_set);
1811
1812     /* Substitute do_round () with do_mal_round () */
1813     GNUNET_SCHEDULER_cancel (do_round_task);
1814     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1815   }
1816
1817   else if (2 == mal_type
1818            || 3 == mal_type)
1819   { /* Try to partition the network */
1820     /* Add other malicious peers to those we already know */
1821     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
1822     num_mal_peers_old = num_mal_peers;
1823     GNUNET_array_grow (mal_peers,
1824                        num_mal_peers,
1825                        num_mal_peers + num_mal_peers_sent);
1826     memcpy (&mal_peers[num_mal_peers_old],
1827             peers,
1828             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1829
1830     /* Add all mal peers to mal_peer_set */
1831     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
1832                            num_mal_peers_sent,
1833                            mal_peer_set);
1834
1835     /* Store the one attacked peer */
1836     memcpy (&attacked_peer,
1837             &in_msg->attacked_peer,
1838             sizeof (struct GNUNET_PeerIdentity));
1839
1840     LOG (GNUNET_ERROR_TYPE_DEBUG,
1841          "Attacked peer is %s\n",
1842          GNUNET_i2s (&attacked_peer));
1843
1844     /* Substitute do_round () with do_mal_round () */
1845     GNUNET_SCHEDULER_cancel (do_round_task);
1846     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1847   }
1848   else if (0 == mal_type)
1849   { /* Stop acting malicious */
1850     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
1851
1852     /* Substitute do_mal_round () with do_round () */
1853     GNUNET_SCHEDULER_cancel (do_round_task);
1854     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1855   }
1856   else
1857   {
1858     GNUNET_break (0);
1859   }
1860
1861   GNUNET_SERVER_receive_done (client,   GNUNET_OK);
1862 }
1863
1864
1865 /**
1866  * Send out PUSHes and PULLs maliciously.
1867  *
1868  * This is executed regylary.
1869  */
1870 static void
1871 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1872 {
1873   uint32_t num_pushes;
1874   uint32_t i;
1875   struct GNUNET_TIME_Relative time_next_round;
1876   struct AttackedPeer *tmp_att_peer;
1877
1878   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously.\n");
1879
1880   /* Do malicious actions */
1881   if (1 == mal_type)
1882   { /* Try to maximise representation */
1883
1884     /* The maximum of pushes we're going to send this round */
1885     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
1886                                          num_attacked_peers),
1887                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1888
1889     LOG (GNUNET_ERROR_TYPE_DEBUG,
1890          "Going to send %" PRIu32 " pushes\n",
1891          num_pushes);
1892
1893     /* Send PUSHes to attacked peers */
1894     for (i = 0 ; i < num_pushes ; i++)
1895     {
1896       if (att_peers_tail == att_peer_index)
1897         att_peer_index = att_peers_head;
1898       else
1899         att_peer_index = att_peer_index->next;
1900
1901       send_push (&att_peer_index->peer_id);
1902     }
1903
1904     /* Send PULLs to some peers to learn about additional peers to attack */
1905     tmp_att_peer = att_peer_index;
1906     for (i = 0 ; i < num_pushes * alpha ; i++)
1907     {
1908       if (att_peers_tail == tmp_att_peer)
1909         tmp_att_peer = att_peers_head;
1910       else
1911         att_peer_index = tmp_att_peer->next;
1912
1913       send_pull_request (&tmp_att_peer->peer_id);
1914     }
1915   }
1916
1917
1918   else if (2 == mal_type)
1919   { /**
1920      * Try to partition the network
1921      * Send as many pushes to the attacked peer as possible
1922      * That is one push per round as it will ignore more.
1923      */
1924       send_push (&attacked_peer);
1925   }
1926
1927
1928   if (3 == mal_type)
1929   { /* Combined attack */
1930
1931     /* The maximum of pushes we're going to send this round */
1932     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
1933                                          num_attacked_peers),
1934                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1935
1936     LOG (GNUNET_ERROR_TYPE_DEBUG,
1937          "Going to send %" PRIu32 " pushes\n",
1938          num_pushes);
1939
1940     /* Send PUSHes to attacked peers */
1941     send_push (&attacked_peer);
1942
1943     for (i = 0 ; i < num_pushes ; i++)
1944     {
1945       if (att_peers_tail == att_peer_index)
1946         att_peer_index = att_peers_head;
1947       else
1948         att_peer_index = att_peer_index->next;
1949
1950       send_push (&att_peer_index->peer_id);
1951     }
1952
1953     /* Send PULLs to some peers to learn about additional peers to attack */
1954     for (i = 0 ; i < num_pushes * alpha ; i++)
1955     {
1956       if (att_peers_tail == tmp_att_peer)
1957         tmp_att_peer = att_peers_head;
1958       else
1959         att_peer_index = tmp_att_peer->next;
1960
1961       send_pull_request (&tmp_att_peer->peer_id);
1962     }
1963   }
1964
1965   /* Schedule next round */
1966   time_next_round = compute_rand_delay (round_interval, 2);
1967
1968   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
1969   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
1970   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1971 }
1972 #endif /* ENABLE_MALICIOUS */
1973
1974
1975 /**
1976  * Send out PUSHes and PULLs, possibly update #gossip_list, samplers.
1977  *
1978  * This is executed regylary.
1979  */
1980 static void
1981 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1982 {
1983   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
1984
1985   uint32_t i;
1986   unsigned int *permut;
1987   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1988   struct GNUNET_PeerIdentity peer;
1989   struct GNUNET_PeerIdentity *tmp_peer;
1990
1991   LOG (GNUNET_ERROR_TYPE_DEBUG,
1992        "Printing gossip list:\n");
1993   for (i = 0 ; i < gossip_list_size ; i++)
1994   {
1995     LOG (GNUNET_ERROR_TYPE_DEBUG,
1996          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1997     to_file (file_name_view_log,
1998              "=%s\t(do round)",
1999              GNUNET_i2s_full (&gossip_list[i]));
2000   }
2001   // TODO log lists, ...
2002
2003   /* Would it make sense to have one shuffeled gossip list and then
2004    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
2005    * use the rest to update sampler?
2006    * in essence get random peers with consumption */
2007
2008   /* Send PUSHes */
2009   if (0 < gossip_list_size)
2010   {
2011     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2012                                            (unsigned int) gossip_list_size);
2013     n_peers = ceil (alpha * gossip_list_size);
2014     LOG (GNUNET_ERROR_TYPE_DEBUG,
2015          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
2016          n_peers, alpha, gossip_list_size);
2017     for (i = 0 ; i < n_peers ; i++)
2018     {
2019       peer = gossip_list[permut[i]];
2020       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
2021       { // FIXME if this fails schedule/loop this for later
2022         send_push (&peer);
2023       }
2024     }
2025     GNUNET_free (permut);
2026   }
2027
2028
2029   /* Send PULL requests */
2030   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
2031   n_peers = ceil (beta * gossip_list_size);
2032   LOG (GNUNET_ERROR_TYPE_DEBUG,
2033        "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
2034        n_peers, beta, gossip_list_size);
2035   for (i = 0 ; i < n_peers ; i++)
2036   {
2037     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
2038         pending_pull_reply_list, pending_pull_reply_list_size);
2039     if (NULL != tmp_peer)
2040     {
2041       peer = *tmp_peer;
2042       GNUNET_free (tmp_peer);
2043
2044       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
2045       {
2046         send_pull_request (&peer);
2047       }
2048     }
2049   }
2050
2051
2052   /* Update gossip list */
2053   /* TODO see how many peers are in push-/pull- list! */
2054
2055   if (push_list_size <= alpha * gossip_list_size
2056       && push_list_size > 0
2057       && pull_list_size > 0)
2058   {
2059     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
2060
2061     uint32_t first_border;
2062     uint32_t second_border;
2063     uint32_t r_index;
2064     uint32_t peers_to_clean_size;
2065     struct GNUNET_PeerIdentity *peers_to_clean;
2066
2067     peers_to_clean = NULL;
2068     peers_to_clean_size = 0;
2069     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
2070     memcpy (peers_to_clean,
2071             gossip_list,
2072             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
2073
2074     first_border  =                ceil (alpha * sampler_size_est_need);
2075     second_border = first_border + ceil (beta  * sampler_size_est_need);
2076
2077     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
2078
2079     to_file (file_name_view_log,
2080              "--- emptied ---");
2081
2082     for (i = 0 ; i < first_border ; i++)
2083     {/* Update gossip list with peers received through PUSHes */
2084       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
2085                                           push_list_size);
2086       gossip_list[i] = push_list[r_index];
2087       to_file (file_name_view_log,
2088                "+%s't(push list)",
2089                GNUNET_i2s_full (&gossip_list[i]));
2090       // TODO change the peer_flags accordingly
2091     }
2092
2093     for (i = first_border ; i < second_border ; i++)
2094     {/* Update gossip list with peers received through PULLs */
2095       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
2096                                           pull_list_size);
2097       gossip_list[i] = pull_list[r_index];
2098       to_file (file_name_view_log,
2099                "+%s\t(pull list)",
2100                GNUNET_i2s_full (&gossip_list[i]));
2101       // TODO change the peer_flags accordingly
2102     }
2103
2104     for (i = second_border ; i < sampler_size_est_need ; i++)
2105     {/* Update gossip list with peers from history */
2106       RPS_sampler_get_n_rand_peers (prot_sampler,
2107                                     hist_update,
2108                                     NULL,
2109                                     1);
2110       num_hist_update_tasks++;
2111       // TODO change the peer_flags accordingly
2112     }
2113
2114     for (i = 0 ; i < gossip_list_size ; i++)
2115       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
2116
2117     for (i = 0 ; i < peers_to_clean_size ; i++)
2118     {
2119       peer_clean (&peers_to_clean[i]);
2120       /* to_file (file_name_view_log,
2121                "-%s",
2122                GNUNET_i2s_full (&peers_to_clean[i])); */
2123     }
2124
2125     GNUNET_free (peers_to_clean);
2126   }
2127   else
2128   {
2129     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
2130   }
2131   // TODO independent of that also get some peers from CADET_get_peers()?
2132
2133   LOG (GNUNET_ERROR_TYPE_DEBUG,
2134        "Received %u pushes and %u pulls last round (alpha (%.2f) * gossip_list_size (%u) = %.2f)\n",
2135        push_list_size,
2136        pull_list_size,
2137        alpha,
2138        gossip_list_size,
2139        alpha * gossip_list_size);
2140
2141   /* Update samplers */
2142   for ( i = 0 ; i < push_list_size ; i++ )
2143   {
2144     LOG (GNUNET_ERROR_TYPE_DEBUG,
2145          "Updating with peer %s from push list\n",
2146          GNUNET_i2s (&push_list[i]));
2147     RPS_sampler_update (prot_sampler,   &push_list[i]);
2148     RPS_sampler_update (client_sampler, &push_list[i]);
2149     // TODO set in_flag?
2150   }
2151
2152   for ( i = 0 ; i < pull_list_size ; i++ )
2153   {
2154     LOG (GNUNET_ERROR_TYPE_DEBUG,
2155          "Updating with peer %s from pull list\n",
2156          GNUNET_i2s (&pull_list[i]));
2157     RPS_sampler_update (prot_sampler,   &pull_list[i]);
2158     RPS_sampler_update (client_sampler, &pull_list[i]);
2159     // TODO set in_flag?
2160   }
2161
2162
2163   /* Empty push/pull lists */
2164   GNUNET_array_grow (push_list, push_list_size, 0);
2165   GNUNET_array_grow (pull_list, pull_list_size, 0);
2166
2167   struct GNUNET_TIME_Relative time_next_round;
2168
2169   time_next_round = compute_rand_delay (round_interval, 2);
2170
2171   /* Schedule next round */
2172   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
2173   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
2174   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2175 }
2176
2177
2178 static void
2179 rps_start (struct GNUNET_SERVER_Handle *server);
2180
2181
2182 /**
2183  * This is called from GNUNET_CADET_get_peers().
2184  *
2185  * It is called on every peer(ID) that cadet somehow has contact with.
2186  * We use those to initialise the sampler.
2187  */
2188 void
2189 init_peer_cb (void *cls,
2190               const struct GNUNET_PeerIdentity *peer,
2191               int tunnel, // "Do we have a tunnel towards this peer?"
2192               unsigned int n_paths, // "Number of known paths towards this peer"
2193               unsigned int best_path) // "How long is the best path?
2194                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
2195 {
2196   if (NULL != peer)
2197   {
2198     LOG (GNUNET_ERROR_TYPE_DEBUG,
2199          "Got peer_id %s from cadet\n",
2200          GNUNET_i2s (peer));
2201     new_peer_id (peer);
2202   }
2203 }
2204
2205
2206 /**
2207  * Clean the send channel of a peer
2208  */
2209 void
2210 peer_clean (const struct GNUNET_PeerIdentity *peer)
2211 {
2212   struct PeerContext *peer_ctx;
2213   struct GNUNET_CADET_Channel *channel;
2214
2215   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
2216       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2217   {
2218     peer_ctx = get_peer_ctx (peer_map, peer);
2219     if (NULL != peer_ctx->send_channel)
2220     {
2221       channel = peer_ctx->send_channel;
2222       peer_ctx->send_channel = NULL;
2223       GNUNET_CADET_channel_destroy (channel);
2224     }
2225   }
2226 }
2227
2228
2229 /**
2230  * Callback used to remove peers from the multipeermap.
2231  */
2232   int
2233 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
2234 {
2235   struct PeerContext *peer_ctx;
2236   const struct GNUNET_CADET_Channel *channel =
2237     (const struct GNUNET_CADET_Channel *) cls;
2238   struct GNUNET_CADET_Channel *recv;
2239   struct GNUNET_CADET_Channel *send;
2240
2241   peer_ctx = (struct PeerContext *) value;
2242
2243   LOG (GNUNET_ERROR_TYPE_DEBUG,
2244        "Going to clean peer %s\n",
2245        GNUNET_i2s (&peer_ctx->peer_id));
2246
2247   /* If operations are still scheduled for this peer cancel those */
2248   if (0 != peer_ctx->num_outstanding_ops)
2249     GNUNET_array_grow (peer_ctx->outstanding_ops,
2250                        peer_ctx->num_outstanding_ops,
2251                        0);
2252
2253   /* If we are still waiting for notification whether this peer is live 
2254    * cancel the according task */
2255   if (NULL != peer_ctx->is_live_task)
2256   {
2257   LOG (GNUNET_ERROR_TYPE_DEBUG,
2258        "Trying to cancle is_live_task for peer %s\n",
2259        GNUNET_i2s (key));
2260     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
2261     peer_ctx->is_live_task = NULL;
2262   }
2263
2264
2265   recv = peer_ctx->recv_channel;
2266   peer_ctx->recv_channel = NULL;
2267   if (NULL != recv
2268       && channel != recv)
2269   {
2270     GNUNET_CADET_channel_destroy (recv);
2271   }
2272
2273   /* If there is still a mq destroy it */
2274   if (NULL != peer_ctx->mq)
2275   {
2276     GNUNET_MQ_destroy (peer_ctx->mq);
2277     peer_ctx->mq = NULL;
2278   }
2279
2280   /* Remove the send_channel
2281    * The peer map entry should be removed
2282    * from the callback #cleanup_channel */
2283   send = peer_ctx->send_channel;
2284   peer_ctx->send_channel = NULL;
2285   if (NULL != send
2286       && channel != send)
2287   {
2288     set_peer_flag (peer_ctx, TO_DESTROY);
2289     GNUNET_CADET_channel_destroy (send);
2290   }
2291   else
2292   { /* If there is no channel we have to remove it now */
2293     if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2294       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
2295     else
2296       GNUNET_free (peer_ctx);
2297   }
2298
2299   return GNUNET_YES;
2300 }
2301
2302
2303 /**
2304  * Task run during shutdown.
2305  *
2306  * @param cls unused
2307  * @param tc unused
2308  */
2309 static void
2310 shutdown_task (void *cls,
2311                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2312 {
2313
2314   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
2315
2316   if (NULL != do_round_task)
2317   {
2318     GNUNET_SCHEDULER_cancel (do_round_task);
2319     do_round_task = NULL;
2320   }
2321
2322
2323   {
2324   if (GNUNET_SYSERR ==
2325         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
2326     LOG (GNUNET_ERROR_TYPE_WARNING,
2327         "Iterating over peers to disconnect from them was cancelled\n");
2328   }
2329
2330   GNUNET_NSE_disconnect (nse);
2331   RPS_sampler_destroy (prot_sampler);
2332   RPS_sampler_destroy (client_sampler);
2333   LOG (GNUNET_ERROR_TYPE_DEBUG,
2334        "Size of the peermap: %u\n",
2335        GNUNET_CONTAINER_multipeermap_size (peer_map));
2336   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2337   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2338   GNUNET_CADET_disconnect (cadet_handle);
2339   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
2340   GNUNET_array_grow (push_list, push_list_size, 0);
2341   GNUNET_array_grow (pull_list, pull_list_size, 0);
2342   #ifdef ENABLE_MALICIOUS
2343   struct AttackedPeer *tmp_att_peer;
2344   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2345   if (NULL != mal_peer_set)
2346     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
2347   if (NULL != att_peer_set)
2348     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
2349   while (NULL != att_peers_head)
2350   {
2351     tmp_att_peer = att_peers_head;
2352     GNUNET_CONTAINER_DLL_remove (att_peers_head, att_peers_tail, tmp_att_peer);
2353   }
2354   #endif /* ENABLE_MALICIOUS */
2355 }
2356
2357
2358 /**
2359  * A client disconnected.  Remove all of its data structure entries.
2360  *
2361  * @param cls closure, NULL
2362  * @param client identification of the client
2363  */
2364 static void
2365 handle_client_disconnect (void *cls,
2366                           struct GNUNET_SERVER_Client * client)
2367 {
2368 }
2369
2370
2371 /**
2372  * Handle the channel a peer opens to us.
2373  *
2374  * @param cls The closure
2375  * @param channel The channel the peer wants to establish
2376  * @param initiator The peer's peer ID
2377  * @param port The port the channel is being established over
2378  * @param options Further options
2379  */
2380   static void *
2381 handle_inbound_channel (void *cls,
2382                         struct GNUNET_CADET_Channel *channel,
2383                         const struct GNUNET_PeerIdentity *initiator,
2384                         uint32_t port,
2385                         enum GNUNET_CADET_ChannelOption options)
2386 {
2387   struct PeerContext *peer_ctx;
2388   struct GNUNET_PeerIdentity peer;
2389
2390   peer = *initiator;
2391   LOG (GNUNET_ERROR_TYPE_DEBUG,
2392       "New channel was established to us (Peer %s).\n",
2393       GNUNET_i2s (&peer));
2394
2395   GNUNET_assert (NULL != channel);
2396
2397   // we might not even store the recv_channel
2398
2399   peer_ctx = get_peer_ctx (peer_map, &peer);
2400   // FIXME what do we do if a channel is established twice?
2401   //       overwrite? Clean old channel? ...?
2402   //if (NULL != peer_ctx->recv_channel)
2403   //{
2404   //  peer_ctx->recv_channel = channel;
2405   //}
2406   peer_ctx->recv_channel = channel;
2407
2408   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
2409       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
2410
2411   peer_is_live (peer_ctx);
2412
2413   return NULL; // TODO
2414 }
2415
2416
2417 /**
2418  * This is called when a remote peer destroys a channel.
2419  *
2420  * @param cls The closure
2421  * @param channel The channel being closed
2422  * @param channel_ctx The context associated with this channel
2423  */
2424   static void
2425 cleanup_channel (void *cls,
2426                 const struct GNUNET_CADET_Channel *channel,
2427                 void *channel_ctx)
2428 {
2429   struct GNUNET_PeerIdentity *peer;
2430   struct PeerContext *peer_ctx;
2431
2432   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2433       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2434        // Guess simply casting isn't the nicest way...
2435        // FIXME wait for cadet to change this function
2436
2437   //if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2438   //{
2439     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2440
2441     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2442       return;
2443
2444
2445     if (channel == peer_ctx->send_channel)
2446     { /* Something (but us) killd the channel */
2447       LOG (GNUNET_ERROR_TYPE_DEBUG,
2448            "send channel (%s) was destroyed - cleaning up\n",
2449            GNUNET_i2s (peer));
2450
2451       rem_from_list (&gossip_list,
2452                      &gossip_list_size,
2453                      peer);
2454       rem_from_list (&pending_pull_reply_list,
2455                      &pending_pull_reply_list_size,
2456                      peer);
2457       to_file (file_name_view_log,
2458                "-%s\t(cleanup channel, other peer)",
2459                GNUNET_i2s_full (peer));
2460
2461       peer_ctx->send_channel = NULL;
2462       /* Somwewhat {ab,re}use the iterator function */
2463       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2464       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2465
2466       //if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2467       //  LOG (GNUNET_ERROR_TYPE_WARNING, "Removing peer from peer_map failed\n");
2468       //else
2469       //  GNUNET_free (peer_ctx);
2470     }
2471     else if (channel == peer_ctx->recv_channel)
2472     { /* Other peer doesn't want to send us messages anymore */
2473       LOG (GNUNET_ERROR_TYPE_DEBUG,
2474            "Peer %s destroyed recv channel - cleaning up channel\n",
2475            GNUNET_i2s (peer));
2476       peer_ctx->recv_channel = NULL;
2477     }
2478     else if (NULL == peer_ctx->send_channel &&
2479              get_peer_flag (peer_ctx, TO_DESTROY))
2480     { /* We closed the channel to that peer */
2481       LOG (GNUNET_ERROR_TYPE_DEBUG,
2482            "send channel (%s) was destroyed by us - cleaning up\n",
2483            GNUNET_i2s (peer));
2484
2485       rem_from_list (&gossip_list,
2486                      &gossip_list_size,
2487                      peer);
2488       rem_from_list (&pending_pull_reply_list,
2489                      &pending_pull_reply_list_size,
2490                      peer);
2491       to_file (file_name_view_log,
2492                "-%s\t(cleanup channel, ourself)",
2493                GNUNET_i2s_full (peer));
2494
2495       /* Somwewhat {ab,re}use the iterator function */
2496       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2497       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2498     }
2499     else
2500     {
2501       LOG (GNUNET_ERROR_TYPE_WARNING,
2502            "unknown channel (%s) was destroyed\n",
2503            GNUNET_i2s (peer));
2504     }
2505   //}
2506 }
2507
2508
2509 /**
2510  * Actually start the service.
2511  */
2512   static void
2513 rps_start (struct GNUNET_SERVER_Handle *server)
2514 {
2515   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2516     {&handle_client_request,     NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2517       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2518     {&handle_client_seed,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2519     #ifdef ENABLE_MALICIOUS
2520     {&handle_client_act_malicious, NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2521     #endif /* ENABLE_MALICIOUS */
2522     {NULL, NULL, 0, 0}
2523   };
2524
2525   GNUNET_SERVER_add_handlers (server, handlers);
2526   GNUNET_SERVER_disconnect_notify (server,
2527                                    &handle_client_disconnect,
2528                                    NULL);
2529   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
2530
2531
2532   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2533   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2534
2535   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2536                                                         &shutdown_task,
2537                                                         NULL);
2538 }
2539
2540
2541 /**
2542  * Process statistics requests.
2543  *
2544  * @param cls closure
2545  * @param server the initialized server
2546  * @param c configuration to use
2547  */
2548   static void
2549 run (void *cls,
2550      struct GNUNET_SERVER_Handle *server,
2551      const struct GNUNET_CONFIGURATION_Handle *c)
2552 {
2553   int size;
2554   int out_size;
2555
2556   // TODO check what this does -- copied from gnunet-boss
2557   // - seems to work as expected
2558   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2559   cfg = c;
2560
2561
2562   /* Get own ID */
2563   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2564   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2565               "STARTING SERVICE (rps) for peer [%s]\n",
2566               GNUNET_i2s (&own_identity));
2567   #ifdef ENABLE_MALICIOUS
2568   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2569               "Malicious execution compiled in.\n");
2570   #endif /* ENABLE_MALICIOUS */
2571
2572
2573
2574   /* Get time interval from the configuration */
2575   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2576                                                         "ROUNDINTERVAL",
2577                                                         &round_interval))
2578   {
2579     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
2580     GNUNET_SCHEDULER_shutdown ();
2581     return;
2582   }
2583
2584   /* Get initial size of sampler/gossip list from the configuration */
2585   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
2586                                                          "INITSIZE",
2587                                                          (long long unsigned int *) &sampler_size_est_need))
2588   {
2589     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
2590     GNUNET_SCHEDULER_shutdown ();
2591     return;
2592   }
2593   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2594
2595
2596   gossip_list = NULL;
2597   gossip_list_size = 0;
2598
2599   /* file_name_view_log */
2600   GNUNET_DISK_directory_create ("/tmp/rps/");
2601
2602   size = (14 + strlen (GNUNET_i2s_full (&own_identity)) + 1) * sizeof (char);
2603   file_name_view_log = GNUNET_malloc (size);
2604   out_size = GNUNET_snprintf (file_name_view_log,
2605                               size,
2606                               "/tmp/rps/view-%s",
2607                               GNUNET_i2s_full (&own_identity));
2608   if (size < out_size ||
2609       0 > out_size)
2610   {
2611     LOG (GNUNET_ERROR_TYPE_WARNING,
2612          "Failed to write string to buffer (size: %i, out_size: %i)\n",
2613          size,
2614          out_size);
2615   }
2616
2617
2618   /* connect to NSE */
2619   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2620
2621
2622   alpha = 0.45;
2623   beta  = 0.45;
2624
2625   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2626
2627
2628   /* Initialise cadet */
2629   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2630     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2631       sizeof (struct GNUNET_MessageHeader)},
2632     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2633       sizeof (struct GNUNET_MessageHeader)},
2634     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2635     {NULL, 0, 0}
2636   };
2637
2638   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2639   cadet_handle = GNUNET_CADET_connect (cfg,
2640                                        cls,
2641                                        &handle_inbound_channel,
2642                                        &cleanup_channel,
2643                                        cadet_handlers,
2644                                        ports);
2645
2646
2647   /* Initialise sampler */
2648   struct GNUNET_TIME_Relative half_round_interval;
2649   struct GNUNET_TIME_Relative  max_round_interval;
2650
2651   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2652   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2653
2654   prot_sampler =   RPS_sampler_init     (sampler_size_est_need, max_round_interval);
2655   client_sampler = RPS_sampler_mod_init (sampler_size_est_need, max_round_interval);
2656
2657   /* Initialise push and pull maps */
2658   push_list = NULL;
2659   push_list_size = 0;
2660   pull_list = NULL;
2661   pull_list_size = 0;
2662   pending_pull_reply_list = NULL;
2663   pending_pull_reply_list_size = 0;
2664
2665
2666   num_hist_update_tasks = 0;
2667
2668
2669   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2670   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2671   // TODO send push/pull to each of those peers?
2672
2673
2674   rps_start (server);
2675 }
2676
2677
2678 /**
2679  * The main function for the rps service.
2680  *
2681  * @param argc number of arguments from the command line
2682  * @param argv command line arguments
2683  * @return 0 ok, 1 on error
2684  */
2685   int
2686 main (int argc, char *const *argv)
2687 {
2688   return (GNUNET_OK ==
2689           GNUNET_SERVICE_run (argc,
2690                               argv,
2691                               "rps",
2692                               GNUNET_SERVICE_OPTION_NONE,
2693                               &run, NULL)) ? 0 : 1;
2694 }
2695
2696 /* end of gnunet-service-rps.c */