2 This file is part of GNUnet.
3 Copyright (C) 2013-2015 GNUnet e.V.
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.
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.
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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file rps/gnunet-service-rps.c
23 * @brief rps service implementation
24 * @author Julius Bünger
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"
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"
44 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
46 // TODO check for overflows
48 // TODO align message structs
50 // TODO connect to friends
52 // TODO blacklist? (-> mal peer detection on top of brahms)
54 // hist_size_init, hist_size_max
56 /***********************************************************************
57 * Old gnunet-service-rps_peers.c
58 ***********************************************************************/
61 * Set a peer flag of given peer context.
63 #define SET_PEER_FLAG(peer_ctx, mask) ((peer_ctx->peer_flags) |= (mask))
66 * Get peer flag of given peer context.
68 #define check_peer_flag_set(peer_ctx, mask)\
69 ((peer_ctx->peer_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
72 * Unset flag of given peer context.
74 #define UNSET_PEER_FLAG(peer_ctx, mask) ((peer_ctx->peer_flags) &= ~(mask))
77 * Get channel flag of given channel context.
79 #define check_channel_flag_set(channel_flags, mask)\
80 ((*channel_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
83 * Unset flag of given channel context.
85 #define unset_channel_flag(channel_flags, mask) ((*channel_flags) &= ~(mask))
90 * Pending operation on peer consisting of callback and closure
92 * When an operation cannot be executed right now this struct is used to store
93 * the callback and closure for later execution.
109 * List containing all messages that are yet to be send
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.
114 struct PendingMessage
119 struct PendingMessage *next;
120 struct PendingMessage *prev;
123 * The envelope to the corresponding message
125 struct GNUNET_MQ_Envelope *ev;
128 * The corresponding context
130 struct PeerContext *peer_ctx;
139 * @brief Context for a channel
144 * Struct used to keep track of other peer's status
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, ...)
154 * The Sub this context belongs to.
159 * Message queue open to client
161 struct GNUNET_MQ_Handle *mq;
164 * Channel open to client.
166 struct ChannelCtx *send_channel_ctx;
169 * Channel open from client.
171 struct ChannelCtx *recv_channel_ctx;
174 * Array of pending operations on this peer.
176 struct PeerPendingOp *pending_ops;
179 * Handle to the callback given to cadet_ntfy_tmt_rdy()
181 * To be canceled on shutdown.
183 struct PendingMessage *online_check_pending;
186 * Number of pending operations.
188 unsigned int num_pending_ops;
191 * Identity of the peer
193 struct GNUNET_PeerIdentity peer_id;
196 * Flags indicating status of peer
201 * Last time we received something from that peer.
203 struct GNUNET_TIME_Absolute last_message_recv;
206 * Last time we received a keepalive message.
208 struct GNUNET_TIME_Absolute last_keepalive;
211 * DLL with all messages that are yet to be sent
213 struct PendingMessage *pending_messages_head;
214 struct PendingMessage *pending_messages_tail;
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),
221 uint32_t round_pull_req;
225 * @brief Closure to #valid_peer_iterator
227 struct PeersIteratorCls
232 PeersIterator iterator;
235 * Closure to iterator
241 * @brief Context for a channel
246 * @brief The channel itself
248 struct GNUNET_CADET_Channel *channel;
251 * @brief The peer context associated with the channel
253 struct PeerContext *peer_ctx;
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.
260 struct GNUNET_SCHEDULER_Task *destruction_task;
267 * If type is 2 This struct is used to store the attacked peers in a DLL
274 struct AttackedPeer *next;
275 struct AttackedPeer *prev;
280 struct GNUNET_PeerIdentity peer_id;
283 #endif /* ENABLE_MALICIOUS */
286 * @brief This number determines the number of slots for files that represent
289 #define HISTOGRAM_FILE_SLOTS 32
292 * @brief The size (in bytes) a file needs to store the histogram
294 * Per slot: 1 newline, up to 4 chars,
295 * Additionally: 1 null termination
297 #define SIZE_DUMP_FILE (HISTOGRAM_FILE_SLOTS * 5) + 1
302 * Essentially one instance of brahms that only connects to other instances
303 * with the same (secret) value.
308 * @brief Hash of the shared value that defines Subs.
310 struct GNUNET_HashCode hash;
313 * @brief Port to communicate to other peers.
315 struct GNUNET_CADET_Port *cadet_port;
318 * @brief Hashmap of valid peers.
320 struct GNUNET_CONTAINER_MultiPeerMap *valid_peers;
323 * @brief Filename of the file that stores the valid peers persistently.
325 char *filename_valid_peers;
328 * Set of all peers to keep track of them.
330 struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
333 * @brief This is the minimum estimate used as sampler size.
335 * It is configured by the user.
337 unsigned int sampler_size_est_min;
340 * The size of sampler we need to be able to satisfy the Brahms protocol's
341 * need of random peers.
343 * This is one minimum size the sampler grows to.
345 unsigned int sampler_size_est_need;
348 * Time inverval the do_round task runs in.
350 struct GNUNET_TIME_Relative round_interval;
353 * Sampler used for the Brahms protocol itself.
355 struct RPS_Sampler *sampler;
359 * Name to log view to
361 char *file_name_view_log;
362 #endif /* TO_FILE_FULL */
367 * Name to log number of observed peers to
369 char *file_name_observed_log;
370 #endif /* TO_FILE_FULL */
373 * @brief Count the observed peers
375 uint32_t num_observed_peers;
378 * @brief Multipeermap (ab-) used to count unique peer_ids
380 struct GNUNET_CONTAINER_MultiPeerMap *observed_unique_peers;
384 * List to store peers received through pushes temporary.
386 struct CustomPeerMap *push_map;
389 * List to store peers received through pulls temporary.
391 struct CustomPeerMap *pull_map;
394 * @brief This is the estimate used as view size.
396 * It is initialised with the minimum
398 unsigned int view_size_est_need;
401 * @brief This is the minimum estimate used as view size.
403 * It is configured by the user.
405 unsigned int view_size_est_min;
413 * Identifier for the main task that runs periodically.
415 struct GNUNET_SCHEDULER_Task *do_round_task;
420 * @brief Counts the executed rounds.
425 * @brief This array accumulates the number of received pushes per round.
427 * Number at index i represents the number of rounds with i observed pushes.
429 uint32_t push_recv[HISTOGRAM_FILE_SLOTS];
432 * @brief Histogram of deltas between the expected and actual number of
435 * As half of the entries are expected to be negative, this is shifted by
436 * #HISTOGRAM_FILE_SLOTS/2.
438 uint32_t push_delta[HISTOGRAM_FILE_SLOTS];
441 * @brief Number of pull replies with this delay measured in rounds.
443 * Number at index i represents the number of pull replies with a delay of i
446 uint32_t pull_delays[HISTOGRAM_FILE_SLOTS];
450 /***********************************************************************
452 ***********************************************************************/
457 static const struct GNUNET_CONFIGURATION_Handle *cfg;
460 * Handle to the statistics service.
462 struct GNUNET_STATISTICS_Handle *stats;
467 struct GNUNET_CADET_Handle *cadet_handle;
472 struct GNUNET_CORE_Handle *core_handle;
475 * @brief PeerMap to keep track of connected peers.
477 struct GNUNET_CONTAINER_MultiPeerMap *map_single_hop;
482 static struct GNUNET_PeerIdentity own_identity;
485 * Percentage of total peer number in the view
486 * to send random PUSHes to
491 * Percentage of total peer number in the view
492 * to send random PULLs to
499 static struct GNUNET_NSE_Handle *nse;
502 * Handler to PEERINFO.
504 static struct GNUNET_PEERINFO_Handle *peerinfo_handle;
507 * Handle for cancellation of iteration over peers.
509 static struct GNUNET_PEERINFO_NotifyContext *peerinfo_notify_handle;
514 * Type of malicious peer
516 * 0 Don't act malicious at all - Default
517 * 1 Try to maximise representation
518 * 2 Try to partition the network
521 static uint32_t mal_type;
524 * Other malicious peers
526 static struct GNUNET_PeerIdentity *mal_peers;
529 * Hashmap of malicious peers used as set.
530 * Used to more efficiently check whether we know that peer.
532 static struct GNUNET_CONTAINER_MultiPeerMap *mal_peer_set;
535 * Number of other malicious peers
537 static uint32_t num_mal_peers;
541 * If type is 2 this is the DLL of attacked peers
543 static struct AttackedPeer *att_peers_head;
544 static struct AttackedPeer *att_peers_tail;
547 * This index is used to point to an attacked peer to
548 * implement the round-robin-ish way to select attacked peers.
550 static struct AttackedPeer *att_peer_index;
553 * Hashmap of attacked peers used as set.
554 * Used to more efficiently check whether we know that peer.
556 static struct GNUNET_CONTAINER_MultiPeerMap *att_peer_set;
559 * Number of attacked peers
561 static uint32_t num_attacked_peers;
564 * If type is 1 this is the attacked peer
566 static struct GNUNET_PeerIdentity attacked_peer;
569 * The limit of PUSHes we can send in one round.
570 * This is an assumption of the Brahms protocol and either implemented
573 * assumend to be the bandwidth limitation.
575 static uint32_t push_limit = 10000;
576 #endif /* ENABLE_MALICIOUS */
581 * This is run in any case by all peers and connects to all peers without
582 * specifying a shared value.
584 static struct Sub *msub;
587 * @brief Maximum number of valid peers to keep.
588 * TODO read from config
590 static const uint32_t num_valid_peers_max = UINT32_MAX;
592 /***********************************************************************
594 ***********************************************************************/
598 do_round (void *cls);
601 do_mal_round (void *cls);
605 * @brief Get the #PeerContext associated with a peer
607 * @param peer_map The peer map containing the context
608 * @param peer the peer id
610 * @return the #PeerContext
612 static struct PeerContext *
613 get_peer_ctx (const struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
614 const struct GNUNET_PeerIdentity *peer)
616 struct PeerContext *ctx;
619 ret = GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
620 GNUNET_assert (GNUNET_YES == ret);
621 ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
622 GNUNET_assert (NULL != ctx);
627 * @brief Check whether we have information about the given peer.
629 * FIXME probably deprecated. Make this the new _online.
631 * @param peer_map The peer map to check for the existence of @a peer
632 * @param peer peer in question
634 * @return #GNUNET_YES if peer is known
635 * #GNUNET_NO if peer is not knwon
638 check_peer_known (const struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
639 const struct GNUNET_PeerIdentity *peer)
641 if (NULL != peer_map)
643 return GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
653 * @brief Create a new #PeerContext and insert it into the peer map
655 * @param sub The Sub this context belongs to.
656 * @param peer the peer to create the #PeerContext for
658 * @return the #PeerContext
660 static struct PeerContext *
661 create_peer_ctx (struct Sub *sub,
662 const struct GNUNET_PeerIdentity *peer)
664 struct PeerContext *ctx;
667 GNUNET_assert (GNUNET_NO == check_peer_known (sub->peer_map, peer));
669 ctx = GNUNET_new (struct PeerContext);
670 ctx->peer_id = *peer;
672 ret = GNUNET_CONTAINER_multipeermap_put (sub->peer_map, peer, ctx,
673 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
674 GNUNET_assert (GNUNET_OK == ret);
677 GNUNET_STATISTICS_set (stats,
679 GNUNET_CONTAINER_multipeermap_size (sub->peer_map),
687 * @brief Create or get a #PeerContext
689 * @param sub The Sub to which the created context belongs to
690 * @param peer the peer to get the associated context to
692 * @return the context
694 static struct PeerContext *
695 create_or_get_peer_ctx (struct Sub *sub,
696 const struct GNUNET_PeerIdentity *peer)
698 if (GNUNET_NO == check_peer_known (sub->peer_map, peer))
700 return create_peer_ctx (sub, peer);
702 return get_peer_ctx (sub->peer_map, peer);
707 * @brief Check whether we have a connection to this @a peer
709 * Also sets the #Peers_ONLINE flag accordingly
711 * @param peer_ctx Context of the peer of which connectivity is to be checked
713 * @return #GNUNET_YES if we are connected
714 * #GNUNET_NO otherwise
717 check_connected (struct PeerContext *peer_ctx)
719 /* If we don't know about this peer we don't know whether it's online */
720 if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
725 /* Get the context */
726 peer_ctx = get_peer_ctx (peer_ctx->sub->peer_map, &peer_ctx->peer_id);
727 /* If we have no channel to this peer we don't know whether it's online */
728 if ( (NULL == peer_ctx->send_channel_ctx) &&
729 (NULL == peer_ctx->recv_channel_ctx) )
731 UNSET_PEER_FLAG (peer_ctx, Peers_ONLINE);
734 /* Otherwise (if we have a channel, we know that it's online */
735 SET_PEER_FLAG (peer_ctx, Peers_ONLINE);
741 * @brief The closure to #get_rand_peer_iterator.
743 struct GetRandPeerIteratorCls
746 * @brief The index of the peer to return.
747 * Will be decreased until 0.
748 * Then current peer is returned.
753 * @brief Pointer to peer to return.
755 const struct GNUNET_PeerIdentity *peer;
760 * @brief Iterator function for #get_random_peer_from_peermap.
762 * Implements #GNUNET_CONTAINER_PeerMapIterator.
763 * Decreases the index until the index is null.
764 * Then returns the current peer.
766 * @param cls the #GetRandPeerIteratorCls containing index and peer
767 * @param peer current peer
768 * @param value unused
770 * @return #GNUNET_YES if we should continue to
775 get_rand_peer_iterator (void *cls,
776 const struct GNUNET_PeerIdentity *peer,
779 struct GetRandPeerIteratorCls *iterator_cls = cls;
782 if (0 >= iterator_cls->index)
784 iterator_cls->peer = peer;
787 iterator_cls->index--;
793 * @brief Get a random peer from @a peer_map
795 * @param valid_peers Peer map containing valid peers from which to select a
798 * @return a random peer
800 static const struct GNUNET_PeerIdentity *
801 get_random_peer_from_peermap (struct GNUNET_CONTAINER_MultiPeerMap *valid_peers)
803 struct GetRandPeerIteratorCls *iterator_cls;
804 const struct GNUNET_PeerIdentity *ret;
806 iterator_cls = GNUNET_new (struct GetRandPeerIteratorCls);
807 iterator_cls->index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
808 GNUNET_CONTAINER_multipeermap_size (valid_peers));
809 (void) GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
810 get_rand_peer_iterator,
812 ret = iterator_cls->peer;
813 GNUNET_free (iterator_cls);
819 * @brief Add a given @a peer to valid peers.
821 * If valid peers are already #num_valid_peers_max, delete a peer previously.
823 * @param peer The peer that is added to the valid peers.
824 * @param valid_peers Peer map of valid peers to which to add the @a peer
826 * @return #GNUNET_YES if no other peer had to be removed
827 * #GNUNET_NO otherwise
830 add_valid_peer (const struct GNUNET_PeerIdentity *peer,
831 struct GNUNET_CONTAINER_MultiPeerMap *valid_peers)
833 const struct GNUNET_PeerIdentity *rand_peer;
837 /* Remove random peers until there is space for a new one */
838 while (num_valid_peers_max <=
839 GNUNET_CONTAINER_multipeermap_size (valid_peers))
841 rand_peer = get_random_peer_from_peermap (valid_peers);
842 GNUNET_CONTAINER_multipeermap_remove_all (valid_peers, rand_peer);
845 (void) GNUNET_CONTAINER_multipeermap_put (valid_peers, peer, NULL,
846 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
847 if (valid_peers == msub->valid_peers)
849 GNUNET_STATISTICS_set (stats,
851 GNUNET_CONTAINER_multipeermap_size (valid_peers),
858 remove_pending_message (struct PendingMessage *pending_msg, int cancel);
861 * @brief Set the peer flag to living and
862 * call the pending operations on this peer.
864 * Also adds peer to #valid_peers.
866 * @param peer_ctx the #PeerContext of the peer to set online
869 set_peer_online (struct PeerContext *peer_ctx)
871 struct GNUNET_PeerIdentity *peer;
874 peer = &peer_ctx->peer_id;
875 LOG (GNUNET_ERROR_TYPE_DEBUG,
876 "Peer %s is online and valid, calling %i pending operations on it\n",
878 peer_ctx->num_pending_ops);
880 if (NULL != peer_ctx->online_check_pending)
882 LOG (GNUNET_ERROR_TYPE_DEBUG,
883 "Removing pending online check for peer %s\n",
884 GNUNET_i2s (&peer_ctx->peer_id));
885 // TODO wait until cadet sets mq->cancel_impl
886 //GNUNET_MQ_send_cancel (peer_ctx->online_check_pending->ev);
887 remove_pending_message (peer_ctx->online_check_pending, GNUNET_YES);
888 peer_ctx->online_check_pending = NULL;
891 SET_PEER_FLAG (peer_ctx, Peers_ONLINE);
893 /* Call pending operations */
894 for (i = 0; i < peer_ctx->num_pending_ops; i++)
896 peer_ctx->pending_ops[i].op (peer_ctx->pending_ops[i].op_cls, peer);
898 GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
902 cleanup_destroyed_channel (void *cls,
903 const struct GNUNET_CADET_Channel *channel);
905 /* Declaration of handlers */
907 handle_peer_check (void *cls,
908 const struct GNUNET_MessageHeader *msg);
911 handle_peer_push (void *cls,
912 const struct GNUNET_MessageHeader *msg);
915 handle_peer_pull_request (void *cls,
916 const struct GNUNET_MessageHeader *msg);
919 check_peer_pull_reply (void *cls,
920 const struct GNUNET_RPS_P2P_PullReplyMessage *msg);
923 handle_peer_pull_reply (void *cls,
924 const struct GNUNET_RPS_P2P_PullReplyMessage *msg);
926 /* End declaration of handlers */
929 * @brief Allocate memory for a new channel context and insert it into DLL
931 * @param peer_ctx context of the according peer
933 * @return The channel context
935 static struct ChannelCtx *
936 add_channel_ctx (struct PeerContext *peer_ctx)
938 struct ChannelCtx *channel_ctx;
939 channel_ctx = GNUNET_new (struct ChannelCtx);
940 channel_ctx->peer_ctx = peer_ctx;
946 * @brief Free memory and NULL pointers.
948 * @param channel_ctx The channel context.
951 remove_channel_ctx (struct ChannelCtx *channel_ctx)
953 struct PeerContext *peer_ctx = channel_ctx->peer_ctx;
955 if (NULL != channel_ctx->destruction_task)
957 GNUNET_SCHEDULER_cancel (channel_ctx->destruction_task);
958 channel_ctx->destruction_task = NULL;
961 GNUNET_free (channel_ctx);
963 if (NULL == peer_ctx) return;
964 if (channel_ctx == peer_ctx->send_channel_ctx)
966 peer_ctx->send_channel_ctx = NULL;
969 else if (channel_ctx == peer_ctx->recv_channel_ctx)
971 peer_ctx->recv_channel_ctx = NULL;
977 * @brief Get the channel of a peer. If not existing, create.
979 * @param peer_ctx Context of the peer of which to get the channel
980 * @return the #GNUNET_CADET_Channel used to send data to @a peer_ctx
982 struct GNUNET_CADET_Channel *
983 get_channel (struct PeerContext *peer_ctx)
985 /* There exists a copy-paste-clone in run() */
986 struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
987 GNUNET_MQ_hd_fixed_size (peer_check,
988 GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE,
989 struct GNUNET_MessageHeader,
991 GNUNET_MQ_hd_fixed_size (peer_push,
992 GNUNET_MESSAGE_TYPE_RPS_PP_PUSH,
993 struct GNUNET_MessageHeader,
995 GNUNET_MQ_hd_fixed_size (peer_pull_request,
996 GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
997 struct GNUNET_MessageHeader,
999 GNUNET_MQ_hd_var_size (peer_pull_reply,
1000 GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY,
1001 struct GNUNET_RPS_P2P_PullReplyMessage,
1003 GNUNET_MQ_handler_end ()
1007 if (NULL == peer_ctx->send_channel_ctx)
1009 LOG (GNUNET_ERROR_TYPE_DEBUG,
1010 "Trying to establish channel to peer %s\n",
1011 GNUNET_i2s (&peer_ctx->peer_id));
1012 peer_ctx->send_channel_ctx = add_channel_ctx (peer_ctx);
1013 peer_ctx->send_channel_ctx->channel =
1014 GNUNET_CADET_channel_create (cadet_handle,
1015 peer_ctx->send_channel_ctx, /* context */
1017 &peer_ctx->sub->hash,
1018 GNUNET_CADET_OPTION_RELIABLE,
1019 NULL, /* WindowSize handler */
1020 &cleanup_destroyed_channel, /* Disconnect handler */
1023 GNUNET_assert (NULL != peer_ctx->send_channel_ctx);
1024 GNUNET_assert (NULL != peer_ctx->send_channel_ctx->channel);
1025 return peer_ctx->send_channel_ctx->channel;
1030 * Get the message queue (#GNUNET_MQ_Handle) of a specific peer.
1032 * If we already have a message queue open to this client,
1033 * simply return it, otherways create one.
1035 * @param peer_ctx Context of the peer of whicht to get the mq
1036 * @return the #GNUNET_MQ_Handle
1038 static struct GNUNET_MQ_Handle *
1039 get_mq (struct PeerContext *peer_ctx)
1041 if (NULL == peer_ctx->mq)
1043 peer_ctx->mq = GNUNET_CADET_get_mq (get_channel (peer_ctx));
1045 return peer_ctx->mq;
1049 * @brief Add an envelope to a message passed to mq to list of pending messages
1051 * @param peer_ctx Context of the peer for which to insert the envelope
1052 * @param ev envelope to the message
1053 * @param type type of the message to be sent
1054 * @return pointer to pending message
1056 static struct PendingMessage *
1057 insert_pending_message (struct PeerContext *peer_ctx,
1058 struct GNUNET_MQ_Envelope *ev,
1061 struct PendingMessage *pending_msg;
1063 pending_msg = GNUNET_new (struct PendingMessage);
1064 pending_msg->ev = ev;
1065 pending_msg->peer_ctx = peer_ctx;
1066 pending_msg->type = type;
1067 GNUNET_CONTAINER_DLL_insert (peer_ctx->pending_messages_head,
1068 peer_ctx->pending_messages_tail,
1075 * @brief Remove a pending message from the respective DLL
1077 * @param pending_msg the pending message to remove
1078 * @param cancel whether to cancel the pending message, too
1081 remove_pending_message (struct PendingMessage *pending_msg, int cancel)
1083 struct PeerContext *peer_ctx;
1086 peer_ctx = pending_msg->peer_ctx;
1087 GNUNET_assert (NULL != peer_ctx);
1088 GNUNET_CONTAINER_DLL_remove (peer_ctx->pending_messages_head,
1089 peer_ctx->pending_messages_tail,
1091 // TODO wait for the cadet implementation of message cancellation
1092 //if (GNUNET_YES == cancel)
1094 // GNUNET_MQ_send_cancel (pending_msg->ev);
1096 GNUNET_free (pending_msg);
1101 * @brief This is called in response to the first message we sent as a
1104 * @param cls #PeerContext of peer with pending online check
1107 mq_online_check_successful (void *cls)
1109 struct PeerContext *peer_ctx = cls;
1111 if (NULL != peer_ctx->online_check_pending)
1113 LOG (GNUNET_ERROR_TYPE_DEBUG,
1114 "Online check for peer %s was successfull\n",
1115 GNUNET_i2s (&peer_ctx->peer_id));
1116 remove_pending_message (peer_ctx->online_check_pending, GNUNET_YES);
1117 peer_ctx->online_check_pending = NULL;
1118 set_peer_online (peer_ctx);
1119 (void) add_valid_peer (&peer_ctx->peer_id, peer_ctx->sub->valid_peers);
1124 * Issue a check whether peer is online
1126 * @param peer_ctx the context of the peer
1129 check_peer_online (struct PeerContext *peer_ctx)
1131 LOG (GNUNET_ERROR_TYPE_DEBUG,
1132 "Get informed about peer %s getting online\n",
1133 GNUNET_i2s (&peer_ctx->peer_id));
1135 struct GNUNET_MQ_Handle *mq;
1136 struct GNUNET_MQ_Envelope *ev;
1138 ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE);
1139 peer_ctx->online_check_pending =
1140 insert_pending_message (peer_ctx, ev, "Check online");
1141 mq = get_mq (peer_ctx);
1142 GNUNET_MQ_notify_sent (ev,
1143 mq_online_check_successful,
1145 GNUNET_MQ_send (mq, ev);
1146 if (peer_ctx->sub == msub)
1148 GNUNET_STATISTICS_update (stats,
1149 "# pending online checks",
1157 * @brief Check whether function of type #PeerOp was already scheduled
1159 * The array with pending operations will probably never grow really big, so
1160 * iterating over it should be ok.
1162 * @param peer_ctx Context of the peer to check for the operation
1163 * @param peer_op the operation (#PeerOp) on the peer
1165 * @return #GNUNET_YES if this operation is scheduled on that peer
1166 * #GNUNET_NO otherwise
1169 check_operation_scheduled (const struct PeerContext *peer_ctx,
1170 const PeerOp peer_op)
1174 for (i = 0; i < peer_ctx->num_pending_ops; i++)
1175 if (peer_op == peer_ctx->pending_ops[i].op)
1182 * @brief Callback for scheduler to destroy a channel
1184 * @param cls Context of the channel
1187 destroy_channel (struct ChannelCtx *channel_ctx)
1189 struct GNUNET_CADET_Channel *channel;
1191 if (NULL != channel_ctx->destruction_task)
1193 GNUNET_SCHEDULER_cancel (channel_ctx->destruction_task);
1194 channel_ctx->destruction_task = NULL;
1196 GNUNET_assert (channel_ctx->channel != NULL);
1197 channel = channel_ctx->channel;
1198 channel_ctx->channel = NULL;
1199 GNUNET_CADET_channel_destroy (channel);
1200 remove_channel_ctx (channel_ctx);
1205 * @brief Destroy a cadet channel.
1207 * This satisfies the function signature of #GNUNET_SCHEDULER_TaskCallback.
1212 destroy_channel_cb (void *cls)
1214 struct ChannelCtx *channel_ctx = cls;
1216 channel_ctx->destruction_task = NULL;
1217 destroy_channel (channel_ctx);
1222 * @brief Schedule the destruction of a channel for immediately afterwards.
1224 * In case a channel is to be destroyed from within the callback to the
1225 * destruction of another channel (send channel), we cannot call
1226 * GNUNET_CADET_channel_destroy directly, but need to use this scheduling
1229 * @param channel_ctx channel to be destroyed.
1232 schedule_channel_destruction (struct ChannelCtx *channel_ctx)
1234 GNUNET_assert (NULL ==
1235 channel_ctx->destruction_task);
1236 GNUNET_assert (NULL !=
1237 channel_ctx->channel);
1238 channel_ctx->destruction_task =
1239 GNUNET_SCHEDULER_add_now (&destroy_channel_cb,
1245 * @brief Remove peer
1247 * - Empties the list with pending operations
1248 * - Empties the list with pending messages
1249 * - Cancels potentially existing online check
1250 * - Schedules closing of send and recv channels
1251 * - Removes peer from peer map
1253 * @param peer_ctx Context of the peer to be destroyed
1254 * @return #GNUNET_YES if peer was removed
1255 * #GNUNET_NO otherwise
1258 destroy_peer (struct PeerContext *peer_ctx)
1260 GNUNET_assert (NULL != peer_ctx);
1261 GNUNET_assert (NULL != peer_ctx->sub->peer_map);
1263 GNUNET_CONTAINER_multipeermap_contains (peer_ctx->sub->peer_map,
1264 &peer_ctx->peer_id))
1268 SET_PEER_FLAG (peer_ctx, Peers_TO_DESTROY);
1269 LOG (GNUNET_ERROR_TYPE_DEBUG,
1270 "Going to remove peer %s\n",
1271 GNUNET_i2s (&peer_ctx->peer_id));
1272 UNSET_PEER_FLAG (peer_ctx, Peers_ONLINE);
1274 /* Clear list of pending operations */
1275 // TODO this probably leaks memory
1276 // ('only' the cls to the function. Not sure what to do with it)
1277 GNUNET_array_grow (peer_ctx->pending_ops,
1278 peer_ctx->num_pending_ops,
1280 /* Remove all pending messages */
1281 while (NULL != peer_ctx->pending_messages_head)
1283 LOG (GNUNET_ERROR_TYPE_DEBUG,
1284 "Removing unsent %s\n",
1285 peer_ctx->pending_messages_head->type);
1286 /* Cancle pending message, too */
1287 if ( (NULL != peer_ctx->online_check_pending) &&
1288 (0 == memcmp (peer_ctx->pending_messages_head,
1289 peer_ctx->online_check_pending,
1290 sizeof (struct PendingMessage))) )
1292 peer_ctx->online_check_pending = NULL;
1293 if (peer_ctx->sub == msub)
1295 GNUNET_STATISTICS_update (stats,
1296 "# pending online checks",
1301 remove_pending_message (peer_ctx->pending_messages_head,
1305 /* If we are still waiting for notification whether this peer is online
1306 * cancel the according task */
1307 if (NULL != peer_ctx->online_check_pending)
1309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1310 "Removing pending online check for peer %s\n",
1311 GNUNET_i2s (&peer_ctx->peer_id));
1312 // TODO wait until cadet sets mq->cancel_impl
1313 //GNUNET_MQ_send_cancel (peer_ctx->online_check_pending->ev);
1314 remove_pending_message (peer_ctx->online_check_pending,
1316 peer_ctx->online_check_pending = NULL;
1319 if (NULL != peer_ctx->send_channel_ctx)
1321 /* This is possibly called from within channel destruction */
1322 peer_ctx->send_channel_ctx->peer_ctx = NULL;
1323 schedule_channel_destruction (peer_ctx->send_channel_ctx);
1324 peer_ctx->send_channel_ctx = NULL;
1325 peer_ctx->mq = NULL;
1327 if (NULL != peer_ctx->recv_channel_ctx)
1329 /* This is possibly called from within channel destruction */
1330 peer_ctx->recv_channel_ctx->peer_ctx = NULL;
1331 schedule_channel_destruction (peer_ctx->recv_channel_ctx);
1332 peer_ctx->recv_channel_ctx = NULL;
1336 GNUNET_CONTAINER_multipeermap_remove_all (peer_ctx->sub->peer_map,
1337 &peer_ctx->peer_id))
1339 LOG (GNUNET_ERROR_TYPE_WARNING,
1340 "removing peer from peer_ctx->sub->peer_map failed\n");
1342 if (peer_ctx->sub == msub)
1344 GNUNET_STATISTICS_set (stats,
1346 GNUNET_CONTAINER_multipeermap_size (peer_ctx->sub->peer_map),
1349 GNUNET_free (peer_ctx);
1355 * Iterator over hash map entries. Deletes all contexts of peers.
1357 * @param cls closure
1358 * @param key current public key
1359 * @param value value in the hash map
1360 * @return #GNUNET_YES if we should continue to iterate,
1361 * #GNUNET_NO if not.
1364 peermap_clear_iterator (void *cls,
1365 const struct GNUNET_PeerIdentity *key,
1368 struct Sub *sub = cls;
1371 destroy_peer (get_peer_ctx (sub->peer_map, key));
1377 * @brief This is called once a message is sent.
1379 * Removes the pending message
1381 * @param cls type of the message that was sent
1384 mq_notify_sent_cb (void *cls)
1386 struct PendingMessage *pending_msg = (struct PendingMessage *) cls;
1387 LOG (GNUNET_ERROR_TYPE_DEBUG,
1390 if (pending_msg->peer_ctx->sub == msub)
1392 if (0 == strncmp ("PULL REPLY", pending_msg->type, 10))
1393 GNUNET_STATISTICS_update(stats, "# pull replys sent", 1, GNUNET_NO);
1394 if (0 == strncmp ("PULL REQUEST", pending_msg->type, 12))
1395 GNUNET_STATISTICS_update(stats, "# pull requests sent", 1, GNUNET_NO);
1396 if (0 == strncmp ("PUSH", pending_msg->type, 4))
1397 GNUNET_STATISTICS_update(stats, "# pushes sent", 1, GNUNET_NO);
1398 if (0 == strncmp ("PULL REQUEST", pending_msg->type, 12) &&
1399 NULL != map_single_hop &&
1400 GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
1401 &pending_msg->peer_ctx->peer_id))
1402 GNUNET_STATISTICS_update(stats,
1403 "# pull requests sent (multi-hop peer)",
1407 /* Do not cancle message */
1408 remove_pending_message (pending_msg, GNUNET_NO);
1413 * @brief Iterator function for #store_valid_peers.
1415 * Implements #GNUNET_CONTAINER_PeerMapIterator.
1416 * Writes single peer to disk.
1418 * @param cls the file handle to write to.
1419 * @param peer current peer
1420 * @param value unused
1422 * @return #GNUNET_YES if we should continue to
1424 * #GNUNET_NO if not.
1427 store_peer_presistently_iterator (void *cls,
1428 const struct GNUNET_PeerIdentity *peer,
1431 const struct GNUNET_DISK_FileHandle *fh = cls;
1432 char peer_string[128];
1441 size = GNUNET_snprintf (peer_string,
1442 sizeof (peer_string),
1444 GNUNET_i2s_full (peer));
1445 GNUNET_assert (53 == size);
1446 ret = GNUNET_DISK_file_write (fh,
1449 GNUNET_assert (size == ret);
1455 * @brief Store the peers currently in #valid_peers to disk.
1457 * @param sub Sub for which to store the valid peers
1460 store_valid_peers (const struct Sub *sub)
1462 struct GNUNET_DISK_FileHandle *fh;
1463 uint32_t number_written_peers;
1466 if (0 == strncmp ("DISABLE", sub->filename_valid_peers, 7))
1471 ret = GNUNET_DISK_directory_create_for_file (sub->filename_valid_peers);
1472 if (GNUNET_SYSERR == ret)
1474 LOG (GNUNET_ERROR_TYPE_WARNING,
1475 "Not able to create directory for file `%s'\n",
1476 sub->filename_valid_peers);
1479 else if (GNUNET_NO == ret)
1481 LOG (GNUNET_ERROR_TYPE_WARNING,
1482 "Directory for file `%s' exists but is not writable for us\n",
1483 sub->filename_valid_peers);
1486 fh = GNUNET_DISK_file_open (sub->filename_valid_peers,
1487 GNUNET_DISK_OPEN_WRITE |
1488 GNUNET_DISK_OPEN_CREATE,
1489 GNUNET_DISK_PERM_USER_READ |
1490 GNUNET_DISK_PERM_USER_WRITE);
1493 LOG (GNUNET_ERROR_TYPE_WARNING,
1494 "Not able to write valid peers to file `%s'\n",
1495 sub->filename_valid_peers);
1498 LOG (GNUNET_ERROR_TYPE_DEBUG,
1499 "Writing %u valid peers to disk\n",
1500 GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1501 number_written_peers =
1502 GNUNET_CONTAINER_multipeermap_iterate (sub->valid_peers,
1503 store_peer_presistently_iterator,
1505 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1506 GNUNET_assert (number_written_peers ==
1507 GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1512 * @brief Convert string representation of peer id to peer id.
1514 * Counterpart to #GNUNET_i2s_full.
1516 * @param string_repr The string representation of the peer id
1518 * @return The peer id
1520 static const struct GNUNET_PeerIdentity *
1521 s2i_full (const char *string_repr)
1523 struct GNUNET_PeerIdentity *peer;
1527 peer = GNUNET_new (struct GNUNET_PeerIdentity);
1528 len = strlen (string_repr);
1531 LOG (GNUNET_ERROR_TYPE_WARNING,
1532 "Not able to convert string representation of PeerID to PeerID\n"
1533 "Sting representation: %s (len %lu) - too short\n",
1542 ret = GNUNET_CRYPTO_eddsa_public_key_from_string (string_repr,
1545 if (GNUNET_OK != ret)
1547 LOG (GNUNET_ERROR_TYPE_WARNING,
1548 "Not able to convert string representation of PeerID to PeerID\n"
1549 "Sting representation: %s\n",
1558 * @brief Restore the peers on disk to #valid_peers.
1560 * @param sub Sub for which to restore the valid peers
1563 restore_valid_peers (const struct Sub *sub)
1567 struct GNUNET_DISK_FileHandle *fh;
1572 const struct GNUNET_PeerIdentity *peer;
1574 if (0 == strncmp ("DISABLE", sub->filename_valid_peers, 7))
1579 if (GNUNET_OK != GNUNET_DISK_file_test (sub->filename_valid_peers))
1583 fh = GNUNET_DISK_file_open (sub->filename_valid_peers,
1584 GNUNET_DISK_OPEN_READ,
1585 GNUNET_DISK_PERM_NONE);
1586 GNUNET_assert (NULL != fh);
1587 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_handle_size (fh, &file_size));
1588 num_peers = file_size / 53;
1589 buf = GNUNET_malloc (file_size);
1590 size_read = GNUNET_DISK_file_read (fh, buf, file_size);
1591 GNUNET_assert (size_read == file_size);
1592 LOG (GNUNET_ERROR_TYPE_DEBUG,
1593 "Restoring %" PRIu32 " peers from file `%s'\n",
1595 sub->filename_valid_peers);
1596 for (iter_buf = buf; iter_buf < buf + file_size - 1; iter_buf += 53)
1598 str_repr = GNUNET_strndup (iter_buf, 53);
1599 peer = s2i_full (str_repr);
1600 GNUNET_free (str_repr);
1601 add_valid_peer (peer, sub->valid_peers);
1602 LOG (GNUNET_ERROR_TYPE_DEBUG,
1603 "Restored valid peer %s from disk\n",
1604 GNUNET_i2s_full (peer));
1608 LOG (GNUNET_ERROR_TYPE_DEBUG,
1609 "num_peers: %" PRIu32 ", _size (sub->valid_peers): %u\n",
1611 GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1612 if (num_peers != GNUNET_CONTAINER_multipeermap_size (sub->valid_peers))
1614 LOG (GNUNET_ERROR_TYPE_WARNING,
1615 "Number of restored peers does not match file size. Have probably duplicates.\n");
1617 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1618 LOG (GNUNET_ERROR_TYPE_DEBUG,
1619 "Restored %u valid peers from disk\n",
1620 GNUNET_CONTAINER_multipeermap_size (sub->valid_peers));
1625 * @brief Delete storage of peers that was created with #initialise_peers ()
1627 * @param sub Sub for which the storage is deleted
1630 peers_terminate (struct Sub *sub)
1632 if (GNUNET_SYSERR ==
1633 GNUNET_CONTAINER_multipeermap_iterate (sub->peer_map,
1634 &peermap_clear_iterator,
1637 LOG (GNUNET_ERROR_TYPE_WARNING,
1638 "Iteration destroying peers was aborted.\n");
1640 GNUNET_CONTAINER_multipeermap_destroy (sub->peer_map);
1641 sub->peer_map = NULL;
1642 store_valid_peers (sub);
1643 GNUNET_free (sub->filename_valid_peers);
1644 sub->filename_valid_peers = NULL;
1645 GNUNET_CONTAINER_multipeermap_destroy (sub->valid_peers);
1646 sub->valid_peers = NULL;
1651 * Iterator over #valid_peers hash map entries.
1653 * @param cls Closure that contains iterator function and closure
1654 * @param peer current peer id
1655 * @param value value in the hash map - unused
1656 * @return #GNUNET_YES if we should continue to
1658 * #GNUNET_NO if not.
1661 valid_peer_iterator (void *cls,
1662 const struct GNUNET_PeerIdentity *peer,
1665 struct PeersIteratorCls *it_cls = cls;
1668 return it_cls->iterator (it_cls->cls, peer);
1673 * @brief Get all currently known, valid peer ids.
1675 * @param valid_peers Peer map containing the valid peers in question
1676 * @param iterator function to call on each peer id
1677 * @param it_cls extra argument to @a iterator
1678 * @return the number of key value pairs processed,
1679 * #GNUNET_SYSERR if it aborted iteration
1682 get_valid_peers (struct GNUNET_CONTAINER_MultiPeerMap *valid_peers,
1683 PeersIterator iterator,
1686 struct PeersIteratorCls *cls;
1689 cls = GNUNET_new (struct PeersIteratorCls);
1690 cls->iterator = iterator;
1692 ret = GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
1693 valid_peer_iterator,
1701 * @brief Add peer to known peers.
1703 * This function is called on new peer_ids from 'external' sources
1704 * (client seed, cadet get_peers(), ...)
1706 * @param sub Sub with the peer map that the @a peer will be added to
1707 * @param peer the new #GNUNET_PeerIdentity
1709 * @return #GNUNET_YES if peer was inserted
1710 * #GNUNET_NO otherwise
1713 insert_peer (struct Sub *sub,
1714 const struct GNUNET_PeerIdentity *peer)
1716 if (GNUNET_YES == check_peer_known (sub->peer_map, peer))
1718 return GNUNET_NO; /* We already know this peer - nothing to do */
1720 (void) create_peer_ctx (sub, peer);
1726 * @brief Check whether flags on a peer are set.
1728 * @param peer_map Peer map that is expected to contain the @a peer
1729 * @param peer the peer to check the flag of
1730 * @param flags the flags to check
1732 * @return #GNUNET_SYSERR if peer is not known
1733 * #GNUNET_YES if all given flags are set
1734 * #GNUNET_NO otherwise
1737 check_peer_flag (const struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
1738 const struct GNUNET_PeerIdentity *peer,
1739 enum Peers_PeerFlags flags)
1741 struct PeerContext *peer_ctx;
1743 if (GNUNET_NO == check_peer_known (peer_map, peer))
1745 return GNUNET_SYSERR;
1747 peer_ctx = get_peer_ctx (peer_map, peer);
1748 return check_peer_flag_set (peer_ctx, flags);
1752 * @brief Try connecting to a peer to see whether it is online
1754 * If not known yet, insert into known peers
1756 * @param sub Sub which would contain the @a peer
1757 * @param peer the peer whose online is to be checked
1758 * @return #GNUNET_YES if the check was issued
1759 * #GNUNET_NO otherwise
1762 issue_peer_online_check (struct Sub *sub,
1763 const struct GNUNET_PeerIdentity *peer)
1765 struct PeerContext *peer_ctx;
1767 (void) insert_peer (sub, peer); // TODO even needed?
1768 peer_ctx = get_peer_ctx (sub->peer_map, peer);
1769 if ( (GNUNET_NO == check_peer_flag (sub->peer_map, peer, Peers_ONLINE)) &&
1770 (NULL == peer_ctx->online_check_pending) )
1772 check_peer_online (peer_ctx);
1780 * @brief Check if peer is removable.
1783 * - a recv channel exists
1784 * - there are pending messages
1785 * - there is no pending pull reply
1787 * @param peer_ctx Context of the peer in question
1788 * @return #GNUNET_YES if peer is removable
1789 * #GNUNET_NO if peer is NOT removable
1790 * #GNUNET_SYSERR if peer is not known
1793 check_removable (const struct PeerContext *peer_ctx)
1795 if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_ctx->sub->peer_map,
1796 &peer_ctx->peer_id))
1798 return GNUNET_SYSERR;
1801 if ( (NULL != peer_ctx->recv_channel_ctx) ||
1802 (NULL != peer_ctx->pending_messages_head) ||
1803 (GNUNET_YES == check_peer_flag_set (peer_ctx, Peers_PULL_REPLY_PENDING)) )
1812 * @brief Check whether @a peer is actually a peer.
1814 * A valid peer is a peer that we know exists eg. we were connected to once.
1816 * @param valid_peers Peer map that would contain the @a peer
1817 * @param peer peer in question
1819 * @return #GNUNET_YES if peer is valid
1820 * #GNUNET_NO if peer is not valid
1823 check_peer_valid (const struct GNUNET_CONTAINER_MultiPeerMap *valid_peers,
1824 const struct GNUNET_PeerIdentity *peer)
1826 return GNUNET_CONTAINER_multipeermap_contains (valid_peers, peer);
1831 * @brief Indicate that we want to send to the other peer
1833 * This establishes a sending channel
1835 * @param peer_ctx Context of the target peer
1838 indicate_sending_intention (struct PeerContext *peer_ctx)
1840 GNUNET_assert (GNUNET_YES == check_peer_known (peer_ctx->sub->peer_map,
1841 &peer_ctx->peer_id));
1842 (void) get_channel (peer_ctx);
1847 * @brief Check whether other peer has the intention to send/opened channel
1850 * @param peer_ctx Context of the peer in question
1852 * @return #GNUNET_YES if peer has the intention to send
1853 * #GNUNET_NO otherwise
1856 check_peer_send_intention (const struct PeerContext *peer_ctx)
1858 if (NULL != peer_ctx->recv_channel_ctx)
1867 * Handle the channel a peer opens to us.
1869 * @param cls The closure - Sub
1870 * @param channel The channel the peer wants to establish
1871 * @param initiator The peer's peer ID
1873 * @return initial channel context for the channel
1874 * (can be NULL -- that's not an error)
1877 handle_inbound_channel (void *cls,
1878 struct GNUNET_CADET_Channel *channel,
1879 const struct GNUNET_PeerIdentity *initiator)
1881 struct PeerContext *peer_ctx;
1882 struct ChannelCtx *channel_ctx;
1883 struct Sub *sub = cls;
1885 LOG (GNUNET_ERROR_TYPE_DEBUG,
1886 "New channel was established to us (Peer %s).\n",
1887 GNUNET_i2s (initiator));
1888 GNUNET_assert (NULL != channel); /* according to cadet API */
1889 /* Make sure we 'know' about this peer */
1890 peer_ctx = create_or_get_peer_ctx (sub, initiator);
1891 set_peer_online (peer_ctx);
1892 (void) add_valid_peer (&peer_ctx->peer_id, peer_ctx->sub->valid_peers);
1893 channel_ctx = add_channel_ctx (peer_ctx);
1894 channel_ctx->channel = channel;
1895 /* We only accept one incoming channel per peer */
1896 if (GNUNET_YES == check_peer_send_intention (get_peer_ctx (sub->peer_map,
1899 LOG (GNUNET_ERROR_TYPE_WARNING,
1900 "Already got one receive channel. Destroying old one.\n");
1901 GNUNET_break_op (0);
1902 destroy_channel (peer_ctx->recv_channel_ctx);
1903 peer_ctx->recv_channel_ctx = channel_ctx;
1904 /* return the channel context */
1907 peer_ctx->recv_channel_ctx = channel_ctx;
1913 * @brief Check whether a sending channel towards the given peer exists
1915 * @param peer_ctx Context of the peer in question
1917 * @return #GNUNET_YES if a sending channel towards that peer exists
1918 * #GNUNET_NO otherwise
1921 check_sending_channel_exists (const struct PeerContext *peer_ctx)
1923 if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
1924 &peer_ctx->peer_id))
1925 { /* If no such peer exists, there is no channel */
1928 if (NULL == peer_ctx->send_channel_ctx)
1937 * @brief Destroy the send channel of a peer e.g. stop indicating a sending
1938 * intention to another peer
1940 * @param peer_ctx Context to the peer
1941 * @return #GNUNET_YES if channel was destroyed
1942 * #GNUNET_NO otherwise
1945 destroy_sending_channel (struct PeerContext *peer_ctx)
1947 if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
1948 &peer_ctx->peer_id))
1952 if (NULL != peer_ctx->send_channel_ctx)
1954 destroy_channel (peer_ctx->send_channel_ctx);
1955 (void) check_connected (peer_ctx);
1962 * @brief Send a message to another peer.
1964 * Keeps track about pending messages so they can be properly removed when the
1965 * peer is destroyed.
1967 * @param peer_ctx Context of the peer to which the message is to be sent
1968 * @param ev envelope of the message
1969 * @param type type of the message
1972 send_message (struct PeerContext *peer_ctx,
1973 struct GNUNET_MQ_Envelope *ev,
1976 struct PendingMessage *pending_msg;
1977 struct GNUNET_MQ_Handle *mq;
1979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1980 "Sending message to %s of type %s\n",
1981 GNUNET_i2s (&peer_ctx->peer_id),
1983 pending_msg = insert_pending_message (peer_ctx, ev, type);
1984 mq = get_mq (peer_ctx);
1985 GNUNET_MQ_notify_sent (ev,
1988 GNUNET_MQ_send (mq, ev);
1992 * @brief Schedule a operation on given peer
1994 * Avoids scheduling an operation twice.
1996 * @param peer_ctx Context of the peer for which to schedule the operation
1997 * @param peer_op the operation to schedule
1998 * @param cls Closure to @a peer_op
2000 * @return #GNUNET_YES if the operation was scheduled
2001 * #GNUNET_NO otherwise
2004 schedule_operation (struct PeerContext *peer_ctx,
2005 const PeerOp peer_op,
2008 struct PeerPendingOp pending_op;
2010 GNUNET_assert (GNUNET_YES == check_peer_known (peer_ctx->sub->peer_map,
2011 &peer_ctx->peer_id));
2013 //TODO if ONLINE execute immediately
2015 if (GNUNET_NO == check_operation_scheduled (peer_ctx, peer_op))
2017 pending_op.op = peer_op;
2018 pending_op.op_cls = cls;
2019 GNUNET_array_append (peer_ctx->pending_ops,
2020 peer_ctx->num_pending_ops,
2027 /***********************************************************************
2028 * /Old gnunet-service-rps_peers.c
2029 ***********************************************************************/
2032 /***********************************************************************
2033 * Housekeeping with clients
2034 ***********************************************************************/
2037 * Closure used to pass the client and the id to the callback
2038 * that replies to a client's request
2045 struct ReplyCls *next;
2046 struct ReplyCls *prev;
2049 * The identifier of the request
2054 * The handle to the request
2056 struct RPS_SamplerRequestHandle *req_handle;
2059 * The client handle to send the reply to
2061 struct ClientContext *cli_ctx;
2066 * Struct used to store the context of a connected client.
2068 struct ClientContext
2073 struct ClientContext *next;
2074 struct ClientContext *prev;
2077 * The message queue to communicate with the client.
2079 struct GNUNET_MQ_Handle *mq;
2082 * @brief How many updates this client expects to receive.
2084 int64_t view_updates_left;
2087 * @brief Whether this client wants to receive stream updates.
2088 * Either #GNUNET_YES or #GNUNET_NO
2090 int8_t stream_update;
2093 * The client handle to send the reply to
2095 struct GNUNET_SERVICE_Client *client;
2098 * The #Sub this context belongs to
2104 * DLL with all clients currently connected to us
2106 struct ClientContext *cli_ctx_head;
2107 struct ClientContext *cli_ctx_tail;
2109 /***********************************************************************
2110 * /Housekeeping with clients
2111 ***********************************************************************/
2117 /***********************************************************************
2119 ***********************************************************************/
2123 * Print peerlist to log.
2126 print_peer_list (struct GNUNET_PeerIdentity *list,
2131 LOG (GNUNET_ERROR_TYPE_DEBUG,
2132 "Printing peer list of length %u at %p:\n",
2135 for (i = 0 ; i < len ; i++)
2137 LOG (GNUNET_ERROR_TYPE_DEBUG,
2139 i, GNUNET_i2s (&list[i]));
2145 * Remove peer from list.
2148 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
2149 unsigned int *list_size,
2150 const struct GNUNET_PeerIdentity *peer)
2153 struct GNUNET_PeerIdentity *tmp;
2157 LOG (GNUNET_ERROR_TYPE_DEBUG,
2158 "Removing peer %s from list at %p\n",
2162 for ( i = 0 ; i < *list_size ; i++ )
2164 if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
2166 if (i < *list_size -1)
2167 { /* Not at the last entry -- shift peers left */
2168 memmove (&tmp[i], &tmp[i +1],
2169 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
2171 /* Remove last entry (should be now useless PeerID) */
2172 GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
2180 * Insert PeerID in #view
2182 * Called once we know a peer is online.
2183 * Implements #PeerOp
2185 * @return GNUNET_OK if peer was actually inserted
2186 * GNUNET_NO if peer was not inserted
2189 insert_in_view_op (void *cls,
2190 const struct GNUNET_PeerIdentity *peer);
2193 * Insert PeerID in #view
2195 * Called once we know a peer is online.
2197 * @param sub Sub in with the view to insert in
2198 * @param peer the peer to insert
2200 * @return GNUNET_OK if peer was actually inserted
2201 * GNUNET_NO if peer was not inserted
2204 insert_in_view (struct Sub *sub,
2205 const struct GNUNET_PeerIdentity *peer)
2207 struct PeerContext *peer_ctx;
2211 online = check_peer_flag (sub->peer_map, peer, Peers_ONLINE);
2212 peer_ctx = get_peer_ctx (sub->peer_map, peer); // TODO indirection needed?
2213 if ( (GNUNET_NO == online) ||
2214 (GNUNET_SYSERR == online) ) /* peer is not even known */
2216 (void) issue_peer_online_check (sub, peer);
2217 (void) schedule_operation (peer_ctx, insert_in_view_op, sub);
2220 /* Open channel towards peer to keep connection open */
2221 indicate_sending_intention (peer_ctx);
2222 ret = View_put (sub->view, peer);
2223 if (peer_ctx->sub == msub)
2225 GNUNET_STATISTICS_set (stats,
2227 View_size (peer_ctx->sub->view),
2235 * @brief Send view to client
2237 * @param cli_ctx the context of the client
2238 * @param view_array the peerids of the view as array (can be empty)
2239 * @param view_size the size of the view array (can be 0)
2242 send_view (const struct ClientContext *cli_ctx,
2243 const struct GNUNET_PeerIdentity *view_array,
2246 struct GNUNET_MQ_Envelope *ev;
2247 struct GNUNET_RPS_CS_DEBUG_ViewReply *out_msg;
2250 if (NULL == view_array)
2252 if (NULL == cli_ctx->sub) sub = msub;
2253 else sub = cli_ctx->sub;
2254 view_size = View_size (sub->view);
2255 view_array = View_get_as_array (sub->view);
2258 ev = GNUNET_MQ_msg_extra (out_msg,
2259 view_size * sizeof (struct GNUNET_PeerIdentity),
2260 GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REPLY);
2261 out_msg->num_peers = htonl (view_size);
2263 GNUNET_memcpy (&out_msg[1],
2265 view_size * sizeof (struct GNUNET_PeerIdentity));
2266 GNUNET_MQ_send (cli_ctx->mq, ev);
2271 * @brief Send peer from biased stream to client.
2273 * TODO merge with send_view, parameterise
2275 * @param cli_ctx the context of the client
2276 * @param view_array the peerids of the view as array (can be empty)
2277 * @param view_size the size of the view array (can be 0)
2280 send_stream_peers (const struct ClientContext *cli_ctx,
2282 const struct GNUNET_PeerIdentity *peers)
2284 struct GNUNET_MQ_Envelope *ev;
2285 struct GNUNET_RPS_CS_DEBUG_StreamReply *out_msg;
2287 GNUNET_assert (NULL != peers);
2289 ev = GNUNET_MQ_msg_extra (out_msg,
2290 num_peers * sizeof (struct GNUNET_PeerIdentity),
2291 GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_REPLY);
2292 out_msg->num_peers = htonl (num_peers);
2294 GNUNET_memcpy (&out_msg[1],
2296 num_peers * sizeof (struct GNUNET_PeerIdentity));
2297 GNUNET_MQ_send (cli_ctx->mq, ev);
2302 * @brief sends updates to clients that are interested
2304 * @param sub Sub for which to notify clients
2307 clients_notify_view_update (const struct Sub *sub)
2309 struct ClientContext *cli_ctx_iter;
2311 const struct GNUNET_PeerIdentity *view_array;
2313 num_peers = View_size (sub->view);
2314 view_array = View_get_as_array(sub->view);
2315 /* check size of view is small enough */
2316 if (GNUNET_MAX_MESSAGE_SIZE < num_peers)
2318 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2319 "View is too big to send\n");
2323 for (cli_ctx_iter = cli_ctx_head;
2324 NULL != cli_ctx_iter;
2325 cli_ctx_iter = cli_ctx_iter->next)
2327 if (1 < cli_ctx_iter->view_updates_left)
2329 /* Client wants to receive limited amount of updates */
2330 cli_ctx_iter->view_updates_left -= 1;
2331 } else if (1 == cli_ctx_iter->view_updates_left)
2333 /* Last update of view for client */
2334 cli_ctx_iter->view_updates_left = -1;
2335 } else if (0 > cli_ctx_iter->view_updates_left) {
2336 /* Client is not interested in updates */
2339 /* else _updates_left == 0 - infinite amount of updates */
2342 send_view (cli_ctx_iter, view_array, num_peers);
2348 * @brief sends updates to clients that are interested
2350 * @param num_peers Number of peers to send
2351 * @param peers the array of peers to send
2354 clients_notify_stream_peer (const struct Sub *sub,
2356 const struct GNUNET_PeerIdentity *peers)
2357 // TODO enum StreamPeerSource)
2359 struct ClientContext *cli_ctx_iter;
2361 LOG (GNUNET_ERROR_TYPE_DEBUG,
2362 "Got peer (%s) from biased stream - update all clients\n",
2363 GNUNET_i2s (peers));
2365 for (cli_ctx_iter = cli_ctx_head;
2366 NULL != cli_ctx_iter;
2367 cli_ctx_iter = cli_ctx_iter->next)
2369 if (GNUNET_YES == cli_ctx_iter->stream_update &&
2370 (sub == cli_ctx_iter->sub || sub == msub))
2372 send_stream_peers (cli_ctx_iter, num_peers, peers);
2379 * Put random peer from sampler into the view as history update.
2381 * @param ids Array of Peers to insert into view
2382 * @param num_peers Number of peers to insert
2383 * @param cls Closure - The Sub for which this is to be done
2386 hist_update (const struct GNUNET_PeerIdentity *ids,
2391 struct Sub *sub = cls;
2393 for (i = 0; i < num_peers; i++)
2396 if (GNUNET_YES != check_peer_known (sub->peer_map, &ids[i]))
2398 LOG (GNUNET_ERROR_TYPE_WARNING,
2399 "Peer in history update not known!\n");
2402 inserted = insert_in_view (sub, &ids[i]);
2403 if (GNUNET_OK == inserted)
2405 clients_notify_stream_peer (sub, 1, &ids[i]);
2408 to_file (sub->file_name_view_log,
2410 GNUNET_i2s_full (ids));
2411 #endif /* TO_FILE_FULL */
2413 clients_notify_view_update (sub);
2418 * Wrapper around #RPS_sampler_resize()
2420 * If we do not have enough sampler elements, double current sampler size
2421 * If we have more than enough sampler elements, halv current sampler size
2423 * @param sampler The sampler to resize
2424 * @param new_size New size to which to resize
2427 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
2429 unsigned int sampler_size;
2432 // TODO respect the min, max
2433 sampler_size = RPS_sampler_get_size (sampler);
2434 if (sampler_size > new_size * 4)
2436 RPS_sampler_resize (sampler, sampler_size / 2);
2438 else if (sampler_size < new_size)
2440 RPS_sampler_resize (sampler, sampler_size * 2);
2442 LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
2447 * Add all peers in @a peer_array to @a peer_map used as set.
2449 * @param peer_array array containing the peers
2450 * @param num_peers number of peers in @peer_array
2451 * @param peer_map the peermap to use as set
2454 add_peer_array_to_set (const struct GNUNET_PeerIdentity *peer_array,
2455 unsigned int num_peers,
2456 struct GNUNET_CONTAINER_MultiPeerMap *peer_map)
2459 if (NULL == peer_map)
2461 LOG (GNUNET_ERROR_TYPE_WARNING,
2462 "Trying to add peers to non-existing peermap.\n");
2466 for (i = 0; i < num_peers; i++)
2468 GNUNET_CONTAINER_multipeermap_put (peer_map,
2471 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2472 if (msub->peer_map == peer_map)
2474 GNUNET_STATISTICS_set (stats,
2476 GNUNET_CONTAINER_multipeermap_size (peer_map),
2484 * Send a PULL REPLY to @a peer_id
2486 * @param peer_ctx Context of the peer to send the reply to
2487 * @param peer_ids the peers to send to @a peer_id
2488 * @param num_peer_ids the number of peers to send to @a peer_id
2491 send_pull_reply (struct PeerContext *peer_ctx,
2492 const struct GNUNET_PeerIdentity *peer_ids,
2493 unsigned int num_peer_ids)
2496 struct GNUNET_MQ_Envelope *ev;
2497 struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
2499 /* Compute actual size */
2500 send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
2501 num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
2503 if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
2504 /* Compute number of peers to send
2505 * If too long, simply truncate */
2506 // TODO select random ones via permutation
2507 // or even better: do good protocol design
2509 (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
2510 sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
2511 sizeof (struct GNUNET_PeerIdentity);
2513 send_size = num_peer_ids;
2515 LOG (GNUNET_ERROR_TYPE_DEBUG,
2516 "Going to send PULL REPLY with %u peers to %s\n",
2517 send_size, GNUNET_i2s (&peer_ctx->peer_id));
2519 ev = GNUNET_MQ_msg_extra (out_msg,
2520 send_size * sizeof (struct GNUNET_PeerIdentity),
2521 GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
2522 out_msg->num_peers = htonl (send_size);
2523 GNUNET_memcpy (&out_msg[1], peer_ids,
2524 send_size * sizeof (struct GNUNET_PeerIdentity));
2526 send_message (peer_ctx, ev, "PULL REPLY");
2527 if (peer_ctx->sub == msub)
2529 GNUNET_STATISTICS_update(stats, "# pull reply send issued", 1, GNUNET_NO);
2531 // TODO check with send intention: as send_channel is used/opened we indicate
2532 // a sending intention without intending it.
2533 // -> clean peer afterwards?
2534 // -> use recv_channel?
2539 * Insert PeerID in #pull_map
2541 * Called once we know a peer is online.
2543 * @param cls Closure - Sub with the pull map to insert into
2544 * @param peer Peer to insert
2547 insert_in_pull_map (void *cls,
2548 const struct GNUNET_PeerIdentity *peer)
2550 struct Sub *sub = cls;
2552 CustomPeerMap_put (sub->pull_map, peer);
2557 * Insert PeerID in #view
2559 * Called once we know a peer is online.
2560 * Implements #PeerOp
2562 * @param cls Closure - Sub with view to insert peer into
2563 * @param peer the peer to insert
2566 insert_in_view_op (void *cls,
2567 const struct GNUNET_PeerIdentity *peer)
2569 struct Sub *sub = cls;
2572 inserted = insert_in_view (sub, peer);
2573 if (GNUNET_OK == inserted)
2575 clients_notify_stream_peer (sub, 1, peer);
2581 * Update sampler with given PeerID.
2582 * Implements #PeerOp
2584 * @param cls Closure - Sub containing the sampler to insert into
2585 * @param peer Peer to insert
2588 insert_in_sampler (void *cls,
2589 const struct GNUNET_PeerIdentity *peer)
2591 struct Sub *sub = cls;
2593 LOG (GNUNET_ERROR_TYPE_DEBUG,
2594 "Updating samplers with peer %s from insert_in_sampler()\n",
2596 RPS_sampler_update (sub->sampler, peer);
2597 if (0 < RPS_sampler_count_id (sub->sampler, peer))
2599 /* Make sure we 'know' about this peer */
2600 (void) issue_peer_online_check (sub, peer);
2601 /* Establish a channel towards that peer to indicate we are going to send
2603 //indicate_sending_intention (peer);
2606 sub->num_observed_peers++;
2607 GNUNET_CONTAINER_multipeermap_put
2608 (sub->observed_unique_peers,
2611 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2612 uint32_t num_observed_unique_peers =
2613 GNUNET_CONTAINER_multipeermap_size (sub->observed_unique_peers);
2615 to_file (sub->file_name_observed_log,
2616 "%" PRIu32 " %" PRIu32 " %f\n",
2617 sub->num_observed_peers,
2618 num_observed_unique_peers,
2619 1.0*num_observed_unique_peers/sub->num_observed_peers)
2620 #endif /* TO_FILE_FULL */
2621 #endif /* TO_FILE */
2626 * @brief This is called on peers from external sources (cadet, peerinfo, ...)
2627 * If the peer is not known, online check is issued and it is
2628 * scheduled to be inserted in sampler and view.
2630 * "External sources" refer to every source except the gossip.
2632 * @param sub Sub for which @a peer was received
2633 * @param peer peer to insert/peer received
2636 got_peer (struct Sub *sub,
2637 const struct GNUNET_PeerIdentity *peer)
2639 /* If we did not know this peer already, insert it into sampler and view */
2640 if (GNUNET_YES == issue_peer_online_check (sub, peer))
2642 schedule_operation (get_peer_ctx (sub->peer_map, peer),
2643 &insert_in_sampler, sub);
2644 schedule_operation (get_peer_ctx (sub->peer_map, peer),
2645 &insert_in_view_op, sub);
2649 GNUNET_STATISTICS_update (stats,
2658 * @brief Checks if there is a sending channel and if it is needed
2660 * @param peer_ctx Context of the peer to check
2661 * @return GNUNET_YES if sending channel exists and is still needed
2662 * GNUNET_NO otherwise
2665 check_sending_channel_needed (const struct PeerContext *peer_ctx)
2667 /* struct GNUNET_CADET_Channel *channel; */
2668 if (GNUNET_NO == check_peer_known (peer_ctx->sub->peer_map,
2669 &peer_ctx->peer_id))
2673 if (GNUNET_YES == check_sending_channel_exists (peer_ctx))
2675 if ( (0 < RPS_sampler_count_id (peer_ctx->sub->sampler,
2676 &peer_ctx->peer_id)) ||
2677 (GNUNET_YES == View_contains_peer (peer_ctx->sub->view,
2678 &peer_ctx->peer_id)) ||
2679 (GNUNET_YES == CustomPeerMap_contains_peer (peer_ctx->sub->push_map,
2680 &peer_ctx->peer_id)) ||
2681 (GNUNET_YES == CustomPeerMap_contains_peer (peer_ctx->sub->pull_map,
2682 &peer_ctx->peer_id)) ||
2683 (GNUNET_YES == check_peer_flag (peer_ctx->sub->peer_map,
2685 Peers_PULL_REPLY_PENDING)))
2686 { /* If we want to keep the connection to peer open */
2696 * @brief remove peer from our knowledge, the view, push and pull maps and
2699 * @param sub Sub with the data structures the peer is to be removed from
2700 * @param peer the peer to remove
2703 remove_peer (struct Sub *sub,
2704 const struct GNUNET_PeerIdentity *peer)
2706 (void) View_remove_peer (sub->view,
2708 CustomPeerMap_remove_peer (sub->pull_map,
2710 CustomPeerMap_remove_peer (sub->push_map,
2712 RPS_sampler_reinitialise_by_value (sub->sampler,
2714 /* We want to destroy the peer now.
2715 * Sometimes, it just seems that it's already been removed from the peer_map,
2716 * so check the peer_map first. */
2717 if (GNUNET_YES == check_peer_known (sub->peer_map,
2720 destroy_peer (get_peer_ctx (sub->peer_map,
2727 * @brief Remove data that is not needed anymore.
2729 * If the sending channel is no longer needed it is destroyed.
2731 * @param sub Sub in which the current peer is to be cleaned
2732 * @param peer the peer whose data is about to be cleaned
2735 clean_peer (struct Sub *sub,
2736 const struct GNUNET_PeerIdentity *peer)
2738 if (GNUNET_NO == check_sending_channel_needed (get_peer_ctx (sub->peer_map,
2741 LOG (GNUNET_ERROR_TYPE_DEBUG,
2742 "Going to remove send channel to peer %s\n",
2744 #if ENABLE_MALICIOUS
2745 if (0 != GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer,
2747 (void) destroy_sending_channel (get_peer_ctx (sub->peer_map,
2749 #else /* ENABLE_MALICIOUS */
2750 (void) destroy_sending_channel (get_peer_ctx (sub->peer_map,
2752 #endif /* ENABLE_MALICIOUS */
2755 if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (sub->peer_map,
2758 /* Peer was already removed by callback on destroyed channel */
2759 LOG (GNUNET_ERROR_TYPE_WARNING,
2760 "Peer was removed from our knowledge during cleanup\n");
2764 if ( (GNUNET_NO == check_peer_send_intention (get_peer_ctx (sub->peer_map,
2766 (GNUNET_NO == View_contains_peer (sub->view, peer)) &&
2767 (GNUNET_NO == CustomPeerMap_contains_peer (sub->push_map, peer)) &&
2768 (GNUNET_NO == CustomPeerMap_contains_peer (sub->push_map, peer)) &&
2769 (0 == RPS_sampler_count_id (sub->sampler, peer)) &&
2770 (GNUNET_YES == check_removable (get_peer_ctx (sub->peer_map, peer))) )
2771 { /* We can safely remove this peer */
2772 LOG (GNUNET_ERROR_TYPE_DEBUG,
2773 "Going to remove peer %s\n",
2775 remove_peer (sub, peer);
2782 * @brief This is called when a channel is destroyed.
2784 * Removes peer completely from our knowledge if the send_channel was destroyed
2785 * Otherwise simply delete the recv_channel
2786 * Also check if the knowledge about this peer is still needed.
2787 * If not, remove this peer from our knowledge.
2789 * @param cls The closure - Context to the channel
2790 * @param channel The channel being closed
2793 cleanup_destroyed_channel (void *cls,
2794 const struct GNUNET_CADET_Channel *channel)
2796 struct ChannelCtx *channel_ctx = cls;
2797 struct PeerContext *peer_ctx = channel_ctx->peer_ctx;
2800 channel_ctx->channel = NULL;
2801 remove_channel_ctx (channel_ctx);
2802 if (NULL != peer_ctx &&
2803 peer_ctx->send_channel_ctx == channel_ctx &&
2804 GNUNET_YES == check_sending_channel_needed (channel_ctx->peer_ctx))
2806 remove_peer (peer_ctx->sub, &peer_ctx->peer_id);
2810 /***********************************************************************
2812 ***********************************************************************/
2816 /***********************************************************************
2818 ***********************************************************************/
2821 * @brief Create a new Sub
2823 * @param hash Hash of value shared among rps instances on other hosts that
2824 * defines a subgroup to sample from.
2825 * @param sampler_size Size of the sampler
2826 * @param round_interval Interval (in average) between two rounds
2831 new_sub (const struct GNUNET_HashCode *hash,
2832 uint32_t sampler_size,
2833 struct GNUNET_TIME_Relative round_interval)
2837 sub = GNUNET_new (struct Sub);
2839 /* With the hash generated from the secret value this service only connects
2840 * to rps instances that share the value */
2841 struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
2842 GNUNET_MQ_hd_fixed_size (peer_check,
2843 GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE,
2844 struct GNUNET_MessageHeader,
2846 GNUNET_MQ_hd_fixed_size (peer_push,
2847 GNUNET_MESSAGE_TYPE_RPS_PP_PUSH,
2848 struct GNUNET_MessageHeader,
2850 GNUNET_MQ_hd_fixed_size (peer_pull_request,
2851 GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2852 struct GNUNET_MessageHeader,
2854 GNUNET_MQ_hd_var_size (peer_pull_reply,
2855 GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY,
2856 struct GNUNET_RPS_P2P_PullReplyMessage,
2858 GNUNET_MQ_handler_end ()
2862 GNUNET_CADET_open_port (cadet_handle,
2864 &handle_inbound_channel, /* Connect handler */
2866 NULL, /* WindowSize handler */
2867 &cleanup_destroyed_channel, /* Disconnect handler */
2869 if (NULL == sub->cadet_port)
2871 LOG (GNUNET_ERROR_TYPE_ERROR,
2872 "Cadet port `%s' is already in use.\n",
2873 GNUNET_APPLICATION_PORT_RPS);
2877 /* Set up general data structure to keep track about peers */
2878 sub->valid_peers = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
2880 GNUNET_CONFIGURATION_get_value_filename (cfg,
2882 "FILENAME_VALID_PEERS",
2883 &sub->filename_valid_peers))
2885 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2887 "FILENAME_VALID_PEERS");
2889 if (0 != strncmp ("DISABLE", sub->filename_valid_peers, 7))
2891 char *tmp_filename_valid_peers;
2894 GNUNET_snprintf (str_hash,
2896 GNUNET_h2s_full (hash));
2897 tmp_filename_valid_peers = sub->filename_valid_peers;
2898 GNUNET_asprintf (&sub->filename_valid_peers,
2900 tmp_filename_valid_peers,
2902 GNUNET_free (tmp_filename_valid_peers);
2904 sub->peer_map = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
2906 /* Set up the sampler */
2907 sub->sampler_size_est_min = sampler_size;
2908 sub->sampler_size_est_need = sampler_size;;
2909 LOG (GNUNET_ERROR_TYPE_DEBUG, "MINSIZE is %u\n", sub->sampler_size_est_min);
2910 GNUNET_assert (0 != round_interval.rel_value_us);
2911 sub->round_interval = round_interval;
2912 sub->sampler = RPS_sampler_init (sampler_size,
2915 /* Logging of internals */
2917 sub->file_name_view_log = store_prefix_file_name (&own_identity, "view");
2918 #endif /* TO_FILE_FULL */
2921 sub->file_name_observed_log = store_prefix_file_name (&own_identity,
2923 #endif /* TO_FILE_FULL */
2924 sub->num_observed_peers = 0;
2925 sub->observed_unique_peers = GNUNET_CONTAINER_multipeermap_create (1,
2927 #endif /* TO_FILE */
2929 /* Set up data structures for gossip */
2930 sub->push_map = CustomPeerMap_create (4);
2931 sub->pull_map = CustomPeerMap_create (4);
2932 sub->view_size_est_min = sampler_size;;
2933 sub->view = View_create (sub->view_size_est_min);
2936 GNUNET_STATISTICS_set (stats,
2938 sub->view_size_est_min,
2942 /* Start executing rounds */
2943 sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_round, sub);
2951 * @brief Write all numbers in the given array into the given file
2953 * Single numbers devided by a newline
2955 * @param hist_array[] the array to dump
2956 * @param file_name file to dump into
2959 write_histogram_to_file (const uint32_t hist_array[],
2960 const char *file_name)
2962 char collect_str[SIZE_DUMP_FILE + 1] = "";
2963 char *recv_str_iter;
2964 char *file_name_full;
2966 recv_str_iter = collect_str;
2967 file_name_full = store_prefix_file_name (&own_identity,
2969 for (uint32_t i = 0; i < HISTOGRAM_FILE_SLOTS; i++)
2971 char collect_str_tmp[8];
2973 GNUNET_snprintf (collect_str_tmp,
2974 sizeof (collect_str_tmp),
2977 recv_str_iter = stpncpy (recv_str_iter,
2981 (void) stpcpy (recv_str_iter,
2983 LOG (GNUNET_ERROR_TYPE_DEBUG,
2984 "Writing push stats to disk\n");
2985 to_file_w_len (file_name_full,
2988 GNUNET_free (file_name_full);
2990 #endif /* TO_FILE */
2994 * @brief Destroy Sub.
2996 * @param sub Sub to destroy
2999 destroy_sub (struct Sub *sub)
3001 GNUNET_assert (NULL != sub);
3002 GNUNET_assert (NULL != sub->do_round_task);
3003 GNUNET_SCHEDULER_cancel (sub->do_round_task);
3004 sub->do_round_task = NULL;
3006 /* Disconnect from cadet */
3007 GNUNET_CADET_close_port (sub->cadet_port);
3008 sub->cadet_port= NULL;
3010 /* Clean up data structures for peers */
3011 RPS_sampler_destroy (sub->sampler);
3012 sub->sampler = NULL;
3013 View_destroy (sub->view);
3015 CustomPeerMap_destroy (sub->push_map);
3016 sub->push_map = NULL;
3017 CustomPeerMap_destroy (sub->pull_map);
3018 sub->pull_map = NULL;
3019 peers_terminate (sub);
3021 /* Free leftover data structures */
3023 GNUNET_free (sub->file_name_view_log);
3024 sub->file_name_view_log = NULL;
3025 #endif /* TO_FILE_FULL */
3028 GNUNET_free (sub->file_name_observed_log);
3029 sub->file_name_observed_log = NULL;
3030 #endif /* TO_FILE_FULL */
3032 /* Write push frequencies to disk */
3033 write_histogram_to_file (sub->push_recv,
3036 /* Write push deltas to disk */
3037 write_histogram_to_file (sub->push_delta,
3040 /* Write pull delays to disk */
3041 write_histogram_to_file (sub->pull_delays,
3044 GNUNET_CONTAINER_multipeermap_destroy (sub->observed_unique_peers);
3045 sub->observed_unique_peers = NULL;
3046 #endif /* TO_FILE */
3052 /***********************************************************************
3054 ***********************************************************************/
3057 /***********************************************************************
3059 ***********************************************************************/
3062 * @brief Callback on initialisation of Core.
3064 * @param cls - unused
3065 * @param my_identity - unused
3068 core_init (void *cls,
3069 const struct GNUNET_PeerIdentity *my_identity)
3074 map_single_hop = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
3079 * @brief Callback for core.
3080 * Method called whenever a given peer connects.
3082 * @param cls closure - unused
3083 * @param peer peer identity this notification is about
3084 * @return closure given to #core_disconnects as peer_cls
3087 core_connects (void *cls,
3088 const struct GNUNET_PeerIdentity *peer,
3089 struct GNUNET_MQ_Handle *mq)
3094 GNUNET_assert (GNUNET_YES ==
3095 GNUNET_CONTAINER_multipeermap_put (map_single_hop,
3098 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3104 * @brief Callback for core.
3105 * Method called whenever a peer disconnects.
3107 * @param cls closure - unused
3108 * @param peer peer identity this notification is about
3109 * @param peer_cls closure given in #core_connects - unused
3112 core_disconnects (void *cls,
3113 const struct GNUNET_PeerIdentity *peer,
3119 GNUNET_CONTAINER_multipeermap_remove_all (map_single_hop, peer);
3122 /***********************************************************************
3124 ***********************************************************************/
3128 * @brief Destroy the context for a (connected) client
3130 * @param cli_ctx Context to destroy
3133 destroy_cli_ctx (struct ClientContext *cli_ctx)
3135 GNUNET_assert (NULL != cli_ctx);
3136 GNUNET_CONTAINER_DLL_remove (cli_ctx_head,
3139 if (NULL != cli_ctx->sub)
3141 destroy_sub (cli_ctx->sub);
3142 cli_ctx->sub = NULL;
3144 GNUNET_free (cli_ctx);
3149 * @brief Update sizes in sampler and view on estimate update from nse service
3152 * @param logestimate the log(Base 2) value of the current network size estimate
3153 * @param std_dev standard deviation for the estimate
3156 adapt_sizes (struct Sub *sub, double logestimate, double std_dev)
3159 //double scale; // TODO this might go gloabal/config
3161 LOG (GNUNET_ERROR_TYPE_DEBUG,
3162 "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
3163 logestimate, std_dev, RPS_sampler_get_size (sub->sampler));
3165 estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
3166 // GNUNET_NSE_log_estimate_to_n (logestimate);
3167 estimate = pow (estimate, 1.0 / 3);
3168 // TODO add if std_dev is a number
3169 // estimate += (std_dev * scale);
3170 if (sub->view_size_est_min < ceil (estimate))
3172 LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
3173 sub->sampler_size_est_need = estimate;
3174 sub->view_size_est_need = estimate;
3177 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
3178 //sub->sampler_size_est_need = sub->view_size_est_min;
3179 sub->view_size_est_need = sub->view_size_est_min;
3183 GNUNET_STATISTICS_set (stats,
3185 sub->view_size_est_need,
3189 /* If the NSE has changed adapt the lists accordingly */
3190 resize_wrapper (sub->sampler, sub->sampler_size_est_need);
3191 View_change_len (sub->view, sub->view_size_est_need);
3196 * Function called by NSE.
3198 * Updates sizes of sampler list and view and adapt those lists
3201 * implements #GNUNET_NSE_Callback
3203 * @param cls Closure - unused
3204 * @param timestamp time when the estimate was received from the server (or created by the server)
3205 * @param logestimate the log(Base 2) value of the current network size estimate
3206 * @param std_dev standard deviation for the estimate
3209 nse_callback (void *cls,
3210 struct GNUNET_TIME_Absolute timestamp,
3211 double logestimate, double std_dev)
3215 struct ClientContext *cli_ctx_iter;
3217 adapt_sizes (msub, logestimate, std_dev);
3218 for (cli_ctx_iter = cli_ctx_head;
3219 NULL != cli_ctx_iter;
3220 cli_ctx_iter = cli_ctx_iter->next)
3222 if (NULL != cli_ctx_iter->sub)
3224 adapt_sizes (cli_ctx_iter->sub, logestimate, std_dev);
3231 * @brief This function is called, when the client seeds peers.
3232 * It verifies that @a msg is well-formed.
3234 * @param cls the closure (#ClientContext)
3235 * @param msg the message
3236 * @return #GNUNET_OK if @a msg is well-formed
3237 * #GNUNET_SYSERR otherwise
3240 check_client_seed (void *cls, const struct GNUNET_RPS_CS_SeedMessage *msg)
3242 struct ClientContext *cli_ctx = cls;
3243 uint16_t msize = ntohs (msg->header.size);
3244 uint32_t num_peers = ntohl (msg->num_peers);
3246 msize -= sizeof (struct GNUNET_RPS_CS_SeedMessage);
3247 if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
3248 (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
3250 LOG (GNUNET_ERROR_TYPE_ERROR,
3251 "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3252 ntohl (msg->num_peers),
3253 (msize / sizeof (struct GNUNET_PeerIdentity)));
3255 GNUNET_SERVICE_client_drop (cli_ctx->client);
3256 return GNUNET_SYSERR;
3263 * Handle seed from the client.
3265 * @param cls closure
3266 * @param message the actual message
3269 handle_client_seed (void *cls,
3270 const struct GNUNET_RPS_CS_SeedMessage *msg)
3272 struct ClientContext *cli_ctx = cls;
3273 struct GNUNET_PeerIdentity *peers;
3277 num_peers = ntohl (msg->num_peers);
3278 peers = (struct GNUNET_PeerIdentity *) &msg[1];
3280 LOG (GNUNET_ERROR_TYPE_DEBUG,
3281 "Client seeded peers:\n");
3282 print_peer_list (peers, num_peers);
3284 for (i = 0; i < num_peers; i++)
3286 LOG (GNUNET_ERROR_TYPE_DEBUG,
3287 "Updating samplers with seed %" PRIu32 ": %s\n",
3289 GNUNET_i2s (&peers[i]));
3291 if (NULL != msub) got_peer (msub, &peers[i]); /* Condition needed? */
3292 if (NULL != cli_ctx->sub) got_peer (cli_ctx->sub, &peers[i]);
3294 GNUNET_SERVICE_client_continue (cli_ctx->client);
3299 * Handle RPS request from the client.
3301 * @param cls Client context
3302 * @param message Message containing the numer of updates the client wants to
3306 handle_client_view_request (void *cls,
3307 const struct GNUNET_RPS_CS_DEBUG_ViewRequest *msg)
3309 struct ClientContext *cli_ctx = cls;
3310 uint64_t num_updates;
3312 num_updates = ntohl (msg->num_updates);
3314 LOG (GNUNET_ERROR_TYPE_DEBUG,
3315 "Client requested %" PRIu64 " updates of view.\n",
3318 GNUNET_assert (NULL != cli_ctx);
3319 cli_ctx->view_updates_left = num_updates;
3320 send_view (cli_ctx, NULL, 0);
3321 GNUNET_SERVICE_client_continue (cli_ctx->client);
3326 * @brief Handle the cancellation of the view updates.
3328 * @param cls The client context
3332 handle_client_view_cancel (void *cls,
3333 const struct GNUNET_MessageHeader *msg)
3335 struct ClientContext *cli_ctx = cls;
3338 LOG (GNUNET_ERROR_TYPE_DEBUG,
3339 "Client does not want to receive updates of view any more.\n");
3341 GNUNET_assert (NULL != cli_ctx);
3342 cli_ctx->view_updates_left = 0;
3343 GNUNET_SERVICE_client_continue (cli_ctx->client);
3344 if (GNUNET_YES == cli_ctx->stream_update)
3346 destroy_cli_ctx (cli_ctx);
3352 * Handle RPS request for biased stream from the client.
3354 * @param cls Client context
3355 * @param message unused
3358 handle_client_stream_request (void *cls,
3359 const struct GNUNET_RPS_CS_DEBUG_StreamRequest *msg)
3361 struct ClientContext *cli_ctx = cls;
3364 LOG (GNUNET_ERROR_TYPE_DEBUG,
3365 "Client requested peers from biased stream.\n");
3366 cli_ctx->stream_update = GNUNET_YES;
3368 GNUNET_assert (NULL != cli_ctx);
3369 GNUNET_SERVICE_client_continue (cli_ctx->client);
3374 * @brief Handles the cancellation of the stream of biased peer ids
3376 * @param cls The client context
3380 handle_client_stream_cancel (void *cls,
3381 const struct GNUNET_MessageHeader *msg)
3383 struct ClientContext *cli_ctx = cls;
3386 LOG (GNUNET_ERROR_TYPE_DEBUG,
3387 "Client canceled receiving peers from biased stream.\n");
3388 cli_ctx->stream_update = GNUNET_NO;
3390 GNUNET_assert (NULL != cli_ctx);
3391 GNUNET_SERVICE_client_continue (cli_ctx->client);
3396 * @brief Create and start a Sub.
3398 * @param cls Closure - unused
3399 * @param msg Message containing the necessary information
3402 handle_client_start_sub (void *cls,
3403 const struct GNUNET_RPS_CS_SubStartMessage *msg)
3405 struct ClientContext *cli_ctx = cls;
3407 LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested start of a new sub.\n");
3408 if (NULL != cli_ctx->sub &&
3409 0 != memcmp (&cli_ctx->sub->hash,
3411 sizeof (struct GNUNET_HashCode)))
3413 LOG (GNUNET_ERROR_TYPE_WARNING, "Already have a Sub with different share for this client. Remove old one, add new.\n");
3414 destroy_sub (cli_ctx->sub);
3415 cli_ctx->sub = NULL;
3417 cli_ctx->sub = new_sub (&msg->hash,
3418 msub->sampler_size_est_min, // TODO make api input?
3419 GNUNET_TIME_relative_ntoh (msg->round_interval));
3420 GNUNET_SERVICE_client_continue (cli_ctx->client);
3425 * @brief Destroy the Sub
3427 * @param cls Closure - unused
3428 * @param msg Message containing the hash that identifies the Sub
3431 handle_client_stop_sub (void *cls,
3432 const struct GNUNET_RPS_CS_SubStopMessage *msg)
3434 struct ClientContext *cli_ctx = cls;
3436 GNUNET_assert (NULL != cli_ctx->sub);
3437 if (0 != memcmp (&cli_ctx->sub->hash, &msg->hash, sizeof (struct GNUNET_HashCode)))
3439 LOG (GNUNET_ERROR_TYPE_WARNING, "Share of current sub and request differ!\n");
3441 destroy_sub (cli_ctx->sub);
3442 cli_ctx->sub = NULL;
3443 GNUNET_SERVICE_client_continue (cli_ctx->client);
3448 * Handle a CHECK_LIVE message from another peer.
3450 * This does nothing. But without calling #GNUNET_CADET_receive_done()
3451 * the channel is blocked for all other communication.
3453 * @param cls Closure - Context of channel
3454 * @param msg Message - unused
3457 handle_peer_check (void *cls,
3458 const struct GNUNET_MessageHeader *msg)
3460 const struct ChannelCtx *channel_ctx = cls;
3461 const struct GNUNET_PeerIdentity *peer = &channel_ctx->peer_ctx->peer_id;
3464 LOG (GNUNET_ERROR_TYPE_DEBUG,
3465 "Received CHECK_LIVE (%s)\n", GNUNET_i2s (peer));
3466 if (channel_ctx->peer_ctx->sub == msub)
3468 GNUNET_STATISTICS_update (stats,
3469 "# pending online checks",
3474 GNUNET_CADET_receive_done (channel_ctx->channel);
3479 * Handle a PUSH message from another peer.
3481 * Check the proof of work and store the PeerID
3482 * in the temporary list for pushed PeerIDs.
3484 * @param cls Closure - Context of channel
3485 * @param msg Message - unused
3488 handle_peer_push (void *cls,
3489 const struct GNUNET_MessageHeader *msg)
3491 const struct ChannelCtx *channel_ctx = cls;
3492 const struct GNUNET_PeerIdentity *peer = &channel_ctx->peer_ctx->peer_id;
3495 // (check the proof of work (?))
3497 LOG (GNUNET_ERROR_TYPE_DEBUG,
3498 "Received PUSH (%s)\n",
3500 if (channel_ctx->peer_ctx->sub == msub)
3502 GNUNET_STATISTICS_update(stats, "# push message received", 1, GNUNET_NO);
3505 #if ENABLE_MALICIOUS
3506 struct AttackedPeer *tmp_att_peer;
3508 if ( (1 == mal_type) ||
3510 { /* Try to maximise representation */
3511 tmp_att_peer = GNUNET_new (struct AttackedPeer);
3512 tmp_att_peer->peer_id = *peer;
3513 if (NULL == att_peer_set)
3514 att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
3515 if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
3518 GNUNET_CONTAINER_DLL_insert (att_peers_head,
3521 add_peer_array_to_set (peer, 1, att_peer_set);
3525 GNUNET_free (tmp_att_peer);
3530 else if (2 == mal_type)
3532 /* We attack one single well-known peer - simply ignore */
3534 #endif /* ENABLE_MALICIOUS */
3536 /* Add the sending peer to the push_map */
3537 CustomPeerMap_put (channel_ctx->peer_ctx->sub->push_map, peer);
3539 GNUNET_break_op (check_peer_known (channel_ctx->peer_ctx->sub->peer_map,
3540 &channel_ctx->peer_ctx->peer_id));
3541 GNUNET_CADET_receive_done (channel_ctx->channel);
3546 * Handle PULL REQUEST request message from another peer.
3548 * Reply with the view of PeerIDs.
3550 * @param cls Closure - Context of channel
3551 * @param msg Message - unused
3554 handle_peer_pull_request (void *cls,
3555 const struct GNUNET_MessageHeader *msg)
3557 const struct ChannelCtx *channel_ctx = cls;
3558 struct PeerContext *peer_ctx = channel_ctx->peer_ctx;
3559 const struct GNUNET_PeerIdentity *peer = &peer_ctx->peer_id;
3560 const struct GNUNET_PeerIdentity *view_array;
3563 LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REQUEST (%s)\n", GNUNET_i2s (peer));
3564 if (peer_ctx->sub == msub)
3566 GNUNET_STATISTICS_update(stats,
3567 "# pull request message received",
3570 if (NULL != map_single_hop &&
3571 GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
3572 &peer_ctx->peer_id))
3574 GNUNET_STATISTICS_update (stats,
3575 "# pull request message received (multi-hop peer)",
3581 #if ENABLE_MALICIOUS
3584 { /* Try to maximise representation */
3585 send_pull_reply (peer_ctx, mal_peers, num_mal_peers);
3588 else if (2 == mal_type)
3589 { /* Try to partition network */
3590 if (0 == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
3592 send_pull_reply (peer_ctx, mal_peers, num_mal_peers);
3595 #endif /* ENABLE_MALICIOUS */
3597 GNUNET_break_op (check_peer_known (channel_ctx->peer_ctx->sub->peer_map,
3598 &channel_ctx->peer_ctx->peer_id));
3599 GNUNET_CADET_receive_done (channel_ctx->channel);
3600 view_array = View_get_as_array (channel_ctx->peer_ctx->sub->view);
3601 send_pull_reply (peer_ctx,
3603 View_size (channel_ctx->peer_ctx->sub->view));
3608 * Check whether we sent a corresponding request and
3609 * whether this reply is the first one.
3611 * @param cls Closure - Context of channel
3612 * @param msg Message containing the replied peers
3615 check_peer_pull_reply (void *cls,
3616 const struct GNUNET_RPS_P2P_PullReplyMessage *msg)
3618 struct ChannelCtx *channel_ctx = cls;
3619 struct PeerContext *sender_ctx = channel_ctx->peer_ctx;
3621 if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->header.size))
3623 GNUNET_break_op (0);
3624 return GNUNET_SYSERR;
3627 if ((ntohs (msg->header.size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
3628 sizeof (struct GNUNET_PeerIdentity) != ntohl (msg->num_peers))
3630 LOG (GNUNET_ERROR_TYPE_ERROR,
3631 "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3632 ntohl (msg->num_peers),
3633 (ntohs (msg->header.size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
3634 sizeof (struct GNUNET_PeerIdentity));
3635 GNUNET_break_op (0);
3636 return GNUNET_SYSERR;
3639 if (GNUNET_YES != check_peer_flag (sender_ctx->sub->peer_map,
3640 &sender_ctx->peer_id,
3641 Peers_PULL_REPLY_PENDING))
3643 LOG (GNUNET_ERROR_TYPE_WARNING,
3644 "Received a pull reply from a peer (%s) we didn't request one from!\n",
3645 GNUNET_i2s (&sender_ctx->peer_id));
3646 if (sender_ctx->sub == msub)
3648 GNUNET_STATISTICS_update (stats,
3649 "# unrequested pull replies",
3659 * Handle PULL REPLY message from another peer.
3661 * @param cls Closure
3662 * @param msg The message header
3665 handle_peer_pull_reply (void *cls,
3666 const struct GNUNET_RPS_P2P_PullReplyMessage *msg)
3668 const struct ChannelCtx *channel_ctx = cls;
3669 const struct GNUNET_PeerIdentity *sender = &channel_ctx->peer_ctx->peer_id;
3670 const struct GNUNET_PeerIdentity *peers;
3671 struct Sub *sub = channel_ctx->peer_ctx->sub;
3673 #if ENABLE_MALICIOUS
3674 struct AttackedPeer *tmp_att_peer;
3675 #endif /* ENABLE_MALICIOUS */
3677 sub->pull_delays[sub->num_rounds - channel_ctx->peer_ctx->round_pull_req]++;
3678 LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REPLY (%s)\n", GNUNET_i2s (sender));
3679 if (channel_ctx->peer_ctx->sub == msub)
3681 GNUNET_STATISTICS_update (stats,
3682 "# pull reply messages received",
3685 if (NULL != map_single_hop &&
3686 GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
3687 &channel_ctx->peer_ctx->peer_id))
3689 GNUNET_STATISTICS_update (stats,
3690 "# pull reply messages received (multi-hop peer)",
3696 #if ENABLE_MALICIOUS
3697 // We shouldn't even receive pull replies as we're not sending
3701 #endif /* ENABLE_MALICIOUS */
3703 /* Do actual logic */
3704 peers = (const struct GNUNET_PeerIdentity *) &msg[1];
3706 LOG (GNUNET_ERROR_TYPE_DEBUG,
3707 "PULL REPLY received, got following %u peers:\n",
3708 ntohl (msg->num_peers));
3710 for (i = 0; i < ntohl (msg->num_peers); i++)
3712 LOG (GNUNET_ERROR_TYPE_DEBUG,
3715 GNUNET_i2s (&peers[i]));
3717 #if ENABLE_MALICIOUS
3718 if ((NULL != att_peer_set) &&
3719 (1 == mal_type || 3 == mal_type))
3720 { /* Add attacked peer to local list */
3721 // TODO check if we sent a request and this was the first reply
3722 if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
3724 && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
3727 tmp_att_peer = GNUNET_new (struct AttackedPeer);
3728 tmp_att_peer->peer_id = peers[i];
3729 GNUNET_CONTAINER_DLL_insert (att_peers_head,
3732 add_peer_array_to_set (&peers[i], 1, att_peer_set);
3736 #endif /* ENABLE_MALICIOUS */
3737 /* Make sure we 'know' about this peer */
3738 (void) insert_peer (channel_ctx->peer_ctx->sub,
3741 if (GNUNET_YES == check_peer_valid (channel_ctx->peer_ctx->sub->valid_peers,
3744 CustomPeerMap_put (channel_ctx->peer_ctx->sub->pull_map,
3749 schedule_operation (channel_ctx->peer_ctx,
3751 channel_ctx->peer_ctx->sub); /* cls */
3752 (void) issue_peer_online_check (channel_ctx->peer_ctx->sub,
3757 UNSET_PEER_FLAG (get_peer_ctx (channel_ctx->peer_ctx->sub->peer_map,
3759 Peers_PULL_REPLY_PENDING);
3760 clean_peer (channel_ctx->peer_ctx->sub,
3763 GNUNET_break_op (check_peer_known (channel_ctx->peer_ctx->sub->peer_map,
3765 GNUNET_CADET_receive_done (channel_ctx->channel);
3770 * Compute a random delay.
3771 * A uniformly distributed value between mean + spread and mean - spread.
3773 * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
3774 * It would return a random value between 2 and 6 min.
3776 * @param mean the mean time until the next round
3777 * @param spread the inverse amount of deviation from the mean
3779 static struct GNUNET_TIME_Relative
3780 compute_rand_delay (struct GNUNET_TIME_Relative mean,
3781 unsigned int spread)
3783 struct GNUNET_TIME_Relative half_interval;
3784 struct GNUNET_TIME_Relative ret;
3785 unsigned int rand_delay;
3786 unsigned int max_rand_delay;
3790 LOG (GNUNET_ERROR_TYPE_WARNING,
3791 "Not accepting spread of 0\n");
3795 GNUNET_assert (0 != mean.rel_value_us);
3797 /* Compute random time value between spread * mean and spread * mean */
3798 half_interval = GNUNET_TIME_relative_divide (mean, spread);
3800 max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
3802 * Compute random value between (0 and 1) * round_interval
3803 * via multiplying round_interval with a 'fraction' (0 to value)/value
3805 rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
3806 ret = GNUNET_TIME_relative_saturating_multiply (mean, rand_delay);
3807 ret = GNUNET_TIME_relative_divide (ret, max_rand_delay);
3808 ret = GNUNET_TIME_relative_add (ret, half_interval);
3810 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
3811 LOG (GNUNET_ERROR_TYPE_WARNING,
3812 "Returning FOREVER_REL\n");
3819 * Send single pull request
3821 * @param peer_ctx Context to the peer to send request to
3824 send_pull_request (struct PeerContext *peer_ctx)
3826 struct GNUNET_MQ_Envelope *ev;
3828 GNUNET_assert (GNUNET_NO == check_peer_flag (peer_ctx->sub->peer_map,
3830 Peers_PULL_REPLY_PENDING));
3831 SET_PEER_FLAG (peer_ctx,
3832 Peers_PULL_REPLY_PENDING);
3833 peer_ctx->round_pull_req = peer_ctx->sub->num_rounds;
3835 LOG (GNUNET_ERROR_TYPE_DEBUG,
3836 "Going to send PULL REQUEST to peer %s.\n",
3837 GNUNET_i2s (&peer_ctx->peer_id));
3839 ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
3840 send_message (peer_ctx,
3845 GNUNET_STATISTICS_update (stats,
3846 "# pull request send issued",
3849 if (NULL != map_single_hop &&
3850 GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (map_single_hop,
3851 &peer_ctx->peer_id))
3853 GNUNET_STATISTICS_update (stats,
3854 "# pull request send issued (multi-hop peer)",
3865 * @param peer_ctx Context of peer to send push to
3868 send_push (struct PeerContext *peer_ctx)
3870 struct GNUNET_MQ_Envelope *ev;
3872 LOG (GNUNET_ERROR_TYPE_DEBUG,
3873 "Going to send PUSH to peer %s.\n",
3874 GNUNET_i2s (&peer_ctx->peer_id));
3876 ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
3877 send_message (peer_ctx, ev, "PUSH");
3880 GNUNET_STATISTICS_update (stats,
3881 "# push send issued",
3888 #if ENABLE_MALICIOUS
3892 * @brief This function is called, when the client tells us to act malicious.
3893 * It verifies that @a msg is well-formed.
3895 * @param cls the closure (#ClientContext)
3896 * @param msg the message
3897 * @return #GNUNET_OK if @a msg is well-formed
3900 check_client_act_malicious (void *cls,
3901 const struct GNUNET_RPS_CS_ActMaliciousMessage *msg)
3903 struct ClientContext *cli_ctx = cls;
3904 uint16_t msize = ntohs (msg->header.size);
3905 uint32_t num_peers = ntohl (msg->num_peers);
3907 msize -= sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage);
3908 if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
3909 (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
3911 LOG (GNUNET_ERROR_TYPE_ERROR,
3912 "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3913 ntohl (msg->num_peers),
3914 (msize / sizeof (struct GNUNET_PeerIdentity)));
3916 GNUNET_SERVICE_client_drop (cli_ctx->client);
3917 return GNUNET_SYSERR;
3923 * Turn RPS service to act malicious.
3925 * @param cls Closure
3926 * @param client The client that sent the message
3927 * @param msg The message header
3930 handle_client_act_malicious (void *cls,
3931 const struct GNUNET_RPS_CS_ActMaliciousMessage *msg)
3933 struct ClientContext *cli_ctx = cls;
3934 struct GNUNET_PeerIdentity *peers;
3935 uint32_t num_mal_peers_sent;
3936 uint32_t num_mal_peers_old;
3937 struct Sub *sub = cli_ctx->sub;
3939 if (NULL == sub) sub = msub;
3940 /* Do actual logic */
3941 peers = (struct GNUNET_PeerIdentity *) &msg[1];
3942 mal_type = ntohl (msg->type);
3943 if (NULL == mal_peer_set)
3944 mal_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
3946 LOG (GNUNET_ERROR_TYPE_DEBUG,
3947 "Now acting malicious type %" PRIu32 ", got %" PRIu32 " peers.\n",
3949 ntohl (msg->num_peers));
3952 { /* Try to maximise representation */
3953 /* Add other malicious peers to those we already know */
3955 num_mal_peers_sent = ntohl (msg->num_peers);
3956 num_mal_peers_old = num_mal_peers;
3957 GNUNET_array_grow (mal_peers,
3959 num_mal_peers + num_mal_peers_sent);
3960 GNUNET_memcpy (&mal_peers[num_mal_peers_old],
3962 num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
3964 /* Add all mal peers to mal_peer_set */
3965 add_peer_array_to_set (&mal_peers[num_mal_peers_old],
3969 /* Substitute do_round () with do_mal_round () */
3970 GNUNET_assert (NULL != sub->do_round_task);
3971 GNUNET_SCHEDULER_cancel (sub->do_round_task);
3972 sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, sub);
3975 else if ( (2 == mal_type) ||
3977 { /* Try to partition the network */
3978 /* Add other malicious peers to those we already know */
3980 num_mal_peers_sent = ntohl (msg->num_peers) - 1;
3981 num_mal_peers_old = num_mal_peers;
3982 GNUNET_assert (GNUNET_MAX_MALLOC_CHECKED > num_mal_peers_sent);
3983 GNUNET_array_grow (mal_peers,
3985 num_mal_peers + num_mal_peers_sent);
3986 if (NULL != mal_peers &&
3989 GNUNET_memcpy (&mal_peers[num_mal_peers_old],
3991 num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
3993 /* Add all mal peers to mal_peer_set */
3994 add_peer_array_to_set (&mal_peers[num_mal_peers_old],
3999 /* Store the one attacked peer */
4000 GNUNET_memcpy (&attacked_peer,
4001 &msg->attacked_peer,
4002 sizeof (struct GNUNET_PeerIdentity));
4003 /* Set the flag of the attacked peer to valid to avoid problems */
4004 if (GNUNET_NO == check_peer_known (sub->peer_map, &attacked_peer))
4006 (void) issue_peer_online_check (sub, &attacked_peer);
4009 LOG (GNUNET_ERROR_TYPE_DEBUG,
4010 "Attacked peer is %s\n",
4011 GNUNET_i2s (&attacked_peer));
4013 /* Substitute do_round () with do_mal_round () */
4014 if (NULL != sub->do_round_task)
4016 /* Probably in shutdown */
4017 GNUNET_SCHEDULER_cancel (sub->do_round_task);
4018 sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, sub);
4021 else if (0 == mal_type)
4022 { /* Stop acting malicious */
4023 GNUNET_array_grow (mal_peers, num_mal_peers, 0);
4025 /* Substitute do_mal_round () with do_round () */
4026 GNUNET_SCHEDULER_cancel (sub->do_round_task);
4027 sub->do_round_task = GNUNET_SCHEDULER_add_now (&do_round, sub);
4032 GNUNET_SERVICE_client_continue (cli_ctx->client);
4034 GNUNET_SERVICE_client_continue (cli_ctx->client);
4039 * Send out PUSHes and PULLs maliciously.
4041 * This is executed regylary.
4043 * @param cls Closure - Sub
4046 do_mal_round (void *cls)
4048 uint32_t num_pushes;
4050 struct GNUNET_TIME_Relative time_next_round;
4051 struct AttackedPeer *tmp_att_peer;
4052 struct Sub *sub = cls;
4054 LOG (GNUNET_ERROR_TYPE_DEBUG,
4055 "Going to execute next round maliciously type %" PRIu32 ".\n",
4057 sub->do_round_task = NULL;
4058 GNUNET_assert (mal_type <= 3);
4059 /* Do malicious actions */
4061 { /* Try to maximise representation */
4063 /* The maximum of pushes we're going to send this round */
4064 num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
4065 num_attacked_peers),
4066 GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
4068 LOG (GNUNET_ERROR_TYPE_DEBUG,
4069 "Going to send %" PRIu32 " pushes\n",
4072 /* Send PUSHes to attacked peers */
4073 for (i = 0 ; i < num_pushes ; i++)
4075 if (att_peers_tail == att_peer_index)
4076 att_peer_index = att_peers_head;
4078 att_peer_index = att_peer_index->next;
4080 send_push (get_peer_ctx (sub->peer_map, &att_peer_index->peer_id));
4083 /* Send PULLs to some peers to learn about additional peers to attack */
4084 tmp_att_peer = att_peer_index;
4085 for (i = 0 ; i < num_pushes * alpha ; i++)
4087 if (att_peers_tail == tmp_att_peer)
4088 tmp_att_peer = att_peers_head;
4090 att_peer_index = tmp_att_peer->next;
4092 send_pull_request (get_peer_ctx (sub->peer_map, &tmp_att_peer->peer_id));
4097 else if (2 == mal_type)
4099 * Try to partition the network
4100 * Send as many pushes to the attacked peer as possible
4101 * That is one push per round as it will ignore more.
4103 (void) issue_peer_online_check (sub, &attacked_peer);
4104 if (GNUNET_YES == check_peer_flag (sub->peer_map,
4107 send_push (get_peer_ctx (sub->peer_map, &attacked_peer));
4112 { /* Combined attack */
4114 /* Send PUSH to attacked peers */
4115 if (GNUNET_YES == check_peer_known (sub->peer_map, &attacked_peer))
4117 (void) issue_peer_online_check (sub, &attacked_peer);
4118 if (GNUNET_YES == check_peer_flag (sub->peer_map,
4122 LOG (GNUNET_ERROR_TYPE_DEBUG,
4123 "Goding to send push to attacked peer (%s)\n",
4124 GNUNET_i2s (&attacked_peer));
4125 send_push (get_peer_ctx (sub->peer_map, &attacked_peer));
4128 (void) issue_peer_online_check (sub, &attacked_peer);
4130 /* The maximum of pushes we're going to send this round */
4131 num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
4132 num_attacked_peers),
4133 GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
4135 LOG (GNUNET_ERROR_TYPE_DEBUG,
4136 "Going to send %" PRIu32 " pushes\n",
4139 for (i = 0; i < num_pushes; i++)
4141 if (att_peers_tail == att_peer_index)
4142 att_peer_index = att_peers_head;
4144 att_peer_index = att_peer_index->next;
4146 send_push (get_peer_ctx (sub->peer_map, &att_peer_index->peer_id));
4149 /* Send PULLs to some peers to learn about additional peers to attack */
4150 tmp_att_peer = att_peer_index;
4151 for (i = 0; i < num_pushes * alpha; i++)
4153 if (att_peers_tail == tmp_att_peer)
4154 tmp_att_peer = att_peers_head;
4156 att_peer_index = tmp_att_peer->next;
4158 send_pull_request (get_peer_ctx (sub->peer_map, &tmp_att_peer->peer_id));
4162 /* Schedule next round */
4163 time_next_round = compute_rand_delay (sub->round_interval, 2);
4165 GNUNET_assert (NULL == sub->do_round_task);
4166 sub->do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round,
4167 &do_mal_round, sub);
4168 LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
4170 #endif /* ENABLE_MALICIOUS */
4174 * Send out PUSHes and PULLs, possibly update #view, samplers.
4176 * This is executed regylary.
4178 * @param cls Closure - Sub
4181 do_round (void *cls)
4184 const struct GNUNET_PeerIdentity *view_array;
4185 unsigned int *permut;
4186 unsigned int a_peers; /* Number of peers we send pushes to */
4187 unsigned int b_peers; /* Number of peers we send pull requests to */
4188 uint32_t first_border;
4189 uint32_t second_border;
4190 struct GNUNET_PeerIdentity peer;
4191 struct GNUNET_PeerIdentity *update_peer;
4192 struct Sub *sub = cls;
4195 LOG (GNUNET_ERROR_TYPE_DEBUG,
4196 "Going to execute next round.\n");
4199 GNUNET_STATISTICS_update (stats, "# rounds", 1, GNUNET_NO);
4201 sub->do_round_task = NULL;
4203 to_file (sub->file_name_view_log,
4204 "___ new round ___");
4205 #endif /* TO_FILE_FULL */
4206 view_array = View_get_as_array (sub->view);
4207 for (i = 0; i < View_size (sub->view); i++)
4209 LOG (GNUNET_ERROR_TYPE_DEBUG,
4210 "\t%s\n", GNUNET_i2s (&view_array[i]));
4212 to_file (sub->file_name_view_log,
4214 GNUNET_i2s_full (&view_array[i]));
4215 #endif /* TO_FILE_FULL */
4219 /* Send pushes and pull requests */
4220 if (0 < View_size (sub->view))
4222 permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
4223 View_size (sub->view));
4226 a_peers = ceil (alpha * View_size (sub->view));
4228 LOG (GNUNET_ERROR_TYPE_DEBUG,
4229 "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
4230 a_peers, alpha, View_size (sub->view));
4231 for (i = 0; i < a_peers; i++)
4233 peer = view_array[permut[i]];
4234 // FIXME if this fails schedule/loop this for later
4235 send_push (get_peer_ctx (sub->peer_map, &peer));
4238 /* Send PULL requests */
4239 b_peers = ceil (beta * View_size (sub->view));
4240 first_border = a_peers;
4241 second_border = a_peers + b_peers;
4242 if (second_border > View_size (sub->view))
4244 first_border = View_size (sub->view) - b_peers;
4245 second_border = View_size (sub->view);
4247 LOG (GNUNET_ERROR_TYPE_DEBUG,
4248 "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
4249 b_peers, beta, View_size (sub->view));
4250 for (i = first_border; i < second_border; i++)
4252 peer = view_array[permut[i]];
4253 if ( GNUNET_NO == check_peer_flag (sub->peer_map,
4255 Peers_PULL_REPLY_PENDING))
4256 { // FIXME if this fails schedule/loop this for later
4257 send_pull_request (get_peer_ctx (sub->peer_map, &peer));
4261 GNUNET_free (permut);
4267 /* TODO see how many peers are in push-/pull- list! */
4269 if ((CustomPeerMap_size (sub->push_map) <= alpha * sub->view_size_est_need) &&
4270 (0 < CustomPeerMap_size (sub->push_map)) &&
4271 (0 < CustomPeerMap_size (sub->pull_map)))
4272 { /* If conditions for update are fulfilled, update */
4273 LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the view.\n");
4275 uint32_t final_size;
4276 uint32_t peers_to_clean_size;
4277 struct GNUNET_PeerIdentity *peers_to_clean;
4279 peers_to_clean = NULL;
4280 peers_to_clean_size = 0;
4281 GNUNET_array_grow (peers_to_clean,
4282 peers_to_clean_size,
4283 View_size (sub->view));
4284 GNUNET_memcpy (peers_to_clean,
4286 View_size (sub->view) * sizeof (struct GNUNET_PeerIdentity));
4288 /* Seems like recreating is the easiest way of emptying the peermap */
4289 View_clear (sub->view);
4291 to_file (sub->file_name_view_log,
4293 #endif /* TO_FILE_FULL */
4295 first_border = GNUNET_MIN (ceil (alpha * sub->view_size_est_need),
4296 CustomPeerMap_size (sub->push_map));
4297 second_border = first_border +
4298 GNUNET_MIN (floor (beta * sub->view_size_est_need),
4299 CustomPeerMap_size (sub->pull_map));
4300 final_size = second_border +
4301 ceil ((1 - (alpha + beta)) * sub->view_size_est_need);
4302 LOG (GNUNET_ERROR_TYPE_DEBUG,
4303 "first border: %" PRIu32 ", second border: %" PRIu32 ", final size: %"PRIu32 "\n",
4308 /* Update view with peers received through PUSHes */
4309 permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
4310 CustomPeerMap_size (sub->push_map));
4311 for (i = 0; i < first_border; i++)
4314 inserted = insert_in_view (sub,
4315 CustomPeerMap_get_peer_by_index (sub->push_map,
4317 if (GNUNET_OK == inserted)
4319 clients_notify_stream_peer (sub,
4321 CustomPeerMap_get_peer_by_index (sub->push_map, permut[i]));
4324 to_file (sub->file_name_view_log,
4326 GNUNET_i2s_full (&view_array[i]));
4327 #endif /* TO_FILE_FULL */
4328 // TODO change the peer_flags accordingly
4330 GNUNET_free (permut);
4333 /* Update view with peers received through PULLs */
4334 permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
4335 CustomPeerMap_size (sub->pull_map));
4336 for (i = first_border; i < second_border; i++)
4339 inserted = insert_in_view (sub,
4340 CustomPeerMap_get_peer_by_index (sub->pull_map,
4341 permut[i - first_border]));
4342 if (GNUNET_OK == inserted)
4344 clients_notify_stream_peer (sub,
4346 CustomPeerMap_get_peer_by_index (sub->pull_map,
4347 permut[i - first_border]));
4350 to_file (sub->file_name_view_log,
4352 GNUNET_i2s_full (&view_array[i]));
4353 #endif /* TO_FILE_FULL */
4354 // TODO change the peer_flags accordingly
4356 GNUNET_free (permut);
4359 /* Update view with peers from history */
4360 RPS_sampler_get_n_rand_peers (sub->sampler,
4361 final_size - second_border,
4364 // TODO change the peer_flags accordingly
4366 for (i = 0; i < View_size (sub->view); i++)
4367 rem_from_list (&peers_to_clean, &peers_to_clean_size, &view_array[i]);
4369 /* Clean peers that were removed from the view */
4370 for (i = 0; i < peers_to_clean_size; i++)
4373 to_file (sub->file_name_view_log,
4375 GNUNET_i2s_full (&peers_to_clean[i]));
4376 #endif /* TO_FILE_FULL */
4377 clean_peer (sub, &peers_to_clean[i]);
4380 GNUNET_array_grow (peers_to_clean, peers_to_clean_size, 0);
4381 clients_notify_view_update (sub);
4383 LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the view.\n");
4386 GNUNET_STATISTICS_update(stats, "# rounds blocked", 1, GNUNET_NO);
4387 if (CustomPeerMap_size (sub->push_map) > alpha * sub->view_size_est_need &&
4388 !(0 >= CustomPeerMap_size (sub->pull_map)))
4389 GNUNET_STATISTICS_update(stats, "# rounds blocked - too many pushes", 1, GNUNET_NO);
4390 if (CustomPeerMap_size (sub->push_map) > alpha * sub->view_size_est_need &&
4391 (0 >= CustomPeerMap_size (sub->pull_map)))
4392 GNUNET_STATISTICS_update(stats, "# rounds blocked - too many pushes, no pull replies", 1, GNUNET_NO);
4393 if (0 >= CustomPeerMap_size (sub->push_map) &&
4394 !(0 >= CustomPeerMap_size (sub->pull_map)))
4395 GNUNET_STATISTICS_update(stats, "# rounds blocked - no pushes", 1, GNUNET_NO);
4396 if (0 >= CustomPeerMap_size (sub->push_map) &&
4397 (0 >= CustomPeerMap_size (sub->pull_map)))
4398 GNUNET_STATISTICS_update(stats, "# rounds blocked - no pushes, no pull replies", 1, GNUNET_NO);
4399 if (0 >= CustomPeerMap_size (sub->pull_map) &&
4400 CustomPeerMap_size (sub->push_map) > alpha * sub->view_size_est_need &&
4401 0 >= CustomPeerMap_size (sub->push_map))
4402 GNUNET_STATISTICS_update(stats, "# rounds blocked - no pull replies", 1, GNUNET_NO);
4405 // TODO independent of that also get some peers from CADET_get_peers()?
4406 if (CustomPeerMap_size (sub->push_map) < HISTOGRAM_FILE_SLOTS)
4408 sub->push_recv[CustomPeerMap_size (sub->push_map)]++;
4412 LOG (GNUNET_ERROR_TYPE_WARNING,
4413 "Push map size too big for histogram (%u, %u)\n",
4414 CustomPeerMap_size (sub->push_map),
4415 HISTOGRAM_FILE_SLOTS);
4417 // FIXME check bounds of histogram
4418 sub->push_delta[(int32_t) (CustomPeerMap_size (sub->push_map) -
4419 (alpha * sub->view_size_est_need)) +
4420 (HISTOGRAM_FILE_SLOTS/2)]++;
4423 GNUNET_STATISTICS_set (stats,
4424 "# peers in push map at end of round",
4425 CustomPeerMap_size (sub->push_map),
4427 GNUNET_STATISTICS_set (stats,
4428 "# peers in pull map at end of round",
4429 CustomPeerMap_size (sub->pull_map),
4431 GNUNET_STATISTICS_set (stats,
4432 "# peers in view at end of round",
4433 View_size (sub->view),
4435 GNUNET_STATISTICS_set (stats,
4436 "# expected pushes",
4437 alpha * sub->view_size_est_need,
4439 GNUNET_STATISTICS_set (stats,
4440 "delta expected - received pushes",
4441 CustomPeerMap_size (sub->push_map) - (alpha * sub->view_size_est_need),
4445 LOG (GNUNET_ERROR_TYPE_DEBUG,
4446 "Received %u pushes and %u pulls last round (alpha (%.2f) * view_size (sub->view%u) = %.2f)\n",
4447 CustomPeerMap_size (sub->push_map),
4448 CustomPeerMap_size (sub->pull_map),
4450 View_size (sub->view),
4451 alpha * View_size (sub->view));
4453 /* Update samplers */
4454 for (i = 0; i < CustomPeerMap_size (sub->push_map); i++)
4456 update_peer = CustomPeerMap_get_peer_by_index (sub->push_map, i);
4457 LOG (GNUNET_ERROR_TYPE_DEBUG,
4458 "Updating with peer %s from push list\n",
4459 GNUNET_i2s (update_peer));
4460 insert_in_sampler (sub, update_peer);
4461 clean_peer (sub, update_peer); /* This cleans only if it is not in the view */
4464 for (i = 0; i < CustomPeerMap_size (sub->pull_map); i++)
4466 LOG (GNUNET_ERROR_TYPE_DEBUG,
4467 "Updating with peer %s from pull list\n",
4468 GNUNET_i2s (CustomPeerMap_get_peer_by_index (sub->pull_map, i)));
4469 insert_in_sampler (sub, CustomPeerMap_get_peer_by_index (sub->pull_map, i));
4470 /* This cleans only if it is not in the view */
4471 clean_peer (sub, CustomPeerMap_get_peer_by_index (sub->pull_map, i));
4475 /* Empty push/pull lists */
4476 CustomPeerMap_clear (sub->push_map);
4477 CustomPeerMap_clear (sub->pull_map);
4481 GNUNET_STATISTICS_set (stats,
4483 View_size(sub->view),
4487 struct GNUNET_TIME_Relative time_next_round;
4489 time_next_round = compute_rand_delay (sub->round_interval, 2);
4491 /* Schedule next round */
4492 sub->do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round,
4494 LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
4499 * This is called from GNUNET_CADET_get_peers().
4501 * It is called on every peer(ID) that cadet somehow has contact with.
4502 * We use those to initialise the sampler.
4504 * implements #GNUNET_CADET_PeersCB
4506 * @param cls Closure - Sub
4507 * @param peer Peer, or NULL on "EOF".
4508 * @param tunnel Do we have a tunnel towards this peer?
4509 * @param n_paths Number of known paths towards this peer.
4510 * @param best_path How long is the best path?
4511 * (0 = unknown, 1 = ourselves, 2 = neighbor)
4514 init_peer_cb (void *cls,
4515 const struct GNUNET_PeerIdentity *peer,
4516 int tunnel, /* "Do we have a tunnel towards this peer?" */
4517 unsigned int n_paths, /* "Number of known paths towards this peer" */
4518 unsigned int best_path) /* "How long is the best path?
4519 * (0 = unknown, 1 = ourselves, 2 = neighbor)" */
4521 struct Sub *sub = cls;
4528 LOG (GNUNET_ERROR_TYPE_DEBUG,
4529 "Got peer_id %s from cadet\n",
4531 got_peer (sub, peer);
4537 * @brief Iterator function over stored, valid peers.
4539 * We initialise the sampler with those.
4541 * @param cls Closure - Sub
4542 * @param peer the peer id
4543 * @return #GNUNET_YES if we should continue to
4545 * #GNUNET_NO if not.
4548 valid_peers_iterator (void *cls,
4549 const struct GNUNET_PeerIdentity *peer)
4551 struct Sub *sub = cls;
4555 LOG (GNUNET_ERROR_TYPE_DEBUG,
4556 "Got stored, valid peer %s\n",
4558 got_peer (sub, peer);
4565 * Iterator over peers from peerinfo.
4567 * @param cls Closure - Sub
4568 * @param peer id of the peer, NULL for last call
4569 * @param hello hello message for the peer (can be NULL)
4570 * @param error message
4573 process_peerinfo_peers (void *cls,
4574 const struct GNUNET_PeerIdentity *peer,
4575 const struct GNUNET_HELLO_Message *hello,
4576 const char *err_msg)
4578 struct Sub *sub = cls;
4584 LOG (GNUNET_ERROR_TYPE_DEBUG,
4585 "Got peer_id %s from peerinfo\n",
4587 got_peer (sub, peer);
4593 * Task run during shutdown.
4595 * @param cls Closure - unused
4598 shutdown_task (void *cls)
4601 struct ClientContext *client_ctx;
4603 LOG (GNUNET_ERROR_TYPE_DEBUG,
4604 "RPS service is going down\n");
4606 /* Clean all clients */
4607 for (client_ctx = cli_ctx_head;
4608 NULL != cli_ctx_head;
4609 client_ctx = cli_ctx_head)
4611 destroy_cli_ctx (client_ctx);
4619 /* Disconnect from other services */
4620 GNUNET_PEERINFO_notify_cancel (peerinfo_notify_handle);
4621 GNUNET_PEERINFO_disconnect (peerinfo_handle);
4622 peerinfo_handle = NULL;
4623 GNUNET_NSE_disconnect (nse);
4624 if (NULL != map_single_hop)
4626 /* core_init was called - core was initialised */
4627 /* disconnect first, so no callback tries to access missing peermap */
4628 GNUNET_CORE_disconnect (core_handle);
4630 GNUNET_CONTAINER_multipeermap_destroy (map_single_hop);
4631 map_single_hop = NULL;
4636 GNUNET_STATISTICS_destroy (stats,
4640 GNUNET_CADET_disconnect (cadet_handle);
4641 cadet_handle = NULL;
4642 #if ENABLE_MALICIOUS
4643 struct AttackedPeer *tmp_att_peer;
4644 GNUNET_array_grow (mal_peers,
4647 if (NULL != mal_peer_set)
4648 GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
4649 if (NULL != att_peer_set)
4650 GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
4651 while (NULL != att_peers_head)
4653 tmp_att_peer = att_peers_head;
4654 GNUNET_CONTAINER_DLL_remove (att_peers_head,
4657 GNUNET_free (tmp_att_peer);
4659 #endif /* ENABLE_MALICIOUS */
4665 * Handle client connecting to the service.
4668 * @param client the new client
4669 * @param mq the message queue of @a client
4673 client_connect_cb (void *cls,
4674 struct GNUNET_SERVICE_Client *client,
4675 struct GNUNET_MQ_Handle *mq)
4677 struct ClientContext *cli_ctx;
4680 LOG (GNUNET_ERROR_TYPE_DEBUG,
4681 "Client connected\n");
4683 return client; /* Server was destroyed before a client connected. Shutting down */
4684 cli_ctx = GNUNET_new (struct ClientContext);
4686 cli_ctx->view_updates_left = -1;
4687 cli_ctx->stream_update = GNUNET_NO;
4688 cli_ctx->client = client;
4689 GNUNET_CONTAINER_DLL_insert (cli_ctx_head,
4696 * Callback called when a client disconnected from the service
4698 * @param cls closure for the service
4699 * @param c the client that disconnected
4700 * @param internal_cls should be equal to @a c
4703 client_disconnect_cb (void *cls,
4704 struct GNUNET_SERVICE_Client *client,
4707 struct ClientContext *cli_ctx = internal_cls;
4710 GNUNET_assert (client == cli_ctx->client);
4712 {/* shutdown task - destroy all clients */
4713 while (NULL != cli_ctx_head)
4714 destroy_cli_ctx (cli_ctx_head);
4717 { /* destroy this client */
4718 LOG (GNUNET_ERROR_TYPE_DEBUG,
4719 "Client disconnected. Destroy its context.\n");
4720 destroy_cli_ctx (cli_ctx);
4726 * Handle random peer sampling clients.
4728 * @param cls closure
4729 * @param c configuration to use
4730 * @param service the initialized service
4734 const struct GNUNET_CONFIGURATION_Handle *c,
4735 struct GNUNET_SERVICE_Handle *service)
4737 struct GNUNET_TIME_Relative round_interval;
4738 long long unsigned int sampler_size;
4739 char hash_port_string[] = GNUNET_APPLICATION_PORT_RPS;
4740 struct GNUNET_HashCode hash;
4745 GNUNET_log_setup ("rps",
4746 GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG),
4750 GNUNET_CRYPTO_get_peer_identity (cfg,
4751 &own_identity); // TODO check return value
4752 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4753 "STARTING SERVICE (rps) for peer [%s]\n",
4754 GNUNET_i2s (&own_identity));
4755 #if ENABLE_MALICIOUS
4756 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4757 "Malicious execution compiled in.\n");
4758 #endif /* ENABLE_MALICIOUS */
4760 /* Get time interval from the configuration */
4762 GNUNET_CONFIGURATION_get_value_time (cfg,
4767 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4768 "RPS", "ROUNDINTERVAL");
4769 GNUNET_SCHEDULER_shutdown ();
4773 /* Get initial size of sampler/view from the configuration */
4775 GNUNET_CONFIGURATION_get_value_number (cfg,
4780 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4782 GNUNET_SCHEDULER_shutdown ();
4786 cadet_handle = GNUNET_CADET_connect (cfg);
4787 GNUNET_assert (NULL != cadet_handle);
4788 core_handle = GNUNET_CORE_connect (cfg,
4790 core_init, /* init */
4791 core_connects, /* connects */
4792 core_disconnects, /* disconnects */
4793 NULL); /* handlers */
4794 GNUNET_assert (NULL != core_handle);
4801 /* Set up main Sub */
4802 GNUNET_CRYPTO_hash (hash_port_string,
4803 strlen (hash_port_string),
4805 msub = new_sub (&hash,
4806 sampler_size, /* Will be overwritten by config */
4810 peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
4812 /* connect to NSE */
4813 nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
4815 //LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
4816 //GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, msub);
4817 // TODO send push/pull to each of those peers?
4818 LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting stored valid peers\n");
4819 restore_valid_peers (msub);
4820 get_valid_peers (msub->valid_peers, valid_peers_iterator, msub);
4822 peerinfo_notify_handle = GNUNET_PEERINFO_notify (cfg,
4824 process_peerinfo_peers,
4827 LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
4829 GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
4830 stats = GNUNET_STATISTICS_create ("rps", cfg);
4835 * Define "main" method using service macro.
4839 GNUNET_SERVICE_OPTION_NONE,
4842 &client_disconnect_cb,
4844 GNUNET_MQ_hd_var_size (client_seed,
4845 GNUNET_MESSAGE_TYPE_RPS_CS_SEED,
4846 struct GNUNET_RPS_CS_SeedMessage,
4848 #if ENABLE_MALICIOUS
4849 GNUNET_MQ_hd_var_size (client_act_malicious,
4850 GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS,
4851 struct GNUNET_RPS_CS_ActMaliciousMessage,
4853 #endif /* ENABLE_MALICIOUS */
4854 GNUNET_MQ_hd_fixed_size (client_view_request,
4855 GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REQUEST,
4856 struct GNUNET_RPS_CS_DEBUG_ViewRequest,
4858 GNUNET_MQ_hd_fixed_size (client_view_cancel,
4859 GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_CANCEL,
4860 struct GNUNET_MessageHeader,
4862 GNUNET_MQ_hd_fixed_size (client_stream_request,
4863 GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_REQUEST,
4864 struct GNUNET_RPS_CS_DEBUG_StreamRequest,
4866 GNUNET_MQ_hd_fixed_size (client_stream_cancel,
4867 GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_CANCEL,
4868 struct GNUNET_MessageHeader,
4870 GNUNET_MQ_hd_fixed_size (client_start_sub,
4871 GNUNET_MESSAGE_TYPE_RPS_CS_SUB_START,
4872 struct GNUNET_RPS_CS_SubStartMessage,
4874 GNUNET_MQ_hd_fixed_size (client_stop_sub,
4875 GNUNET_MESSAGE_TYPE_RPS_CS_SUB_STOP,
4876 struct GNUNET_RPS_CS_SubStopMessage,
4878 GNUNET_MQ_handler_end());
4880 /* end of gnunet-service-rps.c */