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