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