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