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