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