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