-further implemented mal peer, restructured code
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps.c
23  * @brief rps service implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_cadet_service.h"
29 #include "gnunet_nse_service.h"
30 #include "rps.h"
31
32 #include "gnunet-service-rps_sampler.h"
33
34 #include <math.h>
35 #include <inttypes.h>
36
37 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
38
39 // TODO modify @brief in every file
40
41 // TODO check for overflows
42
43 // TODO align message structs
44
45 // (TODO api -- possibility of getting weak random peer immideately)
46
47 // TODO malicious peer
48
49 // TODO connect to friends
50
51 // TODO store peers somewhere
52
53 // TODO ignore list?
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 client_ctx
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
105 /**
106  * Functions of this type can be used to be stored at a peer for later execution.
107  */
108 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
109
110 /**
111  * Outstanding operation on peer consisting of callback and closure
112  */
113 struct PeerOutstandingOp
114 {
115   /**
116    * Callback
117    */
118   PeerOp op;
119
120   /**
121    * Closure
122    */
123   void *op_cls;
124 };
125
126
127 /**
128  * Struct used to keep track of other peer's status
129  *
130  * This is stored in a multipeermap.
131  */
132 struct PeerContext
133 {
134   /**
135    * In own gossip/sampler list, in other's gossip/sampler list
136    */
137   uint32_t peer_flags;
138
139   /**
140    * Message queue open to client
141    */
142   struct GNUNET_MQ_Handle *mq;
143
144   /**
145    * Channel open to client.
146    */
147   struct GNUNET_CADET_Channel *send_channel;
148
149   /**
150    * Channel open from client.
151    */
152   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
153
154   /**
155    * Array of outstanding operations on this peer.
156    */
157   struct PeerOutstandingOp *outstanding_ops;
158
159   /**
160    * Number of outstanding operations.
161    */
162   unsigned int num_outstanding_ops;
163   //size_t num_outstanding_ops;
164
165   /**
166    * Handle to the callback given to cadet_ntfy_tmt_rdy()
167    *
168    * To be canceled on shutdown.
169    */
170   struct GNUNET_CADET_TransmitHandle *is_live_task;
171
172   /**
173    * Identity of the peer
174    */
175   struct GNUNET_PeerIdentity peer_id;
176
177   /**
178    * This is pobably followed by 'statistical' data (when we first saw
179    * him, how did we get his ID, how many pushes (in a timeinterval),
180    * ...)
181    */
182 };
183
184 /***********************************************************************
185  * /Housekeeping with peers
186 ***********************************************************************/
187
188
189
190
191
192 /***********************************************************************
193  * Globals
194 ***********************************************************************/
195
196 /**
197  * Sampler used for the Brahms protocol itself.
198  */
199 static struct RPS_Sampler *prot_sampler;
200
201 /**
202  * Sampler used for the clients.
203  */
204 static struct RPS_Sampler *client_sampler;
205
206 /**
207  * Set of all peers to keep track of them.
208  */
209 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
210
211
212 /**
213  * The gossiped list of peers.
214  */
215 static struct GNUNET_PeerIdentity *gossip_list;
216
217 /**
218  * Size of the gossiped list
219  */
220 //static unsigned int gossip_list_size;
221 static uint32_t gossip_list_size;
222
223
224 /**
225  * The size of sampler we need to be able to satisfy the client's need of
226  * random peers.
227  */
228 static unsigned int sampler_size_client_need;
229
230 /**
231  * The size of sampler we need to be able to satisfy the Brahms protocol's
232  * need of random peers.
233  *
234  * This is directly taken as the #gossip_list_size on update of the
235  * #gossip_list
236  *
237  * This is one minimum size the sampler grows to.
238  */
239 static unsigned int sampler_size_est_need;
240
241
242 /**
243  * Percentage of total peer number in the gossip list
244  * to send random PUSHes to
245  */
246 static float alpha;
247
248 /**
249  * Percentage of total peer number in the gossip list
250  * to send random PULLs to
251  */
252 static float beta;
253
254 /**
255  * The percentage gamma of history updates.
256  * Simply 1 - alpha - beta
257  */
258
259
260 /**
261  * Identifier for the main task that runs periodically.
262  */
263 static struct GNUNET_SCHEDULER_Task *do_round_task;
264
265 /**
266  * Time inverval the do_round task runs in.
267  */
268 static struct GNUNET_TIME_Relative round_interval;
269
270
271
272 /**
273  * List to store peers received through pushes temporary.
274  *
275  * TODO -> multipeermap
276  */
277 static struct GNUNET_PeerIdentity *push_list;
278
279 /**
280  * Size of the push_list;
281  */
282 static unsigned int push_list_size;
283 //size_t push_list_size;
284
285 /**
286  * List to store peers received through pulls temporary.
287  *
288  * TODO -> multipeermap
289  */
290 static struct GNUNET_PeerIdentity *pull_list;
291
292 /**
293  * Size of the pull_list;
294  */
295 static unsigned int pull_list_size;
296 //size_t pull_list_size;
297
298
299 /**
300  * Handler to NSE.
301  */
302 static struct GNUNET_NSE_Handle *nse;
303
304 /**
305  * Handler to CADET.
306  */
307 static struct GNUNET_CADET_Handle *cadet_handle;
308
309
310 /**
311  * Request counter.
312  *
313  * Only needed in the beginning to check how many of the 64 deltas
314  * we already have
315  */
316 static unsigned int req_counter;
317
318 /**
319  * Time of the last request we received.
320  *
321  * Used to compute the expected request rate.
322  */
323 static struct GNUNET_TIME_Absolute last_request;
324
325 /**
326  * Size of #request_deltas.
327  */
328 #define REQUEST_DELTAS_SIZE 64
329 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
330
331 /**
332  * Last 64 deltas between requests
333  */
334 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
335
336 /**
337  * The prediction of the rate of requests
338  */
339 static struct GNUNET_TIME_Relative  request_rate;
340
341
342 /**
343  * List with the peers we sent requests to.
344  */
345 struct GNUNET_PeerIdentity *pending_pull_reply_list;
346
347 /**
348  * Size of #pending_pull_reply_list.
349  */
350 uint32_t pending_pull_reply_list_size;
351
352
353 /**
354  * Number of history update tasks.
355  */
356 uint32_t num_hist_update_tasks;
357
358
359 #ifdef ENABLE_MALICIOUS
360 /**
361  * Type of malicious peer
362  *
363  * 0 Don't act malicious at all - Default
364  * 1 Try to maximise representation
365  * 2 Try to partition the network
366  */
367 uint32_t mal_type = 0;
368
369 /**
370  * Other malicious peers
371  */
372 static struct GNUNET_PeerIdentity *mal_peers = NULL;
373
374 /**
375  * Number of other malicious peers
376  */
377 static uint32_t num_mal_peers = 0;
378
379
380 /**
381  * If type is 2 This struct is used to store the attacked peers in a DLL
382  */
383 struct AttackedPeer
384 {
385   /**
386    * DLL
387    */
388   struct AttackedPeer *next;
389   struct AttackedPeer *prev;
390
391   /**
392    * PeerID
393    */
394   struct GNUNET_PeerIdentity *peer_id;
395 };
396
397 /**
398  * If type is 2 this is the DLL of attacked peers
399  */
400 //static struct AttackedPeer *att_peers_head = NULL;
401 //static struct AttackedPeer *att_peers_tail = NULL;
402
403 /**
404  * Number of attacked peers
405  */
406 //static uint32_t num_attacked_peers = 0;
407
408
409 /**
410  * If type is 1 this is the attacked peer
411  */
412 static struct GNUNET_PeerIdentity attacked_peer;
413
414 /**
415  * The limit of PUSHes we can send in one round.
416  * This is an assumption of the Brahms protocol and either implemented
417  * via proof of work
418  * or
419  * assumend to be the bandwidth limitation.
420  */
421 static uint32_t push_limit = 10000;
422 #endif /* ENABLE_MALICIOUS */
423
424
425 /***********************************************************************
426  * /Globals
427 ***********************************************************************/
428
429
430
431
432
433
434 /***********************************************************************
435  * Util functions
436 ***********************************************************************/
437
438 /**
439  * Set a peer flag of given peer context.
440  */
441 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
442
443 /**
444  * Get peer flag of given peer context.
445  */
446 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
447
448 /**
449  * Unset flag of given peer context.
450  */
451 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
452
453 /**
454  * Compute the minimum of two ints
455  */
456 #define min(x, y) ((x < y) ? x : y)
457
458 /**
459  * Clean the send channel of a peer
460  */
461 void
462 peer_clean (const struct GNUNET_PeerIdentity *peer);
463
464
465 /**
466  * Check if peer is already in peer array.
467  */
468   int
469 in_arr (const struct GNUNET_PeerIdentity *array,
470         unsigned int arr_size,
471         const struct GNUNET_PeerIdentity *peer)
472 {
473   GNUNET_assert (NULL != peer);
474
475   if (0 == arr_size)
476     return GNUNET_NO;
477
478   GNUNET_assert (NULL != array);
479
480   unsigned int i;
481
482   for (i = 0; i < arr_size ; i++)
483     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
484       return GNUNET_YES;
485   return GNUNET_NO;
486 }
487
488
489 /**
490  * Print peerlist to log.
491  */
492 void
493 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
494 {
495   unsigned int i;
496
497   LOG (GNUNET_ERROR_TYPE_DEBUG,
498        "Printing peer list of length %u at %p:\n",
499        len,
500        list);
501   for (i = 0 ; i < len ; i++)
502   {
503     LOG (GNUNET_ERROR_TYPE_DEBUG,
504          "%u. peer: %s\n",
505          i, GNUNET_i2s (&list[i]));
506   }
507 }
508
509
510 /**
511  * Remove peer from list.
512  */
513   void
514 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
515                unsigned int *list_size,
516                const struct GNUNET_PeerIdentity *peer)
517 {
518   unsigned int i;
519   struct GNUNET_PeerIdentity *tmp;
520
521   tmp = *peer_list;
522
523   LOG (GNUNET_ERROR_TYPE_DEBUG,
524        "Removing peer %s from list at %p\n",
525        GNUNET_i2s (peer),
526        tmp);
527
528   for ( i = 0 ; i < *list_size ; i++ )
529   {
530     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
531     {
532       if (i < *list_size -1)
533       { /* Not at the last entry -- shift peers left */
534         memcpy (&tmp[i], &tmp[i +1],
535                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
536       }
537       /* Remove last entry (should be now useless PeerID) */
538       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
539     }
540   }
541   *peer_list = tmp;
542 }
543
544 /**
545  * Get random peer from the given list but don't return one from the @a ignore_list.
546  */
547   struct GNUNET_PeerIdentity *
548 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
549                            uint32_t list_size,
550                            const struct GNUNET_PeerIdentity *ignore_list,
551                            uint32_t ignore_size)
552 {
553   uint32_t r_index;
554   uint32_t tmp_size;
555   struct GNUNET_PeerIdentity *tmp_peer_list;
556   struct GNUNET_PeerIdentity *peer;
557
558   GNUNET_assert (NULL != peer_list);
559   if (0 == list_size)
560     return NULL;
561
562   tmp_size = 0;
563   tmp_peer_list = NULL;
564   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
565   memcpy (tmp_peer_list,
566           peer_list,
567           list_size * sizeof (struct GNUNET_PeerIdentity));
568   peer = GNUNET_new (struct GNUNET_PeerIdentity);
569
570   /**;
571    * Choose the r_index of the peer we want to return
572    * at random from the interval of the gossip list
573    */
574   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
575                                       tmp_size);
576   *peer = tmp_peer_list[r_index];
577
578   while (in_arr (ignore_list, ignore_size, peer))
579   {
580     rem_from_list (&tmp_peer_list, &tmp_size, peer);
581
582     print_peer_list (tmp_peer_list, tmp_size);
583
584     if (0 == tmp_size)
585     {
586       GNUNET_free (peer);
587       return NULL;
588     }
589
590     /**;
591      * Choose the r_index of the peer we want to return
592      * at random from the interval of the gossip list
593      */
594     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
595                                         tmp_size);
596     *peer = tmp_peer_list[r_index];
597   }
598
599
600   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
601
602   return peer;
603 }
604
605
606 /**
607  * Get the context of a peer. If not existing, create.
608  */
609   struct PeerContext *
610 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
611               const struct GNUNET_PeerIdentity *peer)
612 {
613   struct PeerContext *ctx;
614
615   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
616   {
617     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
618   }
619   else
620   {
621     ctx = GNUNET_new (struct PeerContext);
622     ctx->peer_flags = 0;
623     ctx->mq = NULL;
624     ctx->send_channel = NULL;
625     ctx->recv_channel = NULL;
626     ctx->outstanding_ops = NULL;
627     ctx->num_outstanding_ops = 0;
628     ctx->is_live_task = NULL;
629     ctx->peer_id = *peer;
630     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
631                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
632   }
633   return ctx;
634 }
635
636
637 /**
638  * Put random peer from sampler into the gossip list as history update.
639  */
640   void
641 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
642 {
643   GNUNET_assert (1 == num_peers);
644
645   if (gossip_list_size < sampler_size_est_need)
646     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
647
648   if (0 < num_hist_update_tasks)
649     num_hist_update_tasks--;
650 }
651
652
653 /**
654  * Set the peer flag to living and call the outstanding operations on this peer.
655  */
656 static size_t
657 peer_is_live (struct PeerContext *peer_ctx)
658 {
659   struct GNUNET_PeerIdentity *peer;
660
661   /* Cancle is_live_task if still scheduled */
662   if (NULL != peer_ctx->is_live_task)
663   {
664     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
665     peer_ctx->is_live_task = NULL;
666   }
667
668   peer = &peer_ctx->peer_id;
669   set_peer_flag (peer_ctx, VALID);
670
671   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
672
673   if (0 != peer_ctx->num_outstanding_ops)
674   { /* Call outstanding operations */
675     unsigned int i;
676
677     for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
678       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
679     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
680   }
681
682   return 0;
683 }
684
685
686 /**
687  * Callback that is called when a channel was effectively established.
688  * This is given to ntfy_tmt_rdy and called when the channel was
689  * successfully established.
690  */
691 static size_t
692 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
693 {
694   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
695
696   if (NULL != buf
697       && 0 != size)
698   {
699     peer_ctx->is_live_task = NULL;
700     peer_is_live (peer_ctx);
701   }
702
703   //if (NULL != peer_ctx->is_live_task)
704   //{
705   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
706   //       "Trying to cancle is_live_task for peer %s\n",
707   //       GNUNET_i2s (&peer_ctx->peer_id));
708   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
709   //  peer_ctx->is_live_task = NULL;
710   //}
711
712   return 0;
713 }
714
715
716 /**
717  * Get the channel of a peer. If not existing, create.
718  */
719   struct GNUNET_CADET_Channel *
720 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
721              const struct GNUNET_PeerIdentity *peer)
722 {
723   struct PeerContext *peer_ctx;
724
725   peer_ctx = get_peer_ctx (peer_map, peer);
726   if (NULL == peer_ctx->send_channel)
727   {
728     LOG (GNUNET_ERROR_TYPE_DEBUG,
729          "Trying to establish channel to peer %s\n",
730          GNUNET_i2s (peer));
731
732     peer_ctx->send_channel =
733       GNUNET_CADET_channel_create (cadet_handle,
734                                    NULL,
735                                    peer,
736                                    GNUNET_RPS_CADET_PORT,
737                                    GNUNET_CADET_OPTION_RELIABLE);
738
739     // do I have to explicitly put it in the peer_map?
740     (void) GNUNET_CONTAINER_multipeermap_put
741       (peer_map,
742        peer,
743        peer_ctx,
744        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
745   }
746   return peer_ctx->send_channel;
747 }
748
749
750 /**
751  * Get the message queue of a specific peer.
752  *
753  * If we already have a message queue open to this client,
754  * simply return it, otherways create one.
755  */
756   struct GNUNET_MQ_Handle *
757 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
758         const struct GNUNET_PeerIdentity *peer_id)
759 {
760   struct PeerContext *peer_ctx;
761
762   peer_ctx = get_peer_ctx (peer_map, peer_id);
763
764   if (NULL == peer_ctx->mq)
765   {
766     (void) get_channel (peer_map, peer_id);
767     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
768     //do I have to explicitly put it in the peer_map?
769     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
770                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
771   }
772   return peer_ctx->mq;
773 }
774
775
776 /**
777  * Issue check whether peer is live
778  *
779  * @param peer_ctx the context of the peer
780  */
781 void
782 check_peer_live (struct PeerContext *peer_ctx)
783 {
784   (void) get_channel (peer_map, &peer_ctx->peer_id);
785   LOG (GNUNET_ERROR_TYPE_DEBUG,
786        "Get informed about peer %s getting live\n",
787        GNUNET_i2s (&peer_ctx->peer_id));
788   peer_ctx->is_live_task =
789       GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
790                                           GNUNET_NO,
791                                           GNUNET_TIME_UNIT_FOREVER_REL,
792                                           sizeof (struct GNUNET_MessageHeader),
793                                           cadet_ntfy_tmt_rdy_cb,
794                                           peer_ctx);
795   // FIXME check whether this is NULL
796 }
797
798
799 /**
800  * Sum all time relatives of an array.
801   */
802   struct GNUNET_TIME_Relative
803 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
804 {
805   struct GNUNET_TIME_Relative sum;
806   uint32_t i;
807
808   sum = GNUNET_TIME_UNIT_ZERO;
809   for ( i = 0 ; i < arr_size ; i++ )
810   {
811     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
812   }
813   return sum;
814 }
815
816
817 /**
818  * Compute the average of given time relatives.
819  */
820   struct GNUNET_TIME_Relative
821 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
822 {
823   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
824 }
825
826
827 /**
828  * Insert PeerID in #pull_list
829  *
830  * Called once we know a peer is live.
831  */
832   void
833 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
834 {
835   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
836     GNUNET_array_append (pull_list, pull_list_size, *peer);
837
838   peer_clean (peer);
839 }
840
841 /**
842  * Check whether #insert_in_pull_list was already scheduled
843  */
844   int
845 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
846 {
847   unsigned int i;
848
849   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
850     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
851       return GNUNET_YES;
852   return GNUNET_NO;
853 }
854
855
856 /**
857  * Insert PeerID in #gossip_list
858  *
859  * Called once we know a peer is live.
860  */
861   void
862 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
863 {
864   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
865     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
866
867   (void) get_channel (peer_map, peer);
868 }
869
870 /**
871  * Check whether #insert_in_gossip_list was already scheduled
872  */
873   int
874 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
875 {
876   unsigned int i;
877
878   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
879     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
880       return GNUNET_YES;
881   return GNUNET_NO;
882 }
883
884
885 /**
886  * Update sampler with given PeerID.
887  */
888   void
889 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
890 {
891   LOG (GNUNET_ERROR_TYPE_DEBUG,
892        "Updating samplers with peer %s from insert_in_sampler()\n",
893        GNUNET_i2s (peer));
894   RPS_sampler_update (prot_sampler,   peer);
895   RPS_sampler_update (client_sampler, peer);
896 }
897
898
899 /**
900  * Check whether #insert_in_sampler was already scheduled
901  */
902 static int
903 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
904 {
905   unsigned int i;
906
907   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
908     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
909       return GNUNET_YES;
910   return GNUNET_NO;
911 }
912
913
914 /**
915  * Wrapper around #RPS_sampler_resize()
916  *
917  * If we do not have enough sampler elements, double current sampler size
918  * If we have more than enough sampler elements, halv current sampler size
919  */
920 static void
921 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
922 {
923   unsigned int sampler_size;
924
925   // TODO statistics
926   // TODO respect the min, max
927   sampler_size = RPS_sampler_get_size (sampler);
928   if (sampler_size > new_size * 4)
929   { /* Shrinking */
930     RPS_sampler_resize (sampler, sampler_size / 2);
931   }
932   else if (sampler_size < new_size)
933   { /* Growing */
934     RPS_sampler_resize (sampler, sampler_size * 2);
935   }
936   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
937 }
938
939
940 /**
941  * Wrapper around #RPS_sampler_resize() resizing the client sampler
942  */
943 static void
944 client_resize_wrapper ()
945 {
946   uint32_t bigger_size;
947   unsigned int sampler_size;
948
949   // TODO statistics
950
951   sampler_size = RPS_sampler_get_size (client_sampler);
952
953   if (sampler_size_est_need > sampler_size_client_need)
954     bigger_size = sampler_size_est_need;
955   else
956     bigger_size = sampler_size_client_need;
957
958   // TODO respect the min, max
959   resize_wrapper (client_sampler, bigger_size);
960   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
961 }
962
963
964 /**
965  * Estimate request rate
966  *
967  * Called every time we receive a request from the client.
968  */
969   void
970 est_request_rate()
971 {
972   struct GNUNET_TIME_Relative max_round_duration;
973
974   if (request_deltas_size > req_counter)
975     req_counter++;
976   if ( 1 < req_counter)
977   {
978     /* Shift last request deltas to the right */
979     memcpy (&request_deltas[1],
980         request_deltas,
981         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
982
983     /* Add current delta to beginning */
984     request_deltas[0] =
985         GNUNET_TIME_absolute_get_difference (last_request,
986                                              GNUNET_TIME_absolute_get ());
987     request_rate = T_relative_avg (request_deltas, req_counter);
988
989     /* Compute the duration a round will maximally take */
990     max_round_duration =
991         GNUNET_TIME_relative_add (round_interval,
992                                   GNUNET_TIME_relative_divide (round_interval, 2));
993
994     /* Set the estimated size the sampler has to have to
995      * satisfy the current client request rate */
996     sampler_size_client_need =
997         max_round_duration.rel_value_us / request_rate.rel_value_us;
998
999     /* Resize the sampler */
1000     client_resize_wrapper ();
1001   }
1002   last_request = GNUNET_TIME_absolute_get ();
1003 }
1004
1005
1006 /***********************************************************************
1007  * /Util functions
1008 ***********************************************************************/
1009
1010
1011
1012
1013
1014 /**
1015  * Function called by NSE.
1016  *
1017  * Updates sizes of sampler list and gossip list and adapt those lists
1018  * accordingly.
1019  */
1020   void
1021 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1022               double logestimate, double std_dev)
1023 {
1024   double estimate;
1025   //double scale; // TODO this might go gloabal/config
1026
1027   LOG (GNUNET_ERROR_TYPE_DEBUG,
1028        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1029        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1030   //scale = .01;
1031   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1032   // GNUNET_NSE_log_estimate_to_n (logestimate);
1033   estimate = pow (estimate, 1.0 / 3);
1034   // TODO add if std_dev is a number
1035   // estimate += (std_dev * scale);
1036   if (2 < ceil (estimate))
1037   {
1038     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1039     sampler_size_est_need = estimate;
1040   } else
1041     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1042
1043   /* If the NSE has changed adapt the lists accordingly */
1044   resize_wrapper (prot_sampler, sampler_size_est_need);
1045   client_resize_wrapper ();
1046 }
1047
1048
1049 /**
1050  * Callback called once the requested PeerIDs are ready.
1051  *
1052  * Sends those to the requesting client.
1053  */
1054 void client_respond (void *cls,
1055     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
1056 {
1057   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
1058   struct GNUNET_MQ_Envelope *ev;
1059   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1060   struct GNUNET_SERVER_Client *client;
1061   uint32_t size_needed;
1062   struct client_ctx *cli_ctx;
1063
1064   client = (struct GNUNET_SERVER_Client *) cls;
1065
1066   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1067                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1068
1069   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1070
1071   ev = GNUNET_MQ_msg_extra (out_msg,
1072                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1073                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1074   out_msg->num_peers = htonl (num_peers);
1075
1076   memcpy (&out_msg[1],
1077       ids,
1078       num_peers * sizeof (struct GNUNET_PeerIdentity));
1079   GNUNET_free (ids);
1080
1081   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
1082   if (NULL == cli_ctx) {
1083     cli_ctx = GNUNET_new (struct client_ctx);
1084     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
1085     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
1086   }
1087
1088   GNUNET_MQ_send (cli_ctx->mq, ev);
1089 }
1090
1091
1092 /**
1093  * Handle RPS request from the client.
1094  *
1095  * @param cls closure
1096  * @param client identification of the client
1097  * @param message the actual message
1098  */
1099 static void
1100 handle_client_request (void *cls,
1101             struct GNUNET_SERVER_Client *client,
1102             const struct GNUNET_MessageHeader *message)
1103 {
1104   struct GNUNET_RPS_CS_RequestMessage *msg;
1105   uint32_t num_peers;
1106   uint32_t size_needed;
1107   uint32_t i;
1108
1109   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1110
1111   num_peers = ntohl (msg->num_peers);
1112   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1113                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1114
1115   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1116   {
1117     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1118     return;
1119   }
1120
1121   for (i = 0 ; i < num_peers ; i++)
1122     est_request_rate();
1123
1124   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
1125
1126   RPS_sampler_get_n_rand_peers (client_sampler, client_respond,
1127                                 client, num_peers, GNUNET_YES);
1128
1129   GNUNET_SERVER_receive_done (client,
1130                               GNUNET_OK);
1131 }
1132
1133
1134 /**
1135  * Handle seed from the client.
1136  *
1137  * @param cls closure
1138  * @param client identification of the client
1139  * @param message the actual message
1140  */
1141   static void
1142 handle_client_seed (void *cls,
1143                     struct GNUNET_SERVER_Client *client,
1144                     const struct GNUNET_MessageHeader *message)
1145 {
1146   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1147   struct GNUNET_PeerIdentity *peers;
1148   uint32_t num_peers;
1149   uint32_t i;
1150
1151   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1152   {
1153     GNUNET_break_op (0);
1154     GNUNET_SERVER_receive_done (client,
1155                                 GNUNET_SYSERR);
1156   }
1157
1158   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1159   num_peers = ntohl (in_msg->num_peers);
1160   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1161   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1162   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1163
1164   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1165       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1166   {
1167     GNUNET_break_op (0);
1168     GNUNET_SERVER_receive_done (client,
1169                                 GNUNET_SYSERR);
1170   }
1171
1172   LOG (GNUNET_ERROR_TYPE_DEBUG,
1173        "Client seeded peers:\n");
1174   print_peer_list (peers, num_peers);
1175
1176   // TODO check for validity of ids
1177
1178   for (i = 0 ; i < num_peers ; i++)
1179   {
1180     LOG (GNUNET_ERROR_TYPE_DEBUG,
1181          "Updating samplers with seed %" PRIX32 ": %s\n",
1182          i,
1183          GNUNET_i2s (&peers[i]));
1184
1185     RPS_sampler_update (prot_sampler,   &peers[i]);
1186     RPS_sampler_update (client_sampler, &peers[i]);
1187   }
1188
1189   //GNUNET_free (peers);
1190
1191   GNUNET_SERVER_receive_done (client,
1192                                                 GNUNET_OK);
1193 }
1194
1195
1196 /**
1197  * Handle a PUSH message from another peer.
1198  *
1199  * Check the proof of work and store the PeerID
1200  * in the temporary list for pushed PeerIDs.
1201  *
1202  * @param cls Closure
1203  * @param channel The channel the PUSH was received over
1204  * @param channel_ctx The context associated with this channel
1205  * @param msg The message header
1206  */
1207 static int
1208 handle_peer_push (void *cls,
1209     struct GNUNET_CADET_Channel *channel,
1210     void **channel_ctx,
1211     const struct GNUNET_MessageHeader *msg)
1212 {
1213   const struct GNUNET_PeerIdentity *peer;
1214
1215   // (check the proof of work)
1216
1217   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1218   // FIXME wait for cadet to change this function
1219   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1220
1221   /* Add the sending peer to the push_list */
1222   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1223     GNUNET_array_append (push_list, push_list_size, *peer);
1224
1225   return GNUNET_OK;
1226 }
1227
1228 /**
1229  * Handle PULL REQUEST request message from another peer.
1230  *
1231  * Reply with the gossip list of PeerIDs.
1232  *
1233  * @param cls Closure
1234  * @param channel The channel the PUSH was received over
1235  * @param channel_ctx The context associated with this channel
1236  * @param msg The message header
1237  */
1238 static int
1239 handle_peer_pull_request (void *cls,
1240     struct GNUNET_CADET_Channel *channel,
1241     void **channel_ctx,
1242     const struct GNUNET_MessageHeader *msg)
1243 {
1244   struct GNUNET_PeerIdentity *peer;
1245   uint32_t send_size;
1246   struct GNUNET_MQ_Handle *mq;
1247   struct GNUNET_MQ_Envelope *ev;
1248   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1249
1250
1251   peer = (struct GNUNET_PeerIdentity *)
1252     GNUNET_CADET_channel_get_info (channel,
1253                                    GNUNET_CADET_OPTION_PEER);
1254   // FIXME wait for cadet to change this function
1255
1256   /* Compute actual size */
1257   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1258               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1259
1260   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1261     /* Compute number of peers to send
1262      * If too long, simply truncate */
1263   // TODO select random ones via permutation
1264     send_size =
1265       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1266        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1267        sizeof (struct GNUNET_PeerIdentity);
1268   else
1269     send_size = gossip_list_size;
1270
1271   LOG (GNUNET_ERROR_TYPE_DEBUG,
1272       "PULL REQUEST from peer %s received, going to send %u peers\n",
1273       GNUNET_i2s (peer), send_size);
1274
1275   mq = get_mq (peer_map, peer);
1276
1277   ev = GNUNET_MQ_msg_extra (out_msg,
1278                            send_size * sizeof (struct GNUNET_PeerIdentity),
1279                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1280   //out_msg->num_peers = htonl (gossip_list_size);
1281   out_msg->num_peers = htonl (send_size);
1282   memcpy (&out_msg[1], gossip_list,
1283          send_size * sizeof (struct GNUNET_PeerIdentity));
1284
1285   GNUNET_MQ_send (mq, ev);
1286
1287   return GNUNET_OK;
1288 }
1289
1290
1291 /**
1292  * Handle PULL REPLY message from another peer.
1293  *
1294  * Check whether we sent a corresponding request and
1295  * whether this reply is the first one.
1296  *
1297  * @param cls Closure
1298  * @param channel The channel the PUSH was received over
1299  * @param channel_ctx The context associated with this channel
1300  * @param msg The message header
1301  */
1302   static int
1303 handle_peer_pull_reply (void *cls,
1304                         struct GNUNET_CADET_Channel *channel,
1305                         void **channel_ctx,
1306                         const struct GNUNET_MessageHeader *msg)
1307 {
1308   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1309
1310   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1311   struct GNUNET_PeerIdentity *peers;
1312   struct PeerContext *peer_ctx;
1313   struct GNUNET_PeerIdentity *sender;
1314   struct PeerContext *sender_ctx;
1315   struct PeerOutstandingOp out_op;
1316   uint32_t i;
1317
1318   /* Check for protocol violation */
1319   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1320   {
1321     GNUNET_break_op (0);
1322     return GNUNET_SYSERR;
1323   }
1324
1325   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1326   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1327       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1328   {
1329     LOG (GNUNET_ERROR_TYPE_ERROR,
1330         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1331         ntohl (in_msg->num_peers),
1332         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1333             sizeof (struct GNUNET_PeerIdentity));
1334     GNUNET_break_op (0);
1335     return GNUNET_SYSERR;
1336   }
1337
1338   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1339       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1340        // Guess simply casting isn't the nicest way...
1341        // FIXME wait for cadet to change this function
1342   sender_ctx = get_peer_ctx (peer_map, sender);
1343
1344   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1345   {
1346     GNUNET_break_op (0);
1347     return GNUNET_OK;
1348   }
1349
1350
1351   /* Do actual logic */
1352   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1353   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1354   {
1355     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1356     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1357         || NULL != peer_ctx->send_channel
1358         || NULL != peer_ctx->recv_channel)
1359     {
1360       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1361           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1362         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1363     }
1364     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1365     {
1366       out_op.op = insert_in_pull_list;
1367       out_op.op_cls = NULL;
1368       GNUNET_array_append (peer_ctx->outstanding_ops,
1369                            peer_ctx->num_outstanding_ops,
1370                            out_op);
1371       check_peer_live (peer_ctx);
1372     }
1373   }
1374
1375   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1376   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1377
1378   return GNUNET_OK;
1379 }
1380
1381
1382 /**
1383  * Compute a random delay.
1384  * A uniformly distributed value between mean + spread and mean - spread.
1385  *
1386  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1387  * It would return a random value between 2 and 6 min.
1388  *
1389  * @param mean the mean
1390  * @param spread the inverse amount of deviation from the mean
1391  */
1392 static struct GNUNET_TIME_Relative
1393 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1394 {
1395   struct GNUNET_TIME_Relative half_interval;
1396   struct GNUNET_TIME_Relative ret;
1397   unsigned int rand_delay;
1398   unsigned int max_rand_delay;
1399
1400   if (0 == spread)
1401   {
1402     LOG (GNUNET_ERROR_TYPE_WARNING,
1403          "Not accepting spread of 0\n");
1404     GNUNET_break (0);
1405   }
1406
1407   /* Compute random time value between spread * mean and spread * mean */
1408   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1409
1410   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1411   /**
1412    * Compute random value between (0 and 1) * round_interval
1413    * via multiplying round_interval with a 'fraction' (0 to value)/value
1414    */
1415   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1416   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1417   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1418   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1419
1420   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1421     LOG (GNUNET_ERROR_TYPE_WARNING,
1422          "Returning FOREVER_REL\n");
1423
1424   return ret;
1425 }
1426
1427
1428 /**
1429  * Send single pull request
1430  *
1431  * @param peer_id the peer to send the pull request to.
1432  */
1433 static void
1434 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1435 {
1436   struct GNUNET_MQ_Envelope *ev;
1437   struct GNUNET_MQ_Handle *mq;
1438
1439   LOG (GNUNET_ERROR_TYPE_DEBUG,
1440        "Sending PULL request to peer %s of gossiped list.\n",
1441        GNUNET_i2s (peer_id));
1442
1443   GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer_id);
1444
1445   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1446   mq = get_mq (peer_map, peer_id);
1447   GNUNET_MQ_send (mq, ev);
1448 }
1449
1450
1451 /**
1452  * Send single push
1453  *
1454  * @param peer_id the peer to send the push to.
1455  */
1456 static void
1457 send_push (struct GNUNET_PeerIdentity *peer_id)
1458 {
1459   struct GNUNET_MQ_Envelope *ev;
1460   struct GNUNET_MQ_Handle *mq;
1461
1462   LOG (GNUNET_ERROR_TYPE_DEBUG,
1463        "Sending PUSH to peer %s of gossiped list.\n",
1464        GNUNET_i2s (peer_id));
1465
1466   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1467   mq = get_mq (peer_map, peer_id);
1468   GNUNET_MQ_send (mq, ev);
1469 }
1470
1471
1472 static void
1473 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1474
1475 static void
1476 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1477
1478
1479 #ifdef ENABLE_MALICIOUS
1480 /**
1481  * Turn RPS service to act malicious.
1482  *
1483  * @param cls Closure
1484  * @param channel The channel the PUSH was received over
1485  * @param channel_ctx The context associated with this channel
1486  * @param msg The message header
1487  */
1488   static void
1489 handle_client_act_malicious (void *cls,
1490                              struct GNUNET_SERVER_Client *client,
1491                              const struct GNUNET_MessageHeader *msg)
1492 {
1493   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1494   struct GNUNET_PeerIdentity *peers;
1495   uint32_t num_mal_peers_sent;
1496   uint32_t num_mal_peers_old;
1497
1498   /* Check for protocol violation */
1499   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1500   {
1501     GNUNET_break_op (0);
1502   }
1503
1504   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1505   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1506       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1507   {
1508     LOG (GNUNET_ERROR_TYPE_ERROR,
1509         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1510         ntohl (in_msg->num_peers),
1511         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1512             sizeof (struct GNUNET_PeerIdentity));
1513     GNUNET_break_op (0);
1514   }
1515
1516
1517   /* Do actual logic */
1518   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1519   mal_type = ntohl (in_msg->type);
1520
1521   LOG (GNUNET_ERROR_TYPE_DEBUG,
1522        "Now acting malicious type %" PRIu32 "\n",
1523        mal_type);
1524
1525   if (1 == mal_type)
1526   { /* Try to maximise representation */
1527     /* Add other malicious peers to those we already know */
1528     num_mal_peers_sent = ntohl (in_msg->num_peers);
1529     num_mal_peers_old = num_mal_peers;
1530     GNUNET_array_grow (mal_peers,
1531                        num_mal_peers,
1532                        num_mal_peers + num_mal_peers_sent);
1533     memcpy (&mal_peers[num_mal_peers_old],
1534             peers,
1535             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1536
1537     /* Substitute do_round () with do_mal_round () */
1538     GNUNET_SCHEDULER_cancel (do_round_task);
1539     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1540   }
1541   else if (2 == mal_type)
1542   { /* Try to partition the network */
1543     /* Add other malicious peers to those we already know */
1544     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
1545     num_mal_peers_old = num_mal_peers;
1546     GNUNET_array_grow (mal_peers,
1547                        num_mal_peers,
1548                        num_mal_peers + num_mal_peers_sent);
1549     memcpy (&mal_peers[num_mal_peers_old],
1550             peers,
1551             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1552
1553     /* Store the one attacked peer */
1554     memcpy (&attacked_peer,
1555             &peers[num_mal_peers_sent],
1556             sizeof (struct GNUNET_PeerIdentity));
1557
1558     LOG (GNUNET_ERROR_TYPE_DEBUG,
1559          "Attacked peer is %s\n",
1560          GNUNET_i2s (&attacked_peer));
1561
1562     /* Substitute do_round () with do_mal_round () */
1563     GNUNET_SCHEDULER_cancel (do_round_task);
1564     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1565   }
1566   else if (0 == mal_type)
1567   { /* Stop acting malicious */
1568     num_mal_peers = 0;
1569     GNUNET_free (mal_peers);
1570
1571     /* Substitute do_mal_round () with do_round () */
1572     GNUNET_SCHEDULER_cancel (do_round_task);
1573     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1574   }
1575   else
1576   {
1577     GNUNET_break (0);
1578   }
1579 }
1580
1581
1582 /**
1583  * Send out PUSHes and PULLs maliciously.
1584  *
1585  * This is executed regylary.
1586  */
1587 static void
1588 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1589 {
1590   uint32_t num_pushes;
1591   uint32_t i;
1592   struct GNUNET_TIME_Relative time_next_round;
1593
1594   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously.\n");
1595
1596   /* Do malicious actions */
1597   if (1 == mal_type)
1598   { /* Try to maximise representation */
1599     num_pushes = min (min (push_limit, /* FIXME: attacked peer */ num_mal_peers), GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1600     for (i = 0 ; i < num_pushes ; i++)
1601     { /* Send PUSHes to attacked peers */
1602       //GNUNET_CONTAINER_multihashmap_iterator_create
1603       //send_push ();
1604
1605       // TODO send pulls
1606       // send_pull_request
1607     }
1608   }
1609   else if (2 == mal_type)
1610   { /**
1611      * Try to partition the network
1612      * Send as many pushes to attacked peer as possible
1613      */
1614       send_push (&attacked_peer);
1615   }
1616
1617   /* Schedule next round */
1618   time_next_round = compute_rand_delay (round_interval, 2);
1619
1620   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
1621   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
1622   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1623 }
1624 #endif /* ENABLE_MALICIOUS */
1625
1626
1627 /**
1628  * Send out PUSHes and PULLs, possibly update #gossip_list, samplers.
1629  *
1630  * This is executed regylary.
1631  */
1632 static void
1633 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1634 {
1635   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
1636
1637   uint32_t i;
1638   unsigned int *permut;
1639   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1640   struct GNUNET_PeerIdentity peer;
1641   struct GNUNET_PeerIdentity *tmp_peer;
1642
1643   LOG (GNUNET_ERROR_TYPE_DEBUG,
1644        "Printing gossip list:\n");
1645   for (i = 0 ; i < gossip_list_size ; i++)
1646     LOG (GNUNET_ERROR_TYPE_DEBUG,
1647          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1648   // TODO log lists, ...
1649
1650   /* Would it make sense to have one shuffeled gossip list and then
1651    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1652    * use the rest to update sampler?
1653    * in essence get random peers with consumption */
1654
1655   /* Send PUSHes */
1656   if (0 < gossip_list_size)
1657   {
1658     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1659                                            (unsigned int) gossip_list_size);
1660     n_peers = ceil (alpha * gossip_list_size);
1661     LOG (GNUNET_ERROR_TYPE_DEBUG,
1662          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1663          n_peers, alpha, gossip_list_size);
1664     for (i = 0 ; i < n_peers ; i++)
1665     {
1666       peer = gossip_list[permut[i]];
1667       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1668       { // FIXME if this fails schedule/loop this for later
1669         send_push (&peer);
1670       }
1671     }
1672     GNUNET_free (permut);
1673   }
1674
1675
1676   /* Send PULL requests */
1677   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1678   n_peers = ceil (beta * gossip_list_size);
1679   LOG (GNUNET_ERROR_TYPE_DEBUG,
1680        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1681        n_peers, beta, gossip_list_size);
1682   for (i = 0 ; i < n_peers ; i++)
1683   {
1684     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1685         pending_pull_reply_list, pending_pull_reply_list_size);
1686     if (NULL != tmp_peer)
1687     {
1688       peer = *tmp_peer;
1689       GNUNET_free (tmp_peer);
1690
1691       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1692       {
1693         send_pull_request (&peer);
1694       }
1695     }
1696   }
1697
1698
1699   /* Update gossip list */
1700
1701   if ( push_list_size <= alpha * gossip_list_size &&
1702        push_list_size != 0 &&
1703        pull_list_size != 0 )
1704   {
1705     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1706
1707     uint32_t first_border;
1708     uint32_t second_border;
1709     uint32_t r_index;
1710     uint32_t peers_to_clean_size;
1711     struct GNUNET_PeerIdentity *peers_to_clean;
1712
1713     peers_to_clean = NULL;
1714     peers_to_clean_size = 0;
1715     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
1716     memcpy (peers_to_clean,
1717             gossip_list,
1718             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
1719
1720     first_border  =                ceil (alpha * sampler_size_est_need);
1721     second_border = first_border + ceil (beta  * sampler_size_est_need);
1722
1723     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1724
1725     for (i = 0 ; i < first_border ; i++)
1726     { // TODO use RPS_sampler_get_n_rand_peers
1727       /* Update gossip list with peers received through PUSHes */
1728       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1729                                        push_list_size);
1730       gossip_list[i] = push_list[r_index];
1731       // TODO change the peer_flags accordingly
1732     }
1733
1734     for (i = first_border ; i < second_border ; i++)
1735     {
1736       /* Update gossip list with peers received through PULLs */
1737       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1738                                        pull_list_size);
1739       gossip_list[i] = pull_list[r_index];
1740       // TODO change the peer_flags accordingly
1741     }
1742
1743     for (i = second_border ; i < sampler_size_est_need ; i++)
1744     {
1745       /* Update gossip list with peers from history */
1746       RPS_sampler_get_n_rand_peers (prot_sampler, hist_update, NULL, 1, GNUNET_NO);
1747       num_hist_update_tasks++;
1748       // TODO change the peer_flags accordingly
1749     }
1750
1751     for (i = 0 ; i < gossip_list_size ; i++)
1752       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
1753
1754     for (i = 0 ; i < peers_to_clean_size ; i++)
1755       peer_clean (&peers_to_clean[i]);
1756
1757     GNUNET_free (peers_to_clean);
1758   }
1759   else
1760   {
1761     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1762   }
1763   // TODO independent of that also get some peers from CADET_get_peers()?
1764
1765
1766   /* Update samplers */
1767   for ( i = 0 ; i < push_list_size ; i++ )
1768   {
1769     LOG (GNUNET_ERROR_TYPE_DEBUG,
1770          "Updating with peer %s from push list\n",
1771          GNUNET_i2s (&push_list[i]));
1772     RPS_sampler_update (prot_sampler,   &push_list[i]);
1773     RPS_sampler_update (client_sampler, &push_list[i]);
1774     // TODO set in_flag?
1775   }
1776
1777   for ( i = 0 ; i < pull_list_size ; i++ )
1778   {
1779     LOG (GNUNET_ERROR_TYPE_DEBUG,
1780          "Updating with peer %s from pull list\n",
1781          GNUNET_i2s (&pull_list[i]));
1782     RPS_sampler_update (prot_sampler,   &push_list[i]);
1783     RPS_sampler_update (client_sampler, &push_list[i]);
1784     // TODO set in_flag?
1785   }
1786
1787
1788   /* Empty push/pull lists */
1789   GNUNET_array_grow (push_list, push_list_size, 0);
1790   GNUNET_array_grow (pull_list, pull_list_size, 0);
1791
1792   struct GNUNET_TIME_Relative time_next_round;
1793
1794   time_next_round = compute_rand_delay (round_interval, 2);
1795
1796   /* Schedule next round */
1797   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1798   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
1799   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1800 }
1801
1802
1803 static void
1804 rps_start (struct GNUNET_SERVER_Handle *server);
1805
1806
1807 /**
1808  * This is called from GNUNET_CADET_get_peers().
1809  *
1810  * It is called on every peer(ID) that cadet somehow has contact with.
1811  * We use those to initialise the sampler.
1812  */
1813 void
1814 init_peer_cb (void *cls,
1815               const struct GNUNET_PeerIdentity *peer,
1816               int tunnel, // "Do we have a tunnel towards this peer?"
1817               unsigned int n_paths, // "Number of known paths towards this peer"
1818               unsigned int best_path) // "How long is the best path?
1819                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1820 {
1821   struct PeerOutstandingOp out_op;
1822   struct PeerContext *peer_ctx;
1823
1824   if (NULL != peer
1825       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer))
1826   {
1827     LOG (GNUNET_ERROR_TYPE_DEBUG,
1828         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1829         GNUNET_i2s (peer), peer, gossip_list_size);
1830
1831     // maybe create a function for that
1832     peer_ctx = get_peer_ctx (peer_map, peer);
1833     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1834     {
1835       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1836       {
1837         out_op.op = insert_in_sampler;
1838         out_op.op_cls = NULL;
1839         GNUNET_array_append (peer_ctx->outstanding_ops,
1840                              peer_ctx->num_outstanding_ops,
1841                              out_op);
1842       }
1843
1844       if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1845       {
1846         out_op.op = insert_in_gossip_list;
1847         out_op.op_cls = NULL;
1848         GNUNET_array_append (peer_ctx->outstanding_ops,
1849                              peer_ctx->num_outstanding_ops,
1850                              out_op);
1851       }
1852
1853       /* Trigger livelyness test on peer */
1854       check_peer_live (peer_ctx);
1855     }
1856
1857     // send push/pull to each of those peers?
1858   }
1859 }
1860
1861
1862 /**
1863  * Clean the send channel of a peer
1864  */
1865 void
1866 peer_clean (const struct GNUNET_PeerIdentity *peer)
1867 {
1868   struct PeerContext *peer_ctx;
1869   struct GNUNET_CADET_Channel *channel;
1870
1871   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
1872       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1873   {
1874     peer_ctx = get_peer_ctx (peer_map, peer);
1875     if (NULL != peer_ctx->send_channel)
1876     {
1877       channel = peer_ctx->send_channel;
1878       peer_ctx->send_channel = NULL;
1879       GNUNET_CADET_channel_destroy (channel);
1880     }
1881   }
1882 }
1883
1884
1885 /**
1886  * Callback used to remove peers from the multipeermap.
1887  */
1888   int
1889 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1890 {
1891   struct PeerContext *peer_ctx;
1892   const struct GNUNET_CADET_Channel *channel =
1893     (const struct GNUNET_CADET_Channel *) cls;
1894   struct GNUNET_CADET_Channel *recv;
1895   struct GNUNET_CADET_Channel *send;
1896
1897   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, value))
1898   {
1899     peer_ctx = (struct PeerContext *) value;
1900
1901     if (0 != peer_ctx->num_outstanding_ops)
1902       GNUNET_array_grow (peer_ctx->outstanding_ops,
1903                          peer_ctx->num_outstanding_ops,
1904                          0);
1905
1906     if (NULL != peer_ctx->mq)
1907     {
1908       GNUNET_MQ_destroy (peer_ctx->mq);
1909       peer_ctx->mq = NULL;
1910     }
1911
1912
1913     if (NULL != peer_ctx->is_live_task)
1914     {
1915     LOG (GNUNET_ERROR_TYPE_DEBUG,
1916          "Trying to cancle is_live_task for peer %s\n",
1917          GNUNET_i2s (key));
1918       GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1919       peer_ctx->is_live_task = NULL;
1920     }
1921
1922     send = peer_ctx->send_channel;
1923     peer_ctx->send_channel = NULL;
1924     if (NULL != send
1925         && channel != send)
1926     {
1927       GNUNET_CADET_channel_destroy (send);
1928     }
1929
1930     recv = peer_ctx->send_channel;
1931     peer_ctx->recv_channel = NULL;
1932     if (NULL != recv
1933         && channel != recv)
1934     {
1935       GNUNET_CADET_channel_destroy (recv);
1936     }
1937
1938     if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1939       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1940     else
1941       GNUNET_free (peer_ctx);
1942   }
1943
1944   return GNUNET_YES;
1945 }
1946
1947
1948 /**
1949  * Task run during shutdown.
1950  *
1951  * @param cls unused
1952  * @param tc unused
1953  */
1954 static void
1955 shutdown_task (void *cls,
1956                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1957 {
1958   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1959
1960   if (NULL != do_round_task)
1961   {
1962     GNUNET_SCHEDULER_cancel (do_round_task);
1963     do_round_task = NULL;
1964   }
1965
1966
1967   {
1968   if (GNUNET_SYSERR ==
1969         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1970     LOG (GNUNET_ERROR_TYPE_WARNING,
1971         "Iterating over peers to disconnect from them was cancelled\n");
1972   }
1973
1974   GNUNET_NSE_disconnect (nse);
1975   GNUNET_CADET_disconnect (cadet_handle);
1976   RPS_sampler_destroy (prot_sampler);
1977   RPS_sampler_destroy (client_sampler);
1978   LOG (GNUNET_ERROR_TYPE_DEBUG,
1979        "Size of the peermap: %u\n",
1980        GNUNET_CONTAINER_multipeermap_size (peer_map));
1981   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
1982   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1983   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1984   GNUNET_array_grow (push_list, push_list_size, 0);
1985   GNUNET_array_grow (pull_list, pull_list_size, 0);
1986   #ifdef ENABLE_MALICIOUS
1987   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
1988   // TODO empty attacked_peers DLL
1989   #endif /* ENABLE_MALICIOUS */
1990 }
1991
1992
1993 /**
1994  * A client disconnected.  Remove all of its data structure entries.
1995  *
1996  * @param cls closure, NULL
1997  * @param client identification of the client
1998  */
1999 static void
2000 handle_client_disconnect (void *cls,
2001                           struct GNUNET_SERVER_Client * client)
2002 {
2003 }
2004
2005
2006 /**
2007  * Handle the channel a peer opens to us.
2008  *
2009  * @param cls The closure
2010  * @param channel The channel the peer wants to establish
2011  * @param initiator The peer's peer ID
2012  * @param port The port the channel is being established over
2013  * @param options Further options
2014  */
2015   static void *
2016 handle_inbound_channel (void *cls,
2017                         struct GNUNET_CADET_Channel *channel,
2018                         const struct GNUNET_PeerIdentity *initiator,
2019                         uint32_t port,
2020                         enum GNUNET_CADET_ChannelOption options)
2021 {
2022   struct PeerContext *peer_ctx;
2023   struct GNUNET_PeerIdentity peer;
2024
2025   peer = *initiator;
2026   LOG (GNUNET_ERROR_TYPE_DEBUG,
2027       "New channel was established to us (Peer %s).\n",
2028       GNUNET_i2s (&peer));
2029
2030   GNUNET_assert (NULL != channel);
2031
2032   // we might not even store the recv_channel
2033
2034   peer_ctx = get_peer_ctx (peer_map, &peer);
2035   // FIXME what do we do if a channel is established twice?
2036   //       overwrite? Clean old channel? ...?
2037   //if (NULL != peer_ctx->recv_channel)
2038   //{
2039   //  peer_ctx->recv_channel = channel;
2040   //}
2041   peer_ctx->recv_channel = channel;
2042
2043   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
2044       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
2045
2046   peer_is_live (peer_ctx);
2047
2048   return NULL; // TODO
2049 }
2050
2051
2052 /**
2053  * This is called when a remote peer destroys a channel.
2054  *
2055  * @param cls The closure
2056  * @param channel The channel being closed
2057  * @param channel_ctx The context associated with this channel
2058  */
2059   static void
2060 cleanup_channel (void *cls,
2061                 const struct GNUNET_CADET_Channel *channel,
2062                 void *channel_ctx)
2063 {
2064   struct GNUNET_PeerIdentity *peer;
2065   struct PeerContext *peer_ctx;
2066
2067   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2068       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2069        // Guess simply casting isn't the nicest way...
2070        // FIXME wait for cadet to change this function
2071   LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up channel to peer %s\n",
2072        GNUNET_i2s (peer));
2073
2074   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2075   {
2076     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2077
2078     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2079       return;
2080
2081     if (channel == peer_ctx->send_channel)
2082     { /* Peer probably went down */
2083       rem_from_list (&gossip_list, &gossip_list_size, peer);
2084       rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, peer);
2085
2086       /* Somwewhat {ab,re}use the iterator function */
2087       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2088       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2089     }
2090     else /* Other peer doesn't want to send us messages anymore */
2091       peer_ctx->recv_channel = NULL;
2092   }
2093 }
2094
2095
2096 /**
2097  * Actually start the service.
2098  */
2099   static void
2100 rps_start (struct GNUNET_SERVER_Handle *server)
2101 {
2102   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2103     {&handle_client_request,     NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2104       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2105     {&handle_client_seed,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2106     #ifdef ENABLE_MALICIOUS
2107     {&handle_client_act_malicious, NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2108     #endif /* ENABLE_MALICIOUS */
2109     {NULL, NULL, 0, 0}
2110   };
2111
2112   GNUNET_SERVER_add_handlers (server, handlers);
2113   GNUNET_SERVER_disconnect_notify (server,
2114                                    &handle_client_disconnect,
2115                                    NULL);
2116   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
2117
2118
2119   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2120   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2121
2122   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2123                                                         &shutdown_task,
2124                                                         NULL);
2125 }
2126
2127
2128 /**
2129  * Process statistics requests.
2130  *
2131  * @param cls closure
2132  * @param server the initialized server
2133  * @param c configuration to use
2134  */
2135   static void
2136 run (void *cls,
2137      struct GNUNET_SERVER_Handle *server,
2138      const struct GNUNET_CONFIGURATION_Handle *c)
2139 {
2140   // TODO check what this does -- copied from gnunet-boss
2141   // - seems to work as expected
2142   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2143   cfg = c;
2144
2145
2146   /* Get own ID */
2147   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2148   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2149               "STARTING SERVICE (rps) for peer [%s]\n",
2150               GNUNET_i2s (&own_identity));
2151   #ifdef ENABLE_MALICIOUS
2152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2153               "Malicious execution compiled in.\n");
2154   #endif /* ENABLE_MALICIOUS */
2155
2156
2157
2158   /* Get time interval from the configuration */
2159   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2160                                                         "ROUNDINTERVAL",
2161                                                         &round_interval))
2162   {
2163     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
2164     GNUNET_SCHEDULER_shutdown ();
2165     return;
2166   }
2167
2168   /* Get initial size of sampler/gossip list from the configuration */
2169   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
2170                                                          "INITSIZE",
2171                                                          (long long unsigned int *) &sampler_size_est_need))
2172   {
2173     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
2174     GNUNET_SCHEDULER_shutdown ();
2175     return;
2176   }
2177   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2178
2179
2180   gossip_list = NULL;
2181
2182
2183   /* connect to NSE */
2184   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2185   // TODO check whether that was successful
2186   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
2187
2188
2189   alpha = 0.45;
2190   beta  = 0.45;
2191
2192   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2193
2194
2195   /* Initialise cadet */
2196   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2197     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2198       sizeof (struct GNUNET_MessageHeader)},
2199     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2200       sizeof (struct GNUNET_MessageHeader)},
2201     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2202     {NULL, 0, 0}
2203   };
2204
2205   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2206   cadet_handle = GNUNET_CADET_connect (cfg,
2207                                        cls,
2208                                        &handle_inbound_channel,
2209                                        &cleanup_channel,
2210                                        cadet_handlers,
2211                                        ports);
2212   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
2213
2214
2215   /* Initialise sampler */
2216   struct GNUNET_TIME_Relative half_round_interval;
2217   struct GNUNET_TIME_Relative  max_round_interval;
2218
2219   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2220   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2221
2222   prot_sampler =   RPS_sampler_init (sampler_size_est_need, max_round_interval);
2223   client_sampler = RPS_sampler_init (sampler_size_est_need, max_round_interval);
2224
2225   /* Initialise push and pull maps */
2226   push_list = NULL;
2227   push_list_size = 0;
2228   pull_list = NULL;
2229   pull_list_size = 0;
2230   pending_pull_reply_list = NULL;
2231   pending_pull_reply_list_size = 0;
2232
2233
2234   num_hist_update_tasks = 0;
2235
2236
2237   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2238   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2239   // TODO send push/pull to each of those peers?
2240
2241
2242   rps_start (server);
2243 }
2244
2245
2246 /**
2247  * The main function for the rps service.
2248  *
2249  * @param argc number of arguments from the command line
2250  * @param argv command line arguments
2251  * @return 0 ok, 1 on error
2252  */
2253   int
2254 main (int argc, char *const *argv)
2255 {
2256   return (GNUNET_OK ==
2257           GNUNET_SERVICE_run (argc,
2258                               argv,
2259                               "rps",
2260                               GNUNET_SERVICE_OPTION_NONE,
2261                               &run, NULL)) ? 0 : 1;
2262 }
2263
2264 /* end of gnunet-service-rps.c */