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