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