note
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013-2015 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
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_applications.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_cadet_service.h"
30 #include "gnunet_core_service.h"
31 #include "gnunet_peerinfo_service.h"
32 #include "gnunet_nse_service.h"
33 #include "gnunet_statistics_service.h"
34 #include "rps.h"
35 #include "rps-test_util.h"
36 #include "gnunet-service-rps_sampler.h"
37 #include "gnunet-service-rps_custommap.h"
38 #include "gnunet-service-rps_view.h"
39
40 #include <math.h>
41 #include <inttypes.h>
42 #include <string.h>
43
44 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
45
46 // TODO check for overflows
47
48 // TODO align message structs
49
50 // TODO connect to friends
51
52 // TODO blacklist? (-> mal peer detection on top of brahms)
53
54 // hist_size_init, hist_size_max
55
56 /***********************************************************************
57  * Old gnunet-service-rps_peers.c
58 ***********************************************************************/
59
60 /**
61  * Set a peer flag of given peer context.
62  */
63 #define SET_PEER_FLAG(peer_ctx, mask) ((peer_ctx->peer_flags) |= (mask))
64
65 /**
66  * Get peer flag of given peer context.
67  */
68 #define check_peer_flag_set(peer_ctx, mask)\
69   ((peer_ctx->peer_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
70
71 /**
72  * Unset flag of given peer context.
73  */
74 #define UNSET_PEER_FLAG(peer_ctx, mask) ((peer_ctx->peer_flags) &= ~(mask))
75
76 /**
77  * Get channel flag of given channel context.
78  */
79 #define check_channel_flag_set(channel_flags, mask)\
80   ((*channel_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
81
82 /**
83  * Unset flag of given channel context.
84  */
85 #define unset_channel_flag(channel_flags, mask) ((*channel_flags) &= ~(mask))
86
87
88
89 /**
90  * Pending operation on peer consisting of callback and closure
91  *
92  * When an operation cannot be executed right now this struct is used to store
93  * the callback and closure for later execution.
94  */
95 struct PeerPendingOp
96 {
97   /**
98    * Callback
99    */
100   PeerOp op;
101
102   /**
103    * Closure
104    */
105   void *op_cls;
106 };
107
108 /**
109  * List containing all messages that are yet to be send
110  *
111  * This is used to keep track of all messages that have not been sent yet. When
112  * a peer is to be removed the pending messages can be removed properly.
113  */
114 struct PendingMessage
115 {
116   /**
117    * DLL next, prev
118    */
119   struct PendingMessage *next;
120   struct PendingMessage *prev;
121
122   /**
123    * The envelope to the corresponding message
124    */
125   struct GNUNET_MQ_Envelope *ev;
126
127   /**
128    * The corresponding context
129    */
130   struct PeerContext *peer_ctx;
131
132   /**
133    * The message type
134    */
135   const char *type;
136 };
137
138 /**
139  * @brief Context for a channel
140  */
141 struct ChannelCtx;
142
143 /**
144  * Struct used to keep track of other peer's status
145  *
146  * This is stored in a multipeermap.
147  * It contains information such as cadet channels, a message queue for sending,
148  * status about the channels, the pending operations on this peer and some flags
149  * about the status of the peer itself. (online, valid, ...)
150  */
151 struct PeerContext
152 {
153   /**
154    * The Sub this context belongs to.
155    */
156   struct Sub *sub;
157
158   /**
159    * Message queue open to client
160    */
161   struct GNUNET_MQ_Handle *mq;
162
163   /**
164    * Channel open to client.
165    */
166   struct ChannelCtx *send_channel_ctx;
167
168   /**
169    * Channel open from client.
170    */
171   struct ChannelCtx *recv_channel_ctx;
172
173   /**
174    * Array of pending operations on this peer.
175    */
176   struct PeerPendingOp *pending_ops;
177
178   /**
179    * Handle to the callback given to cadet_ntfy_tmt_rdy()
180    *
181    * To be canceled on shutdown.
182    */
183   struct PendingMessage *online_check_pending;
184
185   /**
186    * Number of pending operations.
187    */
188   unsigned int num_pending_ops;
189
190   /**
191    * Identity of the peer
192    */
193   struct GNUNET_PeerIdentity peer_id;
194
195   /**
196    * Flags indicating status of peer
197    */
198   uint32_t peer_flags;
199
200   /**
201    * Last time we received something from that peer.
202    */
203   struct GNUNET_TIME_Absolute last_message_recv;
204
205   /**
206    * Last time we received a keepalive message.
207    */
208   struct GNUNET_TIME_Absolute last_keepalive;
209
210   /**
211    * DLL with all messages that are yet to be sent
212    */
213   struct PendingMessage *pending_messages_head;
214   struct PendingMessage *pending_messages_tail;
215
216   /**
217    * This is pobably followed by 'statistical' data (when we first saw
218    * it, how did we get its ID, how many pushes (in a timeinterval),
219    * ...)
220    */
221   uint32_t round_pull_req;
222 };
223
224 /**
225  * @brief Closure to #valid_peer_iterator
226  */
227 struct PeersIteratorCls
228 {
229   /**
230    * Iterator function
231    */
232   PeersIterator iterator;
233
234   /**
235    * Closure to iterator
236    */
237   void *cls;
238 };
239
240 /**
241  * @brief Context for a channel
242  */
243 struct ChannelCtx
244 {
245   /**
246    * @brief The channel itself
247    */
248   struct GNUNET_CADET_Channel *channel;
249
250   /**
251    * @brief The peer context associated with the channel
252    */
253   struct PeerContext *peer_ctx;
254
255   /**
256    * @brief When channel destruction needs to be delayed (because it is called
257    * from within the cadet routine of another channel destruction) this task
258    * refers to the respective _SCHEDULER_Task.
259    */
260   struct GNUNET_SCHEDULER_Task *destruction_task;
261 };
262
263
264 #if ENABLE_MALICIOUS
265
266 /**
267  * If type is 2 This struct is used to store the attacked peers in a DLL
268  */
269 struct AttackedPeer
270 {
271   /**
272    * DLL
273    */
274   struct AttackedPeer *next;
275   struct AttackedPeer *prev;
276
277   /**
278    * PeerID
279    */
280   struct GNUNET_PeerIdentity peer_id;
281 };
282
283 #endif /* ENABLE_MALICIOUS */
284
285 /**
286  * @brief One Sub.
287  *
288  * Essentially one instance of brahms that only connects to other instances
289  * with the same (secret) value.
290  */
291 struct Sub
292 {
293   /**
294    * @brief Hash of the shared value that defines Subs.
295    */
296   struct GNUNET_HashCode hash;
297
298   /**
299    * @brief Port to communicate to other peers.
300    */
301   struct GNUNET_CADET_Port *cadet_port;
302
303   /**
304    * @brief Hashmap of valid peers.
305    */
306   struct GNUNET_CONTAINER_MultiPeerMap *valid_peers;
307
308   /**
309    * @brief Filename of the file that stores the valid peers persistently.
310    */
311   char *filename_valid_peers;
312
313   /**
314    * Set of all peers to keep track of them.
315    */
316   struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
317
318   /**
319    * @brief This is the minimum estimate used as sampler size.
320    *
321    * It is configured by the user.
322    */
323   unsigned int sampler_size_est_min;
324
325   /**
326    * The size of sampler we need to be able to satisfy the Brahms protocol's
327    * need of random peers.
328    *
329    * This is one minimum size the sampler grows to.
330    */
331   unsigned int sampler_size_est_need;
332
333   /**
334    * Time inverval the do_round task runs in.
335    */
336   struct GNUNET_TIME_Relative round_interval;
337
338   /**
339    * Sampler used for the Brahms protocol itself.
340    */
341   struct RPS_Sampler *sampler;
342
343   /**
344    * Name to log view to
345    */
346   char *file_name_view_log;
347
348 #ifdef TO_FILE
349   /**
350    * Name to log number of observed peers to
351    */
352   char *file_name_observed_log;
353
354   /**
355    * @brief Count the observed peers
356    */
357   uint32_t num_observed_peers;
358
359   /**
360    * @brief File name to log number of pushes per round to
361    */
362   char *file_name_push_recv;
363
364   /**
365    * @brief File name to log number of pushes per round to
366    */
367   char *file_name_pull_delays;
368
369   /**
370    * @brief Multipeermap (ab-) used to count unique peer_ids
371    */
372   struct GNUNET_CONTAINER_MultiPeerMap *observed_unique_peers;
373 #endif /* TO_FILE */
374
375   /**
376    * List to store peers received through pushes temporary.
377    */
378   struct CustomPeerMap *push_map;
379
380   /**
381    * List to store peers received through pulls temporary.
382    */
383   struct CustomPeerMap *pull_map;
384
385   /**
386    * @brief This is the estimate used as view size.
387    *
388    * It is initialised with the minimum
389    */
390   unsigned int view_size_est_need;
391
392   /**
393    * @brief This is the minimum estimate used as view size.
394    *
395    * It is configured by the user.
396    */
397   unsigned int view_size_est_min;
398
399   /**
400    * @brief The view.
401    */
402   struct View *view;
403
404   /**
405    * Identifier for the main task that runs periodically.
406    */
407   struct GNUNET_SCHEDULER_Task *do_round_task;
408
409   /* === stats === */
410
411   /**
412    * @brief Counts the executed rounds.
413    */
414   uint32_t num_rounds;
415
416   /**
417    * @brief This array accumulates the number of received pushes per round.
418    *
419    * Number at index i represents the number of rounds with i observed pushes.
420    */
421   uint32_t push_recv[256];
422
423   /**
424    * @brief Number of pull replies with this delay measured in rounds.
425    *
426    * Number at index i represents the number of pull replies with a delay of i
427    * rounds.
428    */
429   uint32_t pull_delays[256];
430 };
431
432
433 /***********************************************************************
434  * Globals
435 ***********************************************************************/
436
437 /**
438  * Our configuration.
439  */
440 static const struct GNUNET_CONFIGURATION_Handle *cfg;
441
442 /**
443  * Handle to the statistics service.
444  */
445 struct GNUNET_STATISTICS_Handle *stats;
446
447 /**
448  * Handler to CADET.
449  */
450 struct GNUNET_CADET_Handle *cadet_handle;
451
452 /**
453  * Handle to CORE
454  */
455 struct GNUNET_CORE_Handle *core_handle;
456
457 /**
458  * @brief PeerMap to keep track of connected peers.
459  */
460 struct GNUNET_CONTAINER_MultiPeerMap *map_single_hop;
461
462 /**
463  * Our own identity.
464  */
465 static struct GNUNET_PeerIdentity own_identity;
466
467 /**
468  * Percentage of total peer number in the view
469  * to send random PUSHes to
470  */
471 static float alpha;
472
473 /**
474  * Percentage of total peer number in the view
475  * to send random PULLs to
476  */
477 static float beta;
478
479 /**
480  * Handler to NSE.
481  */
482 static struct GNUNET_NSE_Handle *nse;
483
484 /**
485  * Handler to PEERINFO.
486  */
487 static struct GNUNET_PEERINFO_Handle *peerinfo_handle;
488
489 /**
490  * Handle for cancellation of iteration over peers.
491  */
492 static struct GNUNET_PEERINFO_NotifyContext *peerinfo_notify_handle;
493
494
495 #if ENABLE_MALICIOUS
496 /**
497  * Type of malicious peer
498  *
499  * 0 Don't act malicious at all - Default
500  * 1 Try to maximise representation
501  * 2 Try to partition the network
502  * 3 Combined attack
503  */
504 static uint32_t mal_type;
505
506 /**
507  * Other malicious peers
508  */
509 static struct GNUNET_PeerIdentity *mal_peers;
510
511 /**
512  * Hashmap of malicious peers used as set.
513  * Used to more efficiently check whether we know that peer.
514  */
515 static struct GNUNET_CONTAINER_MultiPeerMap *mal_peer_set;
516
517 /**
518  * Number of other malicious peers
519  */
520 static uint32_t num_mal_peers;
521
522
523 /**
524  * If type is 2 this is the DLL of attacked peers
525  */
526 static struct AttackedPeer *att_peers_head;
527 static struct AttackedPeer *att_peers_tail;
528
529 /**
530  * This index is used to point to an attacked peer to
531  * implement the round-robin-ish way to select attacked peers.
532  */
533 static struct AttackedPeer *att_peer_index;
534
535 /**
536  * Hashmap of attacked peers used as set.
537  * Used to more efficiently check whether we know that peer.
538  */
539 static struct GNUNET_CONTAINER_MultiPeerMap *att_peer_set;
540
541 /**
542  * Number of attacked peers
543  */
544 static uint32_t num_attacked_peers;
545
546 /**
547  * If type is 1 this is the attacked peer
548  */
549 static struct GNUNET_PeerIdentity attacked_peer;
550
551 /**
552  * The limit of PUSHes we can send in one round.
553  * This is an assumption of the Brahms protocol and either implemented
554  * via proof of work
555  * or
556  * assumend to be the bandwidth limitation.
557  */
558 static uint32_t push_limit = 10000;
559 #endif /* ENABLE_MALICIOUS */
560
561 /**
562  * @brief Main Sub.
563  *
564  * This is run in any case by all peers and connects to all peers without
565  * specifying a shared value.
566  */
567 static struct Sub *msub;
568
569 /**
570  * @brief Maximum number of valid peers to keep.
571  * TODO read from config
572  */
573 static const uint32_t num_valid_peers_max = UINT32_MAX;
574
575 /***********************************************************************
576  * /Globals
577 ***********************************************************************/
578
579
580 static void
581 do_round (void *cls);
582
583 static void
584 do_mal_round (void *cls);
585
586
587 /**
588  * @brief Get the #PeerContext associated with a peer
589  *
590  * @param peer_map The peer map containing the context
591  * @param peer the peer id
592  *
593  * @return the #PeerContext
594  */
595 static struct PeerContext *
596 get_peer_ctx (const struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
597               const struct GNUNET_PeerIdentity *peer)
598 {
599   struct PeerContext *ctx;
600   int ret;
601
602   ret = GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
603   GNUNET_assert (GNUNET_YES == ret);
604   ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
605   GNUNET_assert (NULL != ctx);
606   return ctx;
607 }
608
609 /**
610  * @brief Check whether we have information about the given peer.
611  *
612  * FIXME probably deprecated. Make this the new _online.
613  *
614  * @param peer_map The peer map to check for the existence of @a peer
615  * @param peer peer in question
616  *
617  * @return #GNUNET_YES if peer is known
618  *         #GNUNET_NO  if peer is not knwon
619  */
620 static int
621 check_peer_known (const struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
622                   const struct GNUNET_PeerIdentity *peer)
623 {
624   if (NULL != peer_map)
625   {
626     return GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
627   }
628   else
629   {
630     return GNUNET_NO;
631   }
632 }
633
634
635 /**
636  * @brief Create a new #PeerContext and insert it into the peer map
637  *
638  * @param sub The Sub this context belongs to.
639  * @param peer the peer to create the #PeerContext for
640  *
641  * @return the #PeerContext
642  */
643 static struct PeerContext *
644 create_peer_ctx (struct Sub *sub,
645                  const struct GNUNET_PeerIdentity *peer)
646 {
647   struct PeerContext *ctx;
648   int ret;
649
650   GNUNET_assert (GNUNET_NO == check_peer_known (sub->peer_map, peer));
651
652   ctx = GNUNET_new (struct PeerContext);
653   ctx->peer_id = *peer;
654   ctx->sub = sub;
655   ret = GNUNET_CONTAINER_multipeermap_put (sub->peer_map, peer, ctx,
656       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
657   GNUNET_assert (GNUNET_OK == ret);
658   if (sub == msub)
659   {
660     GNUNET_STATISTICS_set (stats,
661                           "# known peers",
662                           GNUNET_CONTAINER_multipeermap_size (sub->peer_map),
663                           GNUNET_NO);
664   }
665   return ctx;
666 }
667
668
669 /**
670  * @brief Create or get a #PeerContext
671  *
672  * @param sub The Sub to which the created context belongs to
673  * @param peer the peer to get the associated context to
674  *
675  * @return the context
676  */
677 static struct PeerContext *
678 create_or_get_peer_ctx (struct Sub *sub,
679                         const struct GNUNET_PeerIdentity *peer)
680 {
681   if (GNUNET_NO == check_peer_known (sub->peer_map, peer))
682   {
683     return create_peer_ctx (sub, peer);
684   }
685   return get_peer_ctx (sub->peer_map, peer);
686 }
687
688
689 /**
690  * @brief Check whether we have a connection to this @a peer
691  *
692  * Also sets the #Peers_ONLINE flag accordingly
693  *
694  * @param peer_ctx Context of the peer of which connectivity is to be checked
695  *
696  * @return #GNUNET_YES if we are connected
697  *         #GNUNET_NO  otherwise
698  */
699 static int
700 check_connected (struct PeerContext *peer_ctx)
701 {
702   /* If we don't know about this peer we don't know whether it's online */
703   if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
704                                      &peer_ctx->peer_id))
705   {
706     return GNUNET_NO;
707   }
708   /* Get the context */
709   peer_ctx = get_peer_ctx (peer_ctx->sub->peer_map, &peer_ctx->peer_id);
710   /* If we have no channel to this peer we don't know whether it's online */
711   if ( (NULL == peer_ctx->send_channel_ctx) &&
712        (NULL == peer_ctx->recv_channel_ctx) )
713   {
714     UNSET_PEER_FLAG (peer_ctx, Peers_ONLINE);
715     return GNUNET_NO;
716   }
717   /* Otherwise (if we have a channel, we know that it's online */
718   SET_PEER_FLAG (peer_ctx, Peers_ONLINE);
719   return GNUNET_YES;
720 }
721
722
723 /**
724  * @brief The closure to #get_rand_peer_iterator.
725  */
726 struct GetRandPeerIteratorCls
727 {
728   /**
729    * @brief The index of the peer to return.
730    * Will be decreased until 0.
731    * Then current peer is returned.
732    */
733   uint32_t index;
734
735   /**
736    * @brief Pointer to peer to return.
737    */
738   const struct GNUNET_PeerIdentity *peer;
739 };
740
741
742 /**
743  * @brief Iterator function for #get_random_peer_from_peermap.
744  *
745  * Implements #GNUNET_CONTAINER_PeerMapIterator.
746  * Decreases the index until the index is null.
747  * Then returns the current peer.
748  *
749  * @param cls the #GetRandPeerIteratorCls containing index and peer
750  * @param peer current peer
751  * @param value unused
752  *
753  * @return  #GNUNET_YES if we should continue to
754  *          iterate,
755  *          #GNUNET_NO if not.
756  */
757 static int
758 get_rand_peer_iterator (void *cls,
759                         const struct GNUNET_PeerIdentity *peer,
760                         void *value)
761 {
762   struct GetRandPeerIteratorCls *iterator_cls = cls;
763   (void) value;
764
765   if (0 >= iterator_cls->index)
766   {
767     iterator_cls->peer = peer;
768     return GNUNET_NO;
769   }
770   iterator_cls->index--;
771   return GNUNET_YES;
772 }
773
774
775 /**
776  * @brief Get a random peer from @a peer_map
777  *
778  * @param valid_peers Peer map containing valid peers from which to select a
779  * random one
780  *
781  * @return a random peer
782  */
783 static const struct GNUNET_PeerIdentity *
784 get_random_peer_from_peermap (struct GNUNET_CONTAINER_MultiPeerMap *valid_peers)
785 {
786   struct GetRandPeerIteratorCls *iterator_cls;
787   const struct GNUNET_PeerIdentity *ret;
788
789   iterator_cls = GNUNET_new (struct GetRandPeerIteratorCls);
790   iterator_cls->index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
791       GNUNET_CONTAINER_multipeermap_size (valid_peers));
792   (void) GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
793                                                 get_rand_peer_iterator,
794                                                 iterator_cls);
795   ret = iterator_cls->peer;
796   GNUNET_free (iterator_cls);
797   return ret;
798 }
799
800
801 /**
802  * @brief Add a given @a peer to valid peers.
803  *
804  * If valid peers are already #num_valid_peers_max, delete a peer previously.
805  *
806  * @param peer The peer that is added to the valid peers.
807  * @param valid_peers Peer map of valid peers to which to add the @a peer
808  *
809  * @return #GNUNET_YES if no other peer had to be removed
810  *         #GNUNET_NO  otherwise
811  */
812 static int
813 add_valid_peer (const struct GNUNET_PeerIdentity *peer,
814                 struct GNUNET_CONTAINER_MultiPeerMap *valid_peers)
815 {
816   const struct GNUNET_PeerIdentity *rand_peer;
817   int ret;
818
819   ret = GNUNET_YES;
820   /* Remove random peers until there is space for a new one */
821   while (num_valid_peers_max <=
822          GNUNET_CONTAINER_multipeermap_size (valid_peers))
823   {
824     rand_peer = get_random_peer_from_peermap (valid_peers);
825     GNUNET_CONTAINER_multipeermap_remove_all (valid_peers, rand_peer);
826     ret = GNUNET_NO;
827   }
828   (void) GNUNET_CONTAINER_multipeermap_put (valid_peers, peer, NULL,
829       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
830   if (valid_peers == msub->valid_peers)
831   {
832     GNUNET_STATISTICS_set (stats,
833                            "# valid peers",
834                            GNUNET_CONTAINER_multipeermap_size (valid_peers),
835                            GNUNET_NO);
836   }
837   return ret;
838 }
839
840 static void
841 remove_pending_message (struct PendingMessage *pending_msg, int cancel);
842
843 /**
844  * @brief Set the peer flag to living and
845  *        call the pending operations on this peer.
846  *
847  * Also adds peer to #valid_peers.
848  *
849  * @param peer_ctx the #PeerContext of the peer to set online
850  */
851 static void
852 set_peer_online (struct PeerContext *peer_ctx)
853 {
854   struct GNUNET_PeerIdentity *peer;
855   unsigned int i;
856
857   peer = &peer_ctx->peer_id;
858   LOG (GNUNET_ERROR_TYPE_DEBUG,
859       "Peer %s is online and valid, calling %i pending operations on it\n",
860       GNUNET_i2s (peer),
861       peer_ctx->num_pending_ops);
862
863   if (NULL != peer_ctx->online_check_pending)
864   {
865     LOG (GNUNET_ERROR_TYPE_DEBUG,
866          "Removing pending online check for peer %s\n",
867          GNUNET_i2s (&peer_ctx->peer_id));
868     // TODO wait until cadet sets mq->cancel_impl
869     //GNUNET_MQ_send_cancel (peer_ctx->online_check_pending->ev);
870     remove_pending_message (peer_ctx->online_check_pending, GNUNET_YES);
871     peer_ctx->online_check_pending = NULL;
872   }
873
874   SET_PEER_FLAG (peer_ctx, Peers_ONLINE);
875
876   /* Call pending operations */
877   for (i = 0; i < peer_ctx->num_pending_ops; i++)
878   {
879     peer_ctx->pending_ops[i].op (peer_ctx->pending_ops[i].op_cls, peer);
880   }
881   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
882 }
883
884 static void
885 cleanup_destroyed_channel (void *cls,
886                            const struct GNUNET_CADET_Channel *channel);
887
888 /* Declaration of handlers */
889 static void
890 handle_peer_check (void *cls,
891                    const struct GNUNET_MessageHeader *msg);
892
893 static void
894 handle_peer_push (void *cls,
895                   const struct GNUNET_MessageHeader *msg);
896
897 static void
898 handle_peer_pull_request (void *cls,
899                           const struct GNUNET_MessageHeader *msg);
900
901 static int
902 check_peer_pull_reply (void *cls,
903                        const struct GNUNET_RPS_P2P_PullReplyMessage *msg);
904
905 static void
906 handle_peer_pull_reply (void *cls,
907                         const struct GNUNET_RPS_P2P_PullReplyMessage *msg);
908
909 /* End declaration of handlers */
910
911 /**
912  * @brief Allocate memory for a new channel context and insert it into DLL
913  *
914  * @param peer_ctx context of the according peer
915  *
916  * @return The channel context
917  */
918 static struct ChannelCtx *
919 add_channel_ctx (struct PeerContext *peer_ctx)
920 {
921   struct ChannelCtx *channel_ctx;
922   channel_ctx = GNUNET_new (struct ChannelCtx);
923   channel_ctx->peer_ctx = peer_ctx;
924   return channel_ctx;
925 }
926
927
928 /**
929  * @brief Free memory and NULL pointers.
930  *
931  * @param channel_ctx The channel context.
932  */
933 static void
934 remove_channel_ctx (struct ChannelCtx *channel_ctx)
935 {
936   struct PeerContext *peer_ctx = channel_ctx->peer_ctx;
937
938   if (NULL != channel_ctx->destruction_task)
939   {
940     GNUNET_SCHEDULER_cancel (channel_ctx->destruction_task);
941     channel_ctx->destruction_task = NULL;
942   }
943
944   GNUNET_free (channel_ctx);
945
946   if (NULL == peer_ctx) return;
947   if (channel_ctx == peer_ctx->send_channel_ctx)
948   {
949     peer_ctx->send_channel_ctx = NULL;
950     peer_ctx->mq = NULL;
951   }
952   else if (channel_ctx == peer_ctx->recv_channel_ctx)
953   {
954     peer_ctx->recv_channel_ctx = NULL;
955   }
956 }
957
958
959 /**
960  * @brief Get the channel of a peer. If not existing, create.
961  *
962  * @param peer_ctx Context of the peer of which to get the channel
963  * @return the #GNUNET_CADET_Channel used to send data to @a peer_ctx
964  */
965 struct GNUNET_CADET_Channel *
966 get_channel (struct PeerContext *peer_ctx)
967 {
968   /* There exists a copy-paste-clone in run() */
969   struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
970     GNUNET_MQ_hd_fixed_size (peer_check,
971                              GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE,
972                              struct GNUNET_MessageHeader,
973                              NULL),
974     GNUNET_MQ_hd_fixed_size (peer_push,
975                              GNUNET_MESSAGE_TYPE_RPS_PP_PUSH,
976                              struct GNUNET_MessageHeader,
977                              NULL),
978     GNUNET_MQ_hd_fixed_size (peer_pull_request,
979                              GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
980                              struct GNUNET_MessageHeader,
981                              NULL),
982     GNUNET_MQ_hd_var_size (peer_pull_reply,
983                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY,
984                            struct GNUNET_RPS_P2P_PullReplyMessage,
985                            NULL),
986     GNUNET_MQ_handler_end ()
987   };
988
989
990   if (NULL == peer_ctx->send_channel_ctx)
991   {
992     LOG (GNUNET_ERROR_TYPE_DEBUG,
993          "Trying to establish channel to peer %s\n",
994          GNUNET_i2s (&peer_ctx->peer_id));
995     peer_ctx->send_channel_ctx = add_channel_ctx (peer_ctx);
996     peer_ctx->send_channel_ctx->channel =
997       GNUNET_CADET_channel_create (cadet_handle,
998                                    peer_ctx->send_channel_ctx, /* context */
999                                    &peer_ctx->peer_id,
1000                                    &peer_ctx->sub->hash,
1001                                    GNUNET_CADET_OPTION_RELIABLE,
1002                                    NULL, /* WindowSize handler */
1003                                    &cleanup_destroyed_channel, /* Disconnect handler */
1004                                    cadet_handlers);
1005   }
1006   GNUNET_assert (NULL != peer_ctx->send_channel_ctx);
1007   GNUNET_assert (NULL != peer_ctx->send_channel_ctx->channel);
1008   return peer_ctx->send_channel_ctx->channel;
1009 }
1010
1011
1012 /**
1013  * Get the message queue (#GNUNET_MQ_Handle) of a specific peer.
1014  *
1015  * If we already have a message queue open to this client,
1016  * simply return it, otherways create one.
1017  *
1018  * @param peer_ctx Context of the peer of whicht to get the mq
1019  * @return the #GNUNET_MQ_Handle
1020  */
1021 static struct GNUNET_MQ_Handle *
1022 get_mq (struct PeerContext *peer_ctx)
1023 {
1024   if (NULL == peer_ctx->mq)
1025   {
1026     peer_ctx->mq = GNUNET_CADET_get_mq (get_channel (peer_ctx));
1027   }
1028   return peer_ctx->mq;
1029 }
1030
1031 /**
1032  * @brief Add an envelope to a message passed to mq to list of pending messages
1033  *
1034  * @param peer_ctx Context of the peer for which to insert the envelope
1035  * @param ev envelope to the message
1036  * @param type type of the message to be sent
1037  * @return pointer to pending message
1038  */
1039 static struct PendingMessage *
1040 insert_pending_message (struct PeerContext *peer_ctx,
1041                         struct GNUNET_MQ_Envelope *ev,
1042                         const char *type)
1043 {
1044   struct PendingMessage *pending_msg;
1045
1046   pending_msg = GNUNET_new (struct PendingMessage);
1047   pending_msg->ev = ev;
1048   pending_msg->peer_ctx = peer_ctx;
1049   pending_msg->type = type;
1050   GNUNET_CONTAINER_DLL_insert (peer_ctx->pending_messages_head,
1051                                peer_ctx->pending_messages_tail,
1052                                pending_msg);
1053   return pending_msg;
1054 }
1055
1056
1057 /**
1058  * @brief Remove a pending message from the respective DLL
1059  *
1060  * @param pending_msg the pending message to remove
1061  * @param cancel whether to cancel the pending message, too
1062  */
1063 static void
1064 remove_pending_message (struct PendingMessage *pending_msg, int cancel)
1065 {
1066   struct PeerContext *peer_ctx;
1067   (void) cancel;
1068
1069   peer_ctx = pending_msg->peer_ctx;
1070   GNUNET_assert (NULL != peer_ctx);
1071   GNUNET_CONTAINER_DLL_remove (peer_ctx->pending_messages_head,
1072                                peer_ctx->pending_messages_tail,
1073                                pending_msg);
1074   // TODO wait for the cadet implementation of message cancellation
1075   //if (GNUNET_YES == cancel)
1076   //{
1077   //  GNUNET_MQ_send_cancel (pending_msg->ev);
1078   //}
1079   GNUNET_free (pending_msg);
1080 }
1081
1082
1083 /**
1084  * @brief This is called in response to the first message we sent as a
1085  * online check.
1086  *
1087  * @param cls #PeerContext of peer with pending online check
1088  */
1089 static void
1090 mq_online_check_successful (void *cls)
1091 {
1092   struct PeerContext *peer_ctx = cls;
1093
1094   if (NULL != peer_ctx->online_check_pending)
1095   {
1096     LOG (GNUNET_ERROR_TYPE_DEBUG,
1097         "Online check for peer %s was successfull\n",
1098         GNUNET_i2s (&peer_ctx->peer_id));
1099     remove_pending_message (peer_ctx->online_check_pending, GNUNET_YES);
1100     peer_ctx->online_check_pending = NULL;
1101     set_peer_online (peer_ctx);
1102     (void) add_valid_peer (&peer_ctx->peer_id, peer_ctx->sub->valid_peers);
1103   }
1104 }
1105
1106 /**
1107  * Issue a check whether peer is online
1108  *
1109  * @param peer_ctx the context of the peer
1110  */
1111 static void
1112 check_peer_online (struct PeerContext *peer_ctx)
1113 {
1114   LOG (GNUNET_ERROR_TYPE_DEBUG,
1115        "Get informed about peer %s getting online\n",
1116        GNUNET_i2s (&peer_ctx->peer_id));
1117
1118   struct GNUNET_MQ_Handle *mq;
1119   struct GNUNET_MQ_Envelope *ev;
1120
1121   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE);
1122   peer_ctx->online_check_pending =
1123     insert_pending_message (peer_ctx, ev, "Check online");
1124   mq = get_mq (peer_ctx);
1125   GNUNET_MQ_notify_sent (ev,
1126                          mq_online_check_successful,
1127                          peer_ctx);
1128   GNUNET_MQ_send (mq, ev);
1129   if (peer_ctx->sub == msub)
1130   {
1131     GNUNET_STATISTICS_update (stats,
1132                               "# pending online checks",
1133                               1,
1134                               GNUNET_NO);
1135   }
1136 }
1137
1138
1139 /**
1140  * @brief Check whether function of type #PeerOp was already scheduled
1141  *
1142  * The array with pending operations will probably never grow really big, so
1143  * iterating over it should be ok.
1144  *
1145  * @param peer_ctx Context of the peer to check for the operation
1146  * @param peer_op the operation (#PeerOp) on the peer
1147  *
1148  * @return #GNUNET_YES if this operation is scheduled on that peer
1149  *         #GNUNET_NO  otherwise
1150  */
1151 static int
1152 check_operation_scheduled (const struct PeerContext *peer_ctx,
1153                            const PeerOp peer_op)
1154 {
1155   unsigned int i;
1156
1157   for (i = 0; i < peer_ctx->num_pending_ops; i++)
1158     if (peer_op == peer_ctx->pending_ops[i].op)
1159       return GNUNET_YES;
1160   return GNUNET_NO;
1161 }
1162
1163
1164 /**
1165  * @brief Callback for scheduler to destroy a channel
1166  *
1167  * @param cls Context of the channel
1168  */
1169 static void
1170 destroy_channel (struct ChannelCtx *channel_ctx)
1171 {
1172   struct GNUNET_CADET_Channel *channel;
1173
1174   if (NULL != channel_ctx->destruction_task)
1175   {
1176     GNUNET_SCHEDULER_cancel (channel_ctx->destruction_task);
1177     channel_ctx->destruction_task = NULL;
1178   }
1179   GNUNET_assert (channel_ctx->channel != NULL);
1180   channel = channel_ctx->channel;
1181   channel_ctx->channel = NULL;
1182   GNUNET_CADET_channel_destroy (channel);
1183   remove_channel_ctx (channel_ctx);
1184 }
1185
1186
1187 /**
1188  * @brief Destroy a cadet channel.
1189  *
1190  * This satisfies the function signature of #GNUNET_SCHEDULER_TaskCallback.
1191  *
1192  * @param cls
1193  */
1194 static void
1195 destroy_channel_cb (void *cls)
1196 {
1197   struct ChannelCtx *channel_ctx = cls;
1198
1199   channel_ctx->destruction_task = NULL;
1200   destroy_channel (channel_ctx);
1201 }
1202
1203
1204 /**
1205  * @brief Schedule the destruction of a channel for immediately afterwards.
1206  *
1207  * In case a channel is to be destroyed from within the callback to the
1208  * destruction of another channel (send channel), we cannot call
1209  * GNUNET_CADET_channel_destroy directly, but need to use this scheduling
1210  * construction.
1211  *
1212  * @param channel_ctx channel to be destroyed.
1213  */
1214 static void
1215 schedule_channel_destruction (struct ChannelCtx *channel_ctx)
1216 {
1217   GNUNET_assert (NULL ==
1218                  channel_ctx->destruction_task);
1219   GNUNET_assert (NULL !=
1220                  channel_ctx->channel);
1221   channel_ctx->destruction_task =
1222     GNUNET_SCHEDULER_add_now (&destroy_channel_cb,
1223                               channel_ctx);
1224 }
1225
1226
1227 /**
1228  * @brief Remove peer
1229  *
1230  * - Empties the list with pending operations
1231  * - Empties the list with pending messages
1232  * - Cancels potentially existing online check
1233  * - Schedules closing of send and recv channels
1234  * - Removes peer from peer map
1235  *
1236  * @param peer_ctx Context of the peer to be destroyed
1237  * @return #GNUNET_YES if peer was removed
1238  *         #GNUNET_NO  otherwise
1239  */
1240 static int
1241 destroy_peer (struct PeerContext *peer_ctx)
1242 {
1243   GNUNET_assert (NULL != peer_ctx);
1244   GNUNET_assert (NULL != peer_ctx->sub->peer_map);
1245   if (GNUNET_NO ==
1246       GNUNET_CONTAINER_multipeermap_contains (peer_ctx->sub->peer_map,
1247                                               &peer_ctx->peer_id))
1248   {
1249     return GNUNET_NO;
1250   }
1251   SET_PEER_FLAG (peer_ctx, Peers_TO_DESTROY);
1252   LOG (GNUNET_ERROR_TYPE_DEBUG,
1253        "Going to remove peer %s\n",
1254        GNUNET_i2s (&peer_ctx->peer_id));
1255   UNSET_PEER_FLAG (peer_ctx, Peers_ONLINE);
1256
1257   /* Clear list of pending operations */
1258   // TODO this probably leaks memory
1259   //      ('only' the cls to the function. Not sure what to do with it)
1260   GNUNET_array_grow (peer_ctx->pending_ops,
1261                      peer_ctx->num_pending_ops,
1262                      0);
1263   /* Remove all pending messages */
1264   while (NULL != peer_ctx->pending_messages_head)
1265   {
1266     LOG (GNUNET_ERROR_TYPE_DEBUG,
1267          "Removing unsent %s\n",
1268          peer_ctx->pending_messages_head->type);
1269     /* Cancle pending message, too */
1270     if ( (NULL != peer_ctx->online_check_pending) &&
1271          (0 == memcmp (peer_ctx->pending_messages_head,
1272                      peer_ctx->online_check_pending,
1273                      sizeof (struct PendingMessage))) )
1274       {
1275         peer_ctx->online_check_pending = NULL;
1276         if (peer_ctx->sub == msub)
1277         {
1278           GNUNET_STATISTICS_update (stats,
1279                                     "# pending online checks",
1280                                     -1,
1281                                     GNUNET_NO);
1282         }
1283       }
1284     remove_pending_message (peer_ctx->pending_messages_head,
1285                             GNUNET_YES);
1286   }
1287
1288   /* If we are still waiting for notification whether this peer is online
1289    * cancel the according task */
1290   if (NULL != peer_ctx->online_check_pending)
1291   {
1292     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1293                 "Removing pending online check for peer %s\n",
1294                 GNUNET_i2s (&peer_ctx->peer_id));
1295     // TODO wait until cadet sets mq->cancel_impl
1296     //GNUNET_MQ_send_cancel (peer_ctx->online_check_pending->ev);
1297     remove_pending_message (peer_ctx->online_check_pending,
1298                             GNUNET_YES);
1299     peer_ctx->online_check_pending = NULL;
1300   }
1301
1302   if (NULL != peer_ctx->send_channel_ctx)
1303   {
1304     /* This is possibly called from within channel destruction */
1305     peer_ctx->send_channel_ctx->peer_ctx = NULL;
1306     schedule_channel_destruction (peer_ctx->send_channel_ctx);
1307     peer_ctx->send_channel_ctx = NULL;
1308     peer_ctx->mq = NULL;
1309   }
1310   if (NULL != peer_ctx->recv_channel_ctx)
1311   {
1312     /* This is possibly called from within channel destruction */
1313     peer_ctx->recv_channel_ctx->peer_ctx = NULL;
1314     schedule_channel_destruction (peer_ctx->recv_channel_ctx);
1315     peer_ctx->recv_channel_ctx = NULL;
1316   }
1317
1318   if (GNUNET_YES !=
1319       GNUNET_CONTAINER_multipeermap_remove_all (peer_ctx->sub->peer_map,
1320                                                 &peer_ctx->peer_id))
1321   {
1322     LOG (GNUNET_ERROR_TYPE_WARNING,
1323          "removing peer from peer_ctx->sub->peer_map failed\n");
1324   }
1325   if (peer_ctx->sub == msub)
1326   {
1327     GNUNET_STATISTICS_set (stats,
1328                           "# known peers",
1329                           GNUNET_CONTAINER_multipeermap_size (peer_ctx->sub->peer_map),
1330                           GNUNET_NO);
1331   }
1332   GNUNET_free (peer_ctx);
1333   return GNUNET_YES;
1334 }
1335
1336
1337 /**
1338  * Iterator over hash map entries. Deletes all contexts of peers.
1339  *
1340  * @param cls closure
1341  * @param key current public key
1342  * @param value value in the hash map
1343  * @return #GNUNET_YES if we should continue to iterate,
1344  *         #GNUNET_NO if not.
1345  */
1346 static int
1347 peermap_clear_iterator (void *cls,
1348                         const struct GNUNET_PeerIdentity *key,
1349                         void *value)
1350 {
1351   struct Sub *sub = cls;
1352   (void) value;
1353
1354   destroy_peer (get_peer_ctx (sub->peer_map, key));
1355   return GNUNET_YES;
1356 }
1357
1358
1359 /**
1360  * @brief This is called once a message is sent.
1361  *
1362  * Removes the pending message
1363  *
1364  * @param cls type of the message that was sent
1365  */
1366 static void
1367 mq_notify_sent_cb (void *cls)
1368 {
1369   struct PendingMessage *pending_msg = (struct PendingMessage *) cls;
1370   LOG (GNUNET_ERROR_TYPE_DEBUG,
1371       "%s was sent.\n",
1372       pending_msg->type);
1373   if (pending_msg->peer_ctx->sub == msub)
1374   {
1375     if (0 == strncmp ("PULL REPLY", pending_msg->type, 10))
1376       GNUNET_STATISTICS_update(stats, "# pull replys sent", 1, GNUNET_NO);
1377     if (0 == strncmp ("PULL REQUEST", pending_msg->type, 12))
1378       GNUNET_STATISTICS_update(stats, "# pull requests sent", 1, GNUNET_NO);
1379     if (0 == strncmp ("PUSH", pending_msg->type, 4))
1380       GNUNET_STATISTICS_update(stats, "# pushes sent", 1, GNUNET_NO);
1381     if (0 == strncmp ("PULL REQUEST", pending_msg->type, 12) &&
1382         GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
1383           &pending_msg->peer_ctx->peer_id))
1384       GNUNET_STATISTICS_update(stats,
1385                                "# pull requests sent (multi-hop peer)",
1386                                1,
1387                                GNUNET_NO);
1388   }
1389   /* Do not cancle message */
1390   remove_pending_message (pending_msg, GNUNET_NO);
1391 }
1392
1393
1394 /**
1395  * @brief Iterator function for #store_valid_peers.
1396  *
1397  * Implements #GNUNET_CONTAINER_PeerMapIterator.
1398  * Writes single peer to disk.
1399  *
1400  * @param cls the file handle to write to.
1401  * @param peer current peer
1402  * @param value unused
1403  *
1404  * @return  #GNUNET_YES if we should continue to
1405  *          iterate,
1406  *          #GNUNET_NO if not.
1407  */
1408 static int
1409 store_peer_presistently_iterator (void *cls,
1410                                   const struct GNUNET_PeerIdentity *peer,
1411                                   void *value)
1412 {
1413   const struct GNUNET_DISK_FileHandle *fh = cls;
1414   char peer_string[128];
1415   int size;
1416   ssize_t ret;
1417   (void) value;
1418
1419   if (NULL == peer)
1420   {
1421     return GNUNET_YES;
1422   }
1423   size = GNUNET_snprintf (peer_string,
1424                           sizeof (peer_string),
1425                           "%s\n",
1426                           GNUNET_i2s_full (peer));
1427   GNUNET_assert (53 == size);
1428   ret = GNUNET_DISK_file_write (fh,
1429                                 peer_string,
1430                                 size);
1431   GNUNET_assert (size == ret);
1432   return GNUNET_YES;
1433 }
1434
1435
1436 /**
1437  * @brief Store the peers currently in #valid_peers to disk.
1438  *
1439  * @param sub Sub for which to store the valid peers
1440  */
1441 static void
1442 store_valid_peers (const struct Sub *sub)
1443 {
1444   struct GNUNET_DISK_FileHandle *fh;
1445   uint32_t number_written_peers;
1446   int ret;
1447
1448   if (0 == strncmp ("DISABLE", sub->filename_valid_peers, 7))
1449   {
1450     return;
1451   }
1452
1453   ret = GNUNET_DISK_directory_create_for_file (sub->filename_valid_peers);
1454   if (GNUNET_SYSERR == ret)
1455   {
1456     LOG (GNUNET_ERROR_TYPE_WARNING,
1457         "Not able to create directory for file `%s'\n",
1458         sub->filename_valid_peers);
1459     GNUNET_break (0);
1460   }
1461   else if (GNUNET_NO == ret)
1462   {
1463     LOG (GNUNET_ERROR_TYPE_WARNING,
1464         "Directory for file `%s' exists but is not writable for us\n",
1465         sub->filename_valid_peers);
1466     GNUNET_break (0);
1467   }
1468   fh = GNUNET_DISK_file_open (sub->filename_valid_peers,
1469                               GNUNET_DISK_OPEN_WRITE |
1470                                   GNUNET_DISK_OPEN_CREATE,
1471                               GNUNET_DISK_PERM_USER_READ |
1472                                   GNUNET_DISK_PERM_USER_WRITE);
1473   if (NULL == fh)
1474   {
1475     LOG (GNUNET_ERROR_TYPE_WARNING,
1476         "Not able to write valid peers to file `%s'\n",
1477         sub->filename_valid_peers);
1478     return;
1479   }
1480   LOG (GNUNET_ERROR_TYPE_DEBUG,
1481       "Writing %u valid peers to disk\n",
1482       GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1483   number_written_peers =
1484     GNUNET_CONTAINER_multipeermap_iterate (sub->valid_peers,
1485                                            store_peer_presistently_iterator,
1486                                            fh);
1487   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1488   GNUNET_assert (number_written_peers ==
1489       GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1490 }
1491
1492
1493 /**
1494  * @brief Convert string representation of peer id to peer id.
1495  *
1496  * Counterpart to #GNUNET_i2s_full.
1497  *
1498  * @param string_repr The string representation of the peer id
1499  *
1500  * @return The peer id
1501  */
1502 static const struct GNUNET_PeerIdentity *
1503 s2i_full (const char *string_repr)
1504 {
1505   struct GNUNET_PeerIdentity *peer;
1506   size_t len;
1507   int ret;
1508
1509   peer = GNUNET_new (struct GNUNET_PeerIdentity);
1510   len = strlen (string_repr);
1511   if (52 > len)
1512   {
1513     LOG (GNUNET_ERROR_TYPE_WARNING,
1514         "Not able to convert string representation of PeerID to PeerID\n"
1515         "Sting representation: %s (len %lu) - too short\n",
1516         string_repr,
1517         len);
1518     GNUNET_break (0);
1519   }
1520   else if (52 < len)
1521   {
1522     len = 52;
1523   }
1524   ret = GNUNET_CRYPTO_eddsa_public_key_from_string (string_repr,
1525                                                     len,
1526                                                     &peer->public_key);
1527   if (GNUNET_OK != ret)
1528   {
1529     LOG (GNUNET_ERROR_TYPE_WARNING,
1530         "Not able to convert string representation of PeerID to PeerID\n"
1531         "Sting representation: %s\n",
1532         string_repr);
1533     GNUNET_break (0);
1534   }
1535   return peer;
1536 }
1537
1538
1539 /**
1540  * @brief Restore the peers on disk to #valid_peers.
1541  *
1542  * @param sub Sub for which to restore the valid peers
1543  */
1544 static void
1545 restore_valid_peers (const struct Sub *sub)
1546 {
1547   off_t file_size;
1548   uint32_t num_peers;
1549   struct GNUNET_DISK_FileHandle *fh;
1550   char *buf;
1551   ssize_t size_read;
1552   char *iter_buf;
1553   char *str_repr;
1554   const struct GNUNET_PeerIdentity *peer;
1555
1556   if (0 == strncmp ("DISABLE", sub->filename_valid_peers, 7))
1557   {
1558     return;
1559   }
1560
1561   if (GNUNET_OK != GNUNET_DISK_file_test (sub->filename_valid_peers))
1562   {
1563     return;
1564   }
1565   fh = GNUNET_DISK_file_open (sub->filename_valid_peers,
1566                               GNUNET_DISK_OPEN_READ,
1567                               GNUNET_DISK_PERM_NONE);
1568   GNUNET_assert (NULL != fh);
1569   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_handle_size (fh, &file_size));
1570   num_peers = file_size / 53;
1571   buf = GNUNET_malloc (file_size);
1572   size_read = GNUNET_DISK_file_read (fh, buf, file_size);
1573   GNUNET_assert (size_read == file_size);
1574   LOG (GNUNET_ERROR_TYPE_DEBUG,
1575       "Restoring %" PRIu32 " peers from file `%s'\n",
1576       num_peers,
1577       sub->filename_valid_peers);
1578   for (iter_buf = buf; iter_buf < buf + file_size - 1; iter_buf += 53)
1579   {
1580     str_repr = GNUNET_strndup (iter_buf, 53);
1581     peer = s2i_full (str_repr);
1582     GNUNET_free (str_repr);
1583     add_valid_peer (peer, sub->valid_peers);
1584     LOG (GNUNET_ERROR_TYPE_DEBUG,
1585         "Restored valid peer %s from disk\n",
1586         GNUNET_i2s_full (peer));
1587   }
1588   iter_buf = NULL;
1589   GNUNET_free (buf);
1590   LOG (GNUNET_ERROR_TYPE_DEBUG,
1591       "num_peers: %" PRIu32 ", _size (sub->valid_peers): %u\n",
1592       num_peers,
1593       GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1594   if (num_peers != GNUNET_CONTAINER_multipeermap_size (sub->valid_peers))
1595   {
1596     LOG (GNUNET_ERROR_TYPE_WARNING,
1597         "Number of restored peers does not match file size. Have probably duplicates.\n");
1598   }
1599   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1600   LOG (GNUNET_ERROR_TYPE_DEBUG,
1601       "Restored %u valid peers from disk\n",
1602       GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1603 }
1604
1605
1606 /**
1607  * @brief Delete storage of peers that was created with #initialise_peers ()
1608  *
1609  * @param sub Sub for which the storage is deleted
1610  */
1611 static void
1612 peers_terminate (struct Sub *sub)
1613 {
1614   if (GNUNET_SYSERR ==
1615       GNUNET_CONTAINER_multipeermap_iterate (sub->peer_map,
1616                                              &peermap_clear_iterator,
1617                                              sub))
1618   {
1619     LOG (GNUNET_ERROR_TYPE_WARNING,
1620         "Iteration destroying peers was aborted.\n");
1621   }
1622   GNUNET_CONTAINER_multipeermap_destroy (sub->peer_map);
1623   sub->peer_map = NULL;
1624   store_valid_peers (sub);
1625   GNUNET_free (sub->filename_valid_peers);
1626   sub->filename_valid_peers = NULL;
1627   GNUNET_CONTAINER_multipeermap_destroy (sub->valid_peers);
1628   sub->valid_peers = NULL;
1629 }
1630
1631
1632 /**
1633  * Iterator over #valid_peers hash map entries.
1634  *
1635  * @param cls Closure that contains iterator function and closure
1636  * @param peer current peer id
1637  * @param value value in the hash map - unused
1638  * @return #GNUNET_YES if we should continue to
1639  *         iterate,
1640  *         #GNUNET_NO if not.
1641  */
1642 static int
1643 valid_peer_iterator (void *cls,
1644                      const struct GNUNET_PeerIdentity *peer,
1645                      void *value)
1646 {
1647   struct PeersIteratorCls *it_cls = cls;
1648   (void) value;
1649
1650   return it_cls->iterator (it_cls->cls, peer);
1651 }
1652
1653
1654 /**
1655  * @brief Get all currently known, valid peer ids.
1656  *
1657  * @param valid_peers Peer map containing the valid peers in question
1658  * @param iterator function to call on each peer id
1659  * @param it_cls extra argument to @a iterator
1660  * @return the number of key value pairs processed,
1661  *         #GNUNET_SYSERR if it aborted iteration
1662  */
1663 static int
1664 get_valid_peers (struct GNUNET_CONTAINER_MultiPeerMap *valid_peers,
1665                  PeersIterator iterator,
1666                  void *it_cls)
1667 {
1668   struct PeersIteratorCls *cls;
1669   int ret;
1670
1671   cls = GNUNET_new (struct PeersIteratorCls);
1672   cls->iterator = iterator;
1673   cls->cls = it_cls;
1674   ret = GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
1675                                                valid_peer_iterator,
1676                                                cls);
1677   GNUNET_free (cls);
1678   return ret;
1679 }
1680
1681
1682 /**
1683  * @brief Add peer to known peers.
1684  *
1685  * This function is called on new peer_ids from 'external' sources
1686  * (client seed, cadet get_peers(), ...)
1687  *
1688  * @param sub Sub with the peer map that the @a peer will be added to
1689  * @param peer the new #GNUNET_PeerIdentity
1690  *
1691  * @return #GNUNET_YES if peer was inserted
1692  *         #GNUNET_NO  otherwise
1693  */
1694 static int
1695 insert_peer (struct Sub *sub,
1696              const struct GNUNET_PeerIdentity *peer)
1697 {
1698   if (GNUNET_YES == check_peer_known (sub->peer_map, peer))
1699   {
1700     return GNUNET_NO; /* We already know this peer - nothing to do */
1701   }
1702   (void) create_peer_ctx (sub, peer);
1703   return GNUNET_YES;
1704 }
1705
1706
1707 /**
1708  * @brief Check whether flags on a peer are set.
1709  *
1710  * @param peer_map Peer map that is expected to contain the @a peer
1711  * @param peer the peer to check the flag of
1712  * @param flags the flags to check
1713  *
1714  * @return #GNUNET_SYSERR if peer is not known
1715  *         #GNUNET_YES    if all given flags are set
1716  *         #GNUNET_NO     otherwise
1717  */
1718 static int
1719 check_peer_flag (const struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
1720                  const struct GNUNET_PeerIdentity *peer,
1721                  enum Peers_PeerFlags flags)
1722 {
1723   struct PeerContext *peer_ctx;
1724
1725   if (GNUNET_NO == check_peer_known (peer_map, peer))
1726   {
1727     return GNUNET_SYSERR;
1728   }
1729   peer_ctx = get_peer_ctx (peer_map, peer);
1730   return check_peer_flag_set (peer_ctx, flags);
1731 }
1732
1733 /**
1734  * @brief Try connecting to a peer to see whether it is online
1735  *
1736  * If not known yet, insert into known peers
1737  *
1738  * @param sub Sub which would contain the @a peer
1739  * @param peer the peer whose online is to be checked
1740  * @return #GNUNET_YES if the check was issued
1741  *         #GNUNET_NO  otherwise
1742  */
1743 static int
1744 issue_peer_online_check (struct Sub *sub,
1745                          const struct GNUNET_PeerIdentity *peer)
1746 {
1747   struct PeerContext *peer_ctx;
1748
1749   (void) insert_peer (sub, peer); // TODO even needed?
1750   peer_ctx = get_peer_ctx (sub->peer_map, peer);
1751   if ( (GNUNET_NO == check_peer_flag (sub->peer_map, peer, Peers_ONLINE)) &&
1752        (NULL == peer_ctx->online_check_pending) )
1753   {
1754     check_peer_online (peer_ctx);
1755     return GNUNET_YES;
1756   }
1757   return GNUNET_NO;
1758 }
1759
1760
1761 /**
1762  * @brief Check if peer is removable.
1763  *
1764  * Check if
1765  *  - a recv channel exists
1766  *  - there are pending messages
1767  *  - there is no pending pull reply
1768  *
1769  * @param peer_ctx Context of the peer in question
1770  * @return #GNUNET_YES    if peer is removable
1771  *         #GNUNET_NO     if peer is NOT removable
1772  *         #GNUNET_SYSERR if peer is not known
1773  */
1774 static int
1775 check_removable (const struct PeerContext *peer_ctx)
1776 {
1777   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_ctx->sub->peer_map,
1778                                                            &peer_ctx->peer_id))
1779   {
1780     return GNUNET_SYSERR;
1781   }
1782
1783   if ( (NULL != peer_ctx->recv_channel_ctx) ||
1784        (NULL != peer_ctx->pending_messages_head) ||
1785        (GNUNET_NO == check_peer_flag_set (peer_ctx, Peers_PULL_REPLY_PENDING)) )
1786   {
1787     return GNUNET_NO;
1788   }
1789   return GNUNET_YES;
1790 }
1791
1792
1793 /**
1794  * @brief Check whether @a peer is actually a peer.
1795  *
1796  * A valid peer is a peer that we know exists eg. we were connected to once.
1797  *
1798  * @param valid_peers Peer map that would contain the @a peer
1799  * @param peer peer in question
1800  *
1801  * @return #GNUNET_YES if peer is valid
1802  *         #GNUNET_NO  if peer is not valid
1803  */
1804 static int
1805 check_peer_valid (const struct GNUNET_CONTAINER_MultiPeerMap *valid_peers,
1806                   const struct GNUNET_PeerIdentity *peer)
1807 {
1808   return GNUNET_CONTAINER_multipeermap_contains (valid_peers, peer);
1809 }
1810
1811
1812 /**
1813  * @brief Indicate that we want to send to the other peer
1814  *
1815  * This establishes a sending channel
1816  *
1817  * @param peer_ctx Context of the target peer
1818  */
1819 static void
1820 indicate_sending_intention (struct PeerContext *peer_ctx)
1821 {
1822   GNUNET_assert (GNUNET_YES == check_peer_known (peer_ctx->sub->peer_map,
1823                                                  &peer_ctx->peer_id));
1824   (void) get_channel (peer_ctx);
1825 }
1826
1827
1828 /**
1829  * @brief Check whether other peer has the intention to send/opened channel
1830  *        towars us
1831  *
1832  * @param peer_ctx Context of the peer in question
1833  *
1834  * @return #GNUNET_YES if peer has the intention to send
1835  *         #GNUNET_NO  otherwise
1836  */
1837 static int
1838 check_peer_send_intention (const struct PeerContext *peer_ctx)
1839 {
1840   if (NULL != peer_ctx->recv_channel_ctx)
1841   {
1842     return GNUNET_YES;
1843   }
1844   return GNUNET_NO;
1845 }
1846
1847
1848 /**
1849  * Handle the channel a peer opens to us.
1850  *
1851  * @param cls The closure - Sub
1852  * @param channel The channel the peer wants to establish
1853  * @param initiator The peer's peer ID
1854  *
1855  * @return initial channel context for the channel
1856  *         (can be NULL -- that's not an error)
1857  */
1858 static void *
1859 handle_inbound_channel (void *cls,
1860                         struct GNUNET_CADET_Channel *channel,
1861                         const struct GNUNET_PeerIdentity *initiator)
1862 {
1863   struct PeerContext *peer_ctx;
1864   struct ChannelCtx *channel_ctx;
1865   struct Sub *sub = cls;
1866
1867   LOG (GNUNET_ERROR_TYPE_DEBUG,
1868       "New channel was established to us (Peer %s).\n",
1869       GNUNET_i2s (initiator));
1870   GNUNET_assert (NULL != channel); /* according to cadet API */
1871   /* Make sure we 'know' about this peer */
1872   peer_ctx = create_or_get_peer_ctx (sub, initiator);
1873   set_peer_online (peer_ctx);
1874   (void) add_valid_peer (&peer_ctx->peer_id, peer_ctx->sub->valid_peers);
1875   channel_ctx = add_channel_ctx (peer_ctx);
1876   channel_ctx->channel = channel;
1877   /* We only accept one incoming channel per peer */
1878   if (GNUNET_YES == check_peer_send_intention (get_peer_ctx (sub->peer_map,
1879                                                              initiator)))
1880   {
1881     LOG (GNUNET_ERROR_TYPE_WARNING,
1882         "Already got one receive channel. Destroying old one.\n");
1883     GNUNET_break_op (0);
1884     destroy_channel (peer_ctx->recv_channel_ctx);
1885     peer_ctx->recv_channel_ctx = channel_ctx;
1886     /* return the channel context */
1887     return channel_ctx;
1888   }
1889   peer_ctx->recv_channel_ctx = channel_ctx;
1890   return channel_ctx;
1891 }
1892
1893
1894 /**
1895  * @brief Check whether a sending channel towards the given peer exists
1896  *
1897  * @param peer_ctx Context of the peer in question
1898  *
1899  * @return #GNUNET_YES if a sending channel towards that peer exists
1900  *         #GNUNET_NO  otherwise
1901  */
1902 static int
1903 check_sending_channel_exists (const struct PeerContext *peer_ctx)
1904 {
1905   if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
1906                                      &peer_ctx->peer_id))
1907   { /* If no such peer exists, there is no channel */
1908     return GNUNET_NO;
1909   }
1910   if (NULL == peer_ctx->send_channel_ctx)
1911   {
1912     return GNUNET_NO;
1913   }
1914   return GNUNET_YES;
1915 }
1916
1917
1918 /**
1919  * @brief Destroy the send channel of a peer e.g. stop indicating a sending
1920  *        intention to another peer
1921  *
1922  * @param peer_ctx Context to the peer
1923  * @return #GNUNET_YES if channel was destroyed
1924  *         #GNUNET_NO  otherwise
1925  */
1926 static int
1927 destroy_sending_channel (struct PeerContext *peer_ctx)
1928 {
1929   if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
1930                                      &peer_ctx->peer_id))
1931   {
1932     return GNUNET_NO;
1933   }
1934   if (NULL != peer_ctx->send_channel_ctx)
1935   {
1936     destroy_channel (peer_ctx->send_channel_ctx);
1937     (void) check_connected (peer_ctx);
1938     return GNUNET_YES;
1939   }
1940   return GNUNET_NO;
1941 }
1942
1943 /**
1944  * @brief Send a message to another peer.
1945  *
1946  * Keeps track about pending messages so they can be properly removed when the
1947  * peer is destroyed.
1948  *
1949  * @param peer_ctx Context of the peer to which the message is to be sent
1950  * @param ev envelope of the message
1951  * @param type type of the message
1952  */
1953 static void
1954 send_message (struct PeerContext *peer_ctx,
1955               struct GNUNET_MQ_Envelope *ev,
1956               const char *type)
1957 {
1958   struct PendingMessage *pending_msg;
1959   struct GNUNET_MQ_Handle *mq;
1960
1961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1962               "Sending message to %s of type %s\n",
1963               GNUNET_i2s (&peer_ctx->peer_id),
1964               type);
1965   pending_msg = insert_pending_message (peer_ctx, ev, type);
1966   mq = get_mq (peer_ctx);
1967   GNUNET_MQ_notify_sent (ev,
1968                          mq_notify_sent_cb,
1969                          pending_msg);
1970   GNUNET_MQ_send (mq, ev);
1971 }
1972
1973 /**
1974  * @brief Schedule a operation on given peer
1975  *
1976  * Avoids scheduling an operation twice.
1977  *
1978  * @param peer_ctx Context of the peer for which to schedule the operation
1979  * @param peer_op the operation to schedule
1980  * @param cls Closure to @a peer_op
1981  *
1982  * @return #GNUNET_YES if the operation was scheduled
1983  *         #GNUNET_NO  otherwise
1984  */
1985 static int
1986 schedule_operation (struct PeerContext *peer_ctx,
1987                     const PeerOp peer_op,
1988                     void *cls)
1989 {
1990   struct PeerPendingOp pending_op;
1991
1992   GNUNET_assert (GNUNET_YES == check_peer_known (peer_ctx->sub->peer_map,
1993                                                  &peer_ctx->peer_id));
1994
1995   //TODO if ONLINE execute immediately
1996
1997   if (GNUNET_NO == check_operation_scheduled (peer_ctx, peer_op))
1998   {
1999     pending_op.op = peer_op;
2000     pending_op.op_cls = cls;
2001     GNUNET_array_append (peer_ctx->pending_ops,
2002                          peer_ctx->num_pending_ops,
2003                          pending_op);
2004     return GNUNET_YES;
2005   }
2006   return GNUNET_NO;
2007 }
2008
2009 /***********************************************************************
2010  * /Old gnunet-service-rps_peers.c
2011 ***********************************************************************/
2012
2013
2014 /***********************************************************************
2015  * Housekeeping with clients
2016 ***********************************************************************/
2017
2018 /**
2019  * Closure used to pass the client and the id to the callback
2020  * that replies to a client's request
2021  */
2022 struct ReplyCls
2023 {
2024   /**
2025    * DLL
2026    */
2027   struct ReplyCls *next;
2028   struct ReplyCls *prev;
2029
2030   /**
2031    * The identifier of the request
2032    */
2033   uint32_t id;
2034
2035   /**
2036    * The handle to the request
2037    */
2038   struct RPS_SamplerRequestHandle *req_handle;
2039
2040   /**
2041    * The client handle to send the reply to
2042    */
2043   struct ClientContext *cli_ctx;
2044 };
2045
2046
2047 /**
2048  * Struct used to store the context of a connected client.
2049  */
2050 struct ClientContext
2051 {
2052   /**
2053    * DLL
2054    */
2055   struct ClientContext *next;
2056   struct ClientContext *prev;
2057
2058   /**
2059    * The message queue to communicate with the client.
2060    */
2061   struct GNUNET_MQ_Handle *mq;
2062
2063   /**
2064    * @brief How many updates this client expects to receive.
2065    */
2066   int64_t view_updates_left;
2067
2068   /**
2069    * @brief Whether this client wants to receive stream updates.
2070    * Either #GNUNET_YES or #GNUNET_NO
2071    */
2072   int8_t stream_update;
2073
2074   /**
2075    * The client handle to send the reply to
2076    */
2077   struct GNUNET_SERVICE_Client *client;
2078
2079   /**
2080    * The #Sub this context belongs to
2081    */
2082   struct Sub *sub;
2083 };
2084
2085 /**
2086  * DLL with all clients currently connected to us
2087  */
2088 struct ClientContext *cli_ctx_head;
2089 struct ClientContext *cli_ctx_tail;
2090
2091 /***********************************************************************
2092  * /Housekeeping with clients
2093 ***********************************************************************/
2094
2095
2096
2097
2098
2099 /***********************************************************************
2100  * Util functions
2101 ***********************************************************************/
2102
2103
2104 /**
2105  * Print peerlist to log.
2106  */
2107 static void
2108 print_peer_list (struct GNUNET_PeerIdentity *list,
2109                  unsigned int len)
2110 {
2111   unsigned int i;
2112
2113   LOG (GNUNET_ERROR_TYPE_DEBUG,
2114        "Printing peer list of length %u at %p:\n",
2115        len,
2116        list);
2117   for (i = 0 ; i < len ; i++)
2118   {
2119     LOG (GNUNET_ERROR_TYPE_DEBUG,
2120          "%u. peer: %s\n",
2121          i, GNUNET_i2s (&list[i]));
2122   }
2123 }
2124
2125
2126 /**
2127  * Remove peer from list.
2128  */
2129 static void
2130 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
2131                unsigned int *list_size,
2132                const struct GNUNET_PeerIdentity *peer)
2133 {
2134   unsigned int i;
2135   struct GNUNET_PeerIdentity *tmp;
2136
2137   tmp = *peer_list;
2138
2139   LOG (GNUNET_ERROR_TYPE_DEBUG,
2140        "Removing peer %s from list at %p\n",
2141        GNUNET_i2s (peer),
2142        tmp);
2143
2144   for ( i = 0 ; i < *list_size ; i++ )
2145   {
2146     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
2147     {
2148       if (i < *list_size -1)
2149       { /* Not at the last entry -- shift peers left */
2150         memmove (&tmp[i], &tmp[i +1],
2151                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
2152       }
2153       /* Remove last entry (should be now useless PeerID) */
2154       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
2155     }
2156   }
2157   *peer_list = tmp;
2158 }
2159
2160
2161 /**
2162  * Insert PeerID in #view
2163  *
2164  * Called once we know a peer is online.
2165  * Implements #PeerOp
2166  *
2167  * @return GNUNET_OK if peer was actually inserted
2168  *         GNUNET_NO if peer was not inserted
2169  */
2170 static void
2171 insert_in_view_op (void *cls,
2172                    const struct GNUNET_PeerIdentity *peer);
2173
2174 /**
2175  * Insert PeerID in #view
2176  *
2177  * Called once we know a peer is online.
2178  *
2179  * @param sub Sub in with the view to insert in
2180  * @param peer the peer to insert
2181  *
2182  * @return GNUNET_OK if peer was actually inserted
2183  *         GNUNET_NO if peer was not inserted
2184  */
2185 static int
2186 insert_in_view (struct Sub *sub,
2187                 const struct GNUNET_PeerIdentity *peer)
2188 {
2189   struct PeerContext *peer_ctx;
2190   int online;
2191   int ret;
2192
2193   online = check_peer_flag (sub->peer_map, peer, Peers_ONLINE);
2194   peer_ctx = get_peer_ctx (sub->peer_map, peer); // TODO indirection needed?
2195   if ( (GNUNET_NO == online) ||
2196        (GNUNET_SYSERR == online) ) /* peer is not even known */
2197   {
2198     (void) issue_peer_online_check (sub, peer);
2199     (void) schedule_operation (peer_ctx, insert_in_view_op, sub);
2200     return GNUNET_NO;
2201   }
2202   /* Open channel towards peer to keep connection open */
2203   indicate_sending_intention (peer_ctx);
2204   ret = View_put (sub->view, peer);
2205   if (peer_ctx->sub == msub)
2206   {
2207     GNUNET_STATISTICS_set (stats,
2208                            "view size",
2209                            View_size (peer_ctx->sub->view),
2210                            GNUNET_NO);
2211   }
2212   return ret;
2213 }
2214
2215
2216 /**
2217  * @brief Send view to client
2218  *
2219  * @param cli_ctx the context of the client
2220  * @param view_array the peerids of the view as array (can be empty)
2221  * @param view_size the size of the view array (can be 0)
2222  */
2223 static void
2224 send_view (const struct ClientContext *cli_ctx,
2225            const struct GNUNET_PeerIdentity *view_array,
2226            uint64_t view_size)
2227 {
2228   struct GNUNET_MQ_Envelope *ev;
2229   struct GNUNET_RPS_CS_DEBUG_ViewReply *out_msg;
2230   struct Sub *sub;
2231
2232   if (NULL == view_array)
2233   {
2234     if (NULL == cli_ctx->sub) sub = msub;
2235     else sub = cli_ctx->sub;
2236     view_size = View_size (sub->view);
2237     view_array = View_get_as_array (sub->view);
2238   }
2239
2240   ev = GNUNET_MQ_msg_extra (out_msg,
2241                             view_size * sizeof (struct GNUNET_PeerIdentity),
2242                             GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REPLY);
2243   out_msg->num_peers = htonl (view_size);
2244
2245   GNUNET_memcpy (&out_msg[1],
2246                  view_array,
2247                  view_size * sizeof (struct GNUNET_PeerIdentity));
2248   GNUNET_MQ_send (cli_ctx->mq, ev);
2249 }
2250
2251
2252 /**
2253  * @brief Send peer from biased stream to client.
2254  *
2255  * TODO merge with send_view, parameterise
2256  *
2257  * @param cli_ctx the context of the client
2258  * @param view_array the peerids of the view as array (can be empty)
2259  * @param view_size the size of the view array (can be 0)
2260  */
2261 static void
2262 send_stream_peers (const struct ClientContext *cli_ctx,
2263                    uint64_t num_peers,
2264                    const struct GNUNET_PeerIdentity *peers)
2265 {
2266   struct GNUNET_MQ_Envelope *ev;
2267   struct GNUNET_RPS_CS_DEBUG_StreamReply *out_msg;
2268
2269   GNUNET_assert (NULL != peers);
2270
2271   ev = GNUNET_MQ_msg_extra (out_msg,
2272                             num_peers * sizeof (struct GNUNET_PeerIdentity),
2273                             GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_REPLY);
2274   out_msg->num_peers = htonl (num_peers);
2275
2276   GNUNET_memcpy (&out_msg[1],
2277                  peers,
2278                  num_peers * sizeof (struct GNUNET_PeerIdentity));
2279   GNUNET_MQ_send (cli_ctx->mq, ev);
2280 }
2281
2282
2283 /**
2284  * @brief sends updates to clients that are interested
2285  *
2286  * @param sub Sub for which to notify clients
2287  */
2288 static void
2289 clients_notify_view_update (const struct Sub *sub)
2290 {
2291   struct ClientContext *cli_ctx_iter;
2292   uint64_t num_peers;
2293   const struct GNUNET_PeerIdentity *view_array;
2294
2295   num_peers = View_size (sub->view);
2296   view_array = View_get_as_array(sub->view);
2297   /* check size of view is small enough */
2298   if (GNUNET_MAX_MESSAGE_SIZE < num_peers)
2299   {
2300     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2301                 "View is too big to send\n");
2302     return;
2303   }
2304
2305   for (cli_ctx_iter = cli_ctx_head;
2306        NULL != cli_ctx_iter;
2307        cli_ctx_iter = cli_ctx_iter->next)
2308   {
2309     if (1 < cli_ctx_iter->view_updates_left)
2310     {
2311       /* Client wants to receive limited amount of updates */
2312       cli_ctx_iter->view_updates_left -= 1;
2313     } else if (1 == cli_ctx_iter->view_updates_left)
2314     {
2315       /* Last update of view for client */
2316       cli_ctx_iter->view_updates_left = -1;
2317     } else if (0 > cli_ctx_iter->view_updates_left) {
2318       /* Client is not interested in updates */
2319       continue;
2320     }
2321     /* else _updates_left == 0 - infinite amount of updates */
2322
2323     /* send view */
2324     send_view (cli_ctx_iter, view_array, num_peers);
2325   }
2326 }
2327
2328
2329 /**
2330  * @brief sends updates to clients that are interested
2331  *
2332  * @param num_peers Number of peers to send
2333  * @param peers the array of peers to send
2334  */
2335 static void
2336 clients_notify_stream_peer (const struct Sub *sub,
2337                             uint64_t num_peers,
2338                             const struct GNUNET_PeerIdentity *peers)
2339                             // TODO enum StreamPeerSource)
2340 {
2341   struct ClientContext *cli_ctx_iter;
2342
2343   LOG (GNUNET_ERROR_TYPE_DEBUG,
2344       "Got peer (%s) from biased stream - update all clients\n",
2345       GNUNET_i2s (peers));
2346
2347   for (cli_ctx_iter = cli_ctx_head;
2348        NULL != cli_ctx_iter;
2349        cli_ctx_iter = cli_ctx_iter->next)
2350   {
2351     if (GNUNET_YES == cli_ctx_iter->stream_update &&
2352         (sub == cli_ctx_iter->sub || sub == msub))
2353     {
2354       send_stream_peers (cli_ctx_iter, num_peers, peers);
2355     }
2356   }
2357 }
2358
2359
2360 /**
2361  * Put random peer from sampler into the view as history update.
2362  *
2363  * @param ids Array of Peers to insert into view
2364  * @param num_peers Number of peers to insert
2365  * @param cls Closure - The Sub for which this is to be done
2366  */
2367 static void
2368 hist_update (const struct GNUNET_PeerIdentity *ids,
2369              uint32_t num_peers,
2370              void *cls)
2371 {
2372   unsigned int i;
2373   struct Sub *sub = cls;
2374
2375   for (i = 0; i < num_peers; i++)
2376   {
2377     int inserted;
2378     inserted = insert_in_view (sub, &ids[i]);
2379     if (GNUNET_OK == inserted)
2380     {
2381       clients_notify_stream_peer (sub, 1, &ids[i]);
2382     }
2383     to_file (sub->file_name_view_log,
2384              "+%s\t(hist)",
2385              GNUNET_i2s_full (ids));
2386   }
2387   clients_notify_view_update (sub);
2388 }
2389
2390
2391 /**
2392  * Wrapper around #RPS_sampler_resize()
2393  *
2394  * If we do not have enough sampler elements, double current sampler size
2395  * If we have more than enough sampler elements, halv current sampler size
2396  *
2397  * @param sampler The sampler to resize
2398  * @param new_size New size to which to resize
2399  */
2400 static void
2401 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
2402 {
2403   unsigned int sampler_size;
2404
2405   // TODO statistics
2406   // TODO respect the min, max
2407   sampler_size = RPS_sampler_get_size (sampler);
2408   if (sampler_size > new_size * 4)
2409   { /* Shrinking */
2410     RPS_sampler_resize (sampler, sampler_size / 2);
2411   }
2412   else if (sampler_size < new_size)
2413   { /* Growing */
2414     RPS_sampler_resize (sampler, sampler_size * 2);
2415   }
2416   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
2417 }
2418
2419
2420 /**
2421  * Add all peers in @a peer_array to @a peer_map used as set.
2422  *
2423  * @param peer_array array containing the peers
2424  * @param num_peers number of peers in @peer_array
2425  * @param peer_map the peermap to use as set
2426  */
2427 static void
2428 add_peer_array_to_set (const struct GNUNET_PeerIdentity *peer_array,
2429                        unsigned int num_peers,
2430                        struct GNUNET_CONTAINER_MultiPeerMap *peer_map)
2431 {
2432   unsigned int i;
2433   if (NULL == peer_map)
2434   {
2435     LOG (GNUNET_ERROR_TYPE_WARNING,
2436          "Trying to add peers to non-existing peermap.\n");
2437     return;
2438   }
2439
2440   for (i = 0; i < num_peers; i++)
2441   {
2442     GNUNET_CONTAINER_multipeermap_put (peer_map,
2443                                        &peer_array[i],
2444                                        NULL,
2445                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2446     if (msub->peer_map == peer_map)
2447     {
2448       GNUNET_STATISTICS_set (stats,
2449                             "# known peers",
2450                             GNUNET_CONTAINER_multipeermap_size (peer_map),
2451                             GNUNET_NO);
2452     }
2453   }
2454 }
2455
2456
2457 /**
2458  * Send a PULL REPLY to @a peer_id
2459  *
2460  * @param peer_ctx Context of the peer to send the reply to
2461  * @param peer_ids the peers to send to @a peer_id
2462  * @param num_peer_ids the number of peers to send to @a peer_id
2463  */
2464 static void
2465 send_pull_reply (struct PeerContext *peer_ctx,
2466                  const struct GNUNET_PeerIdentity *peer_ids,
2467                  unsigned int num_peer_ids)
2468 {
2469   uint32_t send_size;
2470   struct GNUNET_MQ_Envelope *ev;
2471   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
2472
2473   /* Compute actual size */
2474   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
2475               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
2476
2477   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
2478     /* Compute number of peers to send
2479      * If too long, simply truncate */
2480     // TODO select random ones via permutation
2481     //      or even better: do good protocol design
2482     send_size =
2483       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
2484        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
2485        sizeof (struct GNUNET_PeerIdentity);
2486   else
2487     send_size = num_peer_ids;
2488
2489   LOG (GNUNET_ERROR_TYPE_DEBUG,
2490       "Going to send PULL REPLY with %u peers to %s\n",
2491       send_size, GNUNET_i2s (&peer_ctx->peer_id));
2492
2493   ev = GNUNET_MQ_msg_extra (out_msg,
2494                             send_size * sizeof (struct GNUNET_PeerIdentity),
2495                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
2496   out_msg->num_peers = htonl (send_size);
2497   GNUNET_memcpy (&out_msg[1], peer_ids,
2498          send_size * sizeof (struct GNUNET_PeerIdentity));
2499
2500   send_message (peer_ctx, ev, "PULL REPLY");
2501   if (peer_ctx->sub == msub)
2502   {
2503     GNUNET_STATISTICS_update(stats, "# pull reply send issued", 1, GNUNET_NO);
2504   }
2505   // TODO check with send intention: as send_channel is used/opened we indicate
2506   // a sending intention without intending it.
2507   // -> clean peer afterwards?
2508   // -> use recv_channel?
2509 }
2510
2511
2512 /**
2513  * Insert PeerID in #pull_map
2514  *
2515  * Called once we know a peer is online.
2516  *
2517  * @param cls Closure - Sub with the pull map to insert into
2518  * @param peer Peer to insert
2519  */
2520 static void
2521 insert_in_pull_map (void *cls,
2522                     const struct GNUNET_PeerIdentity *peer)
2523 {
2524   struct Sub *sub = cls;
2525
2526   CustomPeerMap_put (sub->pull_map, peer);
2527 }
2528
2529
2530 /**
2531  * Insert PeerID in #view
2532  *
2533  * Called once we know a peer is online.
2534  * Implements #PeerOp
2535  *
2536  * @param cls Closure - Sub with view to insert peer into
2537  * @param peer the peer to insert
2538  */
2539 static void
2540 insert_in_view_op (void *cls,
2541                    const struct GNUNET_PeerIdentity *peer)
2542 {
2543   struct Sub *sub = cls;
2544   int inserted;
2545
2546   inserted = insert_in_view (sub, peer);
2547   if (GNUNET_OK == inserted)
2548   {
2549     clients_notify_stream_peer (sub, 1, peer);
2550   }
2551 }
2552
2553
2554 /**
2555  * Update sampler with given PeerID.
2556  * Implements #PeerOp
2557  *
2558  * @param cls Closure - Sub containing the sampler to insert into
2559  * @param peer Peer to insert
2560  */
2561 static void
2562 insert_in_sampler (void *cls,
2563                    const struct GNUNET_PeerIdentity *peer)
2564 {
2565   struct Sub *sub = cls;
2566
2567   LOG (GNUNET_ERROR_TYPE_DEBUG,
2568        "Updating samplers with peer %s from insert_in_sampler()\n",
2569        GNUNET_i2s (peer));
2570   RPS_sampler_update (sub->sampler, peer);
2571   if (0 < RPS_sampler_count_id (sub->sampler, peer))
2572   {
2573     /* Make sure we 'know' about this peer */
2574     (void) issue_peer_online_check (sub, peer);
2575     /* Establish a channel towards that peer to indicate we are going to send
2576      * messages to it */
2577     //indicate_sending_intention (peer);
2578   }
2579 #ifdef TO_FILE
2580   sub->num_observed_peers++;
2581   GNUNET_CONTAINER_multipeermap_put
2582     (sub->observed_unique_peers,
2583      peer,
2584      NULL,
2585      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2586   uint32_t num_observed_unique_peers =
2587     GNUNET_CONTAINER_multipeermap_size (sub->observed_unique_peers);
2588   to_file (sub->file_name_observed_log,
2589           "%" PRIu32 " %" PRIu32 " %f\n",
2590           sub->num_observed_peers,
2591           num_observed_unique_peers,
2592           1.0*num_observed_unique_peers/sub->num_observed_peers)
2593 #endif /* TO_FILE */
2594 }
2595
2596
2597 /**
2598  * @brief This is called on peers from external sources (cadet, peerinfo, ...)
2599  *        If the peer is not known, online check is issued and it is
2600  *        scheduled to be inserted in sampler and view.
2601  *
2602  * "External sources" refer to every source except the gossip.
2603  *
2604  * @param sub Sub for which @a peer was received
2605  * @param peer peer to insert/peer received
2606  */
2607 static void
2608 got_peer (struct Sub *sub,
2609           const struct GNUNET_PeerIdentity *peer)
2610 {
2611   /* If we did not know this peer already, insert it into sampler and view */
2612   if (GNUNET_YES == issue_peer_online_check (sub, peer))
2613   {
2614     schedule_operation (get_peer_ctx (sub->peer_map, peer),
2615                         &insert_in_sampler, sub);
2616     schedule_operation (get_peer_ctx (sub->peer_map, peer),
2617                         &insert_in_view_op, sub);
2618   }
2619   if (sub == msub)
2620   {
2621     GNUNET_STATISTICS_update (stats,
2622                               "# learnd peers",
2623                               1,
2624                               GNUNET_NO);
2625   }
2626 }
2627
2628
2629 /**
2630  * @brief Checks if there is a sending channel and if it is needed
2631  *
2632  * @param peer_ctx Context of the peer to check
2633  * @return GNUNET_YES if sending channel exists and is still needed
2634  *         GNUNET_NO  otherwise
2635  */
2636 static int
2637 check_sending_channel_needed (const struct PeerContext *peer_ctx)
2638 {
2639   /* struct GNUNET_CADET_Channel *channel; */
2640   if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
2641                                      &peer_ctx->peer_id))
2642   {
2643     return GNUNET_NO;
2644   }
2645   if (GNUNET_YES == check_sending_channel_exists (peer_ctx))
2646   {
2647     if ( (0 < RPS_sampler_count_id (peer_ctx->sub->sampler,
2648                                     &peer_ctx->peer_id)) ||
2649          (GNUNET_YES == View_contains_peer (peer_ctx->sub->view,
2650                                             &peer_ctx->peer_id)) ||
2651          (GNUNET_YES == CustomPeerMap_contains_peer (peer_ctx->sub->push_map,
2652                                                      &peer_ctx->peer_id)) ||
2653          (GNUNET_YES == CustomPeerMap_contains_peer (peer_ctx->sub->pull_map,
2654                                                      &peer_ctx->peer_id)) ||
2655          (GNUNET_YES == check_peer_flag (peer_ctx->sub->peer_map,
2656                                          &peer_ctx->peer_id,
2657                                          Peers_PULL_REPLY_PENDING)))
2658     { /* If we want to keep the connection to peer open */
2659       return GNUNET_YES;
2660     }
2661     return GNUNET_NO;
2662   }
2663   return GNUNET_NO;
2664 }
2665
2666
2667 /**
2668  * @brief remove peer from our knowledge, the view, push and pull maps and
2669  * samplers.
2670  *
2671  * @param sub Sub with the data structures the peer is to be removed from
2672  * @param peer the peer to remove
2673  */
2674 static void
2675 remove_peer (struct Sub *sub,
2676              const struct GNUNET_PeerIdentity *peer)
2677 {
2678   (void) View_remove_peer (sub->view, peer);
2679   CustomPeerMap_remove_peer (sub->pull_map, peer);
2680   CustomPeerMap_remove_peer (sub->push_map, peer);
2681   RPS_sampler_reinitialise_by_value (sub->sampler, peer);
2682   destroy_peer (get_peer_ctx (sub->peer_map, peer));
2683 }
2684
2685
2686 /**
2687  * @brief Remove data that is not needed anymore.
2688  *
2689  * If the sending channel is no longer needed it is destroyed.
2690  *
2691  * @param sub Sub in which the current peer is to be cleaned
2692  * @param peer the peer whose data is about to be cleaned
2693  */
2694 static void
2695 clean_peer (struct Sub *sub,
2696             const struct GNUNET_PeerIdentity *peer)
2697 {
2698   if (GNUNET_NO == check_sending_channel_needed (get_peer_ctx (sub->peer_map,
2699                                                                peer)))
2700   {
2701     LOG (GNUNET_ERROR_TYPE_DEBUG,
2702         "Going to remove send channel to peer %s\n",
2703         GNUNET_i2s (peer));
2704     #if ENABLE_MALICIOUS
2705     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
2706       (void) destroy_sending_channel (get_peer_ctx (sub->peer_map, peer));
2707     #else /* ENABLE_MALICIOUS */
2708     (void) destroy_sending_channel (get_peer_ctx (sub->peer_map, peer));
2709     #endif /* ENABLE_MALICIOUS */
2710   }
2711
2712   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (sub->peer_map, peer))
2713   {
2714     /* Peer was already removed by callback on destroyed channel */
2715     LOG (GNUNET_ERROR_TYPE_WARNING,
2716         "Peer was removed from our knowledge during cleanup\n");
2717     return;
2718   }
2719
2720   if ( (GNUNET_NO == check_peer_send_intention (get_peer_ctx (sub->peer_map,
2721                                                               peer))) &&
2722        (GNUNET_NO == View_contains_peer (sub->view, peer)) &&
2723        (GNUNET_NO == CustomPeerMap_contains_peer (sub->push_map, peer)) &&
2724        (GNUNET_NO == CustomPeerMap_contains_peer (sub->push_map, peer)) &&
2725        (0 == RPS_sampler_count_id (sub->sampler,   peer)) &&
2726        (GNUNET_NO != check_removable (get_peer_ctx (sub->peer_map, peer))) )
2727   { /* We can safely remove this peer */
2728     LOG (GNUNET_ERROR_TYPE_DEBUG,
2729         "Going to remove peer %s\n",
2730         GNUNET_i2s (peer));
2731     remove_peer (sub, peer);
2732     return;
2733   }
2734 }
2735
2736
2737 /**
2738  * @brief This is called when a channel is destroyed.
2739  *
2740  * Removes peer completely from our knowledge if the send_channel was destroyed
2741  * Otherwise simply delete the recv_channel
2742  * Also check if the knowledge about this peer is still needed.
2743  * If not, remove this peer from our knowledge.
2744  *
2745  * @param cls The closure - Context to the channel
2746  * @param channel The channel being closed
2747  */
2748 static void
2749 cleanup_destroyed_channel (void *cls,
2750                            const struct GNUNET_CADET_Channel *channel)
2751 {
2752   struct ChannelCtx *channel_ctx = cls;
2753   struct PeerContext *peer_ctx = channel_ctx->peer_ctx;
2754   (void) channel;
2755
2756   channel_ctx->channel = NULL;
2757   remove_channel_ctx (channel_ctx);
2758   if (NULL != peer_ctx &&
2759       peer_ctx->send_channel_ctx == channel_ctx &&
2760       GNUNET_YES == check_sending_channel_needed (channel_ctx->peer_ctx))
2761   {
2762     remove_peer (peer_ctx->sub, &peer_ctx->peer_id);
2763   }
2764 }
2765
2766 /***********************************************************************
2767  * /Util functions
2768 ***********************************************************************/
2769
2770
2771
2772 /***********************************************************************
2773  * Sub
2774 ***********************************************************************/
2775
2776 /**
2777  * @brief Create a new Sub
2778  *
2779  * @param hash Hash of value shared among rps instances on other hosts that
2780  *        defines a subgroup to sample from.
2781  * @param sampler_size Size of the sampler
2782  * @param round_interval Interval (in average) between two rounds
2783  *
2784  * @return Sub
2785  */
2786 struct Sub *
2787 new_sub (const struct GNUNET_HashCode *hash,
2788          uint32_t sampler_size,
2789          struct GNUNET_TIME_Relative round_interval)
2790 {
2791   struct Sub *sub;
2792
2793   sub = GNUNET_new (struct Sub);
2794
2795   /* With the hash generated from the secret value this service only connects
2796    * to rps instances that share the value */
2797   struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
2798     GNUNET_MQ_hd_fixed_size (peer_check,
2799                              GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE,
2800                              struct GNUNET_MessageHeader,
2801                              NULL),
2802     GNUNET_MQ_hd_fixed_size (peer_push,
2803                              GNUNET_MESSAGE_TYPE_RPS_PP_PUSH,
2804                              struct GNUNET_MessageHeader,
2805                              NULL),
2806     GNUNET_MQ_hd_fixed_size (peer_pull_request,
2807                              GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2808                              struct GNUNET_MessageHeader,
2809                              NULL),
2810     GNUNET_MQ_hd_var_size (peer_pull_reply,
2811                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY,
2812                            struct GNUNET_RPS_P2P_PullReplyMessage,
2813                            NULL),
2814     GNUNET_MQ_handler_end ()
2815   };
2816   sub->hash = *hash;
2817   sub->cadet_port =
2818     GNUNET_CADET_open_port (cadet_handle,
2819                             &sub->hash,
2820                             &handle_inbound_channel, /* Connect handler */
2821                             sub, /* cls */
2822                             NULL, /* WindowSize handler */
2823                             &cleanup_destroyed_channel, /* Disconnect handler */
2824                             cadet_handlers);
2825   if (NULL == sub->cadet_port)
2826   {
2827     LOG (GNUNET_ERROR_TYPE_ERROR,
2828         "Cadet port `%s' is already in use.\n",
2829         GNUNET_APPLICATION_PORT_RPS);
2830     GNUNET_assert (0);
2831   }
2832
2833   /* Set up general data structure to keep track about peers */
2834   sub->valid_peers = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
2835   if (GNUNET_OK !=
2836       GNUNET_CONFIGURATION_get_value_filename (cfg,
2837                                                "rps",
2838                                                "FILENAME_VALID_PEERS",
2839                                                &sub->filename_valid_peers))
2840   {
2841     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2842                                "rps",
2843                                "FILENAME_VALID_PEERS");
2844   }
2845   if (0 != strncmp ("DISABLE", sub->filename_valid_peers, 7))
2846   {
2847     char *tmp_filename_valid_peers;
2848     char str_hash[105];
2849
2850     GNUNET_snprintf (str_hash,
2851                      strlen (str_hash),
2852                      GNUNET_h2s_full (hash));
2853     tmp_filename_valid_peers = sub->filename_valid_peers;
2854     GNUNET_asprintf (&sub->filename_valid_peers,
2855                      "%s%s",
2856                      tmp_filename_valid_peers,
2857                      str_hash);
2858     GNUNET_free (tmp_filename_valid_peers);
2859   }
2860   sub->peer_map = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
2861
2862   /* Set up the sampler */
2863   sub->sampler_size_est_min = sampler_size;
2864   sub->sampler_size_est_need = sampler_size;;
2865   LOG (GNUNET_ERROR_TYPE_DEBUG, "MINSIZE is %u\n", sub->sampler_size_est_min);
2866   GNUNET_assert (0 != round_interval.rel_value_us);
2867   sub->round_interval = round_interval;
2868   sub->sampler = RPS_sampler_init (sampler_size,
2869                                   round_interval);
2870
2871   /* Logging of internals */
2872   sub->file_name_view_log = store_prefix_file_name (&own_identity, "view");
2873 #ifdef TO_FILE
2874   sub->file_name_observed_log = store_prefix_file_name (&own_identity,
2875                                                        "observed");
2876   sub->file_name_push_recv = store_prefix_file_name (&own_identity,
2877                                                      "push_recv");
2878   sub->file_name_pull_delays = store_prefix_file_name (&own_identity,
2879                                                        "pull_delays");
2880   sub->num_observed_peers = 0;
2881   sub->observed_unique_peers = GNUNET_CONTAINER_multipeermap_create (1,
2882                                                                     GNUNET_NO);
2883 #endif /* TO_FILE */
2884
2885   /* Set up data structures for gossip */
2886   sub->push_map = CustomPeerMap_create (4);
2887   sub->pull_map = CustomPeerMap_create (4);
2888   sub->view_size_est_min = sampler_size;;
2889   sub->view = View_create (sub->view_size_est_min);
2890   if (sub == msub)
2891   {
2892     GNUNET_STATISTICS_set (stats,
2893                            "view size aim",
2894                            sub->view_size_est_min,
2895                            GNUNET_NO);
2896   }
2897
2898   /* Start executing rounds */
2899   sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_round, sub);
2900
2901   return sub;
2902 }
2903
2904
2905 /**
2906  * @brief Destroy Sub.
2907  *
2908  * @param sub Sub to destroy
2909  */
2910 static void
2911 destroy_sub (struct Sub *sub)
2912 {
2913 #ifdef TO_FILE
2914   char push_recv_str[1536] = ""; /* 256 * 6 (1 whitespace, 1 comma, up to 4 chars) */
2915   char pull_delays_str[1536] = ""; /* 256 * 6 (1 whitespace, 1 comma, up to 4 chars) */
2916 #endif /* TO_FILE */
2917   GNUNET_assert (NULL != sub);
2918   GNUNET_assert (NULL != sub->do_round_task);
2919   GNUNET_SCHEDULER_cancel (sub->do_round_task);
2920   sub->do_round_task = NULL;
2921
2922   /* Disconnect from cadet */
2923   GNUNET_CADET_close_port (sub->cadet_port);
2924
2925   /* Clean up data structures for peers */
2926   RPS_sampler_destroy (sub->sampler);
2927   sub->sampler = NULL;
2928   View_destroy (sub->view);
2929   sub->view = NULL;
2930   CustomPeerMap_destroy (sub->push_map);
2931   sub->push_map = NULL;
2932   CustomPeerMap_destroy (sub->pull_map);
2933   sub->pull_map = NULL;
2934   peers_terminate (sub);
2935
2936   /* Free leftover data structures */
2937   GNUNET_free (sub->file_name_view_log);
2938   sub->file_name_view_log = NULL;
2939 #ifdef TO_FILE
2940   GNUNET_free (sub->file_name_observed_log);
2941   sub->file_name_observed_log = NULL;
2942
2943   /* Write push frequencies to disk */
2944   for (uint32_t i = 0; i < 256; i++)
2945   {
2946     char push_recv_str_tmp[8];
2947     
2948     GNUNET_snprintf (push_recv_str_tmp,
2949                      sizeof (push_recv_str_tmp),
2950                      "%" PRIu32 "\n",
2951                      sub->push_recv[i]);
2952     // FIXME: better use stpcpy!
2953     (void) strncat (push_recv_str,
2954                     push_recv_str_tmp,
2955                     1535 - strnlen (push_recv_str, 1536));
2956   }
2957   (void) strncat (push_recv_str,
2958                   "\n",
2959                   1535 - strnlen (push_recv_str, 1536));
2960   LOG (GNUNET_ERROR_TYPE_DEBUG,
2961        "Writing push stats to disk\n");
2962   to_file_w_len (sub->file_name_push_recv, 1535, push_recv_str);
2963   GNUNET_free (sub->file_name_push_recv);
2964   sub->file_name_push_recv = NULL;
2965
2966   /* Write pull delays to disk */
2967   for (uint32_t i = 0; i < 256; i++)
2968   {
2969     char pull_delays_str_tmp[8];
2970
2971     GNUNET_snprintf (pull_delays_str_tmp,
2972                      sizeof (pull_delays_str_tmp),
2973                      "%" PRIu32 "\n",
2974                      sub->pull_delays[i]);
2975     // FIXME: better use stpcpy!
2976     (void) strncat (pull_delays_str,
2977                     pull_delays_str_tmp,
2978                     1535 - strnlen (pull_delays_str, 1536));
2979   }
2980   (void) strncat (pull_delays_str,
2981                   "\n",
2982                   1535 - strnlen (pull_delays_str, 1536));
2983   LOG (GNUNET_ERROR_TYPE_DEBUG, "Writing pull delays to disk\n");
2984   to_file_w_len (sub->file_name_pull_delays, 1535, pull_delays_str);
2985   GNUNET_free (sub->file_name_pull_delays);
2986   sub->file_name_pull_delays = NULL;
2987
2988   GNUNET_CONTAINER_multipeermap_destroy (sub->observed_unique_peers);
2989   sub->observed_unique_peers = NULL;
2990 #endif /* TO_FILE */
2991
2992   GNUNET_free (sub);
2993 }
2994
2995
2996 /***********************************************************************
2997  * /Sub
2998 ***********************************************************************/
2999
3000
3001 /***********************************************************************
3002  * Core handlers
3003 ***********************************************************************/
3004
3005 /**
3006  * @brief Callback on initialisation of Core.
3007  *
3008  * @param cls - unused
3009  * @param my_identity - unused
3010  */
3011 void
3012 core_init (void *cls,
3013            const struct GNUNET_PeerIdentity *my_identity)
3014 {
3015   (void) cls;
3016   (void) my_identity;
3017
3018   map_single_hop = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
3019 }
3020
3021
3022 /**
3023  * @brief Callback for core.
3024  * Method called whenever a given peer connects.
3025  *
3026  * @param cls closure - unused
3027  * @param peer peer identity this notification is about
3028  * @return closure given to #core_disconnects as peer_cls
3029  */
3030 void *
3031 core_connects (void *cls,
3032                const struct GNUNET_PeerIdentity *peer,
3033                struct GNUNET_MQ_Handle *mq)
3034 {
3035   (void) cls;
3036   (void) mq;
3037
3038   GNUNET_assert (GNUNET_YES ==
3039                  GNUNET_CONTAINER_multipeermap_put (map_single_hop,
3040                                                     peer,
3041                                                     NULL,
3042                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3043   return NULL;
3044 }
3045
3046
3047 /**
3048  * @brief Callback for core.
3049  * Method called whenever a peer disconnects.
3050  *
3051  * @param cls closure - unused
3052  * @param peer peer identity this notification is about
3053  * @param peer_cls closure given in #core_connects - unused
3054  */
3055 void
3056 core_disconnects (void *cls,
3057                   const struct GNUNET_PeerIdentity *peer,
3058                   void *peer_cls)
3059 {
3060   (void) cls;
3061   (void) peer_cls;
3062
3063   GNUNET_CONTAINER_multipeermap_remove_all (map_single_hop, peer);
3064 }
3065
3066 /***********************************************************************
3067  * /Core handlers
3068 ***********************************************************************/
3069
3070
3071 /**
3072  * @brief Destroy the context for a (connected) client
3073  *
3074  * @param cli_ctx Context to destroy
3075  */
3076 static void
3077 destroy_cli_ctx (struct ClientContext *cli_ctx)
3078 {
3079   GNUNET_assert (NULL != cli_ctx);
3080   GNUNET_CONTAINER_DLL_remove (cli_ctx_head,
3081                                cli_ctx_tail,
3082                                cli_ctx);
3083   if (NULL != cli_ctx->sub)
3084   {
3085     destroy_sub (cli_ctx->sub);
3086     cli_ctx->sub = NULL;
3087   }
3088   GNUNET_free (cli_ctx);
3089 }
3090
3091
3092 /**
3093  * @brief Update sizes in sampler and view on estimate update from nse service
3094  *
3095  * @param sub Sub
3096  * @param logestimate the log(Base 2) value of the current network size estimate
3097  * @param std_dev standard deviation for the estimate
3098  */
3099 static void
3100 adapt_sizes (struct Sub *sub, double logestimate, double std_dev)
3101 {
3102   double estimate;
3103   //double scale; // TODO this might go gloabal/config
3104
3105   LOG (GNUNET_ERROR_TYPE_DEBUG,
3106        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
3107        logestimate, std_dev, RPS_sampler_get_size (sub->sampler));
3108   //scale = .01;
3109   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
3110   // GNUNET_NSE_log_estimate_to_n (logestimate);
3111   estimate = pow (estimate, 1.0 / 3);
3112   // TODO add if std_dev is a number
3113   // estimate += (std_dev * scale);
3114   if (sub->view_size_est_min < ceil (estimate))
3115   {
3116     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
3117     sub->sampler_size_est_need = estimate;
3118     sub->view_size_est_need = estimate;
3119   } else
3120   {
3121     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
3122     //sub->sampler_size_est_need = sub->view_size_est_min;
3123     sub->view_size_est_need = sub->view_size_est_min;
3124   }
3125   if (sub == msub)
3126   {
3127     GNUNET_STATISTICS_set (stats,
3128                            "view size aim",
3129                            sub->view_size_est_need,
3130                            GNUNET_NO);
3131   }
3132
3133   /* If the NSE has changed adapt the lists accordingly */
3134   resize_wrapper (sub->sampler, sub->sampler_size_est_need);
3135   View_change_len (sub->view, sub->view_size_est_need);
3136 }
3137
3138
3139 /**
3140  * Function called by NSE.
3141  *
3142  * Updates sizes of sampler list and view and adapt those lists
3143  * accordingly.
3144  *
3145  * implements #GNUNET_NSE_Callback
3146  *
3147  * @param cls Closure - unused
3148  * @param timestamp time when the estimate was received from the server (or created by the server)
3149  * @param logestimate the log(Base 2) value of the current network size estimate
3150  * @param std_dev standard deviation for the estimate
3151  */
3152 static void
3153 nse_callback (void *cls,
3154               struct GNUNET_TIME_Absolute timestamp,
3155               double logestimate, double std_dev)
3156 {
3157   (void) cls;
3158   (void) timestamp;
3159   struct ClientContext *cli_ctx_iter;
3160
3161   adapt_sizes (msub, logestimate, std_dev);
3162   for (cli_ctx_iter = cli_ctx_head;
3163       NULL != cli_ctx_iter;
3164       cli_ctx_iter = cli_ctx_iter->next)
3165   {
3166     if (NULL != cli_ctx_iter->sub)
3167     {
3168       adapt_sizes (cli_ctx_iter->sub, logestimate, std_dev);
3169     }
3170   }
3171 }
3172
3173
3174 /**
3175  * @brief This function is called, when the client seeds peers.
3176  * It verifies that @a msg is well-formed.
3177  *
3178  * @param cls the closure (#ClientContext)
3179  * @param msg the message
3180  * @return #GNUNET_OK if @a msg is well-formed
3181  *         #GNUNET_SYSERR otherwise
3182  */
3183 static int
3184 check_client_seed (void *cls, const struct GNUNET_RPS_CS_SeedMessage *msg)
3185 {
3186   struct ClientContext *cli_ctx = cls;
3187   uint16_t msize = ntohs (msg->header.size);
3188   uint32_t num_peers = ntohl (msg->num_peers);
3189
3190   msize -= sizeof (struct GNUNET_RPS_CS_SeedMessage);
3191   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
3192        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
3193   {
3194     LOG (GNUNET_ERROR_TYPE_ERROR,
3195         "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3196         ntohl (msg->num_peers),
3197         (msize / sizeof (struct GNUNET_PeerIdentity)));
3198     GNUNET_break (0);
3199     GNUNET_SERVICE_client_drop (cli_ctx->client);
3200     return GNUNET_SYSERR;
3201   }
3202   return GNUNET_OK;
3203 }
3204
3205
3206 /**
3207  * Handle seed from the client.
3208  *
3209  * @param cls closure
3210  * @param message the actual message
3211  */
3212 static void
3213 handle_client_seed (void *cls,
3214                     const struct GNUNET_RPS_CS_SeedMessage *msg)
3215 {
3216   struct ClientContext *cli_ctx = cls;
3217   struct GNUNET_PeerIdentity *peers;
3218   uint32_t num_peers;
3219   uint32_t i;
3220
3221   num_peers = ntohl (msg->num_peers);
3222   peers = (struct GNUNET_PeerIdentity *) &msg[1];
3223
3224   LOG (GNUNET_ERROR_TYPE_DEBUG,
3225        "Client seeded peers:\n");
3226   print_peer_list (peers, num_peers);
3227
3228   for (i = 0; i < num_peers; i++)
3229   {
3230     LOG (GNUNET_ERROR_TYPE_DEBUG,
3231          "Updating samplers with seed %" PRIu32 ": %s\n",
3232          i,
3233          GNUNET_i2s (&peers[i]));
3234
3235     if (NULL != msub) got_peer (msub, &peers[i]); /* Condition needed? */
3236     if (NULL != cli_ctx->sub) got_peer (cli_ctx->sub, &peers[i]);
3237   }
3238   GNUNET_SERVICE_client_continue (cli_ctx->client);
3239 }
3240
3241
3242 /**
3243  * Handle RPS request from the client.
3244  *
3245  * @param cls Client context
3246  * @param message Message containing the numer of updates the client wants to
3247  * receive
3248  */
3249 static void
3250 handle_client_view_request (void *cls,
3251                             const struct GNUNET_RPS_CS_DEBUG_ViewRequest *msg)
3252 {
3253   struct ClientContext *cli_ctx = cls;
3254   uint64_t num_updates;
3255
3256   num_updates = ntohl (msg->num_updates);
3257
3258   LOG (GNUNET_ERROR_TYPE_DEBUG,
3259        "Client requested %" PRIu64 " updates of view.\n",
3260        num_updates);
3261
3262   GNUNET_assert (NULL != cli_ctx);
3263   cli_ctx->view_updates_left = num_updates;
3264   send_view (cli_ctx, NULL, 0);
3265   GNUNET_SERVICE_client_continue (cli_ctx->client);
3266 }
3267
3268
3269 /**
3270  * @brief Handle the cancellation of the view updates.
3271  *
3272  * @param cls The client context
3273  * @param msg Unused
3274  */
3275 static void
3276 handle_client_view_cancel (void *cls,
3277                            const struct GNUNET_MessageHeader *msg)
3278 {
3279   struct ClientContext *cli_ctx = cls;
3280   (void) msg;
3281
3282   LOG (GNUNET_ERROR_TYPE_DEBUG,
3283        "Client does not want to receive updates of view any more.\n");
3284
3285   GNUNET_assert (NULL != cli_ctx);
3286   cli_ctx->view_updates_left = 0;
3287   GNUNET_SERVICE_client_continue (cli_ctx->client);
3288   if (GNUNET_YES == cli_ctx->stream_update)
3289   {
3290     destroy_cli_ctx (cli_ctx);
3291   }
3292 }
3293
3294
3295 /**
3296  * Handle RPS request for biased stream from the client.
3297  *
3298  * @param cls Client context
3299  * @param message unused
3300  */
3301 static void
3302 handle_client_stream_request (void *cls,
3303                               const struct GNUNET_RPS_CS_DEBUG_StreamRequest *msg)
3304 {
3305   struct ClientContext *cli_ctx = cls;
3306   (void) msg;
3307
3308   LOG (GNUNET_ERROR_TYPE_DEBUG,
3309        "Client requested peers from biased stream.\n");
3310   cli_ctx->stream_update = GNUNET_YES;
3311
3312   GNUNET_assert (NULL != cli_ctx);
3313   GNUNET_SERVICE_client_continue (cli_ctx->client);
3314 }
3315
3316
3317 /**
3318  * @brief Handles the cancellation of the stream of biased peer ids
3319  *
3320  * @param cls The client context
3321  * @param msg unused
3322  */
3323 static void
3324 handle_client_stream_cancel (void *cls,
3325                              const struct GNUNET_MessageHeader *msg)
3326 {
3327   struct ClientContext *cli_ctx = cls;
3328   (void) msg;
3329
3330   LOG (GNUNET_ERROR_TYPE_DEBUG,
3331        "Client canceled receiving peers from biased stream.\n");
3332   cli_ctx->stream_update = GNUNET_NO;
3333
3334   GNUNET_assert (NULL != cli_ctx);
3335   GNUNET_SERVICE_client_continue (cli_ctx->client);
3336 }
3337
3338
3339 /**
3340  * @brief Create and start a Sub.
3341  *
3342  * @param cls Closure - unused
3343  * @param msg Message containing the necessary information
3344  */
3345 static void
3346 handle_client_start_sub (void *cls,
3347                          const struct GNUNET_RPS_CS_SubStartMessage *msg)
3348 {
3349   struct ClientContext *cli_ctx = cls;
3350
3351   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested start of a new sub.\n");
3352   if (NULL != cli_ctx->sub &&
3353       0 != memcmp (&cli_ctx->sub->hash,
3354                    &msg->hash,
3355                    sizeof (struct GNUNET_HashCode)))
3356   {
3357     LOG (GNUNET_ERROR_TYPE_WARNING, "Already have a Sub with different share for this client. Remove old one, add new.\n");
3358     destroy_sub (cli_ctx->sub);
3359     cli_ctx->sub = NULL;
3360   }
3361   cli_ctx->sub = new_sub (&msg->hash,
3362                          msub->sampler_size_est_min, // TODO make api input?
3363                          GNUNET_TIME_relative_ntoh (msg->round_interval));
3364   GNUNET_SERVICE_client_continue (cli_ctx->client);
3365 }
3366
3367
3368 /**
3369  * @brief Destroy the Sub
3370  *
3371  * @param cls Closure - unused
3372  * @param msg Message containing the hash that identifies the Sub
3373  */
3374 static void
3375 handle_client_stop_sub (void *cls,
3376                         const struct GNUNET_RPS_CS_SubStopMessage *msg)
3377 {
3378   struct ClientContext *cli_ctx = cls;
3379
3380   GNUNET_assert (NULL != cli_ctx->sub);
3381   if (0 != memcmp (&cli_ctx->sub->hash, &msg->hash, sizeof (struct GNUNET_HashCode)))
3382   {
3383     LOG (GNUNET_ERROR_TYPE_WARNING, "Share of current sub and request differ!\n");
3384   }
3385   destroy_sub (cli_ctx->sub);
3386   cli_ctx->sub = NULL;
3387   GNUNET_SERVICE_client_continue (cli_ctx->client);
3388 }
3389
3390
3391 /**
3392  * Handle a CHECK_LIVE message from another peer.
3393  *
3394  * This does nothing. But without calling #GNUNET_CADET_receive_done()
3395  * the channel is blocked for all other communication.
3396  *
3397  * @param cls Closure - Context of channel
3398  * @param msg Message - unused
3399  */
3400 static void
3401 handle_peer_check (void *cls,
3402                    const struct GNUNET_MessageHeader *msg)
3403 {
3404   const struct ChannelCtx *channel_ctx = cls;
3405   const struct GNUNET_PeerIdentity *peer = &channel_ctx->peer_ctx->peer_id;
3406   (void) msg;
3407
3408   LOG (GNUNET_ERROR_TYPE_DEBUG,
3409       "Received CHECK_LIVE (%s)\n", GNUNET_i2s (peer));
3410   if (channel_ctx->peer_ctx->sub == msub)
3411   {
3412     GNUNET_STATISTICS_update (stats,
3413                               "# pending online checks",
3414                               -1,
3415                               GNUNET_NO);
3416   }
3417
3418   GNUNET_CADET_receive_done (channel_ctx->channel);
3419 }
3420
3421
3422 /**
3423  * Handle a PUSH message from another peer.
3424  *
3425  * Check the proof of work and store the PeerID
3426  * in the temporary list for pushed PeerIDs.
3427  *
3428  * @param cls Closure - Context of channel
3429  * @param msg Message - unused
3430  */
3431 static void
3432 handle_peer_push (void *cls,
3433                   const struct GNUNET_MessageHeader *msg)
3434 {
3435   const struct ChannelCtx *channel_ctx = cls;
3436   const struct GNUNET_PeerIdentity *peer = &channel_ctx->peer_ctx->peer_id;
3437   (void) msg;
3438
3439   // (check the proof of work (?))
3440
3441   LOG (GNUNET_ERROR_TYPE_DEBUG,
3442        "Received PUSH (%s)\n",
3443        GNUNET_i2s (peer));
3444   if (channel_ctx->peer_ctx->sub == msub)
3445   {
3446     GNUNET_STATISTICS_update(stats, "# push message received", 1, GNUNET_NO);
3447   }
3448
3449   #if ENABLE_MALICIOUS
3450   struct AttackedPeer *tmp_att_peer;
3451
3452   if ( (1 == mal_type) ||
3453        (3 == mal_type) )
3454   { /* Try to maximise representation */
3455     tmp_att_peer = GNUNET_new (struct AttackedPeer);
3456     tmp_att_peer->peer_id = *peer;
3457     if (NULL == att_peer_set)
3458       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
3459     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
3460                                                              peer))
3461     {
3462       GNUNET_CONTAINER_DLL_insert (att_peers_head,
3463                                    att_peers_tail,
3464                                    tmp_att_peer);
3465       add_peer_array_to_set (peer, 1, att_peer_set);
3466     }
3467     else
3468     {
3469       GNUNET_free (tmp_att_peer);
3470     }
3471   }
3472
3473
3474   else if (2 == mal_type)
3475   {
3476     /* We attack one single well-known peer - simply ignore */
3477   }
3478   #endif /* ENABLE_MALICIOUS */
3479
3480   /* Add the sending peer to the push_map */
3481   CustomPeerMap_put (channel_ctx->peer_ctx->sub->push_map, peer);
3482
3483   GNUNET_break_op (check_peer_known (channel_ctx->peer_ctx->sub->peer_map,
3484                                      &channel_ctx->peer_ctx->peer_id));
3485   GNUNET_CADET_receive_done (channel_ctx->channel);
3486 }
3487
3488
3489 /**
3490  * Handle PULL REQUEST request message from another peer.
3491  *
3492  * Reply with the view of PeerIDs.
3493  *
3494  * @param cls Closure - Context of channel
3495  * @param msg Message - unused
3496  */
3497 static void
3498 handle_peer_pull_request (void *cls,
3499                           const struct GNUNET_MessageHeader *msg)
3500 {
3501   const struct ChannelCtx *channel_ctx = cls;
3502   struct PeerContext *peer_ctx = channel_ctx->peer_ctx;
3503   const struct GNUNET_PeerIdentity *peer = &peer_ctx->peer_id;
3504   const struct GNUNET_PeerIdentity *view_array;
3505   (void) msg;
3506
3507   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REQUEST (%s)\n", GNUNET_i2s (peer));
3508   if (peer_ctx->sub == msub)
3509   {
3510     GNUNET_STATISTICS_update(stats,
3511                              "# pull request message received",
3512                              1,
3513                              GNUNET_NO);
3514     if (NULL != map_single_hop &&
3515         GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
3516                                                              &peer_ctx->peer_id))
3517     {
3518       GNUNET_STATISTICS_update (stats,
3519                                 "# pull request message received (multi-hop peer)",
3520                                 1,
3521                                 GNUNET_NO);
3522     }
3523   }
3524
3525   #if ENABLE_MALICIOUS
3526   if (1 == mal_type
3527       || 3 == mal_type)
3528   { /* Try to maximise representation */
3529     send_pull_reply (peer_ctx, mal_peers, num_mal_peers);
3530   }
3531
3532   else if (2 == mal_type)
3533   { /* Try to partition network */
3534     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
3535     {
3536       send_pull_reply (peer_ctx, mal_peers, num_mal_peers);
3537     }
3538   }
3539   #endif /* ENABLE_MALICIOUS */
3540
3541   GNUNET_break_op (check_peer_known (channel_ctx->peer_ctx->sub->peer_map,
3542                                      &channel_ctx->peer_ctx->peer_id));
3543   GNUNET_CADET_receive_done (channel_ctx->channel);
3544   view_array = View_get_as_array (channel_ctx->peer_ctx->sub->view);
3545   send_pull_reply (peer_ctx,
3546                    view_array,
3547                    View_size (channel_ctx->peer_ctx->sub->view));
3548 }
3549
3550
3551 /**
3552  * Check whether we sent a corresponding request and
3553  * whether this reply is the first one.
3554  *
3555  * @param cls Closure - Context of channel
3556  * @param msg Message containing the replied peers
3557  */
3558 static int
3559 check_peer_pull_reply (void *cls,
3560                        const struct GNUNET_RPS_P2P_PullReplyMessage *msg)
3561 {
3562   struct ChannelCtx *channel_ctx = cls;
3563   struct PeerContext *sender_ctx = channel_ctx->peer_ctx;
3564
3565   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->header.size))
3566   {
3567     GNUNET_break_op (0);
3568     return GNUNET_SYSERR;
3569   }
3570
3571   if ((ntohs (msg->header.size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
3572       sizeof (struct GNUNET_PeerIdentity) != ntohl (msg->num_peers))
3573   {
3574     LOG (GNUNET_ERROR_TYPE_ERROR,
3575         "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3576         ntohl (msg->num_peers),
3577         (ntohs (msg->header.size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
3578             sizeof (struct GNUNET_PeerIdentity));
3579     GNUNET_break_op (0);
3580     return GNUNET_SYSERR;
3581   }
3582
3583   if (GNUNET_YES != check_peer_flag (sender_ctx->sub->peer_map,
3584                                      &sender_ctx->peer_id,
3585                                      Peers_PULL_REPLY_PENDING))
3586   {
3587     LOG (GNUNET_ERROR_TYPE_WARNING,
3588         "Received a pull reply from a peer (%s) we didn't request one from!\n",
3589         GNUNET_i2s (&sender_ctx->peer_id));
3590     if (sender_ctx->sub == msub)
3591     {
3592       GNUNET_STATISTICS_update (stats,
3593                                 "# unrequested pull replies",
3594                                 1,
3595                                 GNUNET_NO);
3596     }
3597     GNUNET_break_op (0);
3598     return GNUNET_SYSERR;
3599   }
3600   return GNUNET_OK;
3601 }
3602
3603
3604 /**
3605  * Handle PULL REPLY message from another peer.
3606  *
3607  * @param cls Closure
3608  * @param msg The message header
3609  */
3610 static void
3611 handle_peer_pull_reply (void *cls,
3612                         const struct GNUNET_RPS_P2P_PullReplyMessage *msg)
3613 {
3614   const struct ChannelCtx *channel_ctx = cls;
3615   const struct GNUNET_PeerIdentity *sender = &channel_ctx->peer_ctx->peer_id;
3616   const struct GNUNET_PeerIdentity *peers;
3617   struct Sub *sub = channel_ctx->peer_ctx->sub;
3618   uint32_t i;
3619 #if ENABLE_MALICIOUS
3620   struct AttackedPeer *tmp_att_peer;
3621 #endif /* ENABLE_MALICIOUS */
3622
3623   sub->pull_delays[sub->num_rounds - channel_ctx->peer_ctx->round_pull_req]++;
3624   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REPLY (%s)\n", GNUNET_i2s (sender));
3625   if (channel_ctx->peer_ctx->sub == msub)
3626   {
3627     GNUNET_STATISTICS_update (stats,
3628                               "# pull reply messages received",
3629                               1,
3630                               GNUNET_NO);
3631     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
3632           &channel_ctx->peer_ctx->peer_id))
3633     {
3634       GNUNET_STATISTICS_update (stats,
3635                                 "# pull reply messages received (multi-hop peer)",
3636                                 1,
3637                                 GNUNET_NO);
3638     }
3639   }
3640
3641   #if ENABLE_MALICIOUS
3642   // We shouldn't even receive pull replies as we're not sending
3643   if (2 == mal_type)
3644   {
3645   }
3646   #endif /* ENABLE_MALICIOUS */
3647
3648   /* Do actual logic */
3649   peers = (const struct GNUNET_PeerIdentity *) &msg[1];
3650
3651   LOG (GNUNET_ERROR_TYPE_DEBUG,
3652        "PULL REPLY received, got following %u peers:\n",
3653        ntohl (msg->num_peers));
3654
3655   for (i = 0; i < ntohl (msg->num_peers); i++)
3656   {
3657     LOG (GNUNET_ERROR_TYPE_DEBUG,
3658          "%u. %s\n",
3659          i,
3660          GNUNET_i2s (&peers[i]));
3661
3662     #if ENABLE_MALICIOUS
3663     if ((NULL != att_peer_set) &&
3664         (1 == mal_type || 3 == mal_type))
3665     { /* Add attacked peer to local list */
3666       // TODO check if we sent a request and this was the first reply
3667       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
3668                                                                &peers[i])
3669           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
3670                                                                   &peers[i]))
3671       {
3672         tmp_att_peer = GNUNET_new (struct AttackedPeer);
3673         tmp_att_peer->peer_id = peers[i];
3674         GNUNET_CONTAINER_DLL_insert (att_peers_head,
3675                                      att_peers_tail,
3676                                      tmp_att_peer);
3677         add_peer_array_to_set (&peers[i], 1, att_peer_set);
3678       }
3679       continue;
3680     }
3681     #endif /* ENABLE_MALICIOUS */
3682     /* Make sure we 'know' about this peer */
3683     (void) insert_peer (channel_ctx->peer_ctx->sub, &peers[i]);
3684
3685     if (GNUNET_YES == check_peer_valid (channel_ctx->peer_ctx->sub->valid_peers,
3686                                         &peers[i]))
3687     {
3688       CustomPeerMap_put (channel_ctx->peer_ctx->sub->pull_map, &peers[i]);
3689     }
3690     else
3691     {
3692       schedule_operation (channel_ctx->peer_ctx,
3693                           insert_in_pull_map,
3694                           channel_ctx->peer_ctx->sub); /* cls */
3695       (void) issue_peer_online_check (channel_ctx->peer_ctx->sub, &peers[i]);
3696     }
3697   }
3698
3699   UNSET_PEER_FLAG (get_peer_ctx (channel_ctx->peer_ctx->sub->peer_map, sender),
3700                    Peers_PULL_REPLY_PENDING);
3701   clean_peer (channel_ctx->peer_ctx->sub, sender);
3702
3703   GNUNET_break_op (check_peer_known (channel_ctx->peer_ctx->sub->peer_map,
3704                                      sender));
3705   GNUNET_CADET_receive_done (channel_ctx->channel);
3706 }
3707
3708
3709 /**
3710  * Compute a random delay.
3711  * A uniformly distributed value between mean + spread and mean - spread.
3712  *
3713  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
3714  * It would return a random value between 2 and 6 min.
3715  *
3716  * @param mean the mean time until the next round
3717  * @param spread the inverse amount of deviation from the mean
3718  */
3719 static struct GNUNET_TIME_Relative
3720 compute_rand_delay (struct GNUNET_TIME_Relative mean,
3721                     unsigned int spread)
3722 {
3723   struct GNUNET_TIME_Relative half_interval;
3724   struct GNUNET_TIME_Relative ret;
3725   unsigned int rand_delay;
3726   unsigned int max_rand_delay;
3727
3728   if (0 == spread)
3729   {
3730     LOG (GNUNET_ERROR_TYPE_WARNING,
3731          "Not accepting spread of 0\n");
3732     GNUNET_break (0);
3733     GNUNET_assert (0);
3734   }
3735   GNUNET_assert (0 != mean.rel_value_us);
3736
3737   /* Compute random time value between spread * mean and spread * mean */
3738   half_interval = GNUNET_TIME_relative_divide (mean, spread);
3739
3740   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
3741   /**
3742    * Compute random value between (0 and 1) * round_interval
3743    * via multiplying round_interval with a 'fraction' (0 to value)/value
3744    */
3745   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
3746   ret = GNUNET_TIME_relative_saturating_multiply (mean,  rand_delay);
3747   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
3748   ret = GNUNET_TIME_relative_add      (ret, half_interval);
3749
3750   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
3751     LOG (GNUNET_ERROR_TYPE_WARNING,
3752          "Returning FOREVER_REL\n");
3753
3754   return ret;
3755 }
3756
3757
3758 /**
3759  * Send single pull request
3760  *
3761  * @param peer_ctx Context to the peer to send request to
3762  */
3763 static void
3764 send_pull_request (struct PeerContext *peer_ctx)
3765 {
3766   struct GNUNET_MQ_Envelope *ev;
3767
3768   GNUNET_assert (GNUNET_NO == check_peer_flag (peer_ctx->sub->peer_map,
3769                                                &peer_ctx->peer_id,
3770                                                Peers_PULL_REPLY_PENDING));
3771   SET_PEER_FLAG (peer_ctx, Peers_PULL_REPLY_PENDING);
3772   peer_ctx->round_pull_req = peer_ctx->sub->num_rounds;
3773
3774   LOG (GNUNET_ERROR_TYPE_DEBUG,
3775        "Going to send PULL REQUEST to peer %s.\n",
3776        GNUNET_i2s (&peer_ctx->peer_id));
3777
3778   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
3779   send_message (peer_ctx, ev, "PULL REQUEST");
3780   if (peer_ctx->sub)
3781   {
3782     GNUNET_STATISTICS_update (stats,
3783                               "# pull request send issued",
3784                               1,
3785                               GNUNET_NO);
3786     if (NULL != map_single_hop &&
3787         GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
3788                                                              &peer_ctx->peer_id))
3789     {
3790       GNUNET_STATISTICS_update (stats,
3791                                 "# pull request send issued (multi-hop peer)",
3792                                 1,
3793                                 GNUNET_NO);
3794     }
3795   }
3796 }
3797
3798
3799 /**
3800  * Send single push
3801  *
3802  * @param peer_ctx Context of peer to send push to
3803  */
3804 static void
3805 send_push (struct PeerContext *peer_ctx)
3806 {
3807   struct GNUNET_MQ_Envelope *ev;
3808
3809   LOG (GNUNET_ERROR_TYPE_DEBUG,
3810        "Going to send PUSH to peer %s.\n",
3811        GNUNET_i2s (&peer_ctx->peer_id));
3812
3813   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
3814   send_message (peer_ctx, ev, "PUSH");
3815   if (peer_ctx->sub)
3816   {
3817     GNUNET_STATISTICS_update (stats,
3818                               "# push send issued",
3819                               1,
3820                               GNUNET_NO);
3821   }
3822 }
3823
3824
3825 #if ENABLE_MALICIOUS
3826
3827
3828 /**
3829  * @brief This function is called, when the client tells us to act malicious.
3830  * It verifies that @a msg is well-formed.
3831  *
3832  * @param cls the closure (#ClientContext)
3833  * @param msg the message
3834  * @return #GNUNET_OK if @a msg is well-formed
3835  */
3836 static int
3837 check_client_act_malicious (void *cls,
3838                             const struct GNUNET_RPS_CS_ActMaliciousMessage *msg)
3839 {
3840   struct ClientContext *cli_ctx = cls;
3841   uint16_t msize = ntohs (msg->header.size);
3842   uint32_t num_peers = ntohl (msg->num_peers);
3843
3844   msize -= sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage);
3845   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
3846        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
3847   {
3848     LOG (GNUNET_ERROR_TYPE_ERROR,
3849         "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3850         ntohl (msg->num_peers),
3851         (msize / sizeof (struct GNUNET_PeerIdentity)));
3852     GNUNET_break (0);
3853     GNUNET_SERVICE_client_drop (cli_ctx->client);
3854     return GNUNET_SYSERR;
3855   }
3856   return GNUNET_OK;
3857 }
3858
3859 /**
3860  * Turn RPS service to act malicious.
3861  *
3862  * @param cls Closure
3863  * @param client The client that sent the message
3864  * @param msg The message header
3865  */
3866 static void
3867 handle_client_act_malicious (void *cls,
3868                              const struct GNUNET_RPS_CS_ActMaliciousMessage *msg)
3869 {
3870   struct ClientContext *cli_ctx = cls;
3871   struct GNUNET_PeerIdentity *peers;
3872   uint32_t num_mal_peers_sent;
3873   uint32_t num_mal_peers_old;
3874   struct Sub *sub = cli_ctx->sub;
3875
3876   if (NULL == sub) sub = msub;
3877   /* Do actual logic */
3878   peers = (struct GNUNET_PeerIdentity *) &msg[1];
3879   mal_type = ntohl (msg->type);
3880   if (NULL == mal_peer_set)
3881     mal_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
3882
3883   LOG (GNUNET_ERROR_TYPE_DEBUG,
3884        "Now acting malicious type %" PRIu32 ", got %" PRIu32 " peers.\n",
3885        mal_type,
3886        ntohl (msg->num_peers));
3887
3888   if (1 == mal_type)
3889   { /* Try to maximise representation */
3890     /* Add other malicious peers to those we already know */
3891
3892     num_mal_peers_sent = ntohl (msg->num_peers);
3893     num_mal_peers_old = num_mal_peers;
3894     GNUNET_array_grow (mal_peers,
3895                        num_mal_peers,
3896                        num_mal_peers + num_mal_peers_sent);
3897     GNUNET_memcpy (&mal_peers[num_mal_peers_old],
3898             peers,
3899             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
3900
3901     /* Add all mal peers to mal_peer_set */
3902     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
3903                            num_mal_peers_sent,
3904                            mal_peer_set);
3905
3906     /* Substitute do_round () with do_mal_round () */
3907     GNUNET_assert (NULL != sub->do_round_task);
3908     GNUNET_SCHEDULER_cancel (sub->do_round_task);
3909     sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, sub);
3910   }
3911
3912   else if ( (2 == mal_type) ||
3913             (3 == mal_type) )
3914   { /* Try to partition the network */
3915     /* Add other malicious peers to those we already know */
3916
3917     num_mal_peers_sent = ntohl (msg->num_peers) - 1;
3918     num_mal_peers_old = num_mal_peers;
3919     GNUNET_assert (GNUNET_MAX_MALLOC_CHECKED > num_mal_peers_sent);
3920     GNUNET_array_grow (mal_peers,
3921                        num_mal_peers,
3922                        num_mal_peers + num_mal_peers_sent);
3923     if (NULL != mal_peers &&
3924         0 != num_mal_peers)
3925     {
3926       GNUNET_memcpy (&mal_peers[num_mal_peers_old],
3927               peers,
3928               num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
3929
3930       /* Add all mal peers to mal_peer_set */
3931       add_peer_array_to_set (&mal_peers[num_mal_peers_old],
3932                              num_mal_peers_sent,
3933                              mal_peer_set);
3934     }
3935
3936     /* Store the one attacked peer */
3937     GNUNET_memcpy (&attacked_peer,
3938             &msg->attacked_peer,
3939             sizeof (struct GNUNET_PeerIdentity));
3940     /* Set the flag of the attacked peer to valid to avoid problems */
3941     if (GNUNET_NO == check_peer_known (sub->peer_map, &attacked_peer))
3942     {
3943       (void) issue_peer_online_check (sub, &attacked_peer);
3944     }
3945
3946     LOG (GNUNET_ERROR_TYPE_DEBUG,
3947          "Attacked peer is %s\n",
3948          GNUNET_i2s (&attacked_peer));
3949
3950     /* Substitute do_round () with do_mal_round () */
3951     if (NULL != sub->do_round_task)
3952     {
3953       /* Probably in shutdown */
3954       GNUNET_SCHEDULER_cancel (sub->do_round_task);
3955       sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, sub);
3956     }
3957   }
3958   else if (0 == mal_type)
3959   { /* Stop acting malicious */
3960     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
3961
3962     /* Substitute do_mal_round () with do_round () */
3963     GNUNET_SCHEDULER_cancel (sub->do_round_task);
3964     sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_round, sub);
3965   }
3966   else
3967   {
3968     GNUNET_break (0);
3969     GNUNET_SERVICE_client_continue (cli_ctx->client);
3970   }
3971   GNUNET_SERVICE_client_continue (cli_ctx->client);
3972 }
3973
3974
3975 /**
3976  * Send out PUSHes and PULLs maliciously.
3977  *
3978  * This is executed regylary.
3979  *
3980  * @param cls Closure - Sub
3981  */
3982 static void
3983 do_mal_round (void *cls)
3984 {
3985   uint32_t num_pushes;
3986   uint32_t i;
3987   struct GNUNET_TIME_Relative time_next_round;
3988   struct AttackedPeer *tmp_att_peer;
3989   struct Sub *sub = cls;
3990
3991   LOG (GNUNET_ERROR_TYPE_DEBUG,
3992        "Going to execute next round maliciously type %" PRIu32 ".\n",
3993       mal_type);
3994   sub->do_round_task = NULL;
3995   GNUNET_assert (mal_type <= 3);
3996   /* Do malicious actions */
3997   if (1 == mal_type)
3998   { /* Try to maximise representation */
3999
4000     /* The maximum of pushes we're going to send this round */
4001     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
4002                                          num_attacked_peers),
4003                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
4004
4005     LOG (GNUNET_ERROR_TYPE_DEBUG,
4006          "Going to send %" PRIu32 " pushes\n",
4007          num_pushes);
4008
4009     /* Send PUSHes to attacked peers */
4010     for (i = 0 ; i < num_pushes ; i++)
4011     {
4012       if (att_peers_tail == att_peer_index)
4013         att_peer_index = att_peers_head;
4014       else
4015         att_peer_index = att_peer_index->next;
4016
4017       send_push (get_peer_ctx (sub->peer_map, &att_peer_index->peer_id));
4018     }
4019
4020     /* Send PULLs to some peers to learn about additional peers to attack */
4021     tmp_att_peer = att_peer_index;
4022     for (i = 0 ; i < num_pushes * alpha ; i++)
4023     {
4024       if (att_peers_tail == tmp_att_peer)
4025         tmp_att_peer = att_peers_head;
4026       else
4027         att_peer_index = tmp_att_peer->next;
4028
4029       send_pull_request (get_peer_ctx (sub->peer_map, &tmp_att_peer->peer_id));
4030     }
4031   }
4032
4033
4034   else if (2 == mal_type)
4035   { /**
4036      * Try to partition the network
4037      * Send as many pushes to the attacked peer as possible
4038      * That is one push per round as it will ignore more.
4039      */
4040     (void) issue_peer_online_check (sub, &attacked_peer);
4041     if (GNUNET_YES == check_peer_flag (sub->peer_map,
4042                                        &attacked_peer,
4043                                        Peers_ONLINE))
4044       send_push (get_peer_ctx (sub->peer_map, &attacked_peer));
4045   }
4046
4047
4048   if (3 == mal_type)
4049   { /* Combined attack */
4050
4051     /* Send PUSH to attacked peers */
4052     if (GNUNET_YES == check_peer_known (sub->peer_map, &attacked_peer))
4053     {
4054       (void) issue_peer_online_check (sub, &attacked_peer);
4055       if (GNUNET_YES == check_peer_flag (sub->peer_map,
4056                                          &attacked_peer,
4057                                          Peers_ONLINE))
4058       {
4059         LOG (GNUNET_ERROR_TYPE_DEBUG,
4060             "Goding to send push to attacked peer (%s)\n",
4061             GNUNET_i2s (&attacked_peer));
4062         send_push (get_peer_ctx (sub->peer_map, &attacked_peer));
4063       }
4064     }
4065     (void) issue_peer_online_check (sub, &attacked_peer);
4066
4067     /* The maximum of pushes we're going to send this round */
4068     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
4069                                          num_attacked_peers),
4070                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
4071
4072     LOG (GNUNET_ERROR_TYPE_DEBUG,
4073          "Going to send %" PRIu32 " pushes\n",
4074          num_pushes);
4075
4076     for (i = 0; i < num_pushes; i++)
4077     {
4078       if (att_peers_tail == att_peer_index)
4079         att_peer_index = att_peers_head;
4080       else
4081         att_peer_index = att_peer_index->next;
4082
4083       send_push (get_peer_ctx (sub->peer_map, &att_peer_index->peer_id));
4084     }
4085
4086     /* Send PULLs to some peers to learn about additional peers to attack */
4087     tmp_att_peer = att_peer_index;
4088     for (i = 0; i < num_pushes * alpha; i++)
4089     {
4090       if (att_peers_tail == tmp_att_peer)
4091         tmp_att_peer = att_peers_head;
4092       else
4093         att_peer_index = tmp_att_peer->next;
4094
4095       send_pull_request (get_peer_ctx (sub->peer_map, &tmp_att_peer->peer_id));
4096     }
4097   }
4098
4099   /* Schedule next round */
4100   time_next_round = compute_rand_delay (sub->round_interval, 2);
4101
4102   GNUNET_assert (NULL == sub->do_round_task);
4103   sub->do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round,
4104                                                     &do_mal_round, sub);
4105   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
4106 }
4107 #endif /* ENABLE_MALICIOUS */
4108
4109
4110 /**
4111  * Send out PUSHes and PULLs, possibly update #view, samplers.
4112  *
4113  * This is executed regylary.
4114  *
4115  * @param cls Closure - Sub
4116  */
4117 static void
4118 do_round (void *cls)
4119 {
4120   unsigned int i;
4121   const struct GNUNET_PeerIdentity *view_array;
4122   unsigned int *permut;
4123   unsigned int a_peers; /* Number of peers we send pushes to */
4124   unsigned int b_peers; /* Number of peers we send pull requests to */
4125   uint32_t first_border;
4126   uint32_t second_border;
4127   struct GNUNET_PeerIdentity peer;
4128   struct GNUNET_PeerIdentity *update_peer;
4129   struct Sub *sub = cls;
4130
4131   sub->num_rounds++;
4132   LOG (GNUNET_ERROR_TYPE_DEBUG,
4133        "Going to execute next round.\n");
4134   if (sub == msub)
4135   {
4136     GNUNET_STATISTICS_update (stats, "# rounds", 1, GNUNET_NO);
4137   }
4138   sub->do_round_task = NULL;
4139   LOG (GNUNET_ERROR_TYPE_DEBUG,
4140        "Printing view:\n");
4141   to_file (sub->file_name_view_log,
4142            "___ new round ___");
4143   view_array = View_get_as_array (sub->view);
4144   for (i = 0; i < View_size (sub->view); i++)
4145   {
4146     LOG (GNUNET_ERROR_TYPE_DEBUG,
4147          "\t%s\n", GNUNET_i2s (&view_array[i]));
4148     to_file (sub->file_name_view_log,
4149              "=%s\t(do round)",
4150              GNUNET_i2s_full (&view_array[i]));
4151   }
4152
4153
4154   /* Send pushes and pull requests */
4155   if (0 < View_size (sub->view))
4156   {
4157     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
4158                                            View_size (sub->view));
4159
4160     /* Send PUSHes */
4161     a_peers = ceil (alpha * View_size (sub->view));
4162
4163     LOG (GNUNET_ERROR_TYPE_DEBUG,
4164          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
4165          a_peers, alpha, View_size (sub->view));
4166     for (i = 0; i < a_peers; i++)
4167     {
4168       peer = view_array[permut[i]];
4169       // FIXME if this fails schedule/loop this for later
4170       send_push (get_peer_ctx (sub->peer_map, &peer));
4171     }
4172
4173     /* Send PULL requests */
4174     b_peers = ceil (beta * View_size (sub->view));
4175     first_border = a_peers;
4176     second_border = a_peers + b_peers;
4177     if (second_border > View_size (sub->view))
4178     {
4179       first_border = View_size (sub->view) - b_peers;
4180       second_border = View_size (sub->view);
4181     }
4182     LOG (GNUNET_ERROR_TYPE_DEBUG,
4183         "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
4184         b_peers, beta, View_size (sub->view));
4185     for (i = first_border; i < second_border; i++)
4186     {
4187       peer = view_array[permut[i]];
4188       if ( GNUNET_NO == check_peer_flag (sub->peer_map,
4189                                          &peer,
4190                                          Peers_PULL_REPLY_PENDING))
4191       { // FIXME if this fails schedule/loop this for later
4192         send_pull_request (get_peer_ctx (sub->peer_map, &peer));
4193       }
4194     }
4195
4196     GNUNET_free (permut);
4197     permut = NULL;
4198   }
4199
4200
4201   /* Update view */
4202   /* TODO see how many peers are in push-/pull- list! */
4203
4204   if ((CustomPeerMap_size (sub->push_map) <= alpha * sub->view_size_est_need) &&
4205       (0 < CustomPeerMap_size (sub->push_map)) &&
4206       (0 < CustomPeerMap_size (sub->pull_map)))
4207   { /* If conditions for update are fulfilled, update */
4208     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the view.\n");
4209
4210     uint32_t final_size;
4211     uint32_t peers_to_clean_size;
4212     struct GNUNET_PeerIdentity *peers_to_clean;
4213
4214     peers_to_clean = NULL;
4215     peers_to_clean_size = 0;
4216     GNUNET_array_grow (peers_to_clean,
4217                        peers_to_clean_size,
4218                        View_size (sub->view));
4219     GNUNET_memcpy (peers_to_clean,
4220             view_array,
4221             View_size (sub->view) * sizeof (struct GNUNET_PeerIdentity));
4222
4223     /* Seems like recreating is the easiest way of emptying the peermap */
4224     View_clear (sub->view);
4225     to_file (sub->file_name_view_log,
4226              "--- emptied ---");
4227
4228     first_border  = GNUNET_MIN (ceil (alpha * sub->view_size_est_need),
4229                                 CustomPeerMap_size (sub->push_map));
4230     second_border = first_border +
4231                     GNUNET_MIN (floor (beta  * sub->view_size_est_need),
4232                                 CustomPeerMap_size (sub->pull_map));
4233     final_size    = second_border +
4234       ceil ((1 - (alpha + beta)) * sub->view_size_est_need);
4235     LOG (GNUNET_ERROR_TYPE_DEBUG,
4236         "first border: %" PRIu32 ", second border: %" PRIu32 ", final size: %"PRIu32 "\n",
4237         first_border,
4238         second_border,
4239         final_size);
4240
4241     /* Update view with peers received through PUSHes */
4242     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
4243                                            CustomPeerMap_size (sub->push_map));
4244     for (i = 0; i < first_border; i++)
4245     {
4246       int inserted;
4247       inserted = insert_in_view (sub,
4248                                  CustomPeerMap_get_peer_by_index (sub->push_map,
4249                                                                   permut[i]));
4250       if (GNUNET_OK == inserted)
4251       {
4252         clients_notify_stream_peer (sub,
4253             1,
4254             CustomPeerMap_get_peer_by_index (sub->push_map, permut[i]));
4255       }
4256       to_file (sub->file_name_view_log,
4257                "+%s\t(push list)",
4258                GNUNET_i2s_full (&view_array[i]));
4259       // TODO change the peer_flags accordingly
4260     }
4261     GNUNET_free (permut);
4262     permut = NULL;
4263
4264     /* Update view with peers received through PULLs */
4265     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
4266                                            CustomPeerMap_size (sub->pull_map));
4267     for (i = first_border; i < second_border; i++)
4268     {
4269       int inserted;
4270       inserted = insert_in_view (sub,
4271           CustomPeerMap_get_peer_by_index (sub->pull_map,
4272                                            permut[i - first_border]));
4273       if (GNUNET_OK == inserted)
4274       {
4275         clients_notify_stream_peer (sub,
4276             1,
4277             CustomPeerMap_get_peer_by_index (sub->pull_map,
4278                                              permut[i - first_border]));
4279       }
4280       to_file (sub->file_name_view_log,
4281                "+%s\t(pull list)",
4282                GNUNET_i2s_full (&view_array[i]));
4283       // TODO change the peer_flags accordingly
4284     }
4285     GNUNET_free (permut);
4286     permut = NULL;
4287
4288     /* Update view with peers from history */
4289     RPS_sampler_get_n_rand_peers (sub->sampler,
4290                                   final_size - second_border,
4291                                   hist_update,
4292                                   sub);
4293     // TODO change the peer_flags accordingly
4294
4295     for (i = 0; i < View_size (sub->view); i++)
4296       rem_from_list (&peers_to_clean, &peers_to_clean_size, &view_array[i]);
4297
4298     /* Clean peers that were removed from the view */
4299     for (i = 0; i < peers_to_clean_size; i++)
4300     {
4301       to_file (sub->file_name_view_log,
4302                "-%s",
4303                GNUNET_i2s_full (&peers_to_clean[i]));
4304       clean_peer (sub, &peers_to_clean[i]);
4305     }
4306
4307     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, 0);
4308     clients_notify_view_update (sub);
4309   } else {
4310     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the view.\n");
4311     if (sub == msub)
4312     {
4313       GNUNET_STATISTICS_update(stats, "# rounds blocked", 1, GNUNET_NO);
4314       if (CustomPeerMap_size (sub->push_map) > alpha * View_size (sub->view) &&
4315           !(0 >= CustomPeerMap_size (sub->pull_map)))
4316         GNUNET_STATISTICS_update(stats, "# rounds blocked - too many pushes", 1, GNUNET_NO);
4317       if (CustomPeerMap_size (sub->push_map) > alpha * View_size (sub->view) &&
4318           (0 >= CustomPeerMap_size (sub->pull_map)))
4319         GNUNET_STATISTICS_update(stats, "# rounds blocked - too many pushes, no pull replies", 1, GNUNET_NO);
4320       if (0 >= CustomPeerMap_size (sub->push_map) &&
4321           !(0 >= CustomPeerMap_size (sub->pull_map)))
4322         GNUNET_STATISTICS_update(stats, "# rounds blocked - no pushes", 1, GNUNET_NO);
4323       if (0 >= CustomPeerMap_size (sub->push_map) &&
4324           (0 >= CustomPeerMap_size (sub->pull_map)))
4325         GNUNET_STATISTICS_update(stats, "# rounds blocked - no pushes, no pull replies", 1, GNUNET_NO);
4326       if (0 >= CustomPeerMap_size (sub->pull_map) &&
4327           CustomPeerMap_size (sub->push_map) > alpha * View_size (sub->view) &&
4328           0 >= CustomPeerMap_size (sub->push_map))
4329         GNUNET_STATISTICS_update(stats, "# rounds blocked - no pull replies", 1, GNUNET_NO);
4330     }
4331   }
4332   // TODO independent of that also get some peers from CADET_get_peers()?
4333   sub->push_recv[CustomPeerMap_size (sub->push_map)]++;
4334   if (sub == msub)
4335   {
4336     GNUNET_STATISTICS_set (stats,
4337         "# peers in push map at end of round",
4338         CustomPeerMap_size (sub->push_map),
4339         GNUNET_NO);
4340     GNUNET_STATISTICS_set (stats,
4341         "# peers in pull map at end of round",
4342         CustomPeerMap_size (sub->pull_map),
4343         GNUNET_NO);
4344     GNUNET_STATISTICS_set (stats,
4345         "# peers in view at end of round",
4346         View_size (sub->view),
4347         GNUNET_NO);
4348   }
4349
4350   LOG (GNUNET_ERROR_TYPE_DEBUG,
4351        "Received %u pushes and %u pulls last round (alpha (%.2f) * view_size (sub->view%u) = %.2f)\n",
4352        CustomPeerMap_size (sub->push_map),
4353        CustomPeerMap_size (sub->pull_map),
4354        alpha,
4355        View_size (sub->view),
4356        alpha * View_size (sub->view));
4357
4358   /* Update samplers */
4359   for (i = 0; i < CustomPeerMap_size (sub->push_map); i++)
4360   {
4361     update_peer = CustomPeerMap_get_peer_by_index (sub->push_map, i);
4362     LOG (GNUNET_ERROR_TYPE_DEBUG,
4363          "Updating with peer %s from push list\n",
4364          GNUNET_i2s (update_peer));
4365     insert_in_sampler (sub, update_peer);
4366     clean_peer (sub, update_peer); /* This cleans only if it is not in the view */
4367   }
4368
4369   for (i = 0; i < CustomPeerMap_size (sub->pull_map); i++)
4370   {
4371     LOG (GNUNET_ERROR_TYPE_DEBUG,
4372          "Updating with peer %s from pull list\n",
4373          GNUNET_i2s (CustomPeerMap_get_peer_by_index (sub->pull_map, i)));
4374     insert_in_sampler (sub, CustomPeerMap_get_peer_by_index (sub->pull_map, i));
4375     /* This cleans only if it is not in the view */
4376     clean_peer (sub, CustomPeerMap_get_peer_by_index (sub->pull_map, i));
4377   }
4378
4379
4380   /* Empty push/pull lists */
4381   CustomPeerMap_clear (sub->push_map);
4382   CustomPeerMap_clear (sub->pull_map);
4383
4384   if (sub == msub)
4385   {
4386     GNUNET_STATISTICS_set (stats,
4387                            "view size",
4388                            View_size(sub->view),
4389                            GNUNET_NO);
4390   }
4391
4392   struct GNUNET_TIME_Relative time_next_round;
4393
4394   time_next_round = compute_rand_delay (sub->round_interval, 2);
4395
4396   /* Schedule next round */
4397   sub->do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round,
4398                                                      &do_round, sub);
4399   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
4400 }
4401
4402
4403 /**
4404  * This is called from GNUNET_CADET_get_peers().
4405  *
4406  * It is called on every peer(ID) that cadet somehow has contact with.
4407  * We use those to initialise the sampler.
4408  *
4409  * implements #GNUNET_CADET_PeersCB
4410  *
4411  * @param cls Closure - Sub
4412  * @param peer Peer, or NULL on "EOF".
4413  * @param tunnel Do we have a tunnel towards this peer?
4414  * @param n_paths Number of known paths towards this peer.
4415  * @param best_path How long is the best path?
4416  *                  (0 = unknown, 1 = ourselves, 2 = neighbor)
4417  */
4418 void
4419 init_peer_cb (void *cls,
4420               const struct GNUNET_PeerIdentity *peer,
4421               int tunnel, /* "Do we have a tunnel towards this peer?" */
4422               unsigned int n_paths, /* "Number of known paths towards this peer" */
4423               unsigned int best_path) /* "How long is the best path?
4424                                        * (0 = unknown, 1 = ourselves, 2 = neighbor)" */
4425 {
4426   struct Sub *sub = cls;
4427   (void) tunnel;
4428   (void) n_paths;
4429   (void) best_path;
4430
4431   if (NULL != peer)
4432   {
4433     LOG (GNUNET_ERROR_TYPE_DEBUG,
4434          "Got peer_id %s from cadet\n",
4435          GNUNET_i2s (peer));
4436     got_peer (sub, peer);
4437   }
4438 }
4439
4440
4441 /**
4442  * @brief Iterator function over stored, valid peers.
4443  *
4444  * We initialise the sampler with those.
4445  *
4446  * @param cls Closure - Sub
4447  * @param peer the peer id
4448  * @return #GNUNET_YES if we should continue to
4449  *         iterate,
4450  *         #GNUNET_NO if not.
4451  */
4452 static int
4453 valid_peers_iterator (void *cls,
4454                       const struct GNUNET_PeerIdentity *peer)
4455 {
4456   struct Sub *sub = cls;
4457
4458   if (NULL != peer)
4459   {
4460     LOG (GNUNET_ERROR_TYPE_DEBUG,
4461          "Got stored, valid peer %s\n",
4462          GNUNET_i2s (peer));
4463     got_peer (sub, peer);
4464   }
4465   return GNUNET_YES;
4466 }
4467
4468
4469 /**
4470  * Iterator over peers from peerinfo.
4471  *
4472  * @param cls Closure - Sub
4473  * @param peer id of the peer, NULL for last call
4474  * @param hello hello message for the peer (can be NULL)
4475  * @param error message
4476  */
4477 void
4478 process_peerinfo_peers (void *cls,
4479                         const struct GNUNET_PeerIdentity *peer,
4480                         const struct GNUNET_HELLO_Message *hello,
4481                         const char *err_msg)
4482 {
4483   struct Sub *sub = cls;
4484   (void) hello;
4485   (void) err_msg;
4486
4487   if (NULL != peer)
4488   {
4489     LOG (GNUNET_ERROR_TYPE_DEBUG,
4490          "Got peer_id %s from peerinfo\n",
4491          GNUNET_i2s (peer));
4492     got_peer (sub, peer);
4493   }
4494 }
4495
4496
4497 /**
4498  * Task run during shutdown.
4499  *
4500  * @param cls Closure - unused
4501  */
4502 static void
4503 shutdown_task (void *cls)
4504 {
4505   (void) cls;
4506   struct ClientContext *client_ctx;
4507
4508   LOG (GNUNET_ERROR_TYPE_DEBUG,
4509        "RPS service is going down\n");
4510
4511   /* Clean all clients */
4512   for (client_ctx = cli_ctx_head;
4513        NULL != cli_ctx_head;
4514        client_ctx = cli_ctx_head)
4515   {
4516     destroy_cli_ctx (client_ctx);
4517   }
4518   if (NULL != msub)
4519   {
4520     destroy_sub (msub);
4521     msub = NULL;
4522   }
4523
4524   /* Disconnect from other services */
4525   GNUNET_PEERINFO_notify_cancel (peerinfo_notify_handle);
4526   GNUNET_PEERINFO_disconnect (peerinfo_handle);
4527   peerinfo_handle = NULL;
4528   GNUNET_NSE_disconnect (nse);
4529   if (NULL != map_single_hop)
4530   {
4531     /* core_init was called - core was initialised */
4532     /* disconnect first, so no callback tries to access missing peermap */
4533     GNUNET_CORE_disconnect (core_handle);
4534     core_handle = NULL;
4535     GNUNET_CONTAINER_multipeermap_destroy (map_single_hop);
4536     map_single_hop = NULL;
4537   }
4538
4539   if (NULL != stats)
4540   {
4541     GNUNET_STATISTICS_destroy (stats,
4542                                GNUNET_NO);
4543     stats = NULL;
4544   }
4545   GNUNET_CADET_disconnect (cadet_handle);
4546   cadet_handle = NULL;
4547 #if ENABLE_MALICIOUS
4548   struct AttackedPeer *tmp_att_peer;
4549   GNUNET_array_grow (mal_peers,
4550                      num_mal_peers,
4551                      0);
4552   if (NULL != mal_peer_set)
4553     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
4554   if (NULL != att_peer_set)
4555     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
4556   while (NULL != att_peers_head)
4557   {
4558     tmp_att_peer = att_peers_head;
4559     GNUNET_CONTAINER_DLL_remove (att_peers_head,
4560                                  att_peers_tail,
4561                                  tmp_att_peer);
4562     GNUNET_free (tmp_att_peer);
4563   }
4564 #endif /* ENABLE_MALICIOUS */
4565   close_all_files();
4566 }
4567
4568
4569 /**
4570  * Handle client connecting to the service.
4571  *
4572  * @param cls unused
4573  * @param client the new client
4574  * @param mq the message queue of @a client
4575  * @return @a client
4576  */
4577 static void *
4578 client_connect_cb (void *cls,
4579                    struct GNUNET_SERVICE_Client *client,
4580                    struct GNUNET_MQ_Handle *mq)
4581 {
4582   struct ClientContext *cli_ctx;
4583   (void) cls;
4584
4585   LOG (GNUNET_ERROR_TYPE_DEBUG,
4586        "Client connected\n");
4587   if (NULL == client)
4588     return client; /* Server was destroyed before a client connected. Shutting down */
4589   cli_ctx = GNUNET_new (struct ClientContext);
4590   cli_ctx->mq = mq;
4591   cli_ctx->view_updates_left = -1;
4592   cli_ctx->stream_update = GNUNET_NO;
4593   cli_ctx->client = client;
4594   GNUNET_CONTAINER_DLL_insert (cli_ctx_head,
4595                                cli_ctx_tail,
4596                                cli_ctx);
4597   return cli_ctx;
4598 }
4599
4600 /**
4601  * Callback called when a client disconnected from the service
4602  *
4603  * @param cls closure for the service
4604  * @param c the client that disconnected
4605  * @param internal_cls should be equal to @a c
4606  */
4607 static void
4608 client_disconnect_cb (void *cls,
4609                       struct GNUNET_SERVICE_Client *client,
4610                       void *internal_cls)
4611 {
4612   struct ClientContext *cli_ctx = internal_cls;
4613
4614   (void) cls;
4615   GNUNET_assert (client == cli_ctx->client);
4616   if (NULL == client)
4617   {/* shutdown task - destroy all clients */
4618     while (NULL != cli_ctx_head)
4619       destroy_cli_ctx (cli_ctx_head);
4620   }
4621   else
4622   { /* destroy this client */
4623     LOG (GNUNET_ERROR_TYPE_DEBUG,
4624         "Client disconnected. Destroy its context.\n");
4625     destroy_cli_ctx (cli_ctx);
4626   }
4627 }
4628
4629
4630 /**
4631  * Handle random peer sampling clients.
4632  *
4633  * @param cls closure
4634  * @param c configuration to use
4635  * @param service the initialized service
4636  */
4637 static void
4638 run (void *cls,
4639      const struct GNUNET_CONFIGURATION_Handle *c,
4640      struct GNUNET_SERVICE_Handle *service)
4641 {
4642   struct GNUNET_TIME_Relative round_interval;
4643   long long unsigned int sampler_size;
4644   char hash_port_string[] = GNUNET_APPLICATION_PORT_RPS;
4645   struct GNUNET_HashCode hash;
4646
4647   (void) cls;
4648   (void) service;
4649
4650   GNUNET_log_setup ("rps",
4651                     GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG),
4652                     NULL);
4653   cfg = c;
4654   /* Get own ID */
4655   GNUNET_CRYPTO_get_peer_identity (cfg,
4656                                    &own_identity); // TODO check return value
4657   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4658               "STARTING SERVICE (rps) for peer [%s]\n",
4659               GNUNET_i2s (&own_identity));
4660 #if ENABLE_MALICIOUS
4661   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4662               "Malicious execution compiled in.\n");
4663 #endif /* ENABLE_MALICIOUS */
4664
4665   /* Get time interval from the configuration */
4666   if (GNUNET_OK !=
4667       GNUNET_CONFIGURATION_get_value_time (cfg,
4668                                            "RPS",
4669                                            "ROUNDINTERVAL",
4670                                            &round_interval))
4671   {
4672     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4673                                "RPS", "ROUNDINTERVAL");
4674     GNUNET_SCHEDULER_shutdown ();
4675     return;
4676   }
4677
4678   /* Get initial size of sampler/view from the configuration */
4679   if (GNUNET_OK !=
4680       GNUNET_CONFIGURATION_get_value_number (cfg,
4681                                              "RPS",
4682                                              "MINSIZE",
4683                                              &sampler_size))
4684   {
4685     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4686                                "RPS", "MINSIZE");
4687     GNUNET_SCHEDULER_shutdown ();
4688     return;
4689   }
4690
4691   cadet_handle = GNUNET_CADET_connect (cfg);
4692   GNUNET_assert (NULL != cadet_handle);
4693   core_handle = GNUNET_CORE_connect (cfg,
4694                                      NULL, /* cls */
4695                                      core_init, /* init */
4696                                      core_connects, /* connects */
4697                                      core_disconnects, /* disconnects */
4698                                      NULL); /* handlers */
4699   GNUNET_assert (NULL != core_handle);
4700
4701
4702   alpha = 0.45;
4703   beta  = 0.45;
4704
4705
4706   /* Set up main Sub */
4707   GNUNET_CRYPTO_hash (hash_port_string,
4708                       strlen (hash_port_string),
4709                       &hash);
4710   msub = new_sub (&hash,
4711                  sampler_size, /* Will be overwritten by config */
4712                  round_interval);
4713
4714
4715   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
4716
4717   /* connect to NSE */
4718   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
4719
4720   //LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
4721   //GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, msub);
4722   // TODO send push/pull to each of those peers?
4723   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting stored valid peers\n");
4724   restore_valid_peers (msub);
4725   get_valid_peers (msub->valid_peers, valid_peers_iterator, msub);
4726
4727   peerinfo_notify_handle = GNUNET_PEERINFO_notify (cfg,
4728                                                    GNUNET_NO,
4729                                                    process_peerinfo_peers,
4730                                                    msub);
4731
4732   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
4733
4734   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
4735   stats = GNUNET_STATISTICS_create ("rps", cfg);
4736 }
4737
4738
4739 /**
4740  * Define "main" method using service macro.
4741  */
4742 GNUNET_SERVICE_MAIN
4743 ("rps",
4744  GNUNET_SERVICE_OPTION_NONE,
4745  &run,
4746  &client_connect_cb,
4747  &client_disconnect_cb,
4748  NULL,
4749  GNUNET_MQ_hd_var_size (client_seed,
4750    GNUNET_MESSAGE_TYPE_RPS_CS_SEED,
4751    struct GNUNET_RPS_CS_SeedMessage,
4752    NULL),
4753 #if ENABLE_MALICIOUS
4754  GNUNET_MQ_hd_var_size (client_act_malicious,
4755    GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS,
4756    struct GNUNET_RPS_CS_ActMaliciousMessage,
4757    NULL),
4758 #endif /* ENABLE_MALICIOUS */
4759  GNUNET_MQ_hd_fixed_size (client_view_request,
4760    GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REQUEST,
4761    struct GNUNET_RPS_CS_DEBUG_ViewRequest,
4762    NULL),
4763  GNUNET_MQ_hd_fixed_size (client_view_cancel,
4764    GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_CANCEL,
4765    struct GNUNET_MessageHeader,
4766    NULL),
4767  GNUNET_MQ_hd_fixed_size (client_stream_request,
4768    GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_REQUEST,
4769    struct GNUNET_RPS_CS_DEBUG_StreamRequest,
4770    NULL),
4771  GNUNET_MQ_hd_fixed_size (client_stream_cancel,
4772    GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_CANCEL,
4773    struct GNUNET_MessageHeader,
4774    NULL),
4775  GNUNET_MQ_hd_fixed_size (client_start_sub,
4776    GNUNET_MESSAGE_TYPE_RPS_CS_SUB_START,
4777    struct GNUNET_RPS_CS_SubStartMessage,
4778    NULL),
4779  GNUNET_MQ_hd_fixed_size (client_stop_sub,
4780    GNUNET_MESSAGE_TYPE_RPS_CS_SUB_STOP,
4781    struct GNUNET_RPS_CS_SubStopMessage,
4782    NULL),
4783  GNUNET_MQ_handler_end());
4784
4785 /* end of gnunet-service-rps.c */