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