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