-substitute array-structures push_list, pull_list with custom list structure
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 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 "gnunet-service-rps_peers.h"
33 #include "rps-test_util.h"
34
35 #include "gnunet-service-rps_sampler.h"
36
37 #include <math.h>
38 #include <inttypes.h>
39
40 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
41
42 // TODO modify @brief in every file
43
44 // TODO check for overflows
45
46 // TODO align message structs
47
48 // TODO connect to friends
49
50 // TODO store peers somewhere persistent
51
52 // TODO blacklist? (-> mal peer detection on top of brahms)
53
54 // TODO API request_cancel
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   struct GNUNET_PeerIdentity *
70 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
71                            const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
72
73
74 /***********************************************************************
75  * Housekeeping with peers
76 ***********************************************************************/
77
78 /**
79  * Closure used to pass the client and the id to the callback
80  * that replies to a client's request
81  */
82 struct ReplyCls
83 {
84   /**
85    * DLL
86    */
87   struct ReplyCls *next;
88   struct ReplyCls *prev;
89
90   /**
91    * The identifier of the request
92    */
93   uint32_t id;
94
95   /**
96    * The handle to the request
97    */
98   struct RPS_SamplerRequestHandle *req_handle;
99
100   /**
101    * The client handle to send the reply to
102    */
103   struct GNUNET_SERVER_Client *client;
104 };
105
106
107 /**
108  * Struct used to store the context of a connected client.
109  */
110 struct ClientContext
111 {
112   /**
113    * DLL
114    */
115   struct ClientContext *next;
116   struct ClientContext *prev;
117
118   /**
119    * The message queue to communicate with the client.
120    */
121   struct GNUNET_MQ_Handle *mq;
122
123   /**
124    * DLL with handles to single requests from the client
125    */
126   struct ReplyCls *rep_cls_head;
127   struct ReplyCls *rep_cls_tail;
128 };
129
130 /**
131  * DLL with all clients currently connected to us
132  */
133 struct ClientContext *cli_ctx_head;
134 struct ClientContext *cli_ctx_tail;
135
136 /**
137  * Used to keep track in what lists single peerIDs are.
138  */
139 enum PeerFlags
140 {
141   /**
142    * If we are waiting for a reply from that peer (sent a pull request).
143    */
144   PULL_REPLY_PENDING   = 0x01,
145
146   IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
147   IN_OWN_SAMPLER_LIST  = 0x04, // unneeded?
148   IN_OWN_GOSSIP_LIST   = 0x08, // unneeded?
149
150   /**
151    * We set this bit when we can be sure the other peer is/was live.
152    */
153   VALID                = 0x10,
154
155   /**
156    * We set this bit when we are going to destroy the channel to this peer.
157    * When cleanup_channel is called, we know that we wanted to destroy it.
158    * Otherwise the channel to the other peer was destroyed.
159    */
160   TO_DESTROY           = 0x20,
161 };
162
163
164 /**
165  * Functions of this type can be used to be stored at a peer for later execution.
166  */
167 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
168
169 /**
170  * Outstanding operation on peer consisting of callback and closure
171  */
172 struct PeerOutstandingOp
173 {
174   /**
175    * Callback
176    */
177   PeerOp op;
178
179   /**
180    * Closure
181    */
182   void *op_cls;
183 };
184
185
186 /**
187  * List containing all messages that are yet to be send
188  */
189 struct PendingMessage
190 {
191   /**
192    * DLL next, prev
193    */
194   struct PendingMessage *next;
195   struct PendingMessage *prev;
196
197   /**
198    * The envelope to the corresponding message
199    */
200   struct GNUNET_MQ_Envelope *ev;
201
202   /**
203    * The corresponding context
204    */
205   struct PeerContext *peer_ctx;
206
207   /**
208    * The message type
209    */
210   const char *type;
211 };
212
213
214 /**
215  * Struct used to keep track of other peer's status
216  *
217  * This is stored in a multipeermap.
218  */
219 struct PeerContext
220 {
221   /**
222    * Message queue open to client
223    */
224   struct GNUNET_MQ_Handle *mq;
225
226   /**
227    * Channel open to client.
228    */
229   struct GNUNET_CADET_Channel *send_channel;
230
231   /**
232    * Channel open from client.
233    */
234   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
235
236   /**
237    * Array of outstanding operations on this peer.
238    */
239   struct PeerOutstandingOp *outstanding_ops;
240
241   /**
242    * Handle to the callback given to cadet_ntfy_tmt_rdy()
243    *
244    * To be canceled on shutdown.
245    */
246   struct GNUNET_CADET_TransmitHandle *transmit_handle;
247
248   /**
249    * Number of outstanding operations.
250    */
251   unsigned int num_outstanding_ops;
252
253   /**
254    * Identity of the peer
255    */
256   struct GNUNET_PeerIdentity peer_id;
257   
258   /**
259    * Flags indicating status of peer
260    */
261   uint32_t peer_flags;
262
263   /**
264    * DLL with all messages that are yet to be sent
265    */
266   struct PendingMessage *pending_messages_head;
267   struct PendingMessage *pending_messages_tail;
268
269   /**
270    * This is pobably followed by 'statistical' data (when we first saw
271    * him, how did we get his ID, how many pushes (in a timeinterval),
272    * ...)
273    */
274 };
275
276 /***********************************************************************
277  * /Housekeeping with peers
278 ***********************************************************************/
279
280
281
282
283
284 /***********************************************************************
285  * Globals
286 ***********************************************************************/
287
288 /**
289  * Sampler used for the Brahms protocol itself.
290  */
291 static struct RPS_Sampler *prot_sampler;
292
293 /**
294  * Sampler used for the clients.
295  */
296 static struct RPS_Sampler *client_sampler;
297
298 /**
299  * Set of all peers to keep track of them.
300  */
301 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
302
303
304 /**
305  * Name to log view to
306  */
307 static char *file_name_view_log;
308
309 /**
310  * The "local view" containing peers we learned from gossip and history
311  */
312 static struct GNUNET_CONTAINER_MultiPeerMap *view;
313
314 /**
315  * An array containing the peers of the local view.
316  *
317  * This is created every time we send a pull reply if it has changed since the
318  * last pull reply we sent.
319  */
320 static struct GNUNET_PeerIdentity *view_array;
321
322
323 /**
324  * The size of sampler we need to be able to satisfy the client's need of
325  * random peers.
326  */
327 static unsigned int sampler_size_client_need;
328
329 /**
330  * The size of sampler we need to be able to satisfy the Brahms protocol's
331  * need of random peers.
332  *
333  * This is one minimum size the sampler grows to.
334  */
335 static unsigned int sampler_size_est_need;
336
337
338 /**
339  * Percentage of total peer number in the view
340  * to send random PUSHes to
341  */
342 static float alpha;
343
344 /**
345  * Percentage of total peer number in the view
346  * to send random PULLs to
347  */
348 static float beta;
349
350 /**
351  * The percentage gamma of history updates.
352  * Simply 1 - alpha - beta
353  */
354
355
356 /**
357  * Identifier for the main task that runs periodically.
358  */
359 static struct GNUNET_SCHEDULER_Task *do_round_task;
360
361 /**
362  * Time inverval the do_round task runs in.
363  */
364 static struct GNUNET_TIME_Relative round_interval;
365
366
367
368 /**
369  * List to store peers received through pushes temporary.
370  */
371 static struct CustomPeerMap *push_map;
372
373 /**
374  * List to store peers received through pulls temporary.
375  */
376 static struct CustomPeerMap *pull_map;
377
378
379 /**
380  * Handler to NSE.
381  */
382 static struct GNUNET_NSE_Handle *nse;
383
384 /**
385  * Handler to CADET.
386  */
387 static struct GNUNET_CADET_Handle *cadet_handle;
388
389 /**
390  * Handler to PEERINFO.
391  */
392 static struct GNUNET_PEERINFO_Handle *peerinfo_handle;
393
394 /**
395  * Handle for cancellation of iteration over peers.
396  */
397 struct GNUNET_PEERINFO_NotifyContext *peerinfo_notify_handle;
398
399
400 /**
401  * Request counter.
402  *
403  * Only needed in the beginning to check how many of the 64 deltas
404  * we already have
405  */
406 static unsigned int req_counter;
407
408 /**
409  * Time of the last request we received.
410  *
411  * Used to compute the expected request rate.
412  */
413 static struct GNUNET_TIME_Absolute last_request;
414
415 /**
416  * Size of #request_deltas.
417  */
418 #define REQUEST_DELTAS_SIZE 64
419 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
420
421 /**
422  * Last 64 deltas between requests
423  */
424 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
425
426 /**
427  * The prediction of the rate of requests
428  */
429 static struct GNUNET_TIME_Relative  request_rate;
430
431
432 /**
433  * Number of history update tasks.
434  */
435 uint32_t num_hist_update_tasks;
436
437
438 #ifdef ENABLE_MALICIOUS
439 /**
440  * Type of malicious peer
441  *
442  * 0 Don't act malicious at all - Default
443  * 1 Try to maximise representation
444  * 2 Try to partition the network
445  * 3 Combined attack
446  */
447 uint32_t mal_type = 0;
448
449 /**
450  * Other malicious peers
451  */
452 static struct GNUNET_PeerIdentity *mal_peers = NULL;
453
454 /**
455  * Hashmap of malicious peers used as set.
456  * Used to more efficiently check whether we know that peer.
457  */
458 static struct GNUNET_CONTAINER_MultiPeerMap *mal_peer_set = NULL;
459
460 /**
461  * Number of other malicious peers
462  */
463 static uint32_t num_mal_peers;
464
465
466 /**
467  * If type is 2 This struct is used to store the attacked peers in a DLL
468  */
469 struct AttackedPeer
470 {
471   /**
472    * DLL
473    */
474   struct AttackedPeer *next;
475   struct AttackedPeer *prev;
476
477   /**
478    * PeerID
479    */
480   struct GNUNET_PeerIdentity peer_id;
481 };
482
483 /**
484  * If type is 2 this is the DLL of attacked peers
485  */
486 static struct AttackedPeer *att_peers_head = NULL;
487 static struct AttackedPeer *att_peers_tail = NULL;
488
489 /**
490  * This index is used to point to an attacked peer to
491  * implement the round-robin-ish way to select attacked peers.
492  */
493 static struct AttackedPeer *att_peer_index = NULL;
494
495 /**
496  * Hashmap of attacked peers used as set.
497  * Used to more efficiently check whether we know that peer.
498  */
499 static struct GNUNET_CONTAINER_MultiPeerMap *att_peer_set = NULL;
500
501 /**
502  * Number of attacked peers
503  */
504 static uint32_t num_attacked_peers = 0;
505
506
507 /**
508  * If type is 1 this is the attacked peer
509  */
510 static struct GNUNET_PeerIdentity attacked_peer;
511
512 /**
513  * The limit of PUSHes we can send in one round.
514  * This is an assumption of the Brahms protocol and either implemented
515  * via proof of work
516  * or
517  * assumend to be the bandwidth limitation.
518  */
519 static uint32_t push_limit = 10000;
520 #endif /* ENABLE_MALICIOUS */
521
522
523 /***********************************************************************
524  * /Globals
525 ***********************************************************************/
526
527
528
529
530
531
532 /***********************************************************************
533  * Util functions
534 ***********************************************************************/
535
536 /**
537  * Set a peer flag of given peer context.
538  */
539 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
540
541 /**
542  * Get peer flag of given peer context.
543  */
544 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
545
546 /**
547  * Unset flag of given peer context.
548  */
549 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
550
551 /**
552  * Clean the send channel of a peer
553  */
554 void
555 peer_clean (const struct GNUNET_PeerIdentity *peer);
556
557
558 /**
559  * Check if peer is already in peer array.
560  */
561   int
562 in_arr (const struct GNUNET_PeerIdentity *array,
563         unsigned int arr_size,
564         const struct GNUNET_PeerIdentity *peer)
565 {
566   GNUNET_assert (NULL != peer);
567
568   if (0 == arr_size)
569     return GNUNET_NO;
570
571   GNUNET_assert (NULL != array);
572
573   unsigned int i;
574
575   for (i = 0; i < arr_size ; i++)
576     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
577       return GNUNET_YES;
578   return GNUNET_NO;
579 }
580
581
582 /**
583  * Print peerlist to log.
584  */
585 void
586 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
587 {
588   unsigned int i;
589
590   LOG (GNUNET_ERROR_TYPE_DEBUG,
591        "Printing peer list of length %u at %p:\n",
592        len,
593        list);
594   for (i = 0 ; i < len ; i++)
595   {
596     LOG (GNUNET_ERROR_TYPE_DEBUG,
597          "%u. peer: %s\n",
598          i, GNUNET_i2s (&list[i]));
599   }
600 }
601
602
603 /**
604  * Remove peer from list.
605  */
606   void
607 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
608                unsigned int *list_size,
609                const struct GNUNET_PeerIdentity *peer)
610 {
611   unsigned int i;
612   struct GNUNET_PeerIdentity *tmp;
613
614   tmp = *peer_list;
615
616   LOG (GNUNET_ERROR_TYPE_DEBUG,
617        "Removing peer %s from list at %p\n",
618        GNUNET_i2s (peer),
619        tmp);
620
621   for ( i = 0 ; i < *list_size ; i++ )
622   {
623     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
624     {
625       if (i < *list_size -1)
626       { /* Not at the last entry -- shift peers left */
627         memcpy (&tmp[i], &tmp[i +1],
628                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
629       }
630       /* Remove last entry (should be now useless PeerID) */
631       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
632     }
633   }
634   *peer_list = tmp;
635 }
636
637 /**
638  * Get random peer from the given list but don't return one from the @a ignore_list.
639  */
640   struct GNUNET_PeerIdentity *
641 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
642                            uint32_t list_size,
643                            const struct GNUNET_PeerIdentity *ignore_list,
644                            uint32_t ignore_size)
645 {
646   uint32_t r_index;
647   uint32_t tmp_size;
648   struct GNUNET_PeerIdentity *tmp_peer_list;
649   struct GNUNET_PeerIdentity *peer;
650
651   GNUNET_assert (NULL != peer_list);
652   if (0 == list_size)
653     return NULL;
654
655   tmp_size = 0;
656   tmp_peer_list = NULL;
657   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
658   memcpy (tmp_peer_list,
659           peer_list,
660           list_size * sizeof (struct GNUNET_PeerIdentity));
661   peer = GNUNET_new (struct GNUNET_PeerIdentity);
662
663   /**;
664    * Choose the r_index of the peer we want to return
665    * at random from the interval of the view
666    */
667   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
668                                       tmp_size);
669   *peer = tmp_peer_list[r_index];
670
671   while (in_arr (ignore_list, ignore_size, peer))
672   {
673     rem_from_list (&tmp_peer_list, &tmp_size, peer);
674
675     print_peer_list (tmp_peer_list, tmp_size);
676
677     if (0 == tmp_size)
678     {
679       GNUNET_free (peer);
680       return NULL;
681     }
682
683     /**;
684      * Choose the r_index of the peer we want to return
685      * at random from the interval of the view
686      */
687     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
688                                         tmp_size);
689     *peer = tmp_peer_list[r_index];
690   }
691
692
693   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
694
695   return peer;
696 }
697
698
699 /**
700  * Get the context of a peer. If not existing, create.
701  */
702   struct PeerContext *
703 get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
704 {
705   struct PeerContext *ctx;
706   int ret;
707
708   ret = GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
709   GNUNET_assert (GNUNET_YES == ret);
710   ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
711   GNUNET_assert (NULL != ctx);
712   return ctx;
713 }
714
715 /**
716  * Create a new peer context and insert it into the peer map
717  */
718 struct PeerContext *
719 create_peer_ctx (const struct GNUNET_PeerIdentity *peer)
720 {
721   struct PeerContext *ctx;
722   int ret;
723
724   ctx = GNUNET_new (struct PeerContext);
725   ctx->peer_id = *peer;
726   ret = GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
727                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
728   GNUNET_assert (GNUNET_OK == ret);
729   return ctx;
730 }
731
732
733 /**
734  * Set the peer flag to living and call the outstanding operations on this peer.
735  */
736 static size_t
737 peer_is_live (struct PeerContext *peer_ctx)
738 {
739   struct GNUNET_PeerIdentity *peer;
740
741   /* Cancle transmit_handle if still scheduled */
742   if (NULL != peer_ctx->transmit_handle)
743   {
744     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->transmit_handle);
745     peer_ctx->transmit_handle = NULL;
746   }
747
748   peer = &peer_ctx->peer_id;
749   set_peer_flag (peer_ctx, VALID);
750
751   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
752
753   if (0 < peer_ctx->num_outstanding_ops)
754   { /* Call outstanding operations */
755     unsigned int i;
756
757     for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
758       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
759     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
760   }
761
762   return 0;
763 }
764
765
766 /**
767  * Callback that is called when a channel was effectively established.
768  * This is given to ntfy_tmt_rdy and called when the channel was
769  * successfully established.
770  */
771 static size_t
772 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
773 {
774   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
775
776   peer_ctx->transmit_handle = NULL;
777   LOG (GNUNET_ERROR_TYPE_DEBUG,
778        "Set ->transmit_handle = NULL for peer %s\n",
779        GNUNET_i2s (&peer_ctx->peer_id));
780
781   if (NULL != buf
782       && 0 != size)
783   {
784     peer_is_live (peer_ctx);
785   }
786   else
787   {
788     LOG (GNUNET_ERROR_TYPE_WARNING,
789          "Problems establishing a connection to peer %s in order to check liveliness\n",
790          GNUNET_i2s (&peer_ctx->peer_id));
791     // TODO reschedule? cleanup?
792   }
793
794   //if (NULL != peer_ctx->transmit_handle)
795   //{
796   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
797   //       "Trying to cancle transmit_handle for peer %s\n",
798   //       GNUNET_i2s (&peer_ctx->peer_id));
799   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->transmit_handle);
800   //  peer_ctx->transmit_handle = NULL;
801   //}
802
803   return 0;
804 }
805
806
807 /**
808  * Get the channel of a peer. If not existing, create.
809  */
810   struct GNUNET_CADET_Channel *
811 get_channel (const struct GNUNET_PeerIdentity *peer)
812 {
813   struct PeerContext *peer_ctx;
814
815   peer_ctx = get_peer_ctx (peer);
816   if (NULL == peer_ctx->send_channel)
817   {
818     LOG (GNUNET_ERROR_TYPE_DEBUG,
819          "Trying to establish channel to peer %s\n",
820          GNUNET_i2s (peer));
821
822     peer_ctx->send_channel =
823       GNUNET_CADET_channel_create (cadet_handle,
824                                    NULL,
825                                    peer,
826                                    GNUNET_RPS_CADET_PORT,
827                                    GNUNET_CADET_OPTION_RELIABLE);
828
829   }
830   return peer_ctx->send_channel;
831 }
832
833
834 /**
835  * Get the message queue of a specific peer.
836  *
837  * If we already have a message queue open to this client,
838  * simply return it, otherways create one.
839  */
840   struct GNUNET_MQ_Handle *
841 get_mq (const struct GNUNET_PeerIdentity *peer_id)
842 {
843   struct PeerContext *peer_ctx;
844
845   peer_ctx = get_peer_ctx (peer_id);
846
847   GNUNET_assert (NULL == peer_ctx->transmit_handle);
848
849   if (NULL == peer_ctx->mq)
850   {
851     (void) get_channel (peer_id);
852     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
853     //do I have to explicitly put it in the peer_map?
854     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
855                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
856   }
857   return peer_ctx->mq;
858 }
859
860
861 /**
862  * Issue check whether peer is live
863  *
864  * @param peer_ctx the context of the peer
865  */
866 void
867 check_peer_live (struct PeerContext *peer_ctx)
868 {
869   LOG (GNUNET_ERROR_TYPE_DEBUG,
870        "Get informed about peer %s getting live\n",
871        GNUNET_i2s (&peer_ctx->peer_id));
872
873   if (NULL == peer_ctx->transmit_handle &&
874       NULL == peer_ctx->send_channel)
875   {
876     (void) get_channel (&peer_ctx->peer_id);
877     peer_ctx->transmit_handle =
878         GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
879                                             GNUNET_NO,
880                                             GNUNET_TIME_UNIT_FOREVER_REL,
881                                             sizeof (struct GNUNET_MessageHeader),
882                                             cadet_ntfy_tmt_rdy_cb,
883                                             peer_ctx);
884   }
885   else if (NULL != peer_ctx->transmit_handle)
886     LOG (GNUNET_ERROR_TYPE_DEBUG,
887          "Already waiting for notification\n");
888   else if (NULL != peer_ctx->send_channel)
889     LOG (GNUNET_ERROR_TYPE_DEBUG,
890          "Already have established channel to peer\n");
891 }
892
893
894 /**
895  * Sum all time relatives of an array.
896   */
897   struct GNUNET_TIME_Relative
898 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
899 {
900   struct GNUNET_TIME_Relative sum;
901   uint32_t i;
902
903   sum = GNUNET_TIME_UNIT_ZERO;
904   for ( i = 0 ; i < arr_size ; i++ )
905   {
906     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
907   }
908   return sum;
909 }
910
911
912 /**
913  * Compute the average of given time relatives.
914  */
915   struct GNUNET_TIME_Relative
916 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
917 {
918   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
919 }
920
921
922 /**
923  * Insert PeerID in #pull_map
924  *
925  * Called once we know a peer is live.
926  */
927   void
928 insert_in_pull_map (void *cls, const struct GNUNET_PeerIdentity *peer)
929 {
930   CustomPeerMap_put (pull_map, peer);
931 }
932
933 /**
934  * Check whether #insert_in_pull_map was already scheduled
935  */
936   int
937 insert_in_pull_map_scheduled (const struct PeerContext *peer_ctx)
938 {
939   unsigned int i;
940
941   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
942     if (insert_in_pull_map == peer_ctx->outstanding_ops[i].op)
943       return GNUNET_YES;
944   return GNUNET_NO;
945 }
946
947
948 /**
949  * Insert PeerID in #view
950  *
951  * Called once we know a peer is live.
952  */
953   void
954 insert_in_view (void *cls, const struct GNUNET_PeerIdentity *peer)
955 {
956   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (view, peer))
957       return;
958   LOG (GNUNET_ERROR_TYPE_DEBUG,
959       "Going to put %s into view\n",
960       GNUNET_i2s (peer));
961   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_put (view,
962         peer,
963         NULL,
964         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
965   {
966     LOG (GNUNET_ERROR_TYPE_WARNING,
967         "Failed to put peer into view. (insert_in_view)\n");
968   }
969   if (NULL != view_array)
970   {
971     GNUNET_free (view_array);
972     view_array = NULL;
973   }
974   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
975     create_peer_ctx (peer);
976   (void) get_channel (peer);
977 }
978
979 /**
980  * Check whether #insert_in_view was already scheduled
981  */
982   int
983 insert_in_view_scheduled (const struct PeerContext *peer_ctx)
984 {
985   unsigned int i;
986
987   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
988     if (insert_in_view == peer_ctx->outstanding_ops[i].op)
989       return GNUNET_YES;
990   return GNUNET_NO;
991 }
992
993
994 /**
995  * Update sampler with given PeerID.
996  */
997   void
998 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
999 {
1000   LOG (GNUNET_ERROR_TYPE_DEBUG,
1001        "Updating samplers with peer %s from insert_in_sampler()\n",
1002        GNUNET_i2s (peer));
1003   RPS_sampler_update (prot_sampler,   peer);
1004   RPS_sampler_update (client_sampler, peer);
1005   if (0 < RPS_sampler_count_id (prot_sampler, peer))
1006   {
1007     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1008       (void) create_peer_ctx (peer);
1009     (void) get_channel (peer);
1010   }
1011 }
1012
1013
1014 /**
1015  * Check whether #insert_in_sampler was already scheduled
1016  */
1017 static int
1018 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
1019 {
1020   unsigned int i;
1021
1022   for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
1023     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
1024       return GNUNET_YES;
1025   return GNUNET_NO;
1026 }
1027
1028 /**
1029  * Put random peer from sampler into the view as history update.
1030  */
1031   void
1032 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
1033 {
1034   unsigned int i;
1035
1036   for (i = 0; i < GNUNET_MIN (
1037        sampler_size_est_need - GNUNET_CONTAINER_multipeermap_size (view),
1038        num_peers); i++)
1039   {
1040     insert_in_view (NULL, &ids[i]);
1041     to_file (file_name_view_log,
1042              "+%s\t(hist)",
1043              GNUNET_i2s_full (ids));
1044   }
1045   if (0 < num_hist_update_tasks)
1046     num_hist_update_tasks--;
1047 }
1048
1049
1050
1051 /**
1052  * Wrapper around #RPS_sampler_resize()
1053  *
1054  * If we do not have enough sampler elements, double current sampler size
1055  * If we have more than enough sampler elements, halv current sampler size
1056  */
1057 static void
1058 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
1059 {
1060   unsigned int sampler_size;
1061
1062   // TODO statistics
1063   // TODO respect the min, max
1064   sampler_size = RPS_sampler_get_size (sampler);
1065   if (sampler_size > new_size * 4)
1066   { /* Shrinking */
1067     RPS_sampler_resize (sampler, sampler_size / 2);
1068   }
1069   else if (sampler_size < new_size)
1070   { /* Growing */
1071     RPS_sampler_resize (sampler, sampler_size * 2);
1072   }
1073   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
1074 }
1075
1076
1077 /**
1078  * Wrapper around #RPS_sampler_resize() resizing the client sampler
1079  */
1080 static void
1081 client_resize_wrapper ()
1082 {
1083   uint32_t bigger_size;
1084
1085   // TODO statistics
1086
1087   bigger_size = GNUNET_MAX (sampler_size_est_need, sampler_size_client_need);
1088
1089   // TODO respect the min, max
1090   resize_wrapper (client_sampler, bigger_size);
1091   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size_client is now %" PRIu32 "\n",
1092       bigger_size);
1093 }
1094
1095
1096 /**
1097  * Estimate request rate
1098  *
1099  * Called every time we receive a request from the client.
1100  */
1101   void
1102 est_request_rate()
1103 {
1104   struct GNUNET_TIME_Relative max_round_duration;
1105
1106   if (request_deltas_size > req_counter)
1107     req_counter++;
1108   if ( 1 < req_counter)
1109   {
1110     /* Shift last request deltas to the right */
1111     memcpy (&request_deltas[1],
1112         request_deltas,
1113         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
1114
1115     /* Add current delta to beginning */
1116     request_deltas[0] =
1117         GNUNET_TIME_absolute_get_difference (last_request,
1118                                              GNUNET_TIME_absolute_get ());
1119     request_rate = T_relative_avg (request_deltas, req_counter);
1120     request_rate = (request_rate.rel_value_us < 1) ?
1121       GNUNET_TIME_relative_get_unit_ () : request_rate;
1122
1123     /* Compute the duration a round will maximally take */
1124     max_round_duration =
1125         GNUNET_TIME_relative_add (round_interval,
1126                                   GNUNET_TIME_relative_divide (round_interval, 2));
1127
1128     /* Set the estimated size the sampler has to have to
1129      * satisfy the current client request rate */
1130     sampler_size_client_need =
1131         max_round_duration.rel_value_us / request_rate.rel_value_us;
1132
1133     /* Resize the sampler */
1134     client_resize_wrapper ();
1135   }
1136   last_request = GNUNET_TIME_absolute_get ();
1137 }
1138
1139
1140 /**
1141  * Add all peers in @a peer_array to @a peer_map used as set.
1142  *
1143  * @param peer_array array containing the peers
1144  * @param num_peers number of peers in @peer_array
1145  * @param peer_map the peermap to use as set
1146  */
1147 static void
1148 add_peer_array_to_set (const struct GNUNET_PeerIdentity *peer_array,
1149                        unsigned int num_peers,
1150                        struct GNUNET_CONTAINER_MultiPeerMap *peer_map)
1151 {
1152   unsigned int i;
1153   if (NULL == peer_map)
1154   {
1155     LOG (GNUNET_ERROR_TYPE_WARNING,
1156          "Trying to add peers to non-existing peermap.\n");
1157     return;
1158   }
1159
1160   for (i = 0; i < num_peers; i++)
1161   {
1162     GNUNET_CONTAINER_multipeermap_put (peer_map,
1163                                        &peer_array[i],
1164                                        NULL,
1165                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1166   }
1167 }
1168
1169
1170 /**
1171  * @brief Add an envelope to a message passed to mq to list of pending messages
1172  *
1173  * @param peer peer the message was sent to
1174  * @param ev envelope to the message
1175  * @param type type of the message to be sent
1176  */
1177 static struct PendingMessage *
1178 insert_pending_message (const struct GNUNET_PeerIdentity *peer,
1179                         struct GNUNET_MQ_Envelope *ev,
1180                         const char *type)
1181 {
1182   struct PendingMessage *pending_msg;
1183   struct PeerContext *peer_ctx;
1184
1185   peer_ctx = get_peer_ctx (peer);
1186   pending_msg = GNUNET_new (struct PendingMessage);
1187   pending_msg->ev = ev;
1188   pending_msg->peer_ctx = peer_ctx;
1189   pending_msg->type = type;
1190   GNUNET_CONTAINER_DLL_insert (peer_ctx->pending_messages_head,
1191                                peer_ctx->pending_messages_tail,
1192                                pending_msg);
1193   return pending_msg;
1194 }
1195
1196 static void
1197 remove_pending_message (struct PendingMessage *pending_msg)
1198 {
1199   struct PeerContext *peer_ctx;
1200
1201   peer_ctx = pending_msg->peer_ctx;
1202   GNUNET_CONTAINER_DLL_remove (peer_ctx->pending_messages_head,
1203                                peer_ctx->pending_messages_tail,
1204                                pending_msg);
1205   GNUNET_free (pending_msg);
1206 }
1207
1208
1209 /**
1210  * @brief This is called once a message is sent.
1211  *
1212  * @param cls type of the message that was sent
1213  */
1214 static void
1215 mq_notify_sent_cb (void *cls)
1216 {
1217   struct PendingMessage *pending_msg = (struct PendingMessage *) cls;
1218   LOG (GNUNET_ERROR_TYPE_DEBUG,
1219       "%s was sent.\n",
1220       pending_msg->type);
1221   remove_pending_message (pending_msg);
1222 }
1223
1224
1225 /**
1226  * Send a PULL REPLY to @a peer_id
1227  *
1228  * @param peer_id the peer to send the reply to.
1229  * @param peer_ids the peers to send to @a peer_id
1230  * @param num_peer_ids the number of peers to send to @a peer_id
1231  */
1232 static void
1233 send_pull_reply (const struct GNUNET_PeerIdentity *peer_id,
1234                  const struct GNUNET_PeerIdentity *peer_ids,
1235                  unsigned int num_peer_ids)
1236 {
1237   uint32_t send_size;
1238   struct GNUNET_MQ_Handle *mq;
1239   struct GNUNET_MQ_Envelope *ev;
1240   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1241   struct PendingMessage *pending_msg;
1242
1243   /* Compute actual size */
1244   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1245               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
1246
1247   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1248     /* Compute number of peers to send
1249      * If too long, simply truncate */
1250     // TODO select random ones via permutation
1251     //      or even better: do good protocol design
1252     send_size =
1253       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1254        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1255        sizeof (struct GNUNET_PeerIdentity);
1256   else
1257     send_size = num_peer_ids;
1258
1259   LOG (GNUNET_ERROR_TYPE_DEBUG,
1260       "Going to send PULL REPLY with %u peers to %s\n",
1261       send_size, GNUNET_i2s (peer_id));
1262
1263   mq = get_mq (peer_id);
1264
1265   ev = GNUNET_MQ_msg_extra (out_msg,
1266                             send_size * sizeof (struct GNUNET_PeerIdentity),
1267                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1268   out_msg->num_peers = htonl (send_size);
1269   memcpy (&out_msg[1], peer_ids,
1270          send_size * sizeof (struct GNUNET_PeerIdentity));
1271
1272   pending_msg = insert_pending_message (peer_id, ev, "PULL REPLY");
1273   GNUNET_MQ_notify_sent (ev,
1274       mq_notify_sent_cb,
1275       pending_msg);
1276   GNUNET_MQ_send (mq, ev);
1277 }
1278
1279
1280 /**
1281  * This function is called on new peer_ids from 'external' sources
1282  * (client seed, cadet get_peers(), ...)
1283  *
1284  * @param peer_id the new peer_id
1285  */
1286 static void
1287 new_peer_id (const struct GNUNET_PeerIdentity *peer_id)
1288 {
1289   struct PeerOutstandingOp out_op;
1290   struct PeerContext *peer_ctx;
1291
1292   if ((NULL == peer_id) ||
1293       (0 == GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer_id)))
1294     return;
1295   LOG (GNUNET_ERROR_TYPE_DEBUG,
1296        "Got peer_id %s (at %p, view size: %u)\n",
1297        GNUNET_i2s (peer_id),
1298        peer_id,
1299        GNUNET_CONTAINER_multipeermap_size (view));
1300
1301   /* if the seed peer is already know, skip context creation */
1302   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer_id))
1303     peer_ctx = create_peer_ctx (peer_id);
1304   else
1305     peer_ctx = get_peer_ctx (peer_id);
1306
1307   if (GNUNET_NO == get_peer_flag (peer_ctx, VALID))
1308   {
1309     if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1310     {
1311       out_op.op = insert_in_sampler;
1312       out_op.op_cls = NULL;
1313       GNUNET_array_append (peer_ctx->outstanding_ops,
1314                            peer_ctx->num_outstanding_ops,
1315                            out_op);
1316     }
1317
1318     if (GNUNET_NO == insert_in_view_scheduled (peer_ctx))
1319     {
1320       out_op.op = insert_in_view;
1321       out_op.op_cls = NULL;
1322       GNUNET_array_append (peer_ctx->outstanding_ops,
1323                            peer_ctx->num_outstanding_ops,
1324                            out_op);
1325     }
1326
1327     /* Trigger livelyness test on peer */
1328     check_peer_live (peer_ctx);
1329   }
1330   // else...?
1331
1332   // send push/pull to each of those peers?
1333 }
1334
1335
1336 /***********************************************************************
1337  * /Util functions
1338 ***********************************************************************/
1339
1340 static void
1341 destroy_reply_cls (struct ReplyCls *rep_cls)
1342 {
1343   struct ClientContext *cli_ctx;
1344
1345   cli_ctx = GNUNET_SERVER_client_get_user_context (rep_cls->client,
1346                                                    struct ClientContext);
1347   GNUNET_assert (NULL != cli_ctx);
1348   GNUNET_CONTAINER_DLL_remove (cli_ctx->rep_cls_head,
1349                                cli_ctx->rep_cls_tail,
1350                                rep_cls);
1351   GNUNET_free (rep_cls);
1352 }
1353
1354 static void
1355 destroy_cli_ctx (struct ClientContext *cli_ctx)
1356 {
1357   GNUNET_assert (NULL != cli_ctx);
1358   if (NULL != cli_ctx->rep_cls_head)
1359   {
1360     LOG (GNUNET_ERROR_TYPE_WARNING,
1361          "Trying to destroy the context of a client that still has pending requests. Going to clean those\n");
1362     while (NULL != cli_ctx->rep_cls_head)
1363       destroy_reply_cls (cli_ctx->rep_cls_head);
1364   }
1365   GNUNET_CONTAINER_DLL_remove (cli_ctx_head,
1366                                cli_ctx_tail,
1367                                cli_ctx);
1368   GNUNET_free (cli_ctx);
1369 }
1370
1371
1372 /**
1373  * Function called by NSE.
1374  *
1375  * Updates sizes of sampler list and view and adapt those lists
1376  * accordingly.
1377  */
1378   void
1379 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1380               double logestimate, double std_dev)
1381 {
1382   double estimate;
1383   //double scale; // TODO this might go gloabal/config
1384
1385   LOG (GNUNET_ERROR_TYPE_DEBUG,
1386        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1387        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1388   //scale = .01;
1389   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1390   // GNUNET_NSE_log_estimate_to_n (logestimate);
1391   estimate = pow (estimate, 1.0 / 3);
1392   // TODO add if std_dev is a number
1393   // estimate += (std_dev * scale);
1394   if (2 < ceil (estimate))
1395   {
1396     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1397     sampler_size_est_need = estimate;
1398   } else
1399     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1400
1401   /* If the NSE has changed adapt the lists accordingly */
1402   resize_wrapper (prot_sampler, sampler_size_est_need);
1403   client_resize_wrapper ();
1404 }
1405
1406
1407 /**
1408  * Callback called once the requested PeerIDs are ready.
1409  *
1410  * Sends those to the requesting client.
1411  */
1412 void client_respond (void *cls,
1413     struct GNUNET_PeerIdentity *peer_ids, uint32_t num_peers)
1414 {
1415   uint32_t i;
1416   struct GNUNET_MQ_Envelope *ev;
1417   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1418   struct ReplyCls *reply_cls = (struct ReplyCls *) cls;
1419   uint32_t size_needed;
1420   struct ClientContext *cli_ctx;
1421
1422   GNUNET_assert (NULL != reply_cls);
1423   LOG (GNUNET_ERROR_TYPE_DEBUG,
1424        "sampler returned %" PRIu32 " peers:\n",
1425        num_peers);
1426   for (i = 0; i < num_peers; i++)
1427   {
1428     LOG (GNUNET_ERROR_TYPE_DEBUG,
1429          "  %lu: %s\n",
1430          i,
1431          GNUNET_i2s (&peer_ids[i]));
1432   }
1433
1434   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1435                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1436
1437   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1438
1439   ev = GNUNET_MQ_msg_extra (out_msg,
1440                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1441                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1442   out_msg->num_peers = htonl (num_peers);
1443   out_msg->id = htonl (reply_cls->id);
1444
1445   memcpy (&out_msg[1],
1446           peer_ids,
1447           num_peers * sizeof (struct GNUNET_PeerIdentity));
1448   GNUNET_free (peer_ids);
1449
1450   cli_ctx = GNUNET_SERVER_client_get_user_context (reply_cls->client,
1451                                                    struct ClientContext);
1452   GNUNET_assert (NULL != cli_ctx);
1453   destroy_reply_cls (reply_cls);
1454   GNUNET_MQ_send (cli_ctx->mq, ev);
1455 }
1456
1457
1458 /**
1459  * Handle RPS request from the client.
1460  *
1461  * @param cls closure
1462  * @param client identification of the client
1463  * @param message the actual message
1464  */
1465 static void
1466 handle_client_request (void *cls,
1467                        struct GNUNET_SERVER_Client *client,
1468                        const struct GNUNET_MessageHeader *message)
1469 {
1470   struct GNUNET_RPS_CS_RequestMessage *msg;
1471   uint32_t num_peers;
1472   uint32_t size_needed;
1473   struct ReplyCls *reply_cls;
1474   uint32_t i;
1475   struct ClientContext *cli_ctx;
1476
1477   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1478
1479   num_peers = ntohl (msg->num_peers);
1480   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1481                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1482
1483   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1484   {
1485     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1486                 "Message received from client has size larger than expected\n");
1487     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1488     return;
1489   }
1490
1491   for (i = 0 ; i < num_peers ; i++)
1492     est_request_rate();
1493
1494   LOG (GNUNET_ERROR_TYPE_DEBUG,
1495        "Client requested %" PRIu32 " random peer(s).\n",
1496        num_peers);
1497
1498   reply_cls = GNUNET_new (struct ReplyCls);
1499   reply_cls->id = ntohl (msg->id);
1500   reply_cls->client = client;
1501   reply_cls->req_handle = RPS_sampler_get_n_rand_peers (client_sampler,
1502                                                         client_respond,
1503                                                         reply_cls,
1504                                                         num_peers);
1505
1506   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct ClientContext);
1507   GNUNET_assert (NULL != cli_ctx);
1508   GNUNET_CONTAINER_DLL_insert (cli_ctx->rep_cls_head,
1509                                cli_ctx->rep_cls_tail,
1510                                reply_cls);
1511   GNUNET_SERVER_receive_done (client,
1512                               GNUNET_OK);
1513 }
1514
1515
1516 /**
1517  * @brief Handle a message that requests the cancellation of a request
1518  *
1519  * @param cls unused
1520  * @param client the client that requests the cancellation
1521  * @param message the message containing the id of the request
1522  */
1523 static void
1524 handle_client_request_cancel (void *cls,
1525                               struct GNUNET_SERVER_Client *client,
1526                               const struct GNUNET_MessageHeader *message)
1527 {
1528   struct GNUNET_RPS_CS_RequestCancelMessage *msg =
1529     (struct GNUNET_RPS_CS_RequestCancelMessage *) message;
1530   struct ClientContext *cli_ctx;
1531   struct ReplyCls *rep_cls;
1532
1533   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct ClientContext);
1534   GNUNET_assert (NULL != cli_ctx->rep_cls_head);
1535   rep_cls = cli_ctx->rep_cls_head;
1536   LOG (GNUNET_ERROR_TYPE_DEBUG,
1537       "Client cancels request with id %lu\n",
1538       ntohl (msg->id));
1539   while ( (NULL != rep_cls->next) &&
1540           (rep_cls->id != ntohl (msg->id)) )
1541     rep_cls = rep_cls->next;
1542   GNUNET_assert (rep_cls->id == ntohl (msg->id));
1543   RPS_sampler_request_cancel (rep_cls->req_handle);
1544   destroy_reply_cls (rep_cls);
1545   GNUNET_SERVER_receive_done (client,
1546                               GNUNET_OK);
1547 }
1548
1549
1550 /**
1551  * Handle seed from the client.
1552  *
1553  * @param cls closure
1554  * @param client identification of the client
1555  * @param message the actual message
1556  */
1557   static void
1558 handle_client_seed (void *cls,
1559                     struct GNUNET_SERVER_Client *client,
1560                     const struct GNUNET_MessageHeader *message)
1561 {
1562   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1563   struct GNUNET_PeerIdentity *peers;
1564   uint32_t num_peers;
1565   uint32_t i;
1566
1567   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1568   {
1569     GNUNET_break_op (0);
1570     GNUNET_SERVER_receive_done (client,
1571                                 GNUNET_SYSERR);
1572   }
1573
1574   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1575   num_peers = ntohl (in_msg->num_peers);
1576   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1577   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1578   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1579
1580   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1581       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1582   {
1583     GNUNET_break_op (0);
1584     GNUNET_SERVER_receive_done (client,
1585                                 GNUNET_SYSERR);
1586     return;
1587   }
1588
1589   LOG (GNUNET_ERROR_TYPE_DEBUG,
1590        "Client seeded peers:\n");
1591   print_peer_list (peers, num_peers);
1592
1593   for (i = 0 ; i < num_peers ; i++)
1594   {
1595     LOG (GNUNET_ERROR_TYPE_DEBUG,
1596          "Updating samplers with seed %" PRIu32 ": %s\n",
1597          i,
1598          GNUNET_i2s (&peers[i]));
1599
1600     new_peer_id (&peers[i]);
1601
1602     //RPS_sampler_update (prot_sampler,   &peers[i]);
1603     //RPS_sampler_update (client_sampler, &peers[i]);
1604   }
1605
1606   ////GNUNET_free (peers);
1607
1608   GNUNET_SERVER_receive_done (client,
1609                                                 GNUNET_OK);
1610 }
1611
1612
1613 /**
1614  * Handle a PUSH message from another peer.
1615  *
1616  * Check the proof of work and store the PeerID
1617  * in the temporary list for pushed PeerIDs.
1618  *
1619  * @param cls Closure
1620  * @param channel The channel the PUSH was received over
1621  * @param channel_ctx The context associated with this channel
1622  * @param msg The message header
1623  */
1624 static int
1625 handle_peer_push (void *cls,
1626     struct GNUNET_CADET_Channel *channel,
1627     void **channel_ctx,
1628     const struct GNUNET_MessageHeader *msg)
1629 {
1630   const struct GNUNET_PeerIdentity *peer;
1631
1632   // (check the proof of work)
1633
1634   peer = (const struct GNUNET_PeerIdentity *)
1635     GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1636   // FIXME wait for cadet to change this function
1637
1638   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PUSH (%s)\n", GNUNET_i2s (peer));
1639
1640   #ifdef ENABLE_MALICIOUS
1641   struct AttackedPeer *tmp_att_peer;
1642
1643   tmp_att_peer = GNUNET_new (struct AttackedPeer);
1644   memcpy (&tmp_att_peer->peer_id, peer, sizeof (struct GNUNET_PeerIdentity));
1645   if (1 == mal_type
1646       || 3 == mal_type)
1647   { /* Try to maximise representation */
1648     if (NULL == att_peer_set)
1649       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
1650     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1651                                                              peer))
1652     {
1653       GNUNET_CONTAINER_DLL_insert (att_peers_head,
1654                                    att_peers_tail,
1655                                    tmp_att_peer);
1656       add_peer_array_to_set (peer, 1, att_peer_set);
1657     }
1658     return GNUNET_OK;
1659   }
1660
1661
1662   else if (2 == mal_type)
1663   { /* We attack one single well-known peer - simply ignore */
1664     return GNUNET_OK;
1665   }
1666   else
1667   {
1668     GNUNET_free (tmp_att_peer);
1669   }
1670
1671   #endif /* ENABLE_MALICIOUS */
1672
1673   /* Add the sending peer to the push_map */
1674   CustomPeerMap_put (push_map, peer);
1675
1676   GNUNET_CADET_receive_done (channel);
1677   return GNUNET_OK;
1678 }
1679
1680
1681 /**
1682  * Iterator over hash map entries.
1683  * Called from #generate_view_array and writes every peer id into #view_array.
1684  *
1685  * @param cls closure - the pointer to the counter
1686  * @param key current public key
1687  * @param value value in the hash map
1688  * @return #GNUNET_YES if we should continue to
1689  * iterate,
1690  * #GNUNET_NO if not.
1691  */
1692 static int
1693 dump_id_to_view_array (void *cls,
1694                        const struct GNUNET_PeerIdentity *key,
1695                        void *value)
1696 {
1697   unsigned int *i = (unsigned int *) cls;
1698
1699   view_array[(*i)++] = *key;
1700   return GNUNET_YES;
1701 }
1702
1703
1704 /**
1705  * Makes sure the view_array is filled with the peer ids currently in #view.
1706  * Called from within #do_round before sending pushes and pulls and from
1707  * #handle_peer_pull_request when a reply is sent.
1708  */
1709 static void
1710 generate_view_array (unsigned int view_size)
1711 {
1712   unsigned int *i;
1713   int ret;
1714
1715   if (NULL == view_array)
1716   {
1717     view_array = GNUNET_new_array (view_size,
1718                                    struct GNUNET_PeerIdentity);
1719     i = GNUNET_new (unsigned int);
1720     *i = 0;
1721
1722     ret = GNUNET_CONTAINER_multipeermap_iterate (view,
1723                                                  dump_id_to_view_array,
1724                                                  i);
1725     GNUNET_assert (view_size == ret);
1726     GNUNET_assert (view_size == *i);
1727
1728     GNUNET_free (i);
1729   }
1730 }
1731
1732
1733 /**
1734  * Handle PULL REQUEST request message from another peer.
1735  *
1736  * Reply with the view of PeerIDs.
1737  *
1738  * @param cls Closure
1739  * @param channel The channel the PULL REQUEST was received over
1740  * @param channel_ctx The context associated with this channel
1741  * @param msg The message header
1742  */
1743 static int
1744 handle_peer_pull_request (void *cls,
1745     struct GNUNET_CADET_Channel *channel,
1746     void **channel_ctx,
1747     const struct GNUNET_MessageHeader *msg)
1748 {
1749   struct GNUNET_PeerIdentity *peer;
1750   unsigned int view_size;
1751
1752   peer = (struct GNUNET_PeerIdentity *)
1753     GNUNET_CADET_channel_get_info (channel,
1754                                    GNUNET_CADET_OPTION_PEER);
1755   // FIXME wait for cadet to change this function
1756
1757   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REQUEST (%s)\n", GNUNET_i2s (peer));
1758
1759   #ifdef ENABLE_MALICIOUS
1760   if (1 == mal_type
1761       || 3 == mal_type)
1762   { /* Try to maximise representation */
1763     send_pull_reply (peer, mal_peers, num_mal_peers);
1764     return GNUNET_OK;
1765   }
1766
1767   else if (2 == mal_type)
1768   { /* Try to partition network */
1769     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
1770     {
1771       send_pull_reply (peer, mal_peers, num_mal_peers);
1772     }
1773     return GNUNET_OK;
1774   }
1775   #endif /* ENABLE_MALICIOUS */
1776
1777   view_size = GNUNET_CONTAINER_multipeermap_size (view);
1778   generate_view_array (view_size);
1779
1780   send_pull_reply (peer, view_array, view_size);
1781
1782   GNUNET_CADET_receive_done (channel);
1783   return GNUNET_OK;
1784 }
1785
1786
1787 /**
1788  * Handle PULL REPLY message from another peer.
1789  *
1790  * Check whether we sent a corresponding request and
1791  * whether this reply is the first one.
1792  *
1793  * @param cls Closure
1794  * @param channel The channel the PUSH was received over
1795  * @param channel_ctx The context associated with this channel
1796  * @param msg The message header
1797  */
1798   static int
1799 handle_peer_pull_reply (void *cls,
1800                         struct GNUNET_CADET_Channel *channel,
1801                         void **channel_ctx,
1802                         const struct GNUNET_MessageHeader *msg)
1803 {
1804   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1805   struct GNUNET_PeerIdentity *peers;
1806   struct PeerContext *peer_ctx;
1807   struct GNUNET_PeerIdentity *sender;
1808   struct PeerContext *sender_ctx;
1809   struct PeerOutstandingOp out_op;
1810   uint32_t i;
1811 #ifdef ENABLE_MALICIOUS
1812   struct AttackedPeer *tmp_att_peer;
1813 #endif /* ENABLE_MALICIOUS */
1814
1815   /* Check for protocol violation */
1816   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1817   {
1818     GNUNET_break_op (0);
1819     GNUNET_CADET_receive_done (channel);
1820     return GNUNET_SYSERR;
1821   }
1822
1823   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1824   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1825       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1826   {
1827     LOG (GNUNET_ERROR_TYPE_ERROR,
1828         "message says it sends %" PRIu32 " peers, have space for %i peers\n",
1829         ntohl (in_msg->num_peers),
1830         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1831             sizeof (struct GNUNET_PeerIdentity));
1832     GNUNET_break_op (0);
1833     GNUNET_CADET_receive_done (channel);
1834     return GNUNET_SYSERR;
1835   }
1836
1837   // Guess simply casting isn't the nicest way...
1838   // FIXME wait for cadet to change this function
1839   sender = (struct GNUNET_PeerIdentity *)
1840       GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1841   sender_ctx = get_peer_ctx (sender);
1842
1843   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REPLY (%s)\n", GNUNET_i2s (sender));
1844
1845   if (GNUNET_YES != get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1846   {
1847     LOG (GNUNET_ERROR_TYPE_WARNING,
1848         "Received a pull reply from a peer we didn't request one from!\n");
1849     GNUNET_break_op (0);
1850     GNUNET_CADET_receive_done (channel);
1851     return GNUNET_OK;
1852   }
1853
1854
1855   #ifdef ENABLE_MALICIOUS
1856   // We shouldn't even receive pull replies as we're not sending
1857   if (2 == mal_type)
1858     return GNUNET_OK;
1859   #endif /* ENABLE_MALICIOUS */
1860
1861   /* Do actual logic */
1862   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1863
1864   LOG (GNUNET_ERROR_TYPE_DEBUG,
1865        "PULL REPLY received, got following %u peers:\n",
1866        ntohl (in_msg->num_peers));
1867
1868   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1869   {
1870     LOG (GNUNET_ERROR_TYPE_DEBUG,
1871          "%u. %s\n",
1872          i,
1873          GNUNET_i2s (&peers[i]));
1874
1875     #ifdef ENABLE_MALICIOUS
1876     if ((NULL != att_peer_set) &&
1877         (1 == mal_type || 3 == mal_type))
1878     { /* Add attacked peer to local list */
1879       // TODO check if we sent a request and this was the first reply
1880       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1881                                                                &peers[i])
1882           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
1883                                                                   &peers[i])
1884           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&peers[i],
1885                                                    &own_identity))
1886       {
1887         tmp_att_peer = GNUNET_new (struct AttackedPeer);
1888         tmp_att_peer->peer_id = peers[i];
1889         GNUNET_CONTAINER_DLL_insert (att_peers_head,
1890                                      att_peers_tail,
1891                                      tmp_att_peer);
1892         add_peer_array_to_set (&peers[i], 1, att_peer_set);
1893       }
1894       continue;
1895     }
1896     #endif /* ENABLE_MALICIOUS */
1897     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity,
1898                                               &peers[i]))
1899     {
1900       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map,
1901             &peers[i]))
1902         peer_ctx = create_peer_ctx (&peers[i]);
1903       else
1904         peer_ctx = get_peer_ctx (&peers[i]);
1905
1906       if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
1907       {
1908         CustomPeerMap_put (pull_map, &peers[i]);
1909       }
1910       else if (GNUNET_NO == insert_in_pull_map_scheduled (peer_ctx))
1911       {
1912         out_op.op = insert_in_pull_map;
1913         out_op.op_cls = NULL;
1914         GNUNET_array_append (peer_ctx->outstanding_ops,
1915                              peer_ctx->num_outstanding_ops,
1916                              out_op);
1917         check_peer_live (peer_ctx);
1918       }
1919     }
1920   }
1921
1922   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1923
1924   peer_clean (sender);
1925
1926   GNUNET_CADET_receive_done (channel);
1927   return GNUNET_OK;
1928 }
1929
1930
1931 /**
1932  * Compute a random delay.
1933  * A uniformly distributed value between mean + spread and mean - spread.
1934  *
1935  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1936  * It would return a random value between 2 and 6 min.
1937  *
1938  * @param mean the mean
1939  * @param spread the inverse amount of deviation from the mean
1940  */
1941 static struct GNUNET_TIME_Relative
1942 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1943 {
1944   struct GNUNET_TIME_Relative half_interval;
1945   struct GNUNET_TIME_Relative ret;
1946   unsigned int rand_delay;
1947   unsigned int max_rand_delay;
1948
1949   if (0 == spread)
1950   {
1951     LOG (GNUNET_ERROR_TYPE_WARNING,
1952          "Not accepting spread of 0\n");
1953     GNUNET_break (0);
1954   }
1955
1956   /* Compute random time value between spread * mean and spread * mean */
1957   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1958
1959   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1960   /**
1961    * Compute random value between (0 and 1) * round_interval
1962    * via multiplying round_interval with a 'fraction' (0 to value)/value
1963    */
1964   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1965   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1966   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1967   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1968
1969   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1970     LOG (GNUNET_ERROR_TYPE_WARNING,
1971          "Returning FOREVER_REL\n");
1972
1973   return ret;
1974 }
1975
1976
1977 /**
1978  * Send single pull request
1979  *
1980  * @param peer_id the peer to send the pull request to.
1981  */
1982 static void
1983 send_pull_request (const struct GNUNET_PeerIdentity *peer_id)
1984 {
1985   struct GNUNET_MQ_Envelope *ev;
1986   struct GNUNET_MQ_Handle *mq;
1987   struct PeerContext *peer_ctx;
1988   struct PendingMessage *pending_msg;
1989
1990   peer_ctx = get_peer_ctx (peer_id);
1991   GNUNET_assert (GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING));
1992   set_peer_flag (peer_ctx, PULL_REPLY_PENDING);
1993
1994   LOG (GNUNET_ERROR_TYPE_DEBUG,
1995        "Going to send PULL REQUEST to peer %s.\n",
1996        GNUNET_i2s (peer_id));
1997
1998   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1999   mq = get_mq (peer_id);
2000   pending_msg = insert_pending_message (peer_id, ev, "PULL REQUEST");
2001   GNUNET_MQ_notify_sent (ev,
2002       mq_notify_sent_cb,
2003       pending_msg);
2004   GNUNET_MQ_send (mq, ev);
2005 }
2006
2007
2008 /**
2009  * Send single push
2010  *
2011  * @param peer_id the peer to send the push to.
2012  */
2013 static void
2014 send_push (const struct GNUNET_PeerIdentity *peer_id)
2015 {
2016   struct GNUNET_MQ_Envelope *ev;
2017   struct GNUNET_MQ_Handle *mq;
2018   struct PendingMessage *pending_msg;
2019
2020   LOG (GNUNET_ERROR_TYPE_DEBUG,
2021        "Going to send PUSH to peer %s.\n",
2022        GNUNET_i2s (peer_id));
2023
2024   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
2025   mq = get_mq (peer_id);
2026   pending_msg = insert_pending_message (peer_id, ev, "PUSH");
2027   GNUNET_MQ_notify_sent (ev,
2028       mq_notify_sent_cb,
2029       pending_msg);
2030   GNUNET_MQ_send (mq, ev);
2031 }
2032
2033
2034 static void
2035 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2036
2037 static void
2038 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2039
2040
2041 #ifdef ENABLE_MALICIOUS
2042 /**
2043  * Turn RPS service to act malicious.
2044  *
2045  * @param cls Closure
2046  * @param client The client that sent the message
2047  * @param msg The message header
2048  */
2049   static void
2050 handle_client_act_malicious (void *cls,
2051                              struct GNUNET_SERVER_Client *client,
2052                              const struct GNUNET_MessageHeader *msg)
2053 {
2054   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
2055   struct GNUNET_PeerIdentity *peers;
2056   uint32_t num_mal_peers_sent;
2057   uint32_t num_mal_peers_old;
2058
2059   /* Check for protocol violation */
2060   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
2061   {
2062     GNUNET_break_op (0);
2063   }
2064
2065   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
2066   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
2067       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
2068   {
2069     LOG (GNUNET_ERROR_TYPE_ERROR,
2070         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
2071         ntohl (in_msg->num_peers),
2072         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
2073             sizeof (struct GNUNET_PeerIdentity));
2074     GNUNET_break_op (0);
2075   }
2076
2077
2078   /* Do actual logic */
2079   peers = (struct GNUNET_PeerIdentity *) &msg[1];
2080   mal_type = ntohl (in_msg->type);
2081   if (NULL == mal_peer_set)
2082     mal_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
2083
2084   LOG (GNUNET_ERROR_TYPE_DEBUG,
2085        "Now acting malicious type %" PRIu32 ", got %" PRIu32 " peers.\n",
2086        mal_type,
2087        ntohl (in_msg->num_peers));
2088
2089   if (1 == mal_type)
2090   { /* Try to maximise representation */
2091     /* Add other malicious peers to those we already know */
2092
2093     num_mal_peers_sent = ntohl (in_msg->num_peers);
2094     num_mal_peers_old = num_mal_peers;
2095     GNUNET_array_grow (mal_peers,
2096                        num_mal_peers,
2097                        num_mal_peers + num_mal_peers_sent);
2098     memcpy (&mal_peers[num_mal_peers_old],
2099             peers,
2100             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
2101
2102     /* Add all mal peers to mal_peer_set */
2103     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
2104                            num_mal_peers_sent,
2105                            mal_peer_set);
2106
2107     /* Substitute do_round () with do_mal_round () */
2108     GNUNET_SCHEDULER_cancel (do_round_task);
2109     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
2110   }
2111
2112   else if (2 == mal_type
2113            || 3 == mal_type)
2114   { /* Try to partition the network */
2115     /* Add other malicious peers to those we already know */
2116     struct PeerContext *att_ctx;
2117
2118     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
2119     num_mal_peers_old = num_mal_peers;
2120     GNUNET_array_grow (mal_peers,
2121                        num_mal_peers,
2122                        num_mal_peers + num_mal_peers_sent);
2123     if (NULL != mal_peers &&
2124         0 != num_mal_peers)
2125     {
2126       memcpy (&mal_peers[num_mal_peers_old],
2127               peers,
2128               num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
2129
2130       /* Add all mal peers to mal_peer_set */
2131       add_peer_array_to_set (&mal_peers[num_mal_peers_old],
2132                              num_mal_peers_sent,
2133                              mal_peer_set);
2134     }
2135
2136     /* Store the one attacked peer */
2137     memcpy (&attacked_peer,
2138             &in_msg->attacked_peer,
2139             sizeof (struct GNUNET_PeerIdentity));
2140     /* Set the flag of the attacked peer to valid to avoid problems */
2141     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map,
2142           &attacked_peer))
2143     {
2144       att_ctx = create_peer_ctx (&attacked_peer);
2145       check_peer_live (att_ctx);
2146     }
2147
2148     LOG (GNUNET_ERROR_TYPE_DEBUG,
2149          "Attacked peer is %s\n",
2150          GNUNET_i2s (&attacked_peer));
2151
2152     /* Substitute do_round () with do_mal_round () */
2153     GNUNET_SCHEDULER_cancel (do_round_task);
2154     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
2155   }
2156   else if (0 == mal_type)
2157   { /* Stop acting malicious */
2158     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2159
2160     /* Substitute do_mal_round () with do_round () */
2161     GNUNET_SCHEDULER_cancel (do_round_task);
2162     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2163   }
2164   else
2165   {
2166     GNUNET_break (0);
2167   }
2168
2169   GNUNET_SERVER_receive_done (client,   GNUNET_OK);
2170 }
2171
2172
2173 /**
2174  * Send out PUSHes and PULLs maliciously.
2175  *
2176  * This is executed regylary.
2177  */
2178 static void
2179 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2180 {
2181   uint32_t num_pushes;
2182   uint32_t i;
2183   struct GNUNET_TIME_Relative time_next_round;
2184   struct AttackedPeer *tmp_att_peer;
2185   struct PeerContext *peer_ctx;
2186
2187   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously type %" PRIu32 ".\n",
2188       mal_type);
2189   do_round_task = NULL;
2190   GNUNET_assert (mal_type <= 3);
2191   /* Do malicious actions */
2192   if (1 == mal_type)
2193   { /* Try to maximise representation */
2194
2195     /* The maximum of pushes we're going to send this round */
2196     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
2197                                          num_attacked_peers),
2198                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
2199
2200     LOG (GNUNET_ERROR_TYPE_DEBUG,
2201          "Going to send %" PRIu32 " pushes\n",
2202          num_pushes);
2203
2204     /* Send PUSHes to attacked peers */
2205     for (i = 0 ; i < num_pushes ; i++)
2206     {
2207       if (att_peers_tail == att_peer_index)
2208         att_peer_index = att_peers_head;
2209       else
2210         att_peer_index = att_peer_index->next;
2211
2212       send_push (&att_peer_index->peer_id);
2213     }
2214
2215     /* Send PULLs to some peers to learn about additional peers to attack */
2216     tmp_att_peer = att_peer_index;
2217     for (i = 0 ; i < num_pushes * alpha ; i++)
2218     {
2219       if (att_peers_tail == tmp_att_peer)
2220         tmp_att_peer = att_peers_head;
2221       else
2222         att_peer_index = tmp_att_peer->next;
2223
2224       send_pull_request (&tmp_att_peer->peer_id);
2225     }
2226   }
2227
2228
2229   else if (2 == mal_type)
2230   { /**
2231      * Try to partition the network
2232      * Send as many pushes to the attacked peer as possible
2233      * That is one push per round as it will ignore more.
2234      */
2235     peer_ctx = get_peer_ctx (&attacked_peer);
2236     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
2237       send_push (&attacked_peer);
2238   }
2239
2240
2241   if (3 == mal_type)
2242   { /* Combined attack */
2243
2244     /* Send PUSH to attacked peers */
2245     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map,
2246           &attacked_peer))
2247     {
2248       peer_ctx = get_peer_ctx (&attacked_peer);
2249       if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
2250       {
2251         LOG (GNUNET_ERROR_TYPE_DEBUG,
2252             "Goding to send push to attacked peer (%s)\n",
2253             GNUNET_i2s (&attacked_peer));
2254         send_push (&attacked_peer);
2255       }
2256       else
2257         check_peer_live (peer_ctx);
2258     }
2259     else
2260       peer_ctx = create_peer_ctx (&attacked_peer);
2261     check_peer_live (peer_ctx);
2262
2263     /* The maximum of pushes we're going to send this round */
2264     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
2265                                          num_attacked_peers),
2266                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
2267
2268     LOG (GNUNET_ERROR_TYPE_DEBUG,
2269          "Going to send %" PRIu32 " pushes\n",
2270          num_pushes);
2271
2272     for (i = 0 ; i < num_pushes ; i++)
2273     {
2274       if (att_peers_tail == att_peer_index)
2275         att_peer_index = att_peers_head;
2276       else
2277         att_peer_index = att_peer_index->next;
2278
2279       send_push (&att_peer_index->peer_id);
2280     }
2281
2282     /* Send PULLs to some peers to learn about additional peers to attack */
2283     tmp_att_peer = att_peer_index;
2284     for (i = 0 ; i < num_pushes * alpha ; i++)
2285     {
2286       if (att_peers_tail == tmp_att_peer)
2287         tmp_att_peer = att_peers_head;
2288       else
2289         att_peer_index = tmp_att_peer->next;
2290
2291       send_pull_request (&tmp_att_peer->peer_id);
2292     }
2293   }
2294
2295   /* Schedule next round */
2296   time_next_round = compute_rand_delay (round_interval, 2);
2297
2298   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round,
2299   //NULL);
2300   GNUNET_assert (NULL == do_round_task);
2301   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
2302   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2303 }
2304 #endif /* ENABLE_MALICIOUS */
2305
2306
2307 /**
2308  * Send out PUSHes and PULLs, possibly update #view, samplers.
2309  *
2310  * This is executed regylary.
2311  */
2312 static void
2313 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2314 {
2315   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
2316
2317   uint32_t i;
2318   unsigned int view_size;
2319   unsigned int *permut;
2320   unsigned int a_peers; /* Number of peers we send pushes to */
2321   unsigned int b_peers; /* Number of peers we send pull requests to */
2322   uint32_t first_border;
2323   uint32_t second_border;
2324   struct GNUNET_PeerIdentity peer;
2325   struct PeerContext *peer_ctx;
2326   struct GNUNET_PeerIdentity *update_peer;
2327
2328   do_round_task = NULL;
2329   LOG (GNUNET_ERROR_TYPE_DEBUG,
2330        "Printing view:\n");
2331   to_file (file_name_view_log,
2332            "___ new round ___");
2333   view_size = GNUNET_CONTAINER_multipeermap_size (view);
2334   generate_view_array (view_size);
2335   for (i = 0 ; i < view_size ; i++)
2336   {
2337     LOG (GNUNET_ERROR_TYPE_DEBUG,
2338          "\t%s\n", GNUNET_i2s (&view_array[i]));
2339     to_file (file_name_view_log,
2340              "=%s\t(do round)",
2341              GNUNET_i2s_full (&view_array[i]));
2342   }
2343
2344
2345   /* Send pushes and pull requests */
2346   if (0 < view_size)
2347   {
2348     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2349                                            (unsigned int) view_size);
2350
2351     /* Send PUSHes */
2352     a_peers = ceil (alpha * view_size);
2353
2354     LOG (GNUNET_ERROR_TYPE_DEBUG,
2355          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
2356          a_peers, alpha, view_size);
2357     for (i = 0; i < a_peers; i++)
2358     {
2359       peer = view_array[permut[i]];
2360       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
2361       { // FIXME if this fails schedule/loop this for later
2362         send_push (&peer);
2363       }
2364     }
2365
2366     /* Send PULL requests */
2367     b_peers = ceil (beta * view_size);
2368     first_border = a_peers;
2369     second_border = a_peers + b_peers;
2370     if (second_border > view_size)
2371     {
2372       first_border = view_size - b_peers;
2373       second_border = view_size;
2374     }
2375     LOG (GNUNET_ERROR_TYPE_DEBUG,
2376         "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
2377         b_peers, beta, view_size);
2378     for (i = first_border; i < second_border; i++)
2379     {
2380       peer = view_array[permut[i]];
2381       peer_ctx = get_peer_ctx (&peer);
2382       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer) &&
2383           GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING)) // TODO
2384       { // FIXME if this fails schedule/loop this for later
2385         send_pull_request (&peer);
2386       }
2387     }
2388
2389     GNUNET_free (permut);
2390     permut = NULL;
2391   }
2392
2393
2394   /* Update view */
2395   /* TODO see how many peers are in push-/pull- list! */
2396
2397   if ((CustomPeerMap_size (push_map) <= alpha * view_size) &&
2398       (0 < CustomPeerMap_size (push_map)) &&
2399       (0 < CustomPeerMap_size (pull_map)))
2400   { /* If conditions for update are fulfilled, update */
2401     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the view.\n");
2402
2403     uint32_t final_size;
2404     uint32_t peers_to_clean_size;
2405     struct GNUNET_PeerIdentity *peers_to_clean;
2406
2407     peers_to_clean = NULL;
2408     peers_to_clean_size = 0;
2409     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, view_size);
2410     memcpy (peers_to_clean,
2411             view_array,
2412             view_size * sizeof (struct GNUNET_PeerIdentity));
2413
2414     /* Seems like recreating is the easiest way of emptying the peermap */
2415     GNUNET_CONTAINER_multipeermap_destroy (view);
2416     view = GNUNET_CONTAINER_multipeermap_create (view_size, GNUNET_NO);
2417     to_file (file_name_view_log,
2418              "--- emptied ---");
2419
2420     first_border  = GNUNET_MIN (ceil (alpha * sampler_size_est_need),
2421                                 CustomPeerMap_size (push_map));
2422     second_border = first_border +
2423                     GNUNET_MIN (floor (beta  * sampler_size_est_need),
2424                                 CustomPeerMap_size (pull_map));
2425     final_size    = second_border +
2426       ceil ((1 - (alpha + beta)) * sampler_size_est_need);
2427
2428     GNUNET_array_grow (view_array, view_size, second_border);
2429
2430     /* Update view with peers received through PUSHes */
2431     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2432                                            CustomPeerMap_size (push_map));
2433     for (i = 0; i < first_border; i++)
2434     {
2435       view_array[i] = *CustomPeerMap_get_peer_by_index (push_map, permut[i]);
2436       GNUNET_CONTAINER_multipeermap_put (view, &view_array[i], NULL,
2437           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2438
2439       to_file (file_name_view_log,
2440                "+%s\t(push list)",
2441                GNUNET_i2s_full (&view_array[i]));
2442       // TODO change the peer_flags accordingly
2443     }
2444     GNUNET_free (permut);
2445     permut = NULL;
2446
2447     /* Update view with peers received through PULLs */
2448     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2449                                            CustomPeerMap_size (pull_map));
2450     for (i = first_border; i < second_border; i++)
2451     {
2452       view_array[i] =
2453         *CustomPeerMap_get_peer_by_index (pull_map, permut[i - first_border]);
2454       GNUNET_CONTAINER_multipeermap_put (view, &view_array[i], NULL,
2455           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2456
2457       to_file (file_name_view_log,
2458                "+%s\t(pull list)",
2459                GNUNET_i2s_full (&view_array[i]));
2460       // TODO change the peer_flags accordingly
2461     }
2462     GNUNET_free (permut);
2463     permut = NULL;
2464
2465     /* Update view with peers from history */
2466     RPS_sampler_get_n_rand_peers (prot_sampler,
2467                                   hist_update,
2468                                   NULL,
2469                                   final_size - second_border);
2470     num_hist_update_tasks = final_size - second_border;
2471     // TODO change the peer_flags accordingly
2472
2473     for (i = 0; i < view_size; i++)
2474       rem_from_list (&peers_to_clean, &peers_to_clean_size, &view_array[i]);
2475
2476     /* Clean peers that were removed from the view */
2477     for (i = 0; i < peers_to_clean_size; i++)
2478     {
2479       to_file (file_name_view_log,
2480                "-%s",
2481                GNUNET_i2s_full (&peers_to_clean[i]));
2482       peer_clean (&peers_to_clean[i]);
2483     }
2484
2485     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, 0);
2486     peers_to_clean = NULL;
2487   }
2488   else
2489   {
2490     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the view.\n");
2491   }
2492   // TODO independent of that also get some peers from CADET_get_peers()?
2493
2494   LOG (GNUNET_ERROR_TYPE_DEBUG,
2495        "Received %u pushes and %u pulls last round (alpha (%.2f) * view_size (%u) = %.2f)\n",
2496        CustomPeerMap_size (push_map),
2497        CustomPeerMap_size (pull_map),
2498        alpha,
2499        view_size,
2500        alpha * view_size);
2501
2502   /* Update samplers */
2503   for (i = 0; i < CustomPeerMap_size (push_map); i++)
2504   {
2505     update_peer = CustomPeerMap_get_peer_by_index (push_map, i);
2506     LOG (GNUNET_ERROR_TYPE_DEBUG,
2507          "Updating with peer %s from push list\n",
2508          GNUNET_i2s (update_peer));
2509     insert_in_sampler (NULL, update_peer);
2510     peer_clean (update_peer); /* This cleans only if it is not in the view */
2511   }
2512
2513   for (i = 0; i < CustomPeerMap_size (pull_map); i++)
2514   {
2515     LOG (GNUNET_ERROR_TYPE_DEBUG,
2516          "Updating with peer %s from pull list\n",
2517          GNUNET_i2s (CustomPeerMap_get_peer_by_index (pull_map, i)));
2518     insert_in_sampler (NULL, CustomPeerMap_get_peer_by_index (pull_map, i));
2519     /* This cleans only if it is not in the view */
2520     peer_clean (CustomPeerMap_get_peer_by_index (pull_map, i));
2521   }
2522
2523
2524   /* Empty push/pull lists */
2525   CustomPeerMap_clear (push_map);
2526   CustomPeerMap_clear (pull_map);
2527
2528   struct GNUNET_TIME_Relative time_next_round;
2529
2530   time_next_round = compute_rand_delay (round_interval, 2);
2531
2532   /* Schedule next round */
2533   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
2534   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2535 }
2536
2537
2538 static void
2539 rps_start (struct GNUNET_SERVER_Handle *server);
2540
2541
2542 /**
2543  * This is called from GNUNET_CADET_get_peers().
2544  *
2545  * It is called on every peer(ID) that cadet somehow has contact with.
2546  * We use those to initialise the sampler.
2547  */
2548 void
2549 init_peer_cb (void *cls,
2550               const struct GNUNET_PeerIdentity *peer,
2551               int tunnel, // "Do we have a tunnel towards this peer?"
2552               unsigned int n_paths, // "Number of known paths towards this peer"
2553               unsigned int best_path) // "How long is the best path?
2554                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
2555 {
2556   if (NULL != peer)
2557   {
2558     LOG (GNUNET_ERROR_TYPE_DEBUG,
2559          "Got peer_id %s from cadet\n",
2560          GNUNET_i2s (peer));
2561     new_peer_id (peer);
2562   }
2563 }
2564
2565
2566 /**
2567  * Iterator over peers from peerinfo.
2568  *
2569  * @param cls closure
2570  * @param peer id of the peer, NULL for last call
2571  * @param hello hello message for the peer (can be NULL)
2572  * @param error message
2573  */
2574 void
2575 process_peerinfo_peers (void *cls,
2576                         const struct GNUNET_PeerIdentity *peer,
2577                         const struct GNUNET_HELLO_Message *hello,
2578                         const char *err_msg)
2579 {
2580   if (NULL != peer)
2581   {
2582     LOG (GNUNET_ERROR_TYPE_DEBUG,
2583          "Got peer_id %s from peerinfo\n",
2584          GNUNET_i2s (peer));
2585     new_peer_id (peer);
2586   }
2587 }
2588
2589
2590 /**
2591  * Callback used to remove peers from the multipeermap.
2592  */
2593   int
2594 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
2595 {
2596   struct PeerContext *peer_ctx;
2597   const struct GNUNET_CADET_Channel *channel =
2598     (const struct GNUNET_CADET_Channel *) cls;
2599
2600   peer_ctx = (struct PeerContext *) value;
2601   set_peer_flag (peer_ctx, TO_DESTROY);
2602
2603   LOG (GNUNET_ERROR_TYPE_DEBUG,
2604        "Going to remove peer %s\n",
2605        GNUNET_i2s (&peer_ctx->peer_id));
2606
2607   /* Remove it from the sampler used for the Brahms protocol */
2608   RPS_sampler_reinitialise_by_value (prot_sampler, key);
2609
2610   /* If operations are still scheduled for this peer cancel those */
2611   if (0 != peer_ctx->num_outstanding_ops)
2612   {
2613     GNUNET_array_grow (peer_ctx->outstanding_ops,
2614                        peer_ctx->num_outstanding_ops,
2615                        0);
2616   }
2617
2618   /* If we are still waiting for notification whether this peer is live
2619    * cancel the according task */
2620   if (NULL != peer_ctx->transmit_handle)
2621   {
2622     LOG (GNUNET_ERROR_TYPE_DEBUG,
2623          "Trying to cancle transmit_handle for peer %s\n",
2624          GNUNET_i2s (key));
2625     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->transmit_handle);
2626     peer_ctx->transmit_handle = NULL;
2627   }
2628
2629   unset_peer_flag (peer_ctx, PULL_REPLY_PENDING);
2630
2631   /* Remove peer from view */
2632   if (GNUNET_CONTAINER_multipeermap_contains (view, key))
2633   {
2634     to_file (file_name_view_log,
2635         "-%s\t(cleanup channel, other peer)",
2636         GNUNET_i2s_full (key));
2637     GNUNET_CONTAINER_multipeermap_remove_all (view, key);
2638     if (NULL != view_array)
2639     {
2640       GNUNET_free (view_array);
2641       view_array = NULL;
2642     }
2643   }
2644
2645   /* Remove from push and pull lists */
2646   CustomPeerMap_remove_peer (push_map, key);
2647   CustomPeerMap_remove_peer (pull_map, key);
2648
2649   /* Cancle messages that have not been sent yet */
2650   while (NULL != peer_ctx->pending_messages_head)
2651   {
2652     LOG (GNUNET_ERROR_TYPE_DEBUG,
2653         "Removing unsent %s\n",
2654         peer_ctx->pending_messages_head->type);
2655     /* We are not able to cancel messages as #GNUNET_CADET_mq_create () does not
2656      * set a #GNUNET_MQ_CancelImpl */
2657     /* GNUNET_MQ_send_cancel (peer_ctx->pending_messages_head->ev); */
2658     remove_pending_message (peer_ctx->pending_messages_head);
2659   }
2660
2661   /* If there is still a mq destroy it */
2662   if (NULL != peer_ctx->mq)
2663   {
2664     GNUNET_MQ_destroy (peer_ctx->mq);
2665     peer_ctx->mq = NULL;
2666   }
2667
2668
2669   /* Remove the send_channel
2670    * This function should be called again from #cleanup_channel (callback
2671    * called on the destruction of channels) and clean up the rest. */
2672   if (NULL != peer_ctx->send_channel &&
2673       channel != peer_ctx->send_channel)
2674   {
2675     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
2676     peer_ctx->send_channel = NULL;
2677   }
2678
2679   /* Remove the recv_channel
2680    * This function should be called again from #cleanup_channel (callback
2681    * called on the destruction of channels) and clean up the rest. */
2682   if (NULL != peer_ctx->recv_channel &&
2683       channel != peer_ctx->recv_channel)
2684   {
2685     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
2686     peer_ctx->recv_channel = NULL;
2687   }
2688
2689   /* If there is no channel we have to remove the context now */
2690   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2691     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
2692
2693   GNUNET_free (peer_ctx);
2694
2695   return GNUNET_YES;
2696 }
2697
2698
2699 /**
2700  * Clean the send channel of a peer
2701  * If there is also no channel to receive messages from that peer, remove it
2702  * from the peermap.
2703  */
2704 void
2705 peer_clean (const struct GNUNET_PeerIdentity *peer)
2706 {
2707   struct PeerContext *peer_ctx;
2708   /* struct GNUNET_CADET_Channel *channel; */
2709
2710   if ( (0 == RPS_sampler_count_id (prot_sampler, peer)) &&
2711        (GNUNET_NO  == GNUNET_CONTAINER_multipeermap_contains (view, peer)) &&
2712        (GNUNET_NO  == CustomPeerMap_contains_peer (push_map, peer)) &&
2713        (GNUNET_NO  == CustomPeerMap_contains_peer (pull_map, peer)) &&
2714        (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer)) )
2715   {
2716     peer_ctx = get_peer_ctx (peer);
2717
2718     if ( (NULL == peer_ctx->recv_channel) &&
2719          (NULL == peer_ctx->pending_messages_head) &&
2720          (GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING)) )
2721     {
2722       #ifdef ENABLE_MALICIOUS
2723       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
2724         peer_remove_cb (NULL, peer, peer_ctx);
2725       #else /* ENABLE_MALICIOUS */
2726       peer_remove_cb (NULL, peer, peer_ctx);
2727       #endif /* ENABLE_MALICIOUS */
2728     }
2729   }
2730 }
2731
2732
2733 /**
2734  * Task run during shutdown.
2735  *
2736  * @param cls unused
2737  * @param tc unused
2738  */
2739 static void
2740 shutdown_task (void *cls,
2741                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2742 {
2743
2744   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
2745
2746   GNUNET_PEERINFO_notify_cancel (peerinfo_notify_handle);
2747   GNUNET_PEERINFO_disconnect (peerinfo_handle);
2748
2749   if (NULL != do_round_task)
2750   {
2751     GNUNET_SCHEDULER_cancel (do_round_task);
2752     do_round_task = NULL;
2753   }
2754
2755   {
2756   if (GNUNET_SYSERR ==
2757         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
2758     LOG (GNUNET_ERROR_TYPE_WARNING,
2759         "Iterating over peers to disconnect from them was cancelled\n");
2760   }
2761
2762   GNUNET_NSE_disconnect (nse);
2763   RPS_sampler_destroy (prot_sampler);
2764   RPS_sampler_destroy (client_sampler);
2765   LOG (GNUNET_ERROR_TYPE_DEBUG,
2766        "Size of the peermap: %u\n",
2767        GNUNET_CONTAINER_multipeermap_size (peer_map));
2768   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2769   GNUNET_CADET_disconnect (cadet_handle);
2770   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2771   GNUNET_CONTAINER_multipeermap_destroy (view);
2772   view = NULL;
2773   CustomPeerMap_destroy (push_map);
2774   CustomPeerMap_destroy (pull_map);
2775   #ifdef ENABLE_MALICIOUS
2776   struct AttackedPeer *tmp_att_peer;
2777   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2778   if (NULL != mal_peer_set)
2779     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
2780   if (NULL != att_peer_set)
2781     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
2782   while (NULL != att_peers_head)
2783   {
2784     tmp_att_peer = att_peers_head;
2785     GNUNET_CONTAINER_DLL_remove (att_peers_head, att_peers_tail, tmp_att_peer);
2786   }
2787   #endif /* ENABLE_MALICIOUS */
2788 }
2789
2790
2791 /**
2792  * @brief Get informed about a connecting client.
2793  *
2794  * @param cls unused
2795  * @param client the client that connects
2796  */
2797 static void
2798 handle_client_connect (void *cls,
2799                        struct GNUNET_SERVER_Client *client)
2800 {
2801   struct ClientContext *cli_ctx;
2802
2803   LOG (GNUNET_ERROR_TYPE_DEBUG,
2804        "Client connected\n");
2805   if (NULL == client)
2806     return; /* Server was destroyed before a client connected. Shutting down */
2807   cli_ctx = GNUNET_new (struct ClientContext);
2808   cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
2809   GNUNET_SERVER_client_set_user_context (client, cli_ctx);
2810   GNUNET_CONTAINER_DLL_insert (cli_ctx_head,
2811                                cli_ctx_tail,
2812                                cli_ctx);
2813 }
2814
2815 /**
2816  * A client disconnected.  Remove all of its data structure entries.
2817  *
2818  * @param cls closure, NULL
2819  * @param client identification of the client
2820  */
2821 static void
2822 handle_client_disconnect (void *cls,
2823                                             struct GNUNET_SERVER_Client *client)
2824 {
2825   struct ClientContext *cli_ctx;
2826
2827   if (NULL == client)
2828   {/* shutdown task */
2829     while (NULL != cli_ctx_head)
2830       destroy_cli_ctx (cli_ctx_head);
2831   }
2832   else
2833   {
2834     cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct ClientContext);
2835     destroy_cli_ctx (cli_ctx);
2836   }
2837 }
2838
2839
2840 /**
2841  * Handle the channel a peer opens to us.
2842  *
2843  * @param cls The closure
2844  * @param channel The channel the peer wants to establish
2845  * @param initiator The peer's peer ID
2846  * @param port The port the channel is being established over
2847  * @param options Further options
2848  */
2849   static void *
2850 handle_inbound_channel (void *cls,
2851                         struct GNUNET_CADET_Channel *channel,
2852                         const struct GNUNET_PeerIdentity *initiator,
2853                         uint32_t port,
2854                         enum GNUNET_CADET_ChannelOption options)
2855 {
2856   struct PeerContext *peer_ctx;
2857
2858   LOG (GNUNET_ERROR_TYPE_DEBUG,
2859       "New channel was established to us (Peer %s).\n",
2860       GNUNET_i2s (initiator));
2861   GNUNET_assert (NULL != channel); /* according to cadet API */
2862   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, initiator))
2863     peer_ctx = create_peer_ctx (initiator);
2864   else
2865     peer_ctx = get_peer_ctx (initiator);
2866   /* We only accept one incoming channel from peers */
2867   if (NULL != peer_ctx->recv_channel)
2868   {
2869     GNUNET_CADET_channel_destroy (channel);
2870     return NULL;
2871   }
2872   peer_ctx->recv_channel = channel;
2873   peer_is_live (peer_ctx);
2874   return NULL;
2875 }
2876
2877
2878 /**
2879  * This is called when a channel is destroyed.
2880  *
2881  * @param cls The closure
2882  * @param channel The channel being closed
2883  * @param channel_ctx The context associated with this channel
2884  */
2885   static void
2886 cleanup_channel (void *cls,
2887                 const struct GNUNET_CADET_Channel *channel,
2888                 void *channel_ctx)
2889 {
2890   struct GNUNET_PeerIdentity *peer;
2891   struct PeerContext *peer_ctx;
2892
2893   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2894       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2895        // Guess simply casting isn't the nicest way...
2896        // FIXME wait for cadet to change this function
2897
2898   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2899   {/* We don't want to implicitly create a context that we're about to kill */
2900     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2901     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2902       return;
2903
2904     if (get_peer_flag (peer_ctx, TO_DESTROY))
2905     {/* We initiatad the destruction of this particular peer */
2906       if (channel == peer_ctx->send_channel)
2907         peer_ctx->send_channel = NULL;
2908       else if (channel == peer_ctx->recv_channel)
2909         peer_ctx->recv_channel = NULL;
2910
2911       to_file (file_name_view_log,
2912                "-%s\t(cleanup channel, ourself)",
2913                GNUNET_i2s_full (peer));
2914     }
2915
2916     else
2917     { /* We did not initiate the destruction of this peer */
2918       if (channel == peer_ctx->send_channel)
2919       { /* Something (but us) killd the channel - clean up peer */
2920         LOG (GNUNET_ERROR_TYPE_DEBUG,
2921             "send channel (%s) was destroyed - cleaning up\n",
2922             GNUNET_i2s (peer));
2923         peer_ctx->send_channel = NULL;
2924         /* Somwewhat {ab,re}use the iterator function */
2925         /* Cast to void is ok, because it's used as void in peer_remove_cb */
2926         (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2927       }
2928       else if (channel == peer_ctx->recv_channel)
2929       { /* Other peer doesn't want to send us messages anymore */
2930         LOG (GNUNET_ERROR_TYPE_DEBUG,
2931              "Peer %s destroyed recv channel - cleaning up channel\n",
2932              GNUNET_i2s (peer));
2933         peer_ctx->recv_channel = NULL;
2934       }
2935       else
2936       {
2937         LOG (GNUNET_ERROR_TYPE_WARNING,
2938              "unknown channel (%s) was destroyed\n",
2939              GNUNET_i2s (peer));
2940       }
2941     }
2942   }
2943
2944   else
2945   { /* We don't know a context to that peer */
2946     LOG (GNUNET_ERROR_TYPE_DEBUG,
2947          "channel (%s) without associated context was destroyed\n",
2948          GNUNET_i2s (peer));
2949   }
2950 }
2951
2952
2953 /**
2954  * Actually start the service.
2955  */
2956   static void
2957 rps_start (struct GNUNET_SERVER_Handle *server)
2958 {
2959   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2960     {&handle_client_request,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2961       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2962     {&handle_client_request_cancel, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL,
2963       sizeof (struct GNUNET_RPS_CS_RequestCancelMessage)},
2964     {&handle_client_seed,           NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2965     #ifdef ENABLE_MALICIOUS
2966     {&handle_client_act_malicious,  NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2967     #endif /* ENABLE_MALICIOUS */
2968     {NULL, NULL, 0, 0}
2969   };
2970
2971   GNUNET_SERVER_add_handlers (server, handlers);
2972   GNUNET_SERVER_connect_notify (server,
2973                                 &handle_client_connect,
2974                                 NULL);
2975   GNUNET_SERVER_disconnect_notify (server,
2976                                    &handle_client_disconnect,
2977                                    NULL);
2978   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
2979
2980
2981   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2982   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2983
2984   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2985                                                         &shutdown_task,
2986                                                         NULL);
2987 }
2988
2989
2990 /**
2991  * Process statistics requests.
2992  *
2993  * @param cls closure
2994  * @param server the initialized server
2995  * @param c configuration to use
2996  */
2997   static void
2998 run (void *cls,
2999      struct GNUNET_SERVER_Handle *server,
3000      const struct GNUNET_CONFIGURATION_Handle *c)
3001 {
3002   int size;
3003   int out_size;
3004
3005   // TODO check what this does -- copied from gnunet-boss
3006   // - seems to work as expected
3007   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
3008   cfg = c;
3009
3010
3011   /* Get own ID */
3012   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
3013   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3014               "STARTING SERVICE (rps) for peer [%s]\n",
3015               GNUNET_i2s (&own_identity));
3016   #ifdef ENABLE_MALICIOUS
3017   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3018               "Malicious execution compiled in.\n");
3019   #endif /* ENABLE_MALICIOUS */
3020
3021
3022
3023   /* Get time interval from the configuration */
3024   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
3025                                                         "ROUNDINTERVAL",
3026                                                         &round_interval))
3027   {
3028     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3029                                "RPS", "ROUNDINTERVAL");
3030     GNUNET_SCHEDULER_shutdown ();
3031     return;
3032   }
3033
3034   /* Get initial size of sampler/view from the configuration */
3035   if (GNUNET_OK !=
3036       GNUNET_CONFIGURATION_get_value_number (cfg, "RPS", "INITSIZE",
3037         (long long unsigned int *) &sampler_size_est_need))
3038   {
3039     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3040                                "RPS", "INITSIZE");
3041     GNUNET_SCHEDULER_shutdown ();
3042     return;
3043   }
3044   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
3045
3046
3047   view = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
3048
3049   /* file_name_view_log */
3050   if (GNUNET_OK != GNUNET_DISK_directory_create ("/tmp/rps/"))
3051   {
3052     LOG (GNUNET_ERROR_TYPE_WARNING,
3053          "Failed to create directory /tmp/rps/\n");
3054   }
3055
3056   size = (14 + strlen (GNUNET_i2s_full (&own_identity)) + 1) * sizeof (char);
3057   file_name_view_log = GNUNET_malloc (size);
3058   out_size = GNUNET_snprintf (file_name_view_log,
3059                               size,
3060                               "/tmp/rps/view-%s",
3061                               GNUNET_i2s_full (&own_identity));
3062   if (size < out_size ||
3063       0 > out_size)
3064   {
3065     LOG (GNUNET_ERROR_TYPE_WARNING,
3066          "Failed to write string to buffer (size: %i, out_size: %i)\n",
3067          size,
3068          out_size);
3069   }
3070
3071
3072   /* connect to NSE */
3073   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
3074
3075
3076   alpha = 0.45;
3077   beta  = 0.45;
3078
3079   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
3080
3081
3082   /* Initialise cadet */
3083   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
3084     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
3085       sizeof (struct GNUNET_MessageHeader)},
3086     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
3087       sizeof (struct GNUNET_MessageHeader)},
3088     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
3089     {NULL, 0, 0}
3090   };
3091
3092   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
3093   cadet_handle = GNUNET_CADET_connect (cfg,
3094                                        cls,
3095                                        &handle_inbound_channel,
3096                                        &cleanup_channel,
3097                                        cadet_handlers,
3098                                        ports);
3099
3100   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
3101
3102   /* Initialise sampler */
3103   struct GNUNET_TIME_Relative half_round_interval;
3104   struct GNUNET_TIME_Relative  max_round_interval;
3105
3106   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
3107   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
3108
3109   prot_sampler =   RPS_sampler_init     (sampler_size_est_need, max_round_interval);
3110   client_sampler = RPS_sampler_mod_init (sampler_size_est_need, max_round_interval);
3111
3112   /* Initialise push and pull maps */
3113   push_map = CustomPeerMap_create (4);
3114   pull_map = CustomPeerMap_create (4);
3115
3116
3117   num_hist_update_tasks = 0;
3118
3119
3120   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
3121   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
3122   // TODO send push/pull to each of those peers?
3123
3124   peerinfo_notify_handle = GNUNET_PEERINFO_notify (cfg,
3125                                                    GNUNET_NO,
3126                                                    process_peerinfo_peers,
3127                                                    NULL);
3128
3129   rps_start (server);
3130 }
3131
3132
3133 /**
3134  * The main function for the rps service.
3135  *
3136  * @param argc number of arguments from the command line
3137  * @param argv command line arguments
3138  * @return 0 ok, 1 on error
3139  */
3140   int
3141 main (int argc, char *const *argv)
3142 {
3143   return (GNUNET_OK ==
3144           GNUNET_SERVICE_run (argc,
3145                               argv,
3146                               "rps",
3147                               GNUNET_SERVICE_OPTION_NONE,
3148                               &run, NULL)) ? 0 : 1;
3149 }
3150
3151 /* end of gnunet-service-rps.c */