2 This file is part of GNUnet.
3 Copyright (C) 2011, 2016 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
21 * @file fs/gnunet-service-fs_cp.c
22 * @brief API to handle 'connected peers'
23 * @author Christian Grothoff
26 #include "gnunet_util_lib.h"
27 #include "gnunet_load_lib.h"
28 #include "gnunet-service-fs.h"
29 #include "gnunet-service-fs_cp.h"
30 #include "gnunet-service-fs_pe.h"
31 #include "gnunet-service-fs_pr.h"
32 #include "gnunet-service-fs_push.h"
33 #include "gnunet_peerstore_service.h"
37 * Ratio for moving average delay calculation. The previous
38 * average goes in with a factor of (n-1) into the calculation.
41 #define RUNAVG_DELAY_N 16
44 * How often do we flush respect values to disk?
46 #define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply ( \
47 GNUNET_TIME_UNIT_MINUTES, 5)
50 * After how long do we discard a reply?
52 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, \
56 * Collect an instane number of statistics? May cause excessive IPC.
58 #define INSANE_STATISTICS GNUNET_NO
62 * Handle to cancel a transmission request.
64 struct GSF_PeerTransmitHandle
67 * Kept in a doubly-linked list.
69 struct GSF_PeerTransmitHandle *next;
72 * Kept in a doubly-linked list.
74 struct GSF_PeerTransmitHandle *prev;
77 * Time when this transmission request was issued.
79 struct GNUNET_TIME_Absolute transmission_request_start_time;
82 * Envelope with the actual message.
84 struct GNUNET_MQ_Envelope *env;
87 * Peer this request targets.
89 struct GSF_ConnectedPeer *cp;
92 * #GNUNET_YES if this is a query, #GNUNET_NO for content.
97 * Did we get a reservation already?
102 * Priority of this request.
109 * Handle for an entry in our delay list.
111 struct GSF_DelayedHandle
114 * Kept in a doubly-linked list.
116 struct GSF_DelayedHandle *next;
119 * Kept in a doubly-linked list.
121 struct GSF_DelayedHandle *prev;
124 * Peer this transmission belongs to.
126 struct GSF_ConnectedPeer *cp;
129 * Envelope of the message that was delayed.
131 struct GNUNET_MQ_Envelope *env;
134 * Task for the delay.
136 struct GNUNET_SCHEDULER_Task *delay_task;
139 * Size of the message.
146 * Information per peer and request.
151 * Handle to generic request (generic: from peer or local client).
153 struct GSF_PendingRequest *pr;
156 * Which specific peer issued this request?
158 struct GSF_ConnectedPeer *cp;
161 * Task for asynchronous stopping of this request.
163 struct GNUNET_SCHEDULER_Task *kill_task;
170 struct GSF_ConnectedPeer
173 * Performance data for this peer.
175 struct GSF_PeerPerformanceData ppd;
178 * Time until when we blocked this peer from migrating
181 struct GNUNET_TIME_Absolute last_migration_block;
184 * Task scheduled to revive migration to this peer.
186 struct GNUNET_SCHEDULER_Task *mig_revive_task;
189 * Messages (replies, queries, content migration) we would like to
190 * send to this peer in the near future. Sorted by priority, head.
192 struct GSF_PeerTransmitHandle *pth_head;
195 * Messages (replies, queries, content migration) we would like to
196 * send to this peer in the near future. Sorted by priority, tail.
198 struct GSF_PeerTransmitHandle *pth_tail;
201 * Messages (replies, queries, content migration) we would like to
202 * send to this peer in the near future. Sorted by priority, head.
204 struct GSF_DelayedHandle *delayed_head;
207 * Messages (replies, queries, content migration) we would like to
208 * send to this peer in the near future. Sorted by priority, tail.
210 struct GSF_DelayedHandle *delayed_tail;
213 * Context of our GNUNET_ATS_reserve_bandwidth call (or NULL).
215 struct GNUNET_ATS_ReservationContext *rc;
218 * Task scheduled if we need to retry bandwidth reservation later.
220 struct GNUNET_SCHEDULER_Task *rc_delay_task;
223 * Active requests from this neighbour, map of query to `struct PeerRequest`.
225 struct GNUNET_CONTAINER_MultiHashMap *request_map;
228 * Handle for an active request for transmission to this
231 struct GNUNET_MQ_Handle *mq;
234 * Increase in traffic preference still to be submitted
235 * to the core service for this peer.
237 uint64_t inc_preference;
240 * Number of entries in @e delayed_head DLL.
242 unsigned int delay_queue_size;
245 * Respect rating for this peer on disk.
247 uint32_t disk_respect;
250 * Which offset in @e last_p2p_replies will be updated next?
251 * (we go round-robin).
253 unsigned int last_p2p_replies_woff;
256 * Which offset in @e last_client_replies will be updated next?
257 * (we go round-robin).
259 unsigned int last_client_replies_woff;
262 * Current offset into @e last_request_times ring buffer.
264 unsigned int last_request_times_off;
267 * #GNUNET_YES if we did successfully reserve 32k bandwidth,
273 * Handle to the PEERSTORE iterate request for peer respect value
275 struct GNUNET_PEERSTORE_IterateContext *respect_iterate_req;
280 * Map from peer identities to `struct GSF_ConnectPeer` entries.
282 static struct GNUNET_CONTAINER_MultiPeerMap *cp_map;
285 * Handle to peerstore service.
287 static struct GNUNET_PEERSTORE_Handle *peerstore;
290 * Task used to flush respect values to disk.
292 static struct GNUNET_SCHEDULER_Task *fr_task;
296 * Update the latency information kept for the given peer.
298 * @param id peer record to update
299 * @param latency current latency value
302 GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id,
303 struct GNUNET_TIME_Relative latency)
305 struct GSF_ConnectedPeer *cp;
307 cp = GSF_peer_get_ (id);
309 return; /* we're not yet connected at the core level, ignore */
310 GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay,
316 * Return the performance data record for the given peer
318 * @param cp peer to query
319 * @return performance data record for the peer
321 struct GSF_PeerPerformanceData *
322 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
329 * Core is ready to transmit to a peer, get the message.
331 * @param cp which peer to send a message to
334 peer_transmit (struct GSF_ConnectedPeer *cp);
338 * Function called by core upon success or failure of our bandwidth reservation request.
340 * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
341 * @param peer identifies the peer
342 * @param amount set to the amount that was actually reserved or unreserved;
343 * either the full requested amount or zero (no partial reservations)
344 * @param res_delay if the reservation could not be satisfied (amount was 0), how
345 * long should the client wait until re-trying?
348 ats_reserve_callback (void *cls,
349 const struct GNUNET_PeerIdentity *peer,
351 struct GNUNET_TIME_Relative res_delay);
355 * If ready (bandwidth reserved), try to schedule transmission via
356 * core for the given handle.
358 * @param pth transmission handle to schedule
361 schedule_transmission (struct GSF_PeerTransmitHandle *pth)
363 struct GSF_ConnectedPeer *cp;
364 struct GNUNET_PeerIdentity target;
367 GNUNET_assert (0 != cp->ppd.pid);
368 GNUNET_PEER_resolve (cp->ppd.pid, &target);
370 if (0 != cp->inc_preference)
372 GNUNET_ATS_performance_change_preference (GSF_ats,
374 GNUNET_ATS_PREFERENCE_BANDWIDTH,
375 (double) cp->inc_preference,
376 GNUNET_ATS_PREFERENCE_END);
377 cp->inc_preference = 0;
380 if ((GNUNET_YES == pth->is_query) &&
381 (GNUNET_YES != pth->was_reserved))
383 /* query, need reservation */
384 if (GNUNET_YES != cp->did_reserve)
385 return; /* not ready */
386 cp->did_reserve = GNUNET_NO;
387 /* reservation already done! */
388 pth->was_reserved = GNUNET_YES;
389 cp->rc = GNUNET_ATS_reserve_bandwidth (GSF_ats,
392 &ats_reserve_callback,
401 * Core is ready to transmit to a peer, get the message.
403 * @param cp which peer to send a message to
406 peer_transmit (struct GSF_ConnectedPeer *cp)
408 struct GSF_PeerTransmitHandle *pth = cp->pth_head;
409 struct GSF_PeerTransmitHandle *pos;
413 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
416 if (GNUNET_YES == pth->is_query)
418 cp->ppd.last_request_times[(cp->last_request_times_off++)
419 % MAX_QUEUE_PER_PEER] =
420 GNUNET_TIME_absolute_get ();
421 GNUNET_assert (0 < cp->ppd.pending_queries--);
423 else if (GNUNET_NO == pth->is_query)
425 GNUNET_assert (0 < cp->ppd.pending_replies--);
427 GNUNET_LOAD_update (cp->ppd.transmission_delay,
428 GNUNET_TIME_absolute_get_duration
429 (pth->transmission_request_start_time).rel_value_us);
430 GNUNET_MQ_send (cp->mq,
433 if (NULL != (pos = cp->pth_head))
435 GNUNET_assert (pos != pth);
436 schedule_transmission (pos);
442 * (re)try to reserve bandwidth from the given peer.
444 * @param cls the `struct GSF_ConnectedPeer` to reserve from
447 retry_reservation (void *cls)
449 struct GSF_ConnectedPeer *cp = cls;
450 struct GNUNET_PeerIdentity target;
452 GNUNET_PEER_resolve (cp->ppd.pid, &target);
453 cp->rc_delay_task = NULL;
455 GNUNET_ATS_reserve_bandwidth (GSF_ats,
458 &ats_reserve_callback, cp);
463 * Function called by core upon success or failure of our bandwidth reservation request.
465 * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
466 * @param peer identifies the peer
467 * @param amount set to the amount that was actually reserved or unreserved;
468 * either the full requested amount or zero (no partial reservations)
469 * @param res_delay if the reservation could not be satisfied (amount was 0), how
470 * long should the client wait until re-trying?
473 ats_reserve_callback (void *cls,
474 const struct GNUNET_PeerIdentity *peer,
476 struct GNUNET_TIME_Relative res_delay)
478 struct GSF_ConnectedPeer *cp = cls;
479 struct GSF_PeerTransmitHandle *pth;
481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
482 "Reserved %d bytes / need to wait %s for reservation\n",
484 GNUNET_STRINGS_relative_time_to_string (res_delay, GNUNET_YES));
489 GNUNET_SCHEDULER_add_delayed (res_delay,
494 cp->did_reserve = GNUNET_YES;
498 /* reservation success, try transmission now! */
505 * Function called by PEERSTORE with peer respect record
507 * @param cls handle to connected peer entry
508 * @param record peerstore record information
509 * @param emsg error message, or NULL if no errors
512 peer_respect_cb (void *cls,
513 const struct GNUNET_PEERSTORE_Record *record,
516 struct GSF_ConnectedPeer *cp = cls;
518 GNUNET_assert (NULL != cp->respect_iterate_req);
519 if ((NULL != record) &&
520 (sizeof(cp->disk_respect) == record->value_size))
522 cp->disk_respect = *((uint32_t *) record->value);
523 cp->ppd.respect += *((uint32_t *) record->value);
525 GSF_push_start_ (cp);
527 GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
528 cp->respect_iterate_req = NULL;
533 * Function called for each pending request whenever a new
534 * peer connects, giving us a chance to decide about submitting
535 * the existing request to the new peer.
537 * @param cls the `struct GSF_ConnectedPeer` of the new peer
538 * @param key query for the request
539 * @param pr handle to the pending request
540 * @return #GNUNET_YES to continue to iterate
543 consider_peer_for_forwarding (void *cls,
544 const struct GNUNET_HashCode *key,
545 struct GSF_PendingRequest *pr)
547 struct GSF_ConnectedPeer *cp = cls;
548 struct GNUNET_PeerIdentity pid;
551 GSF_pending_request_test_active_ (pr))
552 return GNUNET_YES; /* request is not actually active, skip! */
553 GSF_connected_peer_get_identity_ (cp, &pid);
555 GSF_pending_request_test_target_ (pr, &pid))
557 GNUNET_STATISTICS_update (GSF_stats,
558 gettext_noop ("# Loopback routes suppressed"),
563 GSF_plan_add_ (cp, pr);
569 * A peer connected to us. Setup the connected peer
573 * @param peer identity of peer that connected
574 * @param mq message queue for talking to @a peer
575 * @return our internal handle for the peer
578 GSF_peer_connect_handler (void *cls,
579 const struct GNUNET_PeerIdentity *peer,
580 struct GNUNET_MQ_Handle *mq)
582 struct GSF_ConnectedPeer *cp;
585 GNUNET_memcmp (&GSF_my_id,
588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
589 "Connected to peer %s\n",
591 cp = GNUNET_new (struct GSF_ConnectedPeer);
592 cp->ppd.pid = GNUNET_PEER_intern (peer);
595 cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO);
597 GNUNET_ATS_reserve_bandwidth (GSF_ats,
600 &ats_reserve_callback, cp);
601 cp->request_map = GNUNET_CONTAINER_multihashmap_create (128,
603 GNUNET_break (GNUNET_OK ==
604 GNUNET_CONTAINER_multipeermap_put (cp_map,
605 GSF_connected_peer_get_identity2_ (
608 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
609 GNUNET_STATISTICS_set (GSF_stats,
610 gettext_noop ("# peers connected"),
611 GNUNET_CONTAINER_multipeermap_size (cp_map),
613 cp->respect_iterate_req
614 = GNUNET_PEERSTORE_iterate (peerstore,
620 GSF_iterate_pending_requests_ (&consider_peer_for_forwarding,
627 * It may be time to re-start migrating content to this
628 * peer. Check, and if so, restart migration.
630 * @param cls the `struct GSF_ConnectedPeer`
633 revive_migration (void *cls)
635 struct GSF_ConnectedPeer *cp = cls;
636 struct GNUNET_TIME_Relative bt;
638 cp->mig_revive_task = NULL;
639 bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until);
640 if (0 != bt.rel_value_us)
642 /* still time left... */
643 cp->mig_revive_task =
644 GNUNET_SCHEDULER_add_delayed (bt, &revive_migration, cp);
647 GSF_push_start_ (cp);
652 * Get a handle for a connected peer.
654 * @param peer peer's identity
655 * @return NULL if the peer is not currently connected
657 struct GSF_ConnectedPeer *
658 GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer)
662 return GNUNET_CONTAINER_multipeermap_get (cp_map, peer);
667 * Handle P2P #GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP message.
669 * @param cls closure, the `struct GSF_ConnectedPeer`
670 * @param msm the actual message
673 handle_p2p_migration_stop (void *cls,
674 const struct MigrationStopMessage *msm)
676 struct GSF_ConnectedPeer *cp = cls;
677 struct GNUNET_TIME_Relative bt;
679 GNUNET_STATISTICS_update (GSF_stats,
680 gettext_noop ("# migration stop messages received"),
682 bt = GNUNET_TIME_relative_ntoh (msm->duration);
683 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
684 _ ("Migration of content to peer `%s' blocked for %s\n"),
685 GNUNET_i2s (cp->ppd.peer),
686 GNUNET_STRINGS_relative_time_to_string (bt, GNUNET_YES));
687 cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt);
688 if ((NULL == cp->mig_revive_task) &&
689 (NULL == cp->respect_iterate_req))
692 cp->mig_revive_task =
693 GNUNET_SCHEDULER_add_delayed (bt,
694 &revive_migration, cp);
700 * Free resources associated with the given peer request.
702 * @param peerreq request to free
705 free_pending_request (struct PeerRequest *peerreq)
707 struct GSF_ConnectedPeer *cp = peerreq->cp;
708 struct GSF_PendingRequestData *prd;
710 prd = GSF_pending_request_get_data_ (peerreq->pr);
711 if (NULL != peerreq->kill_task)
713 GNUNET_SCHEDULER_cancel (peerreq->kill_task);
714 peerreq->kill_task = NULL;
716 GNUNET_STATISTICS_update (GSF_stats,
717 gettext_noop ("# P2P searches active"),
720 GNUNET_break (GNUNET_YES ==
721 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
724 GNUNET_free (peerreq);
729 * Cancel all requests associated with the peer.
732 * @param query hash code of the request
733 * @param value the `struct GSF_PendingRequest`
734 * @return #GNUNET_YES (continue to iterate)
737 cancel_pending_request (void *cls,
738 const struct GNUNET_HashCode *query,
741 struct PeerRequest *peerreq = value;
742 struct GSF_PendingRequest *pr = peerreq->pr;
744 free_pending_request (peerreq);
745 GSF_pending_request_cancel_ (pr,
752 * Free the given request.
754 * @param cls the request to free
757 peer_request_destroy (void *cls)
759 struct PeerRequest *peerreq = cls;
760 struct GSF_PendingRequest *pr = peerreq->pr;
761 struct GSF_PendingRequestData *prd;
763 peerreq->kill_task = NULL;
764 prd = GSF_pending_request_get_data_ (pr);
765 cancel_pending_request (NULL,
772 * The artificial delay is over, transmit the message now.
774 * @param cls the `struct GSF_DelayedHandle` with the message
777 transmit_delayed_now (void *cls)
779 struct GSF_DelayedHandle *dh = cls;
780 struct GSF_ConnectedPeer *cp = dh->cp;
782 GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
785 cp->delay_queue_size--;
786 GSF_peer_transmit_ (cp,
795 * Get the randomized delay a response should be subjected to.
797 * @return desired delay
799 static struct GNUNET_TIME_Relative
800 get_randomized_delay ()
802 struct GNUNET_TIME_Relative ret;
805 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
806 GNUNET_CRYPTO_random_u32
807 (GNUNET_CRYPTO_QUALITY_WEAK,
808 2 * GSF_avg_latency.rel_value_us + 1));
809 #if INSANE_STATISTICS
810 GNUNET_STATISTICS_update (GSF_stats,
812 ("# artificial delays introduced (ms)"),
813 ret.rel_value_us / 1000LL, GNUNET_NO);
820 * Handle a reply to a pending request. Also called if a request
821 * expires (then with data == NULL). The handler may be called
822 * many times (depending on the request type), but will not be
823 * called during or after a call to GSF_pending_request_cancel
824 * and will also not be called anymore after a call signalling
827 * @param cls `struct PeerRequest` this is an answer for
828 * @param eval evaluation of the result
829 * @param pr handle to the original pending request
830 * @param reply_anonymity_level anonymity level for the reply, UINT32_MAX for "unknown"
831 * @param expiration when does @a data expire?
832 * @param last_transmission when did we last transmit a request for this block
833 * @param type type of the block
834 * @param data response data, NULL on request expiration
835 * @param data_len number of bytes in @a data
838 handle_p2p_reply (void *cls,
839 enum GNUNET_BLOCK_EvaluationResult eval,
840 struct GSF_PendingRequest *pr,
841 uint32_t reply_anonymity_level,
842 struct GNUNET_TIME_Absolute expiration,
843 struct GNUNET_TIME_Absolute last_transmission,
844 enum GNUNET_BLOCK_Type type,
848 struct PeerRequest *peerreq = cls;
849 struct GSF_ConnectedPeer *cp = peerreq->cp;
850 struct GSF_PendingRequestData *prd;
851 struct GNUNET_MQ_Envelope *env;
852 struct PutMessage *pm;
855 GNUNET_assert (data_len + sizeof(struct PutMessage) <
856 GNUNET_MAX_MESSAGE_SIZE);
857 GNUNET_assert (peerreq->pr == pr);
858 prd = GSF_pending_request_get_data_ (pr);
861 free_pending_request (peerreq);
864 GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type);
865 if ((prd->type != type) && (GNUNET_BLOCK_TYPE_ANY != prd->type))
867 GNUNET_STATISTICS_update (GSF_stats,
869 ("# replies dropped due to type mismatch"),
873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
874 "Transmitting result for query `%s' to peer\n",
875 GNUNET_h2s (&prd->query));
876 GNUNET_STATISTICS_update (GSF_stats,
877 gettext_noop ("# replies received for other peers"),
879 msize = sizeof(struct PutMessage) + data_len;
880 if (msize >= GNUNET_MAX_MESSAGE_SIZE)
885 if ((UINT32_MAX != reply_anonymity_level) && (reply_anonymity_level > 1))
887 if (reply_anonymity_level - 1 > GSF_cover_content_count)
889 GNUNET_STATISTICS_update (GSF_stats,
892 "# replies dropped due to insufficient cover traffic"),
896 GSF_cover_content_count -= (reply_anonymity_level - 1);
899 env = GNUNET_MQ_msg_extra (pm,
901 GNUNET_MESSAGE_TYPE_FS_PUT);
902 pm->type = htonl (type);
903 pm->expiration = GNUNET_TIME_absolute_hton (expiration);
904 GNUNET_memcpy (&pm[1],
907 if ((UINT32_MAX != reply_anonymity_level) &&
908 (0 != reply_anonymity_level) &&
909 (GNUNET_YES == GSF_enable_randomized_delays))
911 struct GSF_DelayedHandle *dh;
913 dh = GNUNET_new (struct GSF_DelayedHandle);
917 GNUNET_CONTAINER_DLL_insert (cp->delayed_head,
920 cp->delay_queue_size++;
922 GNUNET_SCHEDULER_add_delayed (get_randomized_delay (),
923 &transmit_delayed_now,
928 GSF_peer_transmit_ (cp,
933 if (GNUNET_BLOCK_EVALUATION_OK_LAST != eval)
935 if (NULL == peerreq->kill_task)
937 GNUNET_STATISTICS_update (GSF_stats,
940 "# P2P searches destroyed due to ultimate reply"),
944 GNUNET_SCHEDULER_add_now (&peer_request_destroy,
951 * Increase the peer's respect by a value.
953 * @param cp which peer to change the respect value on
954 * @param value is the int value by which the
955 * peer's credit is to be increased or decreased
956 * @returns the actual change in respect (positive or negative)
959 change_peer_respect (struct GSF_ConnectedPeer *cp, int value)
963 GNUNET_assert (NULL != cp);
966 if (cp->ppd.respect + value < cp->ppd.respect)
968 value = UINT32_MAX - cp->ppd.respect;
969 cp->ppd.respect = UINT32_MAX;
972 cp->ppd.respect += value;
976 if (cp->ppd.respect < -value)
978 value = -cp->ppd.respect;
982 cp->ppd.respect += value;
989 * We've received a request with the specified priority. Bound it
990 * according to how much we respect the given peer.
992 * @param prio_in requested priority
993 * @param cp the peer making the request
994 * @return effective priority
997 bound_priority (uint32_t prio_in,
998 struct GSF_ConnectedPeer *cp)
1000 #define N ((double) 128.0)
1005 ld = GSF_test_get_load_too_high_ (0);
1006 if (GNUNET_SYSERR == ld)
1008 #if INSANE_STATISTICS
1009 GNUNET_STATISTICS_update (GSF_stats,
1011 ("# requests done for free (low load)"), 1,
1014 return 0; /* excess resources */
1016 if (prio_in > INT32_MAX)
1017 prio_in = INT32_MAX;
1018 ret = -change_peer_respect (cp, -(int) prio_in);
1021 if (ret > GSF_current_priorities + N)
1022 rret = GSF_current_priorities + N;
1025 GSF_current_priorities = (GSF_current_priorities * (N - 1) + rret) / N;
1027 if ((GNUNET_YES == ld) && (ret > 0))
1029 /* try with charging */
1030 ld = GSF_test_get_load_too_high_ (ret);
1032 if (GNUNET_YES == ld)
1034 GNUNET_STATISTICS_update (GSF_stats,
1036 ("# request dropped, priority insufficient"), 1,
1039 change_peer_respect (cp, (int) ret);
1040 return -1; /* not enough resources */
1044 GNUNET_STATISTICS_update (GSF_stats,
1046 ("# requests done for a price (normal load)"),
1056 * The priority level imposes a bound on the maximum
1057 * value for the ttl that can be requested.
1059 * @param ttl_in requested ttl
1060 * @param prio given priority
1061 * @return @a ttl_in if @a ttl_in is below the limit,
1062 * otherwise the ttl-limit for the given @a prio
1065 bound_ttl (int32_t ttl_in,
1068 unsigned long long allowed;
1072 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1073 if (ttl_in > allowed)
1075 if (allowed >= (1 << 30))
1084 * Closure for #test_exist_cb().
1086 struct TestExistClosure
1089 * Priority of the incoming request.
1094 * Relative TTL of the incoming request.
1099 * Type of the incoming request.
1101 enum GNUNET_BLOCK_Type type;
1104 * Set to #GNUNET_YES if we are done handling the query.
1111 * Test if the query already exists. If so, merge it, otherwise
1112 * keep `finished` at #GNUNET_NO.
1114 * @param cls our `struct TestExistClosure`
1115 * @param hc the key of the query
1116 * @param value the existing `struct PeerRequest`.
1117 * @return #GNUNET_YES to continue to iterate,
1118 * #GNUNET_NO if we successfully merged
1121 test_exist_cb (void *cls,
1122 const struct GNUNET_HashCode *hc,
1125 struct TestExistClosure *tec = cls;
1126 struct PeerRequest *peerreq = value;
1127 struct GSF_PendingRequest *pr;
1128 struct GSF_PendingRequestData *prd;
1131 prd = GSF_pending_request_get_data_ (pr);
1132 if (prd->type != tec->type)
1134 if (prd->ttl.abs_value_us >=
1135 GNUNET_TIME_absolute_get ().abs_value_us + tec->ttl * 1000LL)
1137 /* existing request has higher TTL, drop new one! */
1138 prd->priority += tec->priority;
1139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1140 "Have existing request with higher TTL, dropping new request.\n");
1141 GNUNET_STATISTICS_update (GSF_stats,
1143 ("# requests dropped due to higher-TTL request"),
1145 tec->finished = GNUNET_YES;
1148 /* existing request has lower TTL, drop old one! */
1149 tec->priority += prd->priority;
1150 free_pending_request (peerreq);
1151 GSF_pending_request_cancel_ (pr,
1158 * Handle P2P "QUERY" message. Creates the pending request entry
1159 * and sets up all of the data structures to that we will
1160 * process replies properly. Does not initiate forwarding or
1161 * local database lookups.
1163 * @param cls the other peer involved (sender of the message)
1164 * @param gm the GET message
1167 handle_p2p_get (void *cls,
1168 const struct GetMessage *gm)
1170 struct GSF_ConnectedPeer *cps = cls;
1171 struct PeerRequest *peerreq;
1172 struct GSF_PendingRequest *pr;
1173 struct GSF_ConnectedPeer *cp;
1174 const struct GNUNET_PeerIdentity *target;
1175 enum GSF_PendingRequestOptions options;
1178 const struct GNUNET_PeerIdentity *opt;
1181 uint32_t ttl_decrement;
1182 struct TestExistClosure tec;
1183 GNUNET_PEER_Id spid;
1184 const struct GSF_PendingRequestData *prd;
1186 msize = ntohs (gm->header.size);
1187 tec.type = ntohl (gm->type);
1188 bm = ntohl (gm->hash_bitmap);
1196 opt = (const struct GNUNET_PeerIdentity *) &gm[1];
1197 bfsize = msize - sizeof(struct GetMessage) - bits * sizeof(struct
1198 GNUNET_PeerIdentity);
1199 GNUNET_STATISTICS_update (GSF_stats,
1201 ("# GET requests received (from other peers)"),
1204 GSF_cover_query_count++;
1205 bm = ntohl (gm->hash_bitmap);
1207 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1208 cp = GSF_peer_get_ (&opt[bits++]);
1213 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215 "Failed to find RETURN-TO peer `%s' in connection set. Dropping query.\n",
1216 GNUNET_i2s (&opt[bits - 1]));
1219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1220 "Failed to find peer `%s' in connection set. Dropping query.\n",
1221 GNUNET_i2s (cps->ppd.peer));
1222 GNUNET_STATISTICS_update (GSF_stats,
1225 "# requests dropped due to missing reverse route"),
1230 unsigned int queue_size = GNUNET_MQ_get_length (cp->mq);
1231 queue_size += cp->ppd.pending_replies + cp->delay_queue_size;
1232 if (queue_size > MAX_QUEUE_PER_PEER)
1234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1235 "Peer `%s' has too many replies queued already. Dropping query.\n",
1236 GNUNET_i2s (cps->ppd.peer));
1237 GNUNET_STATISTICS_update (GSF_stats,
1239 "# requests dropped due to full reply queue"),
1244 /* note that we can really only check load here since otherwise
1245 * peers could find out that we are overloaded by not being
1246 * disconnected after sending us a malformed query... */
1247 tec.priority = bound_priority (ntohl (gm->priority),
1249 if (tec.priority < 0)
1251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1252 "Dropping query from `%s', this peer is too busy.\n",
1253 GNUNET_i2s (cps->ppd.peer));
1256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1257 "Received request for `%s' of type %u from peer `%s' with flags %u\n",
1258 GNUNET_h2s (&gm->query),
1259 (unsigned int) tec.type,
1260 GNUNET_i2s (cps->ppd.peer),
1264 (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? (&opt[bits++]) : NULL;
1265 options = GSF_PRO_DEFAULTS;
1267 if ((GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1
1269 || (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) >
1270 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value_us * 2
1271 + GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)))
1273 /* don't have BW to send to peer, or would likely take longer than we have for it,
1274 * so at best indirect the query */
1276 options |= GSF_PRO_FORWARD_ONLY;
1277 spid = GNUNET_PEER_intern (cps->ppd.peer);
1278 GNUNET_assert (0 != spid);
1280 tec.ttl = bound_ttl (ntohl (gm->ttl),
1282 /* decrement ttl (always) */
1284 2 * TTL_DECREMENT + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1286 if ((tec.ttl < 0) &&
1287 (((int32_t) (tec.ttl - ttl_decrement)) > 0))
1289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1290 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
1291 GNUNET_i2s (cps->ppd.peer),
1294 GNUNET_STATISTICS_update (GSF_stats,
1296 ("# requests dropped due TTL underflow"), 1,
1298 /* integer underflow => drop (should be very rare)! */
1301 tec.ttl -= ttl_decrement;
1303 /* test if the request already exists */
1304 tec.finished = GNUNET_NO;
1305 GNUNET_CONTAINER_multihashmap_get_multiple (cp->request_map,
1309 if (GNUNET_YES == tec.finished)
1310 return; /* merged into existing request, we're done */
1312 peerreq = GNUNET_new (struct PeerRequest);
1314 pr = GSF_pending_request_create_ (options,
1319 ? (const char *) &opt[bits]
1322 ntohl (gm->filter_mutator),
1324 (uint32_t) tec.priority,
1327 GNUNET_PEER_intern (cps->ppd.peer),
1328 NULL, 0, /* replies_seen */
1331 GNUNET_assert (NULL != pr);
1332 prd = GSF_pending_request_get_data_ (pr);
1334 GNUNET_break (GNUNET_OK ==
1335 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
1338 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1339 GNUNET_STATISTICS_update (GSF_stats,
1341 "# P2P query messages received and processed"),
1344 GNUNET_STATISTICS_update (GSF_stats,
1345 gettext_noop ("# P2P searches active"),
1348 GSF_pending_request_get_data_ (pr)->has_started = GNUNET_YES;
1349 GSF_local_lookup_ (pr,
1350 &GSF_consider_forwarding,
1356 * Transmit a message to the given peer as soon as possible.
1357 * If the peer disconnects before the transmission can happen,
1358 * the callback is invoked with a `NULL` @a buffer.
1360 * @param cp target peer
1361 * @param is_query is this a query (#GNUNET_YES) or content (#GNUNET_NO) or neither (#GNUNET_SYSERR)
1362 * @param priority how important is this request?
1363 * @param timeout when does this request timeout
1364 * @param size number of bytes we would like to send to the peer
1365 * @param env message to send
1368 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1371 struct GNUNET_MQ_Envelope *env)
1373 struct GSF_PeerTransmitHandle *pth;
1374 struct GSF_PeerTransmitHandle *pos;
1375 struct GSF_PeerTransmitHandle *prev;
1377 pth = GNUNET_new (struct GSF_PeerTransmitHandle);
1378 pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1380 pth->is_query = is_query;
1381 pth->priority = priority;
1383 /* insertion sort (by priority, descending) */
1386 while ((NULL != pos) && (pos->priority > priority))
1391 GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1395 if (GNUNET_YES == is_query)
1396 cp->ppd.pending_queries++;
1397 else if (GNUNET_NO == is_query)
1398 cp->ppd.pending_replies++;
1399 schedule_transmission (pth);
1404 * Report on receiving a reply; update the performance record of the given peer.
1406 * @param cp responding peer (will be updated)
1407 * @param request_time time at which the original query was transmitted
1408 * @param request_priority priority of the original request
1411 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1412 struct GNUNET_TIME_Absolute request_time,
1413 uint32_t request_priority)
1415 struct GNUNET_TIME_Relative delay;
1417 delay = GNUNET_TIME_absolute_get_duration (request_time);
1418 cp->ppd.avg_reply_delay.rel_value_us =
1419 (cp->ppd.avg_reply_delay.rel_value_us * (RUNAVG_DELAY_N - 1)
1420 + delay.rel_value_us) / RUNAVG_DELAY_N;
1421 cp->ppd.avg_priority =
1422 (cp->ppd.avg_priority * (RUNAVG_DELAY_N - 1)
1423 + request_priority) / RUNAVG_DELAY_N;
1428 * Report on receiving a reply in response to an initiating client.
1429 * Remember that this peer is good for this client.
1431 * @param cp responding peer (will be updated)
1432 * @param initiator_client local client on responsible for query
1435 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1436 struct GSF_LocalClient *initiator_client)
1438 cp->ppd.last_client_replies[cp->last_client_replies_woff++
1439 % CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1444 * Report on receiving a reply in response to an initiating peer.
1445 * Remember that this peer is good for this initiating peer.
1447 * @param cp responding peer (will be updated)
1448 * @param initiator_peer other peer responsible for query
1451 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1452 const struct GSF_ConnectedPeer *initiator_peer)
1456 woff = cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE;
1457 GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[woff], -1);
1458 cp->ppd.last_p2p_replies[woff] = initiator_peer->ppd.pid;
1459 GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1460 cp->last_p2p_replies_woff = (woff + 1) % P2P_SUCCESS_LIST_SIZE;
1465 * Write peer-respect information to a file - flush the buffer entry!
1468 * @param key peer identity
1469 * @param value the `struct GSF_ConnectedPeer` to flush
1470 * @return #GNUNET_OK to continue iteration
1473 flush_respect (void *cls,
1474 const struct GNUNET_PeerIdentity *key,
1477 struct GSF_ConnectedPeer *cp = value;
1478 struct GNUNET_PeerIdentity pid;
1480 if (cp->ppd.respect == cp->disk_respect)
1481 return GNUNET_OK; /* unchanged */
1482 GNUNET_assert (0 != cp->ppd.pid);
1483 GNUNET_PEER_resolve (cp->ppd.pid, &pid);
1484 GNUNET_PEERSTORE_store (peerstore, "fs", &pid, "respect", &cp->ppd.respect,
1485 sizeof(cp->ppd.respect),
1486 GNUNET_TIME_UNIT_FOREVER_ABS,
1487 GNUNET_PEERSTORE_STOREOPTION_REPLACE,
1495 * A peer disconnected from us. Tear down the connected peer
1499 * @param peer identity of peer that disconnected
1500 * @param internal_cls the corresponding `struct GSF_ConnectedPeer`
1503 GSF_peer_disconnect_handler (void *cls,
1504 const struct GNUNET_PeerIdentity *peer,
1507 struct GSF_ConnectedPeer *cp = internal_cls;
1508 struct GSF_PeerTransmitHandle *pth;
1509 struct GSF_DelayedHandle *dh;
1512 return; /* must have been disconnect from core with
1513 * 'peer' == my_id, ignore */
1514 flush_respect (NULL,
1517 GNUNET_assert (GNUNET_YES ==
1518 GNUNET_CONTAINER_multipeermap_remove (cp_map,
1521 GNUNET_STATISTICS_set (GSF_stats,
1522 gettext_noop ("# peers connected"),
1523 GNUNET_CONTAINER_multipeermap_size (cp_map),
1525 if (NULL != cp->respect_iterate_req)
1527 GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
1528 cp->respect_iterate_req = NULL;
1532 GNUNET_ATS_reserve_bandwidth_cancel (cp->rc);
1535 if (NULL != cp->rc_delay_task)
1537 GNUNET_SCHEDULER_cancel (cp->rc_delay_task);
1538 cp->rc_delay_task = NULL;
1540 GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1541 &cancel_pending_request,
1543 GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1544 cp->request_map = NULL;
1545 GSF_plan_notify_peer_disconnect_ (cp);
1546 GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1547 GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies,
1548 P2P_SUCCESS_LIST_SIZE);
1549 memset (cp->ppd.last_p2p_replies,
1551 sizeof(cp->ppd.last_p2p_replies));
1552 GSF_push_stop_ (cp);
1553 while (NULL != (pth = cp->pth_head))
1555 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1558 if (GNUNET_YES == pth->is_query)
1559 GNUNET_assert (0 < cp->ppd.pending_queries--);
1560 else if (GNUNET_NO == pth->is_query)
1561 GNUNET_assert (0 < cp->ppd.pending_replies--);
1564 while (NULL != (dh = cp->delayed_head))
1566 GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
1569 GNUNET_MQ_discard (dh->env);
1570 cp->delay_queue_size--;
1571 GNUNET_SCHEDULER_cancel (dh->delay_task);
1574 GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1575 if (NULL != cp->mig_revive_task)
1577 GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1578 cp->mig_revive_task = NULL;
1580 GNUNET_break (0 == cp->ppd.pending_queries);
1581 GNUNET_break (0 == cp->ppd.pending_replies);
1587 * Closure for #call_iterator().
1589 struct IterationContext
1592 * Function to call on each entry.
1594 GSF_ConnectedPeerIterator it;
1597 * Closure for @e it.
1604 * Function that calls the callback for each peer.
1606 * @param cls the `struct IterationContext *`
1607 * @param key identity of the peer
1608 * @param value the `struct GSF_ConnectedPeer *`
1609 * @return #GNUNET_YES to continue iteration
1612 call_iterator (void *cls,
1613 const struct GNUNET_PeerIdentity *key,
1616 struct IterationContext *ic = cls;
1617 struct GSF_ConnectedPeer *cp = value;
1627 * Iterate over all connected peers.
1629 * @param it function to call for each peer
1630 * @param it_cls closure for @a it
1633 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1636 struct IterationContext ic;
1640 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1647 * Obtain the identity of a connected peer.
1649 * @param cp peer to get identity of
1650 * @param id identity to set (written to)
1653 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1654 struct GNUNET_PeerIdentity *id)
1656 GNUNET_assert (0 != cp->ppd.pid);
1657 GNUNET_PEER_resolve (cp->ppd.pid, id);
1662 * Obtain the identity of a connected peer.
1664 * @param cp peer to get identity of
1665 * @return reference to peer identity, valid until peer disconnects (!)
1667 const struct GNUNET_PeerIdentity *
1668 GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp)
1670 GNUNET_assert (0 != cp->ppd.pid);
1671 return GNUNET_PEER_resolve2 (cp->ppd.pid);
1676 * Ask a peer to stop migrating data to us until the given point
1679 * @param cp peer to ask
1680 * @param block_time until when to block
1683 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1684 struct GNUNET_TIME_Absolute block_time)
1686 struct GNUNET_MQ_Envelope *env;
1687 struct MigrationStopMessage *msm;
1689 if (cp->last_migration_block.abs_value_us > block_time.abs_value_us)
1691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1692 "Migration already blocked for another %s\n",
1693 GNUNET_STRINGS_relative_time_to_string (
1694 GNUNET_TIME_absolute_get_remaining
1696 last_migration_block), GNUNET_YES));
1697 return; /* already blocked */
1699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %s\n",
1700 GNUNET_STRINGS_relative_time_to_string (
1701 GNUNET_TIME_absolute_get_remaining (block_time),
1703 cp->last_migration_block = block_time;
1704 env = GNUNET_MQ_msg (msm,
1705 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1706 msm->reserved = htonl (0);
1708 = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1709 (cp->last_migration_block));
1710 GNUNET_STATISTICS_update (GSF_stats,
1711 gettext_noop ("# migration stop messages sent"),
1714 GSF_peer_transmit_ (cp,
1722 * Notify core about a preference we have for the given peer
1723 * (to allocate more resources towards it). The change will
1724 * be communicated the next time we reserve bandwidth with
1725 * core (not instantly).
1727 * @param cp peer to reserve bandwidth from
1728 * @param pref preference change
1731 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1734 cp->inc_preference += pref;
1739 * Call this method periodically to flush respect information to disk.
1741 * @param cls closure, not used
1744 cron_flush_respect (void *cls)
1747 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1750 fr_task = GNUNET_SCHEDULER_add_delayed_with_priority (RESPECT_FLUSH_FREQ,
1751 GNUNET_SCHEDULER_PRIORITY_HIGH,
1752 &cron_flush_respect,
1758 * Initialize peer management subsystem.
1761 GSF_connected_peer_init_ ()
1763 cp_map = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1764 peerstore = GNUNET_PEERSTORE_connect (GSF_cfg);
1765 fr_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1766 &cron_flush_respect, NULL);
1771 * Shutdown peer management subsystem.
1774 GSF_connected_peer_done_ ()
1776 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1779 GNUNET_SCHEDULER_cancel (fr_task);
1781 GNUNET_CONTAINER_multipeermap_destroy (cp_map);
1783 GNUNET_PEERSTORE_disconnect (peerstore,
1789 * Iterator to remove references to LC entry.
1791 * @param cls the `struct GSF_LocalClient *` to look for
1792 * @param key current key code
1793 * @param value value in the hash map (peer entry)
1794 * @return #GNUNET_YES (we should continue to iterate)
1797 clean_local_client (void *cls,
1798 const struct GNUNET_PeerIdentity *key,
1801 const struct GSF_LocalClient *lc = cls;
1802 struct GSF_ConnectedPeer *cp = value;
1805 for (i = 0; i < CS2P_SUCCESS_LIST_SIZE; i++)
1806 if (cp->ppd.last_client_replies[i] == lc)
1807 cp->ppd.last_client_replies[i] = NULL;
1813 * Notification that a local client disconnected. Clean up all of our
1814 * references to the given handle.
1816 * @param lc handle to the local client (henceforth invalid)
1819 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1822 return; /* already cleaned up */
1823 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1824 &clean_local_client,
1829 /* end of gnunet-service-fs_cp.c */