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