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