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