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