b5333ae282a1fb09b6166d2110902d33bcad2d55
[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   peer_ctx->is_live_task = NULL;
697   LOG (GNUNET_ERROR_TYPE_DEBUG,
698        "Set ->is_live_task = NULL for peer %s\n",
699        GNUNET_i2s (&peer_ctx->peer_id));
700
701   if (NULL != buf
702       && 0 != size)
703   {
704     peer_is_live (peer_ctx);
705   }
706   else
707   {
708     LOG (GNUNET_ERROR_TYPE_WARNING,
709          "Problems establishing a connection to peer %s in order to check liveliness\n",
710          GNUNET_i2s (&peer_ctx->peer_id));
711     // TODO reschedule? cleanup?
712   }
713
714   //if (NULL != peer_ctx->is_live_task)
715   //{
716   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
717   //       "Trying to cancle is_live_task for peer %s\n",
718   //       GNUNET_i2s (&peer_ctx->peer_id));
719   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
720   //  peer_ctx->is_live_task = NULL;
721   //}
722
723   return 0;
724 }
725
726
727 /**
728  * Get the channel of a peer. If not existing, create.
729  */
730   struct GNUNET_CADET_Channel *
731 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
732              const struct GNUNET_PeerIdentity *peer)
733 {
734   struct PeerContext *peer_ctx;
735
736   peer_ctx = get_peer_ctx (peer_map, peer);
737   if (NULL == peer_ctx->send_channel)
738   {
739     LOG (GNUNET_ERROR_TYPE_DEBUG,
740          "Trying to establish channel to peer %s\n",
741          GNUNET_i2s (peer));
742
743     peer_ctx->send_channel =
744       GNUNET_CADET_channel_create (cadet_handle,
745                                    NULL,
746                                    peer,
747                                    GNUNET_RPS_CADET_PORT,
748                                    GNUNET_CADET_OPTION_RELIABLE);
749
750     // do I have to explicitly put it in the peer_map?
751     (void) GNUNET_CONTAINER_multipeermap_put
752       (peer_map,
753        peer,
754        peer_ctx,
755        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
756   }
757   return peer_ctx->send_channel;
758 }
759
760
761 /**
762  * Get the message queue of a specific peer.
763  *
764  * If we already have a message queue open to this client,
765  * simply return it, otherways create one.
766  */
767   struct GNUNET_MQ_Handle *
768 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
769         const struct GNUNET_PeerIdentity *peer_id)
770 {
771   struct PeerContext *peer_ctx;
772
773   peer_ctx = get_peer_ctx (peer_map, peer_id);
774
775   if (NULL == peer_ctx->mq)
776   {
777     (void) get_channel (peer_map, peer_id);
778     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
779     //do I have to explicitly put it in the peer_map?
780     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
781                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
782   }
783   return peer_ctx->mq;
784 }
785
786
787 /**
788  * Issue check whether peer is live
789  *
790  * @param peer_ctx the context of the peer
791  */
792 void
793 check_peer_live (struct PeerContext *peer_ctx)
794 {
795   (void) get_channel (peer_map, &peer_ctx->peer_id);
796   LOG (GNUNET_ERROR_TYPE_DEBUG,
797        "Get informed about peer %s getting live\n",
798        GNUNET_i2s (&peer_ctx->peer_id));
799   if (NULL == peer_ctx->is_live_task)
800   {
801     peer_ctx->is_live_task =
802         GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
803                                             GNUNET_NO,
804                                             GNUNET_TIME_UNIT_FOREVER_REL,
805                                             sizeof (struct GNUNET_MessageHeader),
806                                             cadet_ntfy_tmt_rdy_cb,
807                                             peer_ctx);
808   }
809   else
810   {
811     LOG (GNUNET_ERROR_TYPE_DEBUG,
812          "Already waiting for notification\n");
813   }
814 }
815
816
817 /**
818  * Sum all time relatives of an array.
819   */
820   struct GNUNET_TIME_Relative
821 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
822 {
823   struct GNUNET_TIME_Relative sum;
824   uint32_t i;
825
826   sum = GNUNET_TIME_UNIT_ZERO;
827   for ( i = 0 ; i < arr_size ; i++ )
828   {
829     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
830   }
831   return sum;
832 }
833
834
835 /**
836  * Compute the average of given time relatives.
837  */
838   struct GNUNET_TIME_Relative
839 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
840 {
841   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
842 }
843
844
845 /**
846  * Insert PeerID in #pull_list
847  *
848  * Called once we know a peer is live.
849  */
850   void
851 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
852 {
853   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
854     GNUNET_array_append (pull_list, pull_list_size, *peer);
855
856   peer_clean (peer);
857 }
858
859 /**
860  * Check whether #insert_in_pull_list was already scheduled
861  */
862   int
863 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
864 {
865   unsigned int i;
866
867   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
868     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
869       return GNUNET_YES;
870   return GNUNET_NO;
871 }
872
873
874 /**
875  * Insert PeerID in #gossip_list
876  *
877  * Called once we know a peer is live.
878  */
879   void
880 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
881 {
882   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
883     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
884
885   (void) get_channel (peer_map, peer);
886 }
887
888 /**
889  * Check whether #insert_in_gossip_list was already scheduled
890  */
891   int
892 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
893 {
894   unsigned int i;
895
896   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
897     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
898       return GNUNET_YES;
899   return GNUNET_NO;
900 }
901
902
903 /**
904  * Update sampler with given PeerID.
905  */
906   void
907 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
908 {
909   LOG (GNUNET_ERROR_TYPE_DEBUG,
910        "Updating samplers with peer %s from insert_in_sampler()\n",
911        GNUNET_i2s (peer));
912   RPS_sampler_update (prot_sampler,   peer);
913   RPS_sampler_update (client_sampler, peer);
914 }
915
916
917 /**
918  * Check whether #insert_in_sampler was already scheduled
919  */
920 static int
921 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
922 {
923   unsigned int i;
924
925   for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
926     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
927       return GNUNET_YES;
928   return GNUNET_NO;
929 }
930
931
932 /**
933  * Wrapper around #RPS_sampler_resize()
934  *
935  * If we do not have enough sampler elements, double current sampler size
936  * If we have more than enough sampler elements, halv current sampler size
937  */
938 static void
939 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
940 {
941   unsigned int sampler_size;
942
943   // TODO statistics
944   // TODO respect the min, max
945   sampler_size = RPS_sampler_get_size (sampler);
946   if (sampler_size > new_size * 4)
947   { /* Shrinking */
948     RPS_sampler_resize (sampler, sampler_size / 2);
949   }
950   else if (sampler_size < new_size)
951   { /* Growing */
952     RPS_sampler_resize (sampler, sampler_size * 2);
953   }
954   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
955 }
956
957
958 /**
959  * Wrapper around #RPS_sampler_resize() resizing the client sampler
960  */
961 static void
962 client_resize_wrapper ()
963 {
964   uint32_t bigger_size;
965   unsigned int sampler_size;
966
967   // TODO statistics
968
969   sampler_size = RPS_sampler_get_size (client_sampler);
970
971   if (sampler_size_est_need > sampler_size_client_need)
972     bigger_size = sampler_size_est_need;
973   else
974     bigger_size = sampler_size_client_need;
975
976   // TODO respect the min, max
977   resize_wrapper (client_sampler, bigger_size);
978   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
979 }
980
981
982 /**
983  * Estimate request rate
984  *
985  * Called every time we receive a request from the client.
986  */
987   void
988 est_request_rate()
989 {
990   struct GNUNET_TIME_Relative max_round_duration;
991
992   if (request_deltas_size > req_counter)
993     req_counter++;
994   if ( 1 < req_counter)
995   {
996     /* Shift last request deltas to the right */
997     memcpy (&request_deltas[1],
998         request_deltas,
999         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
1000
1001     /* Add current delta to beginning */
1002     request_deltas[0] =
1003         GNUNET_TIME_absolute_get_difference (last_request,
1004                                              GNUNET_TIME_absolute_get ());
1005     request_rate = T_relative_avg (request_deltas, req_counter);
1006
1007     /* Compute the duration a round will maximally take */
1008     max_round_duration =
1009         GNUNET_TIME_relative_add (round_interval,
1010                                   GNUNET_TIME_relative_divide (round_interval, 2));
1011
1012     /* Set the estimated size the sampler has to have to
1013      * satisfy the current client request rate */
1014     sampler_size_client_need =
1015         max_round_duration.rel_value_us / request_rate.rel_value_us;
1016
1017     /* Resize the sampler */
1018     client_resize_wrapper ();
1019   }
1020   last_request = GNUNET_TIME_absolute_get ();
1021 }
1022
1023
1024 /***********************************************************************
1025  * /Util functions
1026 ***********************************************************************/
1027
1028
1029
1030
1031
1032 /**
1033  * Function called by NSE.
1034  *
1035  * Updates sizes of sampler list and gossip list and adapt those lists
1036  * accordingly.
1037  */
1038   void
1039 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1040               double logestimate, double std_dev)
1041 {
1042   double estimate;
1043   //double scale; // TODO this might go gloabal/config
1044
1045   LOG (GNUNET_ERROR_TYPE_DEBUG,
1046        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1047        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1048   //scale = .01;
1049   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1050   // GNUNET_NSE_log_estimate_to_n (logestimate);
1051   estimate = pow (estimate, 1.0 / 3);
1052   // TODO add if std_dev is a number
1053   // estimate += (std_dev * scale);
1054   if (2 < ceil (estimate))
1055   {
1056     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1057     sampler_size_est_need = estimate;
1058   } else
1059     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1060
1061   /* If the NSE has changed adapt the lists accordingly */
1062   resize_wrapper (prot_sampler, sampler_size_est_need);
1063   client_resize_wrapper ();
1064 }
1065
1066
1067 /**
1068  * Callback called once the requested PeerIDs are ready.
1069  *
1070  * Sends those to the requesting client.
1071  */
1072 void client_respond (void *cls,
1073     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
1074 {
1075   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
1076   struct GNUNET_MQ_Envelope *ev;
1077   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1078   struct GNUNET_SERVER_Client *client;
1079   uint32_t size_needed;
1080   struct client_ctx *cli_ctx;
1081
1082   client = (struct GNUNET_SERVER_Client *) cls;
1083
1084   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1085                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1086
1087   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1088
1089   ev = GNUNET_MQ_msg_extra (out_msg,
1090                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1091                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1092   out_msg->num_peers = htonl (num_peers);
1093
1094   memcpy (&out_msg[1],
1095       ids,
1096       num_peers * sizeof (struct GNUNET_PeerIdentity));
1097   GNUNET_free (ids);
1098
1099   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
1100   if (NULL == cli_ctx) {
1101     cli_ctx = GNUNET_new (struct client_ctx);
1102     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
1103     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
1104   }
1105
1106   GNUNET_MQ_send (cli_ctx->mq, ev);
1107 }
1108
1109
1110 /**
1111  * Handle RPS request from the client.
1112  *
1113  * @param cls closure
1114  * @param client identification of the client
1115  * @param message the actual message
1116  */
1117 static void
1118 handle_client_request (void *cls,
1119             struct GNUNET_SERVER_Client *client,
1120             const struct GNUNET_MessageHeader *message)
1121 {
1122   struct GNUNET_RPS_CS_RequestMessage *msg;
1123   uint32_t num_peers;
1124   uint32_t size_needed;
1125   uint32_t i;
1126
1127   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1128
1129   num_peers = ntohl (msg->num_peers);
1130   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1131                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1132
1133   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1134   {
1135     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1136     return;
1137   }
1138
1139   for (i = 0 ; i < num_peers ; i++)
1140     est_request_rate();
1141
1142   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
1143
1144   RPS_sampler_get_n_rand_peers (client_sampler, client_respond,
1145                                 client, num_peers, GNUNET_YES);
1146
1147   GNUNET_SERVER_receive_done (client,
1148                               GNUNET_OK);
1149 }
1150
1151
1152 /**
1153  * Handle seed from the client.
1154  *
1155  * @param cls closure
1156  * @param client identification of the client
1157  * @param message the actual message
1158  */
1159   static void
1160 handle_client_seed (void *cls,
1161                     struct GNUNET_SERVER_Client *client,
1162                     const struct GNUNET_MessageHeader *message)
1163 {
1164   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1165   struct GNUNET_PeerIdentity *peers;
1166   uint32_t num_peers;
1167   uint32_t i;
1168
1169   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1170   {
1171     GNUNET_break_op (0);
1172     GNUNET_SERVER_receive_done (client,
1173                                 GNUNET_SYSERR);
1174   }
1175
1176   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1177   num_peers = ntohl (in_msg->num_peers);
1178   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1179   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1180   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1181
1182   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1183       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1184   {
1185     GNUNET_break_op (0);
1186     GNUNET_SERVER_receive_done (client,
1187                                 GNUNET_SYSERR);
1188   }
1189
1190   LOG (GNUNET_ERROR_TYPE_DEBUG,
1191        "Client seeded peers:\n");
1192   print_peer_list (peers, num_peers);
1193
1194   // TODO check for validity of ids
1195
1196   for (i = 0 ; i < num_peers ; i++)
1197   {
1198     LOG (GNUNET_ERROR_TYPE_DEBUG,
1199          "Updating samplers with seed %" PRIX32 ": %s\n",
1200          i,
1201          GNUNET_i2s (&peers[i]));
1202
1203     RPS_sampler_update (prot_sampler,   &peers[i]);
1204     RPS_sampler_update (client_sampler, &peers[i]);
1205   }
1206
1207   //GNUNET_free (peers);
1208
1209   GNUNET_SERVER_receive_done (client,
1210                                                 GNUNET_OK);
1211 }
1212
1213
1214 /**
1215  * Handle a PUSH message from another peer.
1216  *
1217  * Check the proof of work and store the PeerID
1218  * in the temporary list for pushed PeerIDs.
1219  *
1220  * @param cls Closure
1221  * @param channel The channel the PUSH was received over
1222  * @param channel_ctx The context associated with this channel
1223  * @param msg The message header
1224  */
1225 static int
1226 handle_peer_push (void *cls,
1227     struct GNUNET_CADET_Channel *channel,
1228     void **channel_ctx,
1229     const struct GNUNET_MessageHeader *msg)
1230 {
1231   const struct GNUNET_PeerIdentity *peer;
1232
1233   // (check the proof of work)
1234
1235   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1236   // FIXME wait for cadet to change this function
1237   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1238
1239   /* Add the sending peer to the push_list */
1240   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1241     GNUNET_array_append (push_list, push_list_size, *peer);
1242
1243   return GNUNET_OK;
1244 }
1245
1246 /**
1247  * Handle PULL REQUEST request message from another peer.
1248  *
1249  * Reply with the gossip list of PeerIDs.
1250  *
1251  * @param cls Closure
1252  * @param channel The channel the PUSH was received over
1253  * @param channel_ctx The context associated with this channel
1254  * @param msg The message header
1255  */
1256 static int
1257 handle_peer_pull_request (void *cls,
1258     struct GNUNET_CADET_Channel *channel,
1259     void **channel_ctx,
1260     const struct GNUNET_MessageHeader *msg)
1261 {
1262   struct GNUNET_PeerIdentity *peer;
1263   uint32_t send_size;
1264   struct GNUNET_MQ_Handle *mq;
1265   struct GNUNET_MQ_Envelope *ev;
1266   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1267
1268
1269   peer = (struct GNUNET_PeerIdentity *)
1270     GNUNET_CADET_channel_get_info (channel,
1271                                    GNUNET_CADET_OPTION_PEER);
1272   // FIXME wait for cadet to change this function
1273
1274   /* Compute actual size */
1275   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1276               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1277
1278   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1279     /* Compute number of peers to send
1280      * If too long, simply truncate */
1281   // TODO select random ones via permutation
1282     send_size =
1283       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1284        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1285        sizeof (struct GNUNET_PeerIdentity);
1286   else
1287     send_size = gossip_list_size;
1288
1289   LOG (GNUNET_ERROR_TYPE_DEBUG,
1290       "PULL REQUEST from peer %s received, going to send %u peers\n",
1291       GNUNET_i2s (peer), send_size);
1292
1293   mq = get_mq (peer_map, peer);
1294
1295   ev = GNUNET_MQ_msg_extra (out_msg,
1296                            send_size * sizeof (struct GNUNET_PeerIdentity),
1297                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1298   //out_msg->num_peers = htonl (gossip_list_size);
1299   out_msg->num_peers = htonl (send_size);
1300   memcpy (&out_msg[1], gossip_list,
1301          send_size * sizeof (struct GNUNET_PeerIdentity));
1302
1303   GNUNET_MQ_send (mq, ev);
1304
1305   return GNUNET_OK;
1306 }
1307
1308
1309 /**
1310  * Handle PULL REPLY message from another peer.
1311  *
1312  * Check whether we sent a corresponding request and
1313  * whether this reply is the first one.
1314  *
1315  * @param cls Closure
1316  * @param channel The channel the PUSH was received over
1317  * @param channel_ctx The context associated with this channel
1318  * @param msg The message header
1319  */
1320   static int
1321 handle_peer_pull_reply (void *cls,
1322                         struct GNUNET_CADET_Channel *channel,
1323                         void **channel_ctx,
1324                         const struct GNUNET_MessageHeader *msg)
1325 {
1326   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1327
1328   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1329   struct GNUNET_PeerIdentity *peers;
1330   struct PeerContext *peer_ctx;
1331   struct GNUNET_PeerIdentity *sender;
1332   struct PeerContext *sender_ctx;
1333   struct PeerOutstandingOp out_op;
1334   uint32_t i;
1335
1336   /* Check for protocol violation */
1337   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1338   {
1339     GNUNET_break_op (0);
1340     return GNUNET_SYSERR;
1341   }
1342
1343   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1344   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1345       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1346   {
1347     LOG (GNUNET_ERROR_TYPE_ERROR,
1348         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1349         ntohl (in_msg->num_peers),
1350         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1351             sizeof (struct GNUNET_PeerIdentity));
1352     GNUNET_break_op (0);
1353     return GNUNET_SYSERR;
1354   }
1355
1356   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1357       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1358        // Guess simply casting isn't the nicest way...
1359        // FIXME wait for cadet to change this function
1360   sender_ctx = get_peer_ctx (peer_map, sender);
1361
1362   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1363   {
1364     GNUNET_break_op (0);
1365     return GNUNET_OK;
1366   }
1367
1368
1369   /* Do actual logic */
1370   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1371   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1372   {
1373     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1374     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1375         || NULL != peer_ctx->send_channel
1376         || NULL != peer_ctx->recv_channel)
1377     {
1378       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1379           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1380         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1381     }
1382     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1383     {
1384       out_op.op = insert_in_pull_list;
1385       out_op.op_cls = NULL;
1386       GNUNET_array_append (peer_ctx->outstanding_ops,
1387                            peer_ctx->num_outstanding_ops,
1388                            out_op);
1389       check_peer_live (peer_ctx);
1390     }
1391   }
1392
1393   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1394   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1395
1396   return GNUNET_OK;
1397 }
1398
1399
1400 /**
1401  * Compute a random delay.
1402  * A uniformly distributed value between mean + spread and mean - spread.
1403  *
1404  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1405  * It would return a random value between 2 and 6 min.
1406  *
1407  * @param mean the mean
1408  * @param spread the inverse amount of deviation from the mean
1409  */
1410 static struct GNUNET_TIME_Relative
1411 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1412 {
1413   struct GNUNET_TIME_Relative half_interval;
1414   struct GNUNET_TIME_Relative ret;
1415   unsigned int rand_delay;
1416   unsigned int max_rand_delay;
1417
1418   if (0 == spread)
1419   {
1420     LOG (GNUNET_ERROR_TYPE_WARNING,
1421          "Not accepting spread of 0\n");
1422     GNUNET_break (0);
1423   }
1424
1425   /* Compute random time value between spread * mean and spread * mean */
1426   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1427
1428   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1429   /**
1430    * Compute random value between (0 and 1) * round_interval
1431    * via multiplying round_interval with a 'fraction' (0 to value)/value
1432    */
1433   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1434   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1435   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1436   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1437
1438   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1439     LOG (GNUNET_ERROR_TYPE_WARNING,
1440          "Returning FOREVER_REL\n");
1441
1442   return ret;
1443 }
1444
1445
1446 /**
1447  * Send single pull request
1448  *
1449  * @param peer_id the peer to send the pull request to.
1450  */
1451 static void
1452 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1453 {
1454   struct GNUNET_MQ_Envelope *ev;
1455   struct GNUNET_MQ_Handle *mq;
1456
1457   LOG (GNUNET_ERROR_TYPE_DEBUG,
1458        "Sending PULL request to peer %s of gossiped list.\n",
1459        GNUNET_i2s (peer_id));
1460
1461   GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer_id);
1462
1463   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1464   mq = get_mq (peer_map, peer_id);
1465   GNUNET_MQ_send (mq, ev);
1466 }
1467
1468
1469 /**
1470  * Send single push
1471  *
1472  * @param peer_id the peer to send the push to.
1473  */
1474 static void
1475 send_push (struct GNUNET_PeerIdentity *peer_id)
1476 {
1477   struct GNUNET_MQ_Envelope *ev;
1478   struct GNUNET_MQ_Handle *mq;
1479
1480   LOG (GNUNET_ERROR_TYPE_DEBUG,
1481        "Sending PUSH to peer %s of gossiped list.\n",
1482        GNUNET_i2s (peer_id));
1483
1484   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1485   mq = get_mq (peer_map, peer_id);
1486   GNUNET_MQ_send (mq, ev);
1487 }
1488
1489
1490 static void
1491 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1492
1493 static void
1494 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1495
1496
1497 #ifdef ENABLE_MALICIOUS
1498 /**
1499  * Turn RPS service to act malicious.
1500  *
1501  * @param cls Closure
1502  * @param channel The channel the PUSH was received over
1503  * @param channel_ctx The context associated with this channel
1504  * @param msg The message header
1505  */
1506   static void
1507 handle_client_act_malicious (void *cls,
1508                              struct GNUNET_SERVER_Client *client,
1509                              const struct GNUNET_MessageHeader *msg)
1510 {
1511   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1512   struct GNUNET_PeerIdentity *peers;
1513   uint32_t num_mal_peers_sent;
1514   uint32_t num_mal_peers_old;
1515
1516   /* Check for protocol violation */
1517   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1518   {
1519     GNUNET_break_op (0);
1520   }
1521
1522   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1523   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1524       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1525   {
1526     LOG (GNUNET_ERROR_TYPE_ERROR,
1527         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1528         ntohl (in_msg->num_peers),
1529         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1530             sizeof (struct GNUNET_PeerIdentity));
1531     GNUNET_break_op (0);
1532   }
1533
1534
1535   /* Do actual logic */
1536   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1537   mal_type = ntohl (in_msg->type);
1538
1539   LOG (GNUNET_ERROR_TYPE_DEBUG,
1540        "Now acting malicious type %" PRIu32 "\n",
1541        mal_type);
1542
1543   if (1 == mal_type)
1544   { /* Try to maximise representation */
1545     /* Add other malicious peers to those we already know */
1546     num_mal_peers_sent = ntohl (in_msg->num_peers);
1547     num_mal_peers_old = num_mal_peers;
1548     GNUNET_array_grow (mal_peers,
1549                        num_mal_peers,
1550                        num_mal_peers + num_mal_peers_sent);
1551     memcpy (&mal_peers[num_mal_peers_old],
1552             peers,
1553             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1554
1555     /* Substitute do_round () with do_mal_round () */
1556     GNUNET_SCHEDULER_cancel (do_round_task);
1557     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1558   }
1559   else if (2 == mal_type)
1560   { /* Try to partition the network */
1561     /* Add other malicious peers to those we already know */
1562     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
1563     num_mal_peers_old = num_mal_peers;
1564     GNUNET_array_grow (mal_peers,
1565                        num_mal_peers,
1566                        num_mal_peers + num_mal_peers_sent);
1567     memcpy (&mal_peers[num_mal_peers_old],
1568             peers,
1569             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1570
1571     /* Store the one attacked peer */
1572     memcpy (&attacked_peer,
1573             &peers[num_mal_peers_sent],
1574             sizeof (struct GNUNET_PeerIdentity));
1575
1576     LOG (GNUNET_ERROR_TYPE_DEBUG,
1577          "Attacked peer is %s\n",
1578          GNUNET_i2s (&attacked_peer));
1579
1580     /* Substitute do_round () with do_mal_round () */
1581     GNUNET_SCHEDULER_cancel (do_round_task);
1582     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1583   }
1584   else if (0 == mal_type)
1585   { /* Stop acting malicious */
1586     num_mal_peers = 0;
1587     GNUNET_free (mal_peers);
1588
1589     /* Substitute do_mal_round () with do_round () */
1590     GNUNET_SCHEDULER_cancel (do_round_task);
1591     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1592   }
1593   else
1594   {
1595     GNUNET_break (0);
1596   }
1597 }
1598
1599
1600 /**
1601  * Send out PUSHes and PULLs maliciously.
1602  *
1603  * This is executed regylary.
1604  */
1605 static void
1606 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1607 {
1608   uint32_t num_pushes;
1609   uint32_t i;
1610   struct GNUNET_TIME_Relative time_next_round;
1611
1612   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously.\n");
1613
1614   /* Do malicious actions */
1615   if (1 == mal_type)
1616   { /* Try to maximise representation */
1617     num_pushes = min (min (push_limit, /* FIXME: attacked peer */ num_mal_peers), GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1618     for (i = 0 ; i < num_pushes ; i++)
1619     { /* Send PUSHes to attacked peers */
1620       //GNUNET_CONTAINER_multihashmap_iterator_create
1621       //send_push ();
1622
1623       // TODO send pulls
1624       // send_pull_request
1625     }
1626   }
1627   else if (2 == mal_type)
1628   { /**
1629      * Try to partition the network
1630      * Send as many pushes to attacked peer as possible
1631      */
1632       send_push (&attacked_peer);
1633   }
1634
1635   /* Schedule next round */
1636   time_next_round = compute_rand_delay (round_interval, 2);
1637
1638   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
1639   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
1640   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1641 }
1642 #endif /* ENABLE_MALICIOUS */
1643
1644
1645 /**
1646  * Send out PUSHes and PULLs, possibly update #gossip_list, samplers.
1647  *
1648  * This is executed regylary.
1649  */
1650 static void
1651 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1652 {
1653   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
1654
1655   uint32_t i;
1656   unsigned int *permut;
1657   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1658   struct GNUNET_PeerIdentity peer;
1659   struct GNUNET_PeerIdentity *tmp_peer;
1660
1661   LOG (GNUNET_ERROR_TYPE_DEBUG,
1662        "Printing gossip list:\n");
1663   for (i = 0 ; i < gossip_list_size ; i++)
1664     LOG (GNUNET_ERROR_TYPE_DEBUG,
1665          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1666   // TODO log lists, ...
1667
1668   /* Would it make sense to have one shuffeled gossip list and then
1669    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1670    * use the rest to update sampler?
1671    * in essence get random peers with consumption */
1672
1673   /* Send PUSHes */
1674   if (0 < gossip_list_size)
1675   {
1676     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1677                                            (unsigned int) gossip_list_size);
1678     n_peers = ceil (alpha * gossip_list_size);
1679     LOG (GNUNET_ERROR_TYPE_DEBUG,
1680          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1681          n_peers, alpha, gossip_list_size);
1682     for (i = 0 ; i < n_peers ; i++)
1683     {
1684       peer = gossip_list[permut[i]];
1685       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1686       { // FIXME if this fails schedule/loop this for later
1687         send_push (&peer);
1688       }
1689     }
1690     GNUNET_free (permut);
1691   }
1692
1693
1694   /* Send PULL requests */
1695   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1696   n_peers = ceil (beta * gossip_list_size);
1697   LOG (GNUNET_ERROR_TYPE_DEBUG,
1698        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1699        n_peers, beta, gossip_list_size);
1700   for (i = 0 ; i < n_peers ; i++)
1701   {
1702     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1703         pending_pull_reply_list, pending_pull_reply_list_size);
1704     if (NULL != tmp_peer)
1705     {
1706       peer = *tmp_peer;
1707       GNUNET_free (tmp_peer);
1708
1709       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1710       {
1711         send_pull_request (&peer);
1712       }
1713     }
1714   }
1715
1716
1717   /* Update gossip list */
1718
1719   if ( push_list_size <= alpha * gossip_list_size &&
1720        push_list_size != 0 &&
1721        pull_list_size != 0 )
1722   {
1723     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1724
1725     uint32_t first_border;
1726     uint32_t second_border;
1727     uint32_t r_index;
1728     uint32_t peers_to_clean_size;
1729     struct GNUNET_PeerIdentity *peers_to_clean;
1730
1731     peers_to_clean = NULL;
1732     peers_to_clean_size = 0;
1733     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
1734     memcpy (peers_to_clean,
1735             gossip_list,
1736             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
1737
1738     first_border  =                ceil (alpha * sampler_size_est_need);
1739     second_border = first_border + ceil (beta  * sampler_size_est_need);
1740
1741     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1742
1743     for (i = 0 ; i < first_border ; i++)
1744     { // TODO use RPS_sampler_get_n_rand_peers
1745       /* Update gossip list with peers received through PUSHes */
1746       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1747                                        push_list_size);
1748       gossip_list[i] = push_list[r_index];
1749       // TODO change the peer_flags accordingly
1750     }
1751
1752     for (i = first_border ; i < second_border ; i++)
1753     {
1754       /* Update gossip list with peers received through PULLs */
1755       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1756                                        pull_list_size);
1757       gossip_list[i] = pull_list[r_index];
1758       // TODO change the peer_flags accordingly
1759     }
1760
1761     for (i = second_border ; i < sampler_size_est_need ; i++)
1762     {
1763       /* Update gossip list with peers from history */
1764       RPS_sampler_get_n_rand_peers (prot_sampler, hist_update, NULL, 1, GNUNET_NO);
1765       num_hist_update_tasks++;
1766       // TODO change the peer_flags accordingly
1767     }
1768
1769     for (i = 0 ; i < gossip_list_size ; i++)
1770       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
1771
1772     for (i = 0 ; i < peers_to_clean_size ; i++)
1773       peer_clean (&peers_to_clean[i]);
1774
1775     GNUNET_free (peers_to_clean);
1776   }
1777   else
1778   {
1779     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1780   }
1781   // TODO independent of that also get some peers from CADET_get_peers()?
1782
1783
1784   /* Update samplers */
1785   for ( i = 0 ; i < push_list_size ; i++ )
1786   {
1787     LOG (GNUNET_ERROR_TYPE_DEBUG,
1788          "Updating with peer %s from push list\n",
1789          GNUNET_i2s (&push_list[i]));
1790     RPS_sampler_update (prot_sampler,   &push_list[i]);
1791     RPS_sampler_update (client_sampler, &push_list[i]);
1792     // TODO set in_flag?
1793   }
1794
1795   for ( i = 0 ; i < pull_list_size ; i++ )
1796   {
1797     LOG (GNUNET_ERROR_TYPE_DEBUG,
1798          "Updating with peer %s from pull list\n",
1799          GNUNET_i2s (&pull_list[i]));
1800     RPS_sampler_update (prot_sampler,   &push_list[i]);
1801     RPS_sampler_update (client_sampler, &push_list[i]);
1802     // TODO set in_flag?
1803   }
1804
1805
1806   /* Empty push/pull lists */
1807   GNUNET_array_grow (push_list, push_list_size, 0);
1808   GNUNET_array_grow (pull_list, pull_list_size, 0);
1809
1810   struct GNUNET_TIME_Relative time_next_round;
1811
1812   time_next_round = compute_rand_delay (round_interval, 2);
1813
1814   /* Schedule next round */
1815   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1816   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
1817   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1818 }
1819
1820
1821 static void
1822 rps_start (struct GNUNET_SERVER_Handle *server);
1823
1824
1825 /**
1826  * This is called from GNUNET_CADET_get_peers().
1827  *
1828  * It is called on every peer(ID) that cadet somehow has contact with.
1829  * We use those to initialise the sampler.
1830  */
1831 void
1832 init_peer_cb (void *cls,
1833               const struct GNUNET_PeerIdentity *peer,
1834               int tunnel, // "Do we have a tunnel towards this peer?"
1835               unsigned int n_paths, // "Number of known paths towards this peer"
1836               unsigned int best_path) // "How long is the best path?
1837                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1838 {
1839   struct PeerOutstandingOp out_op;
1840   struct PeerContext *peer_ctx;
1841
1842   if (NULL != peer
1843       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer))
1844   {
1845     LOG (GNUNET_ERROR_TYPE_DEBUG,
1846         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1847         GNUNET_i2s (peer), peer, gossip_list_size);
1848
1849     // maybe create a function for that
1850     peer_ctx = get_peer_ctx (peer_map, peer);
1851     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1852     {
1853       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1854       {
1855         out_op.op = insert_in_sampler;
1856         out_op.op_cls = NULL;
1857         GNUNET_array_append (peer_ctx->outstanding_ops,
1858                              peer_ctx->num_outstanding_ops,
1859                              out_op);
1860       }
1861
1862       if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1863       {
1864         out_op.op = insert_in_gossip_list;
1865         out_op.op_cls = NULL;
1866         GNUNET_array_append (peer_ctx->outstanding_ops,
1867                              peer_ctx->num_outstanding_ops,
1868                              out_op);
1869       }
1870
1871       /* Trigger livelyness test on peer */
1872       check_peer_live (peer_ctx);
1873     }
1874
1875     // send push/pull to each of those peers?
1876   }
1877 }
1878
1879
1880 /**
1881  * Clean the send channel of a peer
1882  */
1883 void
1884 peer_clean (const struct GNUNET_PeerIdentity *peer)
1885 {
1886   struct PeerContext *peer_ctx;
1887   struct GNUNET_CADET_Channel *channel;
1888
1889   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
1890       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1891   {
1892     peer_ctx = get_peer_ctx (peer_map, peer);
1893     if (NULL != peer_ctx->send_channel)
1894     {
1895       channel = peer_ctx->send_channel;
1896       peer_ctx->send_channel = NULL;
1897       GNUNET_CADET_channel_destroy (channel);
1898     }
1899   }
1900 }
1901
1902
1903 /**
1904  * Callback used to remove peers from the multipeermap.
1905  */
1906   int
1907 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1908 {
1909   struct PeerContext *peer_ctx;
1910   const struct GNUNET_CADET_Channel *channel =
1911     (const struct GNUNET_CADET_Channel *) cls;
1912   struct GNUNET_CADET_Channel *recv;
1913   struct GNUNET_CADET_Channel *send;
1914
1915   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, value))
1916   {
1917     peer_ctx = (struct PeerContext *) value;
1918
1919     if (0 != peer_ctx->num_outstanding_ops)
1920       GNUNET_array_grow (peer_ctx->outstanding_ops,
1921                          peer_ctx->num_outstanding_ops,
1922                          0);
1923
1924     if (NULL != peer_ctx->mq)
1925     {
1926       GNUNET_MQ_destroy (peer_ctx->mq);
1927       peer_ctx->mq = NULL;
1928     }
1929
1930
1931     if (NULL != peer_ctx->is_live_task)
1932     {
1933     LOG (GNUNET_ERROR_TYPE_DEBUG,
1934          "Trying to cancle is_live_task for peer %s\n",
1935          GNUNET_i2s (key));
1936       GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1937       peer_ctx->is_live_task = NULL;
1938     }
1939
1940     send = peer_ctx->send_channel;
1941     peer_ctx->send_channel = NULL;
1942     if (NULL != send
1943         && channel != send)
1944     {
1945       GNUNET_CADET_channel_destroy (send);
1946     }
1947
1948     recv = peer_ctx->send_channel;
1949     peer_ctx->recv_channel = NULL;
1950     if (NULL != recv
1951         && channel != recv)
1952     {
1953       GNUNET_CADET_channel_destroy (recv);
1954     }
1955
1956     if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1957       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1958     else
1959       GNUNET_free (peer_ctx);
1960   }
1961
1962   return GNUNET_YES;
1963 }
1964
1965
1966 /**
1967  * Task run during shutdown.
1968  *
1969  * @param cls unused
1970  * @param tc unused
1971  */
1972 static void
1973 shutdown_task (void *cls,
1974                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1975 {
1976   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1977
1978   if (NULL != do_round_task)
1979   {
1980     GNUNET_SCHEDULER_cancel (do_round_task);
1981     do_round_task = NULL;
1982   }
1983
1984
1985   {
1986   if (GNUNET_SYSERR ==
1987         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1988     LOG (GNUNET_ERROR_TYPE_WARNING,
1989         "Iterating over peers to disconnect from them was cancelled\n");
1990   }
1991
1992   GNUNET_NSE_disconnect (nse);
1993   GNUNET_CADET_disconnect (cadet_handle);
1994   RPS_sampler_destroy (prot_sampler);
1995   RPS_sampler_destroy (client_sampler);
1996   LOG (GNUNET_ERROR_TYPE_DEBUG,
1997        "Size of the peermap: %u\n",
1998        GNUNET_CONTAINER_multipeermap_size (peer_map));
1999   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2000   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2001   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
2002   GNUNET_array_grow (push_list, push_list_size, 0);
2003   GNUNET_array_grow (pull_list, pull_list_size, 0);
2004   #ifdef ENABLE_MALICIOUS
2005   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2006   // TODO empty attacked_peers DLL
2007   #endif /* ENABLE_MALICIOUS */
2008 }
2009
2010
2011 /**
2012  * A client disconnected.  Remove all of its data structure entries.
2013  *
2014  * @param cls closure, NULL
2015  * @param client identification of the client
2016  */
2017 static void
2018 handle_client_disconnect (void *cls,
2019                           struct GNUNET_SERVER_Client * client)
2020 {
2021 }
2022
2023
2024 /**
2025  * Handle the channel a peer opens to us.
2026  *
2027  * @param cls The closure
2028  * @param channel The channel the peer wants to establish
2029  * @param initiator The peer's peer ID
2030  * @param port The port the channel is being established over
2031  * @param options Further options
2032  */
2033   static void *
2034 handle_inbound_channel (void *cls,
2035                         struct GNUNET_CADET_Channel *channel,
2036                         const struct GNUNET_PeerIdentity *initiator,
2037                         uint32_t port,
2038                         enum GNUNET_CADET_ChannelOption options)
2039 {
2040   struct PeerContext *peer_ctx;
2041   struct GNUNET_PeerIdentity peer;
2042
2043   peer = *initiator;
2044   LOG (GNUNET_ERROR_TYPE_DEBUG,
2045       "New channel was established to us (Peer %s).\n",
2046       GNUNET_i2s (&peer));
2047
2048   GNUNET_assert (NULL != channel);
2049
2050   // we might not even store the recv_channel
2051
2052   peer_ctx = get_peer_ctx (peer_map, &peer);
2053   // FIXME what do we do if a channel is established twice?
2054   //       overwrite? Clean old channel? ...?
2055   //if (NULL != peer_ctx->recv_channel)
2056   //{
2057   //  peer_ctx->recv_channel = channel;
2058   //}
2059   peer_ctx->recv_channel = channel;
2060
2061   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
2062       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
2063
2064   peer_is_live (peer_ctx);
2065
2066   return NULL; // TODO
2067 }
2068
2069
2070 /**
2071  * This is called when a remote peer destroys a channel.
2072  *
2073  * @param cls The closure
2074  * @param channel The channel being closed
2075  * @param channel_ctx The context associated with this channel
2076  */
2077   static void
2078 cleanup_channel (void *cls,
2079                 const struct GNUNET_CADET_Channel *channel,
2080                 void *channel_ctx)
2081 {
2082   struct GNUNET_PeerIdentity *peer;
2083   struct PeerContext *peer_ctx;
2084
2085   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2086       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2087        // Guess simply casting isn't the nicest way...
2088        // FIXME wait for cadet to change this function
2089
2090   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2091   {
2092     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2093
2094     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2095       return;
2096
2097     if (channel == peer_ctx->send_channel)
2098     { /* Peer probably went down */
2099       LOG (GNUNET_ERROR_TYPE_DEBUG,
2100            "Peer %s destroyed send channel - probably went down, cleaning up\n",
2101            GNUNET_i2s (peer));
2102       rem_from_list (&gossip_list, &gossip_list_size, peer);
2103       rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, peer);
2104
2105       peer_ctx->send_channel = NULL;
2106       /* Somwewhat {ab,re}use the iterator function */
2107       /* Cast to void is ok, because it's used as void in peer_remove_cb */
2108       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2109     }
2110     else if (channel == peer_ctx->recv_channel)
2111     { /* Other peer doesn't want to send us messages anymore */
2112       LOG (GNUNET_ERROR_TYPE_DEBUG,
2113            "Peer %s destroyed recv channel - cleaning up channel\n",
2114            GNUNET_i2s (peer));
2115       peer_ctx->recv_channel = NULL;
2116     }
2117   }
2118 }
2119
2120
2121 /**
2122  * Actually start the service.
2123  */
2124   static void
2125 rps_start (struct GNUNET_SERVER_Handle *server)
2126 {
2127   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2128     {&handle_client_request,     NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2129       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2130     {&handle_client_seed,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2131     #ifdef ENABLE_MALICIOUS
2132     {&handle_client_act_malicious, NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2133     #endif /* ENABLE_MALICIOUS */
2134     {NULL, NULL, 0, 0}
2135   };
2136
2137   GNUNET_SERVER_add_handlers (server, handlers);
2138   GNUNET_SERVER_disconnect_notify (server,
2139                                    &handle_client_disconnect,
2140                                    NULL);
2141   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
2142
2143
2144   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2145   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2146
2147   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2148                                                         &shutdown_task,
2149                                                         NULL);
2150 }
2151
2152
2153 /**
2154  * Process statistics requests.
2155  *
2156  * @param cls closure
2157  * @param server the initialized server
2158  * @param c configuration to use
2159  */
2160   static void
2161 run (void *cls,
2162      struct GNUNET_SERVER_Handle *server,
2163      const struct GNUNET_CONFIGURATION_Handle *c)
2164 {
2165   // TODO check what this does -- copied from gnunet-boss
2166   // - seems to work as expected
2167   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2168   cfg = c;
2169
2170
2171   /* Get own ID */
2172   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2173   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2174               "STARTING SERVICE (rps) for peer [%s]\n",
2175               GNUNET_i2s (&own_identity));
2176   #ifdef ENABLE_MALICIOUS
2177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178               "Malicious execution compiled in.\n");
2179   #endif /* ENABLE_MALICIOUS */
2180
2181
2182
2183   /* Get time interval from the configuration */
2184   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2185                                                         "ROUNDINTERVAL",
2186                                                         &round_interval))
2187   {
2188     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
2189     GNUNET_SCHEDULER_shutdown ();
2190     return;
2191   }
2192
2193   /* Get initial size of sampler/gossip list from the configuration */
2194   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
2195                                                          "INITSIZE",
2196                                                          (long long unsigned int *) &sampler_size_est_need))
2197   {
2198     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
2199     GNUNET_SCHEDULER_shutdown ();
2200     return;
2201   }
2202   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2203
2204
2205   gossip_list = NULL;
2206
2207
2208   /* connect to NSE */
2209   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2210   // TODO check whether that was successful
2211   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
2212
2213
2214   alpha = 0.45;
2215   beta  = 0.45;
2216
2217   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2218
2219
2220   /* Initialise cadet */
2221   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2222     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2223       sizeof (struct GNUNET_MessageHeader)},
2224     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2225       sizeof (struct GNUNET_MessageHeader)},
2226     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2227     {NULL, 0, 0}
2228   };
2229
2230   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2231   cadet_handle = GNUNET_CADET_connect (cfg,
2232                                        cls,
2233                                        &handle_inbound_channel,
2234                                        &cleanup_channel,
2235                                        cadet_handlers,
2236                                        ports);
2237   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
2238
2239
2240   /* Initialise sampler */
2241   struct GNUNET_TIME_Relative half_round_interval;
2242   struct GNUNET_TIME_Relative  max_round_interval;
2243
2244   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2245   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2246
2247   prot_sampler =   RPS_sampler_init (sampler_size_est_need, max_round_interval);
2248   client_sampler = RPS_sampler_init (sampler_size_est_need, max_round_interval);
2249
2250   /* Initialise push and pull maps */
2251   push_list = NULL;
2252   push_list_size = 0;
2253   pull_list = NULL;
2254   pull_list_size = 0;
2255   pending_pull_reply_list = NULL;
2256   pending_pull_reply_list_size = 0;
2257
2258
2259   num_hist_update_tasks = 0;
2260
2261
2262   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2263   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2264   // TODO send push/pull to each of those peers?
2265
2266
2267   rps_start (server);
2268 }
2269
2270
2271 /**
2272  * The main function for the rps service.
2273  *
2274  * @param argc number of arguments from the command line
2275  * @param argv command line arguments
2276  * @return 0 ok, 1 on error
2277  */
2278   int
2279 main (int argc, char *const *argv)
2280 {
2281   return (GNUNET_OK ==
2282           GNUNET_SERVICE_run (argc,
2283                               argv,
2284                               "rps",
2285                               GNUNET_SERVICE_OPTION_NONE,
2286                               &run, NULL)) ? 0 : 1;
2287 }
2288
2289 /* end of gnunet-service-rps.c */