-rename and fix char pointer
[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 non-existing 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  * @brief This is called once a message is sent.
1152  *
1153  * @param cls type of the message that was sent
1154  */
1155 static void
1156 mq_notify_sent_cb (void *cls)
1157 {
1158   const char *type = cls;
1159   LOG (GNUNET_ERROR_TYPE_DEBUG,
1160       "%s was sent.\n",
1161       type);
1162 }
1163
1164
1165 /**
1166  * Send a PULL REPLY to @a peer_id
1167  *
1168  * @param peer_id the peer to send the reply to.
1169  * @param peer_ids the peers to send to @a peer_id
1170  * @param num_peer_ids the number of peers to send to @a peer_id
1171  */
1172 static void
1173 send_pull_reply (const struct GNUNET_PeerIdentity *peer_id,
1174                  const struct GNUNET_PeerIdentity *peer_ids,
1175                  unsigned int num_peer_ids)
1176 {
1177   uint32_t send_size;
1178   struct GNUNET_MQ_Handle *mq;
1179   struct GNUNET_MQ_Envelope *ev;
1180   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1181
1182   /* Compute actual size */
1183   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1184               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
1185
1186   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1187     /* Compute number of peers to send
1188      * If too long, simply truncate */
1189     // TODO select random ones via permutation
1190     //      or even better: do good protocol design
1191     send_size =
1192       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1193        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1194        sizeof (struct GNUNET_PeerIdentity);
1195   else
1196     send_size = num_peer_ids;
1197
1198   LOG (GNUNET_ERROR_TYPE_DEBUG,
1199       "Going to send PULL REPLY with %u peers to %s\n",
1200       send_size, GNUNET_i2s (peer_id));
1201
1202   mq = get_mq (peer_id);
1203
1204   ev = GNUNET_MQ_msg_extra (out_msg,
1205                             send_size * sizeof (struct GNUNET_PeerIdentity),
1206                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1207   out_msg->num_peers = htonl (send_size);
1208   memcpy (&out_msg[1], peer_ids,
1209          send_size * sizeof (struct GNUNET_PeerIdentity));
1210
1211   GNUNET_MQ_notify_sent (ev,
1212       mq_notify_sent_cb,
1213       "PULL REPLY");
1214   GNUNET_MQ_send (mq, ev);
1215 }
1216
1217
1218 /**
1219  * This function is called on new peer_ids from 'external' sources
1220  * (client seed, cadet get_peers(), ...)
1221  *
1222  * @param peer_id the new peer_id
1223  */
1224 static void
1225 new_peer_id (const struct GNUNET_PeerIdentity *peer_id)
1226 {
1227   struct PeerOutstandingOp out_op;
1228   struct PeerContext *peer_ctx;
1229
1230   if ((NULL == peer_id) ||
1231       (0 == GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer_id)))
1232     return;
1233   LOG (GNUNET_ERROR_TYPE_DEBUG,
1234        "Got peer_id %s (at %p, view size: %u)\n",
1235        GNUNET_i2s (peer_id),
1236        peer_id,
1237        GNUNET_CONTAINER_multipeermap_size (view));
1238
1239   /* if the seed peer is already know, skip context creation */
1240   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer_id))
1241     peer_ctx = create_peer_ctx (peer_id);
1242   else
1243     peer_ctx = get_peer_ctx (peer_id);
1244
1245   if (GNUNET_NO == get_peer_flag (peer_ctx, VALID))
1246   {
1247     if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1248     {
1249       out_op.op = insert_in_sampler;
1250       out_op.op_cls = NULL;
1251       GNUNET_array_append (peer_ctx->outstanding_ops,
1252                            peer_ctx->num_outstanding_ops,
1253                            out_op);
1254     }
1255
1256     if (GNUNET_NO == insert_in_view_scheduled (peer_ctx))
1257     {
1258       out_op.op = insert_in_view;
1259       out_op.op_cls = NULL;
1260       GNUNET_array_append (peer_ctx->outstanding_ops,
1261                            peer_ctx->num_outstanding_ops,
1262                            out_op);
1263     }
1264
1265     /* Trigger livelyness test on peer */
1266     check_peer_live (peer_ctx);
1267   }
1268   // else...?
1269
1270   // send push/pull to each of those peers?
1271 }
1272
1273
1274 /***********************************************************************
1275  * /Util functions
1276 ***********************************************************************/
1277
1278 static void
1279 destroy_reply_cls (struct ReplyCls *rep_cls)
1280 {
1281   struct ClientContext *cli_ctx;
1282
1283   cli_ctx = GNUNET_SERVER_client_get_user_context (rep_cls->client,
1284                                                    struct ClientContext);
1285   GNUNET_assert (NULL != cli_ctx);
1286   GNUNET_CONTAINER_DLL_remove (cli_ctx->rep_cls_head,
1287                                cli_ctx->rep_cls_tail,
1288                                rep_cls);
1289   GNUNET_free (rep_cls);
1290 }
1291
1292 static void
1293 destroy_cli_ctx (struct ClientContext *cli_ctx)
1294 {
1295   GNUNET_assert (NULL != cli_ctx);
1296   if (NULL != cli_ctx->rep_cls_head)
1297   {
1298     LOG (GNUNET_ERROR_TYPE_WARNING,
1299          "Trying to destroy the context of a client that still has pending requests. Going to clean those\n");
1300     while (NULL != cli_ctx->rep_cls_head)
1301       destroy_reply_cls (cli_ctx->rep_cls_head);
1302   }
1303   GNUNET_CONTAINER_DLL_remove (cli_ctx_head,
1304                                cli_ctx_tail,
1305                                cli_ctx);
1306   GNUNET_free (cli_ctx);
1307 }
1308
1309
1310 /**
1311  * Function called by NSE.
1312  *
1313  * Updates sizes of sampler list and view and adapt those lists
1314  * accordingly.
1315  */
1316   void
1317 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1318               double logestimate, double std_dev)
1319 {
1320   double estimate;
1321   //double scale; // TODO this might go gloabal/config
1322
1323   LOG (GNUNET_ERROR_TYPE_DEBUG,
1324        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1325        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1326   //scale = .01;
1327   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1328   // GNUNET_NSE_log_estimate_to_n (logestimate);
1329   estimate = pow (estimate, 1.0 / 3);
1330   // TODO add if std_dev is a number
1331   // estimate += (std_dev * scale);
1332   if (2 < ceil (estimate))
1333   {
1334     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1335     sampler_size_est_need = estimate;
1336   } else
1337     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1338
1339   /* If the NSE has changed adapt the lists accordingly */
1340   resize_wrapper (prot_sampler, sampler_size_est_need);
1341   client_resize_wrapper ();
1342 }
1343
1344
1345 /**
1346  * Callback called once the requested PeerIDs are ready.
1347  *
1348  * Sends those to the requesting client.
1349  */
1350 void client_respond (void *cls,
1351     struct GNUNET_PeerIdentity *peer_ids, uint32_t num_peers)
1352 {
1353   uint32_t i;
1354   struct GNUNET_MQ_Envelope *ev;
1355   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1356   struct ReplyCls *reply_cls = (struct ReplyCls *) cls;
1357   uint32_t size_needed;
1358   struct ClientContext *cli_ctx;
1359
1360   GNUNET_assert (NULL != reply_cls);
1361   LOG (GNUNET_ERROR_TYPE_DEBUG,
1362        "sampler returned %" PRIu32 " peers:\n",
1363        num_peers);
1364   for (i = 0; i < num_peers; i++)
1365   {
1366     LOG (GNUNET_ERROR_TYPE_DEBUG,
1367          "  %lu: %s\n",
1368          i,
1369          GNUNET_i2s (&peer_ids[i]));
1370   }
1371
1372   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1373                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1374
1375   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1376
1377   ev = GNUNET_MQ_msg_extra (out_msg,
1378                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1379                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1380   out_msg->num_peers = htonl (num_peers);
1381   out_msg->id = htonl (reply_cls->id);
1382
1383   memcpy (&out_msg[1],
1384           peer_ids,
1385           num_peers * sizeof (struct GNUNET_PeerIdentity));
1386   GNUNET_free (peer_ids);
1387
1388   cli_ctx = GNUNET_SERVER_client_get_user_context (reply_cls->client,
1389                                                    struct ClientContext);
1390   GNUNET_assert (NULL != cli_ctx);
1391   destroy_reply_cls (reply_cls);
1392   GNUNET_MQ_send (cli_ctx->mq, ev);
1393 }
1394
1395
1396 /**
1397  * Handle RPS request from the client.
1398  *
1399  * @param cls closure
1400  * @param client identification of the client
1401  * @param message the actual message
1402  */
1403 static void
1404 handle_client_request (void *cls,
1405                        struct GNUNET_SERVER_Client *client,
1406                        const struct GNUNET_MessageHeader *message)
1407 {
1408   struct GNUNET_RPS_CS_RequestMessage *msg;
1409   uint32_t num_peers;
1410   uint32_t size_needed;
1411   struct ReplyCls *reply_cls;
1412   uint32_t i;
1413   struct ClientContext *cli_ctx;
1414
1415   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1416
1417   num_peers = ntohl (msg->num_peers);
1418   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1419                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1420
1421   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1422   {
1423     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1424                 "Message received from client has size larger than expected\n");
1425     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1426     return;
1427   }
1428
1429   for (i = 0 ; i < num_peers ; i++)
1430     est_request_rate();
1431
1432   LOG (GNUNET_ERROR_TYPE_DEBUG,
1433        "Client requested %" PRIu32 " random peer(s).\n",
1434        num_peers);
1435
1436   reply_cls = GNUNET_new (struct ReplyCls);
1437   reply_cls->id = ntohl (msg->id);
1438   reply_cls->client = client;
1439   reply_cls->req_handle = RPS_sampler_get_n_rand_peers (client_sampler,
1440                                                         client_respond,
1441                                                         reply_cls,
1442                                                         num_peers);
1443
1444   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct ClientContext);
1445   GNUNET_assert (NULL != cli_ctx);
1446   GNUNET_CONTAINER_DLL_insert (cli_ctx->rep_cls_head,
1447                                cli_ctx->rep_cls_tail,
1448                                reply_cls);
1449   GNUNET_SERVER_receive_done (client,
1450                               GNUNET_OK);
1451 }
1452
1453
1454 /**
1455  * @brief Handle a message that requests the cancellation of a request
1456  *
1457  * @param cls unused
1458  * @param client the client that requests the cancellation
1459  * @param message the message containing the id of the request
1460  */
1461 static void
1462 handle_client_request_cancel (void *cls,
1463                               struct GNUNET_SERVER_Client *client,
1464                               const struct GNUNET_MessageHeader *message)
1465 {
1466   struct GNUNET_RPS_CS_RequestCancelMessage *msg =
1467     (struct GNUNET_RPS_CS_RequestCancelMessage *) message;
1468   struct ClientContext *cli_ctx;
1469   struct ReplyCls *rep_cls;
1470
1471   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct ClientContext);
1472   GNUNET_assert (NULL != cli_ctx->rep_cls_head);
1473   rep_cls = cli_ctx->rep_cls_head;
1474   LOG (GNUNET_ERROR_TYPE_DEBUG,
1475       "Client cancels request with id %lu\n",
1476       ntohl (msg->id));
1477   while ( (NULL != rep_cls->next) &&
1478           (rep_cls->id != ntohl (msg->id)) )
1479     rep_cls = rep_cls->next;
1480   GNUNET_assert (rep_cls->id == ntohl (msg->id));
1481   RPS_sampler_request_cancel (rep_cls->req_handle);
1482   destroy_reply_cls (rep_cls);
1483   GNUNET_SERVER_receive_done (client,
1484                               GNUNET_OK);
1485 }
1486
1487
1488 /**
1489  * Handle seed from the client.
1490  *
1491  * @param cls closure
1492  * @param client identification of the client
1493  * @param message the actual message
1494  */
1495   static void
1496 handle_client_seed (void *cls,
1497                     struct GNUNET_SERVER_Client *client,
1498                     const struct GNUNET_MessageHeader *message)
1499 {
1500   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1501   struct GNUNET_PeerIdentity *peers;
1502   uint32_t num_peers;
1503   uint32_t i;
1504
1505   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1506   {
1507     GNUNET_break_op (0);
1508     GNUNET_SERVER_receive_done (client,
1509                                 GNUNET_SYSERR);
1510   }
1511
1512   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1513   num_peers = ntohl (in_msg->num_peers);
1514   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1515   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1516   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1517
1518   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1519       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1520   {
1521     GNUNET_break_op (0);
1522     GNUNET_SERVER_receive_done (client,
1523                                 GNUNET_SYSERR);
1524     return;
1525   }
1526
1527   LOG (GNUNET_ERROR_TYPE_DEBUG,
1528        "Client seeded peers:\n");
1529   print_peer_list (peers, num_peers);
1530
1531   for (i = 0 ; i < num_peers ; i++)
1532   {
1533     LOG (GNUNET_ERROR_TYPE_DEBUG,
1534          "Updating samplers with seed %" PRIu32 ": %s\n",
1535          i,
1536          GNUNET_i2s (&peers[i]));
1537
1538     new_peer_id (&peers[i]);
1539
1540     //RPS_sampler_update (prot_sampler,   &peers[i]);
1541     //RPS_sampler_update (client_sampler, &peers[i]);
1542   }
1543
1544   ////GNUNET_free (peers);
1545
1546   GNUNET_SERVER_receive_done (client,
1547                                                 GNUNET_OK);
1548 }
1549
1550
1551 /**
1552  * Handle a PUSH message from another peer.
1553  *
1554  * Check the proof of work and store the PeerID
1555  * in the temporary list for pushed PeerIDs.
1556  *
1557  * @param cls Closure
1558  * @param channel The channel the PUSH was received over
1559  * @param channel_ctx The context associated with this channel
1560  * @param msg The message header
1561  */
1562 static int
1563 handle_peer_push (void *cls,
1564     struct GNUNET_CADET_Channel *channel,
1565     void **channel_ctx,
1566     const struct GNUNET_MessageHeader *msg)
1567 {
1568   const struct GNUNET_PeerIdentity *peer;
1569
1570   // (check the proof of work)
1571
1572   peer = (const struct GNUNET_PeerIdentity *)
1573     GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1574   // FIXME wait for cadet to change this function
1575
1576   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PUSH (%s)\n", GNUNET_i2s (peer));
1577
1578   #ifdef ENABLE_MALICIOUS
1579   struct AttackedPeer *tmp_att_peer;
1580
1581   tmp_att_peer = GNUNET_new (struct AttackedPeer);
1582   memcpy (&tmp_att_peer->peer_id, peer, sizeof (struct GNUNET_PeerIdentity));
1583   if (1 == mal_type
1584       || 3 == mal_type)
1585   { /* Try to maximise representation */
1586     if (NULL == att_peer_set)
1587       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
1588     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1589                                                              peer))
1590     {
1591       GNUNET_CONTAINER_DLL_insert (att_peers_head,
1592                                    att_peers_tail,
1593                                    tmp_att_peer);
1594       add_peer_array_to_set (peer, 1, att_peer_set);
1595     }
1596     return GNUNET_OK;
1597   }
1598
1599
1600   else if (2 == mal_type)
1601   { /* We attack one single well-known peer - simply ignore */
1602     return GNUNET_OK;
1603   }
1604   else
1605   {
1606     GNUNET_free (tmp_att_peer);
1607   }
1608
1609   #endif /* ENABLE_MALICIOUS */
1610
1611   /* Add the sending peer to the push_list */
1612   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1613   {
1614     GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer));
1615     GNUNET_array_append (push_list, push_list_size, *peer);
1616   }
1617
1618   GNUNET_CADET_receive_done (channel);
1619   return GNUNET_OK;
1620 }
1621
1622
1623 /**
1624  * Iterator over hash map entries.
1625  * Called from #generate_view_array and writes every peer id into #view_array.
1626  *
1627  * @param cls closure - the pointer to the counter
1628  * @param key current public key
1629  * @param value value in the hash map
1630  * @return #GNUNET_YES if we should continue to
1631  * iterate,
1632  * #GNUNET_NO if not.
1633  */
1634 static int
1635 dump_id_to_view_array (void *cls,
1636                        const struct GNUNET_PeerIdentity *key,
1637                        void *value)
1638 {
1639   unsigned int *i = (unsigned int *) cls;
1640
1641   view_array[(*i)++] = *key;
1642   return GNUNET_YES;
1643 }
1644
1645
1646 /**
1647  * Makes sure the view_array is filled with the peer ids currently in #view.
1648  * Called from within #do_round before sending pushes and pulls and from
1649  * #handle_peer_pull_request when a reply is sent.
1650  */
1651 static void
1652 generate_view_array (unsigned int view_size)
1653 {
1654   unsigned int *i;
1655   int ret;
1656
1657   if (NULL == view_array)
1658   {
1659     view_array = GNUNET_new_array (view_size,
1660                                    struct GNUNET_PeerIdentity);
1661     i = GNUNET_new (unsigned int);
1662     *i = 0;
1663
1664     ret = GNUNET_CONTAINER_multipeermap_iterate (view,
1665                                                  dump_id_to_view_array,
1666                                                  i);
1667     GNUNET_assert (view_size == ret);
1668     GNUNET_assert (view_size == *i);
1669
1670     GNUNET_free (i);
1671   }
1672 }
1673
1674
1675 /**
1676  * Handle PULL REQUEST request message from another peer.
1677  *
1678  * Reply with the view of PeerIDs.
1679  *
1680  * @param cls Closure
1681  * @param channel The channel the PULL REQUEST was received over
1682  * @param channel_ctx The context associated with this channel
1683  * @param msg The message header
1684  */
1685 static int
1686 handle_peer_pull_request (void *cls,
1687     struct GNUNET_CADET_Channel *channel,
1688     void **channel_ctx,
1689     const struct GNUNET_MessageHeader *msg)
1690 {
1691   struct GNUNET_PeerIdentity *peer;
1692   unsigned int view_size;
1693
1694   peer = (struct GNUNET_PeerIdentity *)
1695     GNUNET_CADET_channel_get_info (channel,
1696                                    GNUNET_CADET_OPTION_PEER);
1697   // FIXME wait for cadet to change this function
1698
1699   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REQUEST (%s)\n", GNUNET_i2s (peer));
1700
1701   #ifdef ENABLE_MALICIOUS
1702   if (1 == mal_type
1703       || 3 == mal_type)
1704   { /* Try to maximise representation */
1705     send_pull_reply (peer, mal_peers, num_mal_peers);
1706     return GNUNET_OK;
1707   }
1708
1709   else if (2 == mal_type)
1710   { /* Try to partition network */
1711     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
1712     {
1713       send_pull_reply (peer, mal_peers, num_mal_peers);
1714     }
1715     return GNUNET_OK;
1716   }
1717   #endif /* ENABLE_MALICIOUS */
1718
1719   view_size = GNUNET_CONTAINER_multipeermap_size (view);
1720   generate_view_array (view_size);
1721
1722   send_pull_reply (peer, view_array, view_size);
1723
1724   GNUNET_CADET_receive_done (channel);
1725   return GNUNET_OK;
1726 }
1727
1728
1729 /**
1730  * Handle PULL REPLY message from another peer.
1731  *
1732  * Check whether we sent a corresponding request and
1733  * whether this reply is the first one.
1734  *
1735  * @param cls Closure
1736  * @param channel The channel the PUSH was received over
1737  * @param channel_ctx The context associated with this channel
1738  * @param msg The message header
1739  */
1740   static int
1741 handle_peer_pull_reply (void *cls,
1742                         struct GNUNET_CADET_Channel *channel,
1743                         void **channel_ctx,
1744                         const struct GNUNET_MessageHeader *msg)
1745 {
1746   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1747   struct GNUNET_PeerIdentity *peers;
1748   struct PeerContext *peer_ctx;
1749   struct GNUNET_PeerIdentity *sender;
1750   struct PeerContext *sender_ctx;
1751   struct PeerOutstandingOp out_op;
1752   uint32_t i;
1753 #ifdef ENABLE_MALICIOUS
1754   struct AttackedPeer *tmp_att_peer;
1755 #endif /* ENABLE_MALICIOUS */
1756
1757   /* Check for protocol violation */
1758   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1759   {
1760     GNUNET_break_op (0);
1761     GNUNET_CADET_receive_done (channel);
1762     return GNUNET_SYSERR;
1763   }
1764
1765   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1766   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1767       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1768   {
1769     LOG (GNUNET_ERROR_TYPE_ERROR,
1770         "message says it sends %" PRIu32 " peers, have space for %i peers\n",
1771         ntohl (in_msg->num_peers),
1772         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1773             sizeof (struct GNUNET_PeerIdentity));
1774     GNUNET_break_op (0);
1775     GNUNET_CADET_receive_done (channel);
1776     return GNUNET_SYSERR;
1777   }
1778
1779   // Guess simply casting isn't the nicest way...
1780   // FIXME wait for cadet to change this function
1781   sender = (struct GNUNET_PeerIdentity *)
1782       GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1783   sender_ctx = get_peer_ctx (sender);
1784
1785   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REPLY (%s)\n", GNUNET_i2s (sender));
1786
1787   if (GNUNET_YES != get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1788   {
1789     LOG (GNUNET_ERROR_TYPE_WARNING,
1790         "Received a pull reply from a peer we didn't request one from!\n");
1791     GNUNET_break_op (0);
1792     GNUNET_CADET_receive_done (channel);
1793     return GNUNET_OK;
1794   }
1795
1796
1797   #ifdef ENABLE_MALICIOUS
1798   // We shouldn't even receive pull replies as we're not sending
1799   if (2 == mal_type)
1800     return GNUNET_OK;
1801   #endif /* ENABLE_MALICIOUS */
1802
1803   /* Do actual logic */
1804   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1805
1806   LOG (GNUNET_ERROR_TYPE_DEBUG,
1807        "PULL REPLY received, got following %u peers:\n",
1808        ntohl (in_msg->num_peers));
1809
1810   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1811   {
1812     LOG (GNUNET_ERROR_TYPE_DEBUG,
1813          "%u. %s\n",
1814          i,
1815          GNUNET_i2s (&peers[i]));
1816
1817     #ifdef ENABLE_MALICIOUS
1818     if ((NULL != att_peer_set) &&
1819         (1 == mal_type || 3 == mal_type))
1820     { /* Add attacked peer to local list */
1821       // TODO check if we sent a request and this was the first reply
1822       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1823                                                                &peers[i])
1824           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
1825                                                                   &peers[i])
1826           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&peers[i],
1827                                                    &own_identity))
1828       {
1829         tmp_att_peer = GNUNET_new (struct AttackedPeer);
1830         tmp_att_peer->peer_id = peers[i];
1831         GNUNET_CONTAINER_DLL_insert (att_peers_head,
1832                                      att_peers_tail,
1833                                      tmp_att_peer);
1834         add_peer_array_to_set (&peers[i], 1, att_peer_set);
1835       }
1836       continue;
1837     }
1838     #endif /* ENABLE_MALICIOUS */
1839     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity,
1840                                               &peers[i]))
1841     {
1842       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map,
1843             &peers[i]))
1844         peer_ctx = create_peer_ctx (&peers[i]);
1845       else
1846         peer_ctx = get_peer_ctx (&peers[i]);
1847
1848       if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
1849       {
1850         if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
1851           GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1852       }
1853       else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1854       {
1855         out_op.op = insert_in_pull_list;
1856         out_op.op_cls = NULL;
1857         GNUNET_array_append (peer_ctx->outstanding_ops,
1858                              peer_ctx->num_outstanding_ops,
1859                              out_op);
1860         check_peer_live (peer_ctx);
1861       }
1862     }
1863   }
1864
1865   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1866
1867   peer_clean (sender);
1868
1869   GNUNET_CADET_receive_done (channel);
1870   return GNUNET_OK;
1871 }
1872
1873
1874 /**
1875  * Compute a random delay.
1876  * A uniformly distributed value between mean + spread and mean - spread.
1877  *
1878  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1879  * It would return a random value between 2 and 6 min.
1880  *
1881  * @param mean the mean
1882  * @param spread the inverse amount of deviation from the mean
1883  */
1884 static struct GNUNET_TIME_Relative
1885 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1886 {
1887   struct GNUNET_TIME_Relative half_interval;
1888   struct GNUNET_TIME_Relative ret;
1889   unsigned int rand_delay;
1890   unsigned int max_rand_delay;
1891
1892   if (0 == spread)
1893   {
1894     LOG (GNUNET_ERROR_TYPE_WARNING,
1895          "Not accepting spread of 0\n");
1896     GNUNET_break (0);
1897   }
1898
1899   /* Compute random time value between spread * mean and spread * mean */
1900   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1901
1902   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1903   /**
1904    * Compute random value between (0 and 1) * round_interval
1905    * via multiplying round_interval with a 'fraction' (0 to value)/value
1906    */
1907   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1908   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1909   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1910   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1911
1912   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1913     LOG (GNUNET_ERROR_TYPE_WARNING,
1914          "Returning FOREVER_REL\n");
1915
1916   return ret;
1917 }
1918
1919
1920 /**
1921  * Send single pull request
1922  *
1923  * @param peer_id the peer to send the pull request to.
1924  */
1925 static void
1926 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1927 {
1928   struct GNUNET_MQ_Envelope *ev;
1929   struct GNUNET_MQ_Handle *mq;
1930   struct PeerContext *peer_ctx;
1931
1932   peer_ctx = get_peer_ctx (peer_id);
1933   GNUNET_assert (GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING));
1934   set_peer_flag (peer_ctx, PULL_REPLY_PENDING);
1935
1936   LOG (GNUNET_ERROR_TYPE_DEBUG,
1937        "Going to send PULL REQUEST to peer %s.\n",
1938        GNUNET_i2s (peer_id));
1939
1940   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1941   mq = get_mq (peer_id);
1942   GNUNET_MQ_notify_sent (ev,
1943       mq_notify_sent_cb,
1944       "PULL REQUEST");
1945   GNUNET_MQ_send (mq, ev);
1946 }
1947
1948
1949 /**
1950  * Send single push
1951  *
1952  * @param peer_id the peer to send the push to.
1953  */
1954 static void
1955 send_push (struct GNUNET_PeerIdentity *peer_id)
1956 {
1957   struct GNUNET_MQ_Envelope *ev;
1958   struct GNUNET_MQ_Handle *mq;
1959
1960   LOG (GNUNET_ERROR_TYPE_DEBUG,
1961        "Going to send PUSH to peer %s.\n",
1962        GNUNET_i2s (peer_id));
1963
1964   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1965   mq = get_mq (peer_id);
1966   GNUNET_MQ_notify_sent (ev,
1967       mq_notify_sent_cb,
1968       "PUSH");
1969   GNUNET_MQ_send (mq, ev);
1970 }
1971
1972
1973 static void
1974 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1975
1976 static void
1977 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1978
1979
1980 #ifdef ENABLE_MALICIOUS
1981 /**
1982  * Turn RPS service to act malicious.
1983  *
1984  * @param cls Closure
1985  * @param client The client that sent the message
1986  * @param msg The message header
1987  */
1988   static void
1989 handle_client_act_malicious (void *cls,
1990                              struct GNUNET_SERVER_Client *client,
1991                              const struct GNUNET_MessageHeader *msg)
1992 {
1993   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1994   struct GNUNET_PeerIdentity *peers;
1995   uint32_t num_mal_peers_sent;
1996   uint32_t num_mal_peers_old;
1997
1998   /* Check for protocol violation */
1999   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
2000   {
2001     GNUNET_break_op (0);
2002   }
2003
2004   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
2005   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
2006       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
2007   {
2008     LOG (GNUNET_ERROR_TYPE_ERROR,
2009         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
2010         ntohl (in_msg->num_peers),
2011         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
2012             sizeof (struct GNUNET_PeerIdentity));
2013     GNUNET_break_op (0);
2014   }
2015
2016
2017   /* Do actual logic */
2018   peers = (struct GNUNET_PeerIdentity *) &msg[1];
2019   mal_type = ntohl (in_msg->type);
2020   if (NULL == mal_peer_set)
2021     mal_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
2022
2023   LOG (GNUNET_ERROR_TYPE_DEBUG,
2024        "Now acting malicious type %" PRIu32 ", got %" PRIu32 " peers.\n",
2025        mal_type,
2026        ntohl (in_msg->num_peers));
2027
2028   if (1 == mal_type)
2029   { /* Try to maximise representation */
2030     /* Add other malicious peers to those we already know */
2031
2032     num_mal_peers_sent = ntohl (in_msg->num_peers);
2033     num_mal_peers_old = num_mal_peers;
2034     GNUNET_array_grow (mal_peers,
2035                        num_mal_peers,
2036                        num_mal_peers + num_mal_peers_sent);
2037     memcpy (&mal_peers[num_mal_peers_old],
2038             peers,
2039             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
2040
2041     /* Add all mal peers to mal_peer_set */
2042     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
2043                            num_mal_peers_sent,
2044                            mal_peer_set);
2045
2046     /* Substitute do_round () with do_mal_round () */
2047     GNUNET_SCHEDULER_cancel (do_round_task);
2048     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
2049   }
2050
2051   else if (2 == mal_type
2052            || 3 == mal_type)
2053   { /* Try to partition the network */
2054     /* Add other malicious peers to those we already know */
2055     struct PeerContext *att_ctx;
2056
2057     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
2058     num_mal_peers_old = num_mal_peers;
2059     GNUNET_array_grow (mal_peers,
2060                        num_mal_peers,
2061                        num_mal_peers + num_mal_peers_sent);
2062     if (NULL != mal_peers &&
2063         0 != num_mal_peers)
2064     {
2065       memcpy (&mal_peers[num_mal_peers_old],
2066               peers,
2067               num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
2068
2069       /* Add all mal peers to mal_peer_set */
2070       add_peer_array_to_set (&mal_peers[num_mal_peers_old],
2071                              num_mal_peers_sent,
2072                              mal_peer_set);
2073     }
2074
2075     /* Store the one attacked peer */
2076     memcpy (&attacked_peer,
2077             &in_msg->attacked_peer,
2078             sizeof (struct GNUNET_PeerIdentity));
2079     /* Set the flag of the attacked peer to valid to avoid problems */
2080     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map,
2081           &attacked_peer))
2082     {
2083       att_ctx = create_peer_ctx (&attacked_peer);
2084       check_peer_live (att_ctx);
2085     }
2086
2087     LOG (GNUNET_ERROR_TYPE_DEBUG,
2088          "Attacked peer is %s\n",
2089          GNUNET_i2s (&attacked_peer));
2090
2091     /* Substitute do_round () with do_mal_round () */
2092     GNUNET_SCHEDULER_cancel (do_round_task);
2093     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
2094   }
2095   else if (0 == mal_type)
2096   { /* Stop acting malicious */
2097     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2098
2099     /* Substitute do_mal_round () with do_round () */
2100     GNUNET_SCHEDULER_cancel (do_round_task);
2101     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2102   }
2103   else
2104   {
2105     GNUNET_break (0);
2106   }
2107
2108   GNUNET_SERVER_receive_done (client,   GNUNET_OK);
2109 }
2110
2111
2112 /**
2113  * Send out PUSHes and PULLs maliciously.
2114  *
2115  * This is executed regylary.
2116  */
2117 static void
2118 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2119 {
2120   uint32_t num_pushes;
2121   uint32_t i;
2122   struct GNUNET_TIME_Relative time_next_round;
2123   struct AttackedPeer *tmp_att_peer;
2124   struct PeerContext *peer_ctx;
2125
2126   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously type %" PRIu32 ".\n",
2127       mal_type);
2128   do_round_task = NULL;
2129   GNUNET_assert (mal_type <= 3);
2130   /* Do malicious actions */
2131   if (1 == mal_type)
2132   { /* Try to maximise representation */
2133
2134     /* The maximum of pushes we're going to send this round */
2135     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
2136                                          num_attacked_peers),
2137                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
2138
2139     LOG (GNUNET_ERROR_TYPE_DEBUG,
2140          "Going to send %" PRIu32 " pushes\n",
2141          num_pushes);
2142
2143     /* Send PUSHes to attacked peers */
2144     for (i = 0 ; i < num_pushes ; i++)
2145     {
2146       if (att_peers_tail == att_peer_index)
2147         att_peer_index = att_peers_head;
2148       else
2149         att_peer_index = att_peer_index->next;
2150
2151       send_push (&att_peer_index->peer_id);
2152     }
2153
2154     /* Send PULLs to some peers to learn about additional peers to attack */
2155     tmp_att_peer = att_peer_index;
2156     for (i = 0 ; i < num_pushes * alpha ; i++)
2157     {
2158       if (att_peers_tail == tmp_att_peer)
2159         tmp_att_peer = att_peers_head;
2160       else
2161         att_peer_index = tmp_att_peer->next;
2162
2163       send_pull_request (&tmp_att_peer->peer_id);
2164     }
2165   }
2166
2167
2168   else if (2 == mal_type)
2169   { /**
2170      * Try to partition the network
2171      * Send as many pushes to the attacked peer as possible
2172      * That is one push per round as it will ignore more.
2173      */
2174     peer_ctx = get_peer_ctx (&attacked_peer);
2175     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
2176       send_push (&attacked_peer);
2177   }
2178
2179
2180   if (3 == mal_type)
2181   { /* Combined attack */
2182
2183     /* Send PUSH to attacked peers */
2184     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map,
2185           &attacked_peer))
2186     {
2187       peer_ctx = get_peer_ctx (&attacked_peer);
2188       if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
2189       {
2190         LOG (GNUNET_ERROR_TYPE_DEBUG,
2191             "Goding to send push to attacked peer (%s)\n",
2192             GNUNET_i2s (&attacked_peer));
2193         send_push (&attacked_peer);
2194       }
2195       else
2196         check_peer_live (peer_ctx);
2197     }
2198     else
2199       peer_ctx = create_peer_ctx (&attacked_peer);
2200     check_peer_live (peer_ctx);
2201
2202     /* The maximum of pushes we're going to send this round */
2203     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
2204                                          num_attacked_peers),
2205                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
2206
2207     LOG (GNUNET_ERROR_TYPE_DEBUG,
2208          "Going to send %" PRIu32 " pushes\n",
2209          num_pushes);
2210
2211     for (i = 0 ; i < num_pushes ; i++)
2212     {
2213       if (att_peers_tail == att_peer_index)
2214         att_peer_index = att_peers_head;
2215       else
2216         att_peer_index = att_peer_index->next;
2217
2218       send_push (&att_peer_index->peer_id);
2219     }
2220
2221     /* Send PULLs to some peers to learn about additional peers to attack */
2222     tmp_att_peer = att_peer_index;
2223     for (i = 0 ; i < num_pushes * alpha ; i++)
2224     {
2225       if (att_peers_tail == tmp_att_peer)
2226         tmp_att_peer = att_peers_head;
2227       else
2228         att_peer_index = tmp_att_peer->next;
2229
2230       send_pull_request (&tmp_att_peer->peer_id);
2231     }
2232   }
2233
2234   /* Schedule next round */
2235   time_next_round = compute_rand_delay (round_interval, 2);
2236
2237   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round,
2238   //NULL);
2239   GNUNET_assert (NULL == do_round_task);
2240   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
2241   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2242 }
2243 #endif /* ENABLE_MALICIOUS */
2244
2245
2246 /**
2247  * Send out PUSHes and PULLs, possibly update #view, samplers.
2248  *
2249  * This is executed regylary.
2250  */
2251 static void
2252 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2253 {
2254   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
2255
2256   uint32_t i;
2257   unsigned int view_size;
2258   unsigned int *permut;
2259   unsigned int a_peers; /* Number of peers we send pushes to */
2260   unsigned int b_peers; /* Number of peers we send pull requests to */
2261   uint32_t first_border;
2262   uint32_t second_border;
2263   struct GNUNET_PeerIdentity peer;
2264   struct PeerContext *peer_ctx;
2265
2266   do_round_task = NULL;
2267   LOG (GNUNET_ERROR_TYPE_DEBUG,
2268        "Printing view:\n");
2269   to_file (file_name_view_log,
2270            "___ new round ___");
2271   view_size = GNUNET_CONTAINER_multipeermap_size (view);
2272   generate_view_array (view_size);
2273   for (i = 0 ; i < view_size ; i++)
2274   {
2275     LOG (GNUNET_ERROR_TYPE_DEBUG,
2276          "\t%s\n", GNUNET_i2s (&view_array[i]));
2277     to_file (file_name_view_log,
2278              "=%s\t(do round)",
2279              GNUNET_i2s_full (&view_array[i]));
2280   }
2281
2282
2283   /* Send pushes and pull requests */
2284   if (0 < view_size)
2285   {
2286     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2287                                            (unsigned int) view_size);
2288
2289     /* Send PUSHes */
2290     a_peers = ceil (alpha * view_size);
2291
2292     LOG (GNUNET_ERROR_TYPE_DEBUG,
2293          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
2294          a_peers, alpha, view_size);
2295     for (i = 0; i < a_peers; i++)
2296     {
2297       peer = view_array[permut[i]];
2298       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
2299       { // FIXME if this fails schedule/loop this for later
2300         send_push (&peer);
2301       }
2302     }
2303
2304     /* Send PULL requests */
2305     b_peers = ceil (beta * view_size);
2306     first_border = a_peers;
2307     second_border = a_peers + b_peers;
2308     if (second_border > view_size)
2309     {
2310       first_border = view_size - b_peers;
2311       second_border = view_size;
2312     }
2313     LOG (GNUNET_ERROR_TYPE_DEBUG,
2314         "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
2315         b_peers, beta, view_size);
2316     for (i = first_border; i < second_border; i++)
2317     {
2318       peer = view_array[permut[i]];
2319       peer_ctx = get_peer_ctx (&peer);
2320       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer) &&
2321           GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING)) // TODO
2322       { // FIXME if this fails schedule/loop this for later
2323         send_pull_request (&peer);
2324       }
2325     }
2326
2327     GNUNET_free (permut);
2328     permut = NULL;
2329   }
2330
2331
2332   /* Update view */
2333   /* TODO see how many peers are in push-/pull- list! */
2334
2335   if (push_list_size <= alpha * view_size &&
2336       0 < push_list_size &&
2337       0 < pull_list_size)
2338   {
2339     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the view.\n");
2340
2341     uint32_t final_size;
2342     uint32_t peers_to_clean_size;
2343     struct GNUNET_PeerIdentity *peers_to_clean;
2344
2345     peers_to_clean = NULL;
2346     peers_to_clean_size = 0;
2347     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, view_size);
2348     memcpy (peers_to_clean,
2349             view_array,
2350             view_size * sizeof (struct GNUNET_PeerIdentity));
2351
2352     /* Seems like recreating is the easiest way of emptying the peermap */
2353     GNUNET_CONTAINER_multipeermap_destroy (view);
2354     view = GNUNET_CONTAINER_multipeermap_create (view_size, GNUNET_NO);
2355     to_file (file_name_view_log,
2356              "--- emptied ---");
2357
2358     first_border  = GNUNET_MIN (ceil (alpha * sampler_size_est_need),
2359                                 push_list_size);
2360     second_border = first_border +
2361                     GNUNET_MIN (floor (beta  * sampler_size_est_need),
2362                                 pull_list_size);
2363     final_size    = second_border +
2364       ceil ((1 - (alpha + beta)) * sampler_size_est_need);
2365
2366     GNUNET_array_grow (view_array, view_size, second_border);
2367
2368     /* Update view with peers received through PUSHes */
2369     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2370                                            push_list_size);
2371     for (i = 0; i < first_border; i++)
2372     {
2373       view_array[i] = push_list[permut[i]];
2374       GNUNET_CONTAINER_multipeermap_put (view, &push_list[permut[i]], NULL,
2375           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2376
2377       to_file (file_name_view_log,
2378                "+%s\t(push list)",
2379                GNUNET_i2s_full (&view_array[i]));
2380       // TODO change the peer_flags accordingly
2381     }
2382     GNUNET_free (permut);
2383     permut = NULL;
2384
2385     /* Update view with peers received through PULLs */
2386     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2387                                            pull_list_size);
2388     for (i = first_border; i < second_border; i++)
2389     {
2390       view_array[i] = pull_list[permut[i - first_border]];
2391       GNUNET_CONTAINER_multipeermap_put (view,
2392           &pull_list[permut[i - first_border]],
2393           NULL,
2394           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2395
2396       to_file (file_name_view_log,
2397                "+%s\t(pull list)",
2398                GNUNET_i2s_full (&view_array[i]));
2399       // TODO change the peer_flags accordingly
2400     }
2401     GNUNET_free (permut);
2402     permut = NULL;
2403
2404     /* Update view with peers from history */
2405     RPS_sampler_get_n_rand_peers (prot_sampler,
2406                                   hist_update,
2407                                   NULL,
2408                                   final_size - second_border);
2409     num_hist_update_tasks = final_size - second_border;
2410     // TODO change the peer_flags accordingly
2411
2412     for (i = 0; i < view_size; i++)
2413       rem_from_list (&peers_to_clean, &peers_to_clean_size, &view_array[i]);
2414
2415     /* Clean peers that were removed from the view */
2416     for (i = 0; i < peers_to_clean_size; i++)
2417     {
2418       to_file (file_name_view_log,
2419                "-%s",
2420                GNUNET_i2s_full (&peers_to_clean[i]));
2421       peer_clean (&peers_to_clean[i]);
2422     }
2423
2424     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, 0);
2425     peers_to_clean = NULL;
2426   }
2427   else
2428   {
2429     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the view.\n");
2430   }
2431   // TODO independent of that also get some peers from CADET_get_peers()?
2432
2433   LOG (GNUNET_ERROR_TYPE_DEBUG,
2434        "Received %u pushes and %u pulls last round (alpha (%.2f) * view_size (%u) = %.2f)\n",
2435        push_list_size,
2436        pull_list_size,
2437        alpha,
2438        view_size,
2439        alpha * view_size);
2440
2441   /* Update samplers */
2442   for (i = 0; i < push_list_size; i++)
2443   {
2444     LOG (GNUNET_ERROR_TYPE_DEBUG,
2445          "Updating with peer %s from push list\n",
2446          GNUNET_i2s (&push_list[i]));
2447     insert_in_sampler (NULL, &push_list[i]);
2448     peer_clean (&push_list[i]); /* This cleans only if it is not in the view */
2449   }
2450
2451   for (i = 0; i < pull_list_size; i++)
2452   {
2453     LOG (GNUNET_ERROR_TYPE_DEBUG,
2454          "Updating with peer %s from pull list\n",
2455          GNUNET_i2s (&pull_list[i]));
2456     insert_in_sampler (NULL, &pull_list[i]);
2457     peer_clean (&pull_list[i]); /* This cleans only if it is not in the view */
2458   }
2459
2460
2461   /* Empty push/pull lists */
2462   GNUNET_array_grow (push_list, push_list_size, 0);
2463   GNUNET_array_grow (pull_list, pull_list_size, 0);
2464
2465   struct GNUNET_TIME_Relative time_next_round;
2466
2467   time_next_round = compute_rand_delay (round_interval, 2);
2468
2469   /* Schedule next round */
2470   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
2471   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2472 }
2473
2474
2475 static void
2476 rps_start (struct GNUNET_SERVER_Handle *server);
2477
2478
2479 /**
2480  * This is called from GNUNET_CADET_get_peers().
2481  *
2482  * It is called on every peer(ID) that cadet somehow has contact with.
2483  * We use those to initialise the sampler.
2484  */
2485 void
2486 init_peer_cb (void *cls,
2487               const struct GNUNET_PeerIdentity *peer,
2488               int tunnel, // "Do we have a tunnel towards this peer?"
2489               unsigned int n_paths, // "Number of known paths towards this peer"
2490               unsigned int best_path) // "How long is the best path?
2491                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
2492 {
2493   if (NULL != peer)
2494   {
2495     LOG (GNUNET_ERROR_TYPE_DEBUG,
2496          "Got peer_id %s from cadet\n",
2497          GNUNET_i2s (peer));
2498     new_peer_id (peer);
2499   }
2500 }
2501
2502
2503 /**
2504  * Iterator over peers from peerinfo.
2505  *
2506  * @param cls closure
2507  * @param peer id of the peer, NULL for last call
2508  * @param hello hello message for the peer (can be NULL)
2509  * @param error message
2510  */
2511 void
2512 process_peerinfo_peers (void *cls,
2513                         const struct GNUNET_PeerIdentity *peer,
2514                         const struct GNUNET_HELLO_Message *hello,
2515                         const char *err_msg)
2516 {
2517   if (NULL != peer)
2518   {
2519     LOG (GNUNET_ERROR_TYPE_DEBUG,
2520          "Got peer_id %s from peerinfo\n",
2521          GNUNET_i2s (peer));
2522     new_peer_id (peer);
2523   }
2524 }
2525
2526
2527 /**
2528  * Callback used to remove peers from the multipeermap.
2529  */
2530   int
2531 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
2532 {
2533   struct PeerContext *peer_ctx;
2534   const struct GNUNET_CADET_Channel *channel =
2535     (const struct GNUNET_CADET_Channel *) cls;
2536
2537   peer_ctx = (struct PeerContext *) value;
2538   set_peer_flag (peer_ctx, TO_DESTROY);
2539
2540   LOG (GNUNET_ERROR_TYPE_DEBUG,
2541        "Going to remove peer %s\n",
2542        GNUNET_i2s (&peer_ctx->peer_id));
2543
2544   /* Remove it from the sampler used for the Brahms protocol */
2545     RPS_sampler_reinitialise_by_value (prot_sampler, key);
2546
2547   /* If operations are still scheduled for this peer cancel those */
2548   if (0 != peer_ctx->num_outstanding_ops)
2549   {
2550     GNUNET_array_grow (peer_ctx->outstanding_ops,
2551                        peer_ctx->num_outstanding_ops,
2552                        0);
2553   }
2554
2555   /* If we are still waiting for notification whether this peer is live
2556    * cancel the according task */
2557   if (NULL != peer_ctx->transmit_handle)
2558   {
2559     LOG (GNUNET_ERROR_TYPE_DEBUG,
2560          "Trying to cancle transmit_handle for peer %s\n",
2561          GNUNET_i2s (key));
2562     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->transmit_handle);
2563     peer_ctx->transmit_handle = NULL;
2564   }
2565
2566   unset_peer_flag (peer_ctx, PULL_REPLY_PENDING);
2567
2568   /* Remove peer from view */
2569   if (GNUNET_CONTAINER_multipeermap_contains (view, key))
2570   {
2571     to_file (file_name_view_log,
2572         "-%s\t(cleanup channel, other peer)",
2573         GNUNET_i2s_full (key));
2574     GNUNET_CONTAINER_multipeermap_remove_all (view, key);
2575     if (NULL != view_array)
2576     {
2577       GNUNET_free (view_array);
2578       view_array = NULL;
2579     }
2580   }
2581
2582   /* Remove from push and pull lists */
2583   if (GNUNET_YES == in_arr (push_list, push_list_size, key))
2584     rem_from_list (&push_list, &push_list_size, key);
2585   if (GNUNET_YES == in_arr (pull_list, pull_list_size, key))
2586     rem_from_list (&pull_list, &pull_list_size, key);
2587
2588   /* If there is still a mq destroy it */
2589   if (NULL != peer_ctx->mq)
2590   {
2591     GNUNET_MQ_destroy (peer_ctx->mq);
2592     peer_ctx->mq = NULL;
2593   }
2594
2595
2596   /* Remove the send_channel
2597    * This function should be called again from #cleanup_channel (callback
2598    * called on the destruction of channels) and clean up the rest. */
2599   if (NULL != peer_ctx->send_channel &&
2600       channel != peer_ctx->send_channel)
2601   {
2602     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
2603     peer_ctx->send_channel = NULL;
2604   }
2605
2606   /* Remove the recv_channel
2607    * This function should be called again from #cleanup_channel (callback
2608    * called on the destruction of channels) and clean up the rest. */
2609   if (NULL != peer_ctx->recv_channel &&
2610       channel != peer_ctx->recv_channel)
2611   {
2612     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
2613     peer_ctx->recv_channel = NULL;
2614   }
2615
2616   /* If there is no channel we have to remove the context now */
2617   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2618     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
2619
2620   GNUNET_free (peer_ctx);
2621
2622   return GNUNET_YES;
2623 }
2624
2625
2626 /**
2627  * Clean the send channel of a peer
2628  * If there is also no channel to receive messages from that peer, remove it
2629  * from the peermap.
2630  */
2631 void
2632 peer_clean (const struct GNUNET_PeerIdentity *peer)
2633 {
2634   struct PeerContext *peer_ctx;
2635   /* struct GNUNET_CADET_Channel *channel; */
2636
2637   if ( (0 == RPS_sampler_count_id (prot_sampler, peer)) &&
2638        (GNUNET_NO  == GNUNET_CONTAINER_multipeermap_contains (view, peer)) &&
2639        (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer)) &&
2640        (GNUNET_NO  == in_arr (push_list, push_list_size, peer)) &&
2641        (GNUNET_NO  == in_arr (pull_list, pull_list_size, peer)) )
2642   {
2643     peer_ctx = get_peer_ctx (peer);
2644
2645     if ( (NULL == peer_ctx->recv_channel) &&
2646          (GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING)) )
2647     {
2648       #ifdef ENABLE_MALICIOUS
2649       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
2650         peer_remove_cb (NULL, peer, peer_ctx);
2651       #else
2652       peer_remove_cb (NULL, peer, peer_ctx);
2653       #endif /* ENABLE_MALICIOUS */
2654     }
2655   }
2656 }
2657
2658
2659 /**
2660  * Task run during shutdown.
2661  *
2662  * @param cls unused
2663  * @param tc unused
2664  */
2665 static void
2666 shutdown_task (void *cls,
2667                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2668 {
2669
2670   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
2671
2672   GNUNET_PEERINFO_notify_cancel (peerinfo_notify_handle);
2673   GNUNET_PEERINFO_disconnect (peerinfo_handle);
2674
2675   if (NULL != do_round_task)
2676   {
2677     GNUNET_SCHEDULER_cancel (do_round_task);
2678     do_round_task = NULL;
2679   }
2680
2681   {
2682   if (GNUNET_SYSERR ==
2683         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
2684     LOG (GNUNET_ERROR_TYPE_WARNING,
2685         "Iterating over peers to disconnect from them was cancelled\n");
2686   }
2687
2688   GNUNET_NSE_disconnect (nse);
2689   RPS_sampler_destroy (prot_sampler);
2690   RPS_sampler_destroy (client_sampler);
2691   LOG (GNUNET_ERROR_TYPE_DEBUG,
2692        "Size of the peermap: %u\n",
2693        GNUNET_CONTAINER_multipeermap_size (peer_map));
2694   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2695   GNUNET_CADET_disconnect (cadet_handle);
2696   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2697   GNUNET_CONTAINER_multipeermap_destroy (view);
2698   view = NULL;
2699   GNUNET_array_grow (push_list, push_list_size, 0);
2700   GNUNET_array_grow (pull_list, pull_list_size, 0);
2701   #ifdef ENABLE_MALICIOUS
2702   struct AttackedPeer *tmp_att_peer;
2703   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2704   if (NULL != mal_peer_set)
2705     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
2706   if (NULL != att_peer_set)
2707     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
2708   while (NULL != att_peers_head)
2709   {
2710     tmp_att_peer = att_peers_head;
2711     GNUNET_CONTAINER_DLL_remove (att_peers_head, att_peers_tail, tmp_att_peer);
2712   }
2713   #endif /* ENABLE_MALICIOUS */
2714 }
2715
2716
2717 /**
2718  * @brief Get informed about a connecting client.
2719  *
2720  * @param cls unused
2721  * @param client the client that connects
2722  */
2723 static void
2724 handle_client_connect (void *cls,
2725                        struct GNUNET_SERVER_Client *client)
2726 {
2727   struct ClientContext *cli_ctx;
2728
2729   LOG (GNUNET_ERROR_TYPE_DEBUG,
2730        "Client connected\n");
2731   if (NULL == client)
2732     return; /* Server was destroyed before a client connected. Shutting down */
2733   cli_ctx = GNUNET_new (struct ClientContext);
2734   cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
2735   GNUNET_SERVER_client_set_user_context (client, cli_ctx);
2736   GNUNET_CONTAINER_DLL_insert (cli_ctx_head,
2737                                cli_ctx_tail,
2738                                cli_ctx);
2739 }
2740
2741 /**
2742  * A client disconnected.  Remove all of its data structure entries.
2743  *
2744  * @param cls closure, NULL
2745  * @param client identification of the client
2746  */
2747 static void
2748 handle_client_disconnect (void *cls,
2749                                             struct GNUNET_SERVER_Client *client)
2750 {
2751   struct ClientContext *cli_ctx;
2752
2753   if (NULL == client)
2754   {/* shutdown task */
2755     while (NULL != cli_ctx_head)
2756       destroy_cli_ctx (cli_ctx_head);
2757   }
2758   else
2759   {
2760     cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct ClientContext);
2761     destroy_cli_ctx (cli_ctx);
2762   }
2763 }
2764
2765
2766 /**
2767  * Handle the channel a peer opens to us.
2768  *
2769  * @param cls The closure
2770  * @param channel The channel the peer wants to establish
2771  * @param initiator The peer's peer ID
2772  * @param port The port the channel is being established over
2773  * @param options Further options
2774  */
2775   static void *
2776 handle_inbound_channel (void *cls,
2777                         struct GNUNET_CADET_Channel *channel,
2778                         const struct GNUNET_PeerIdentity *initiator,
2779                         uint32_t port,
2780                         enum GNUNET_CADET_ChannelOption options)
2781 {
2782   struct PeerContext *peer_ctx;
2783
2784   LOG (GNUNET_ERROR_TYPE_DEBUG,
2785       "New channel was established to us (Peer %s).\n",
2786       GNUNET_i2s (initiator));
2787   GNUNET_assert (NULL != channel); /* according to cadet API */
2788   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, initiator))
2789     peer_ctx = create_peer_ctx (initiator);
2790   else
2791     peer_ctx = get_peer_ctx (initiator);
2792   /* We only accept one incoming channel from peers */
2793   if (NULL != peer_ctx->recv_channel)
2794   {
2795     GNUNET_CADET_channel_destroy (channel);
2796     return NULL;
2797   }
2798   peer_ctx->recv_channel = channel;
2799   peer_is_live (peer_ctx);
2800   return NULL;
2801 }
2802
2803
2804 /**
2805  * This is called when a channel is destroyed.
2806  *
2807  * @param cls The closure
2808  * @param channel The channel being closed
2809  * @param channel_ctx The context associated with this channel
2810  */
2811   static void
2812 cleanup_channel (void *cls,
2813                 const struct GNUNET_CADET_Channel *channel,
2814                 void *channel_ctx)
2815 {
2816   struct GNUNET_PeerIdentity *peer;
2817   struct PeerContext *peer_ctx;
2818
2819   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2820       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2821        // Guess simply casting isn't the nicest way...
2822        // FIXME wait for cadet to change this function
2823
2824   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2825   {/* We don't want to implicitly create a context that we're about to kill */
2826     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2827     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2828       return;
2829
2830     if (get_peer_flag (peer_ctx, TO_DESTROY))
2831     {/* We initiatad the destruction of this particular peer */
2832       if (channel == peer_ctx->send_channel)
2833         peer_ctx->send_channel = NULL;
2834       else if (channel == peer_ctx->recv_channel)
2835         peer_ctx->recv_channel = NULL;
2836
2837       to_file (file_name_view_log,
2838                "-%s\t(cleanup channel, ourself)",
2839                GNUNET_i2s_full (peer));
2840     }
2841
2842     else
2843     { /* We did not initiate the destruction of this peer */
2844       if (channel == peer_ctx->send_channel)
2845       { /* Something (but us) killd the channel - clean up peer */
2846         LOG (GNUNET_ERROR_TYPE_DEBUG,
2847             "send channel (%s) was destroyed - cleaning up\n",
2848             GNUNET_i2s (peer));
2849         peer_ctx->send_channel = NULL;
2850         /* Somwewhat {ab,re}use the iterator function */
2851         /* Cast to void is ok, because it's used as void in peer_remove_cb */
2852         (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2853       }
2854       else if (channel == peer_ctx->recv_channel)
2855       { /* Other peer doesn't want to send us messages anymore */
2856         LOG (GNUNET_ERROR_TYPE_DEBUG,
2857              "Peer %s destroyed recv channel - cleaning up channel\n",
2858              GNUNET_i2s (peer));
2859         peer_ctx->recv_channel = NULL;
2860       }
2861       else
2862       {
2863         LOG (GNUNET_ERROR_TYPE_WARNING,
2864              "unknown channel (%s) was destroyed\n",
2865              GNUNET_i2s (peer));
2866       }
2867     }
2868   }
2869
2870   else
2871   { /* We don't know a context to that peer */
2872     LOG (GNUNET_ERROR_TYPE_DEBUG,
2873          "channel (%s) without associated context was destroyed\n",
2874          GNUNET_i2s (peer));
2875   }
2876 }
2877
2878
2879 /**
2880  * Actually start the service.
2881  */
2882   static void
2883 rps_start (struct GNUNET_SERVER_Handle *server)
2884 {
2885   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2886     {&handle_client_request,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2887       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2888     {&handle_client_request_cancel, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL,
2889       sizeof (struct GNUNET_RPS_CS_RequestCancelMessage)},
2890     {&handle_client_seed,           NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2891     #ifdef ENABLE_MALICIOUS
2892     {&handle_client_act_malicious,  NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2893     #endif /* ENABLE_MALICIOUS */
2894     {NULL, NULL, 0, 0}
2895   };
2896
2897   GNUNET_SERVER_add_handlers (server, handlers);
2898   GNUNET_SERVER_connect_notify (server,
2899                                 &handle_client_connect,
2900                                 NULL);
2901   GNUNET_SERVER_disconnect_notify (server,
2902                                    &handle_client_disconnect,
2903                                    NULL);
2904   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
2905
2906
2907   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2908   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2909
2910   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2911                                                         &shutdown_task,
2912                                                         NULL);
2913 }
2914
2915
2916 /**
2917  * Process statistics requests.
2918  *
2919  * @param cls closure
2920  * @param server the initialized server
2921  * @param c configuration to use
2922  */
2923   static void
2924 run (void *cls,
2925      struct GNUNET_SERVER_Handle *server,
2926      const struct GNUNET_CONFIGURATION_Handle *c)
2927 {
2928   int size;
2929   int out_size;
2930
2931   // TODO check what this does -- copied from gnunet-boss
2932   // - seems to work as expected
2933   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2934   cfg = c;
2935
2936
2937   /* Get own ID */
2938   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2939   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2940               "STARTING SERVICE (rps) for peer [%s]\n",
2941               GNUNET_i2s (&own_identity));
2942   #ifdef ENABLE_MALICIOUS
2943   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2944               "Malicious execution compiled in.\n");
2945   #endif /* ENABLE_MALICIOUS */
2946
2947
2948
2949   /* Get time interval from the configuration */
2950   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2951                                                         "ROUNDINTERVAL",
2952                                                         &round_interval))
2953   {
2954     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2955                                "RPS", "ROUNDINTERVAL");
2956     GNUNET_SCHEDULER_shutdown ();
2957     return;
2958   }
2959
2960   /* Get initial size of sampler/view from the configuration */
2961   if (GNUNET_OK !=
2962       GNUNET_CONFIGURATION_get_value_number (cfg, "RPS", "INITSIZE",
2963         (long long unsigned int *) &sampler_size_est_need))
2964   {
2965     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2966                                "RPS", "INITSIZE");
2967     GNUNET_SCHEDULER_shutdown ();
2968     return;
2969   }
2970   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2971
2972
2973   view = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
2974
2975   /* file_name_view_log */
2976   if (GNUNET_OK != GNUNET_DISK_directory_create ("/tmp/rps/"))
2977   {
2978     LOG (GNUNET_ERROR_TYPE_WARNING,
2979          "Failed to create directory /tmp/rps/\n");
2980   }
2981
2982   size = (14 + strlen (GNUNET_i2s_full (&own_identity)) + 1) * sizeof (char);
2983   file_name_view_log = GNUNET_malloc (size);
2984   out_size = GNUNET_snprintf (file_name_view_log,
2985                               size,
2986                               "/tmp/rps/view-%s",
2987                               GNUNET_i2s_full (&own_identity));
2988   if (size < out_size ||
2989       0 > out_size)
2990   {
2991     LOG (GNUNET_ERROR_TYPE_WARNING,
2992          "Failed to write string to buffer (size: %i, out_size: %i)\n",
2993          size,
2994          out_size);
2995   }
2996
2997
2998   /* connect to NSE */
2999   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
3000
3001
3002   alpha = 0.45;
3003   beta  = 0.45;
3004
3005   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
3006
3007
3008   /* Initialise cadet */
3009   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
3010     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
3011       sizeof (struct GNUNET_MessageHeader)},
3012     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
3013       sizeof (struct GNUNET_MessageHeader)},
3014     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
3015     {NULL, 0, 0}
3016   };
3017
3018   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
3019   cadet_handle = GNUNET_CADET_connect (cfg,
3020                                        cls,
3021                                        &handle_inbound_channel,
3022                                        &cleanup_channel,
3023                                        cadet_handlers,
3024                                        ports);
3025
3026   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
3027
3028   /* Initialise sampler */
3029   struct GNUNET_TIME_Relative half_round_interval;
3030   struct GNUNET_TIME_Relative  max_round_interval;
3031
3032   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
3033   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
3034
3035   prot_sampler =   RPS_sampler_init     (sampler_size_est_need, max_round_interval);
3036   client_sampler = RPS_sampler_mod_init (sampler_size_est_need, max_round_interval);
3037
3038   /* Initialise push and pull maps */
3039   push_list = NULL;
3040   push_list_size = 0;
3041   pull_list = NULL;
3042   pull_list_size = 0;
3043
3044
3045   num_hist_update_tasks = 0;
3046
3047
3048   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
3049   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
3050   // TODO send push/pull to each of those peers?
3051
3052   peerinfo_notify_handle = GNUNET_PEERINFO_notify (cfg,
3053                                                    GNUNET_NO,
3054                                                    process_peerinfo_peers,
3055                                                    NULL);
3056
3057   rps_start (server);
3058 }
3059
3060
3061 /**
3062  * The main function for the rps service.
3063  *
3064  * @param argc number of arguments from the command line
3065  * @param argv command line arguments
3066  * @return 0 ok, 1 on error
3067  */
3068   int
3069 main (int argc, char *const *argv)
3070 {
3071   return (GNUNET_OK ==
3072           GNUNET_SERVICE_run (argc,
3073                               argv,
3074                               "rps",
3075                               GNUNET_SERVICE_OPTION_NONE,
3076                               &run, NULL)) ? 0 : 1;
3077 }
3078
3079 /* end of gnunet-service-rps.c */