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