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/>.
19 * @file fs/gnunet-service-fs_cp.c
20 * @brief API to handle 'connected peers'
21 * @author Christian Grothoff
24 #include "gnunet_util_lib.h"
25 #include "gnunet_load_lib.h"
26 #include "gnunet-service-fs.h"
27 #include "gnunet-service-fs_cp.h"
28 #include "gnunet-service-fs_pe.h"
29 #include "gnunet-service-fs_pr.h"
30 #include "gnunet-service-fs_push.h"
31 #include "gnunet_peerstore_service.h"
35 * Ratio for moving average delay calculation. The previous
36 * average goes in with a factor of (n-1) into the calculation.
39 #define RUNAVG_DELAY_N 16
42 * How often do we flush respect values to disk?
44 #define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
47 * After how long do we discard a reply?
49 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
52 * Collect an instane number of statistics? May cause excessive IPC.
54 #define INSANE_STATISTICS GNUNET_NO
58 * Handle to cancel a transmission request.
60 struct GSF_PeerTransmitHandle
64 * Kept in a doubly-linked list.
66 struct GSF_PeerTransmitHandle *next;
69 * Kept in a doubly-linked list.
71 struct GSF_PeerTransmitHandle *prev;
74 * Time when this transmission request was issued.
76 struct GNUNET_TIME_Absolute transmission_request_start_time;
79 * Envelope with the actual message.
81 struct GNUNET_MQ_Envelope *env;
84 * Peer this request targets.
86 struct GSF_ConnectedPeer *cp;
89 * #GNUNET_YES if this is a query, #GNUNET_NO for content.
94 * Did we get a reservation already?
99 * Priority of this request.
107 * Handle for an entry in our delay list.
109 struct GSF_DelayedHandle
113 * Kept in a doubly-linked list.
115 struct GSF_DelayedHandle *next;
118 * Kept in a doubly-linked list.
120 struct GSF_DelayedHandle *prev;
123 * Peer this transmission belongs to.
125 struct GSF_ConnectedPeer *cp;
128 * Envelope of the message that was delayed.
130 struct GNUNET_MQ_Envelope *env;
133 * Task for the delay.
135 struct GNUNET_SCHEDULER_Task *delay_task;
138 * Size of the message.
146 * Information per peer and request.
152 * Handle to generic request (generic: from peer or local client).
154 struct GSF_PendingRequest *pr;
157 * Which specific peer issued this request?
159 struct GSF_ConnectedPeer *cp;
162 * Task for asynchronous stopping of this request.
164 struct GNUNET_SCHEDULER_Task *kill_task;
172 struct GSF_ConnectedPeer
176 * Performance data for this peer.
178 struct GSF_PeerPerformanceData ppd;
181 * Time until when we blocked this peer from migrating
184 struct GNUNET_TIME_Absolute last_migration_block;
187 * Task scheduled to revive migration to this peer.
189 struct GNUNET_SCHEDULER_Task *mig_revive_task;
192 * Messages (replies, queries, content migration) we would like to
193 * send to this peer in the near future. Sorted by priority, head.
195 struct GSF_PeerTransmitHandle *pth_head;
198 * Messages (replies, queries, content migration) we would like to
199 * send to this peer in the near future. Sorted by priority, tail.
201 struct GSF_PeerTransmitHandle *pth_tail;
204 * Messages (replies, queries, content migration) we would like to
205 * send to this peer in the near future. Sorted by priority, head.
207 struct GSF_DelayedHandle *delayed_head;
210 * Messages (replies, queries, content migration) we would like to
211 * send to this peer in the near future. Sorted by priority, tail.
213 struct GSF_DelayedHandle *delayed_tail;
216 * Context of our GNUNET_ATS_reserve_bandwidth call (or NULL).
218 struct GNUNET_ATS_ReservationContext *rc;
221 * Task scheduled if we need to retry bandwidth reservation later.
223 struct GNUNET_SCHEDULER_Task *rc_delay_task;
226 * Active requests from this neighbour, map of query to `struct PeerRequest`.
228 struct GNUNET_CONTAINER_MultiHashMap *request_map;
231 * Handle for an active request for transmission to this
234 struct GNUNET_MQ_Handle *mq;
237 * Increase in traffic preference still to be submitted
238 * to the core service for this peer.
240 uint64_t inc_preference;
243 * Number of entries in @e delayed_head DLL.
245 unsigned int delay_queue_size;
248 * Respect rating for this peer on disk.
250 uint32_t disk_respect;
253 * Which offset in @e last_p2p_replies will be updated next?
254 * (we go round-robin).
256 unsigned int last_p2p_replies_woff;
259 * Which offset in @e last_client_replies will be updated next?
260 * (we go round-robin).
262 unsigned int last_client_replies_woff;
265 * Current offset into @e last_request_times ring buffer.
267 unsigned int last_request_times_off;
270 * #GNUNET_YES if we did successfully reserve 32k bandwidth,
276 * Handle to the PEERSTORE iterate request for peer respect value
278 struct GNUNET_PEERSTORE_IterateContext *respect_iterate_req;
284 * Map from peer identities to `struct GSF_ConnectPeer` entries.
286 static struct GNUNET_CONTAINER_MultiPeerMap *cp_map;
289 * Handle to peerstore service.
291 static struct GNUNET_PEERSTORE_Handle *peerstore;
294 * Task used to flush respect values to disk.
296 static struct GNUNET_SCHEDULER_Task *fr_task;
300 * Update the latency information kept for the given peer.
302 * @param id peer record to update
303 * @param latency current latency value
306 GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id,
307 struct GNUNET_TIME_Relative latency)
309 struct GSF_ConnectedPeer *cp;
311 cp = GSF_peer_get_ (id);
313 return; /* we're not yet connected at the core level, ignore */
314 GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay,
320 * Return the performance data record for the given peer
322 * @param cp peer to query
323 * @return performance data record for the peer
325 struct GSF_PeerPerformanceData *
326 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
333 * Core is ready to transmit to a peer, get the message.
335 * @param cp which peer to send a message to
338 peer_transmit (struct GSF_ConnectedPeer *cp);
342 * Function called by core upon success or failure of our bandwidth reservation request.
344 * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
345 * @param peer identifies the peer
346 * @param amount set to the amount that was actually reserved or unreserved;
347 * either the full requested amount or zero (no partial reservations)
348 * @param res_delay if the reservation could not be satisfied (amount was 0), how
349 * long should the client wait until re-trying?
352 ats_reserve_callback (void *cls,
353 const struct GNUNET_PeerIdentity *peer,
355 struct GNUNET_TIME_Relative res_delay);
359 * If ready (bandwidth reserved), try to schedule transmission via
360 * core for the given handle.
362 * @param pth transmission handle to schedule
365 schedule_transmission (struct GSF_PeerTransmitHandle *pth)
367 struct GSF_ConnectedPeer *cp;
368 struct GNUNET_PeerIdentity target;
371 GNUNET_assert (0 != cp->ppd.pid);
372 GNUNET_PEER_resolve (cp->ppd.pid, &target);
374 if (0 != cp->inc_preference)
376 GNUNET_ATS_performance_change_preference (GSF_ats,
378 GNUNET_ATS_PREFERENCE_BANDWIDTH,
379 (double) cp->inc_preference,
380 GNUNET_ATS_PREFERENCE_END);
381 cp->inc_preference = 0;
384 if ( (GNUNET_YES == pth->is_query) &&
385 (GNUNET_YES != pth->was_reserved) )
387 /* query, need reservation */
388 if (GNUNET_YES != cp->did_reserve)
389 return; /* not ready */
390 cp->did_reserve = GNUNET_NO;
391 /* reservation already done! */
392 pth->was_reserved = GNUNET_YES;
393 cp->rc = GNUNET_ATS_reserve_bandwidth (GSF_ats,
396 &ats_reserve_callback,
405 * Core is ready to transmit to a peer, get the message.
407 * @param cp which peer to send a message to
410 peer_transmit (struct GSF_ConnectedPeer *cp)
412 struct GSF_PeerTransmitHandle *pth = cp->pth_head;
413 struct GSF_PeerTransmitHandle *pos;
417 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
420 if (GNUNET_YES == pth->is_query)
422 cp->ppd.last_request_times[(cp->last_request_times_off++) %
423 MAX_QUEUE_PER_PEER] =
424 GNUNET_TIME_absolute_get ();
425 GNUNET_assert (0 < cp->ppd.pending_queries--);
427 else if (GNUNET_NO == pth->is_query)
429 GNUNET_assert (0 < cp->ppd.pending_replies--);
431 GNUNET_LOAD_update (cp->ppd.transmission_delay,
432 GNUNET_TIME_absolute_get_duration
433 (pth->transmission_request_start_time).rel_value_us);
434 GNUNET_MQ_send (cp->mq,
437 if (NULL != (pos = cp->pth_head))
439 GNUNET_assert (pos != pth);
440 schedule_transmission (pos);
446 * (re)try to reserve bandwidth from the given peer.
448 * @param cls the `struct GSF_ConnectedPeer` to reserve from
451 retry_reservation (void *cls)
453 struct GSF_ConnectedPeer *cp = cls;
454 struct GNUNET_PeerIdentity target;
456 GNUNET_PEER_resolve (cp->ppd.pid, &target);
457 cp->rc_delay_task = NULL;
459 GNUNET_ATS_reserve_bandwidth (GSF_ats,
462 &ats_reserve_callback, cp);
467 * Function called by core upon success or failure of our bandwidth reservation request.
469 * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
470 * @param peer identifies the peer
471 * @param amount set to the amount that was actually reserved or unreserved;
472 * either the full requested amount or zero (no partial reservations)
473 * @param res_delay if the reservation could not be satisfied (amount was 0), how
474 * long should the client wait until re-trying?
477 ats_reserve_callback (void *cls,
478 const struct GNUNET_PeerIdentity *peer,
480 struct GNUNET_TIME_Relative res_delay)
482 struct GSF_ConnectedPeer *cp = cls;
483 struct GSF_PeerTransmitHandle *pth;
485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
486 "Reserved %d bytes / need to wait %s for reservation\n",
488 GNUNET_STRINGS_relative_time_to_string (res_delay, GNUNET_YES));
493 GNUNET_SCHEDULER_add_delayed (res_delay,
498 cp->did_reserve = GNUNET_YES;
502 /* reservation success, try transmission now! */
509 * Function called by PEERSTORE with peer respect record
511 * @param cls handle to connected peer entry
512 * @param record peerstore record information
513 * @param emsg error message, or NULL if no errors
516 peer_respect_cb (void *cls,
517 const struct GNUNET_PEERSTORE_Record *record,
520 struct GSF_ConnectedPeer *cp = cls;
522 GNUNET_assert (NULL != cp->respect_iterate_req);
523 if ( (NULL != record) &&
524 (sizeof (cp->disk_respect) == record->value_size))
526 cp->disk_respect = *((uint32_t *)record->value);
527 cp->ppd.respect += *((uint32_t *)record->value);
529 GSF_push_start_ (cp);
531 GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
532 cp->respect_iterate_req = NULL;
537 * Function called for each pending request whenever a new
538 * peer connects, giving us a chance to decide about submitting
539 * the existing request to the new peer.
541 * @param cls the `struct GSF_ConnectedPeer` of the new peer
542 * @param key query for the request
543 * @param pr handle to the pending request
544 * @return #GNUNET_YES to continue to iterate
547 consider_peer_for_forwarding (void *cls,
548 const struct GNUNET_HashCode *key,
549 struct GSF_PendingRequest *pr)
551 struct GSF_ConnectedPeer *cp = cls;
552 struct GNUNET_PeerIdentity pid;
555 GSF_pending_request_test_active_ (pr))
556 return GNUNET_YES; /* request is not actually active, skip! */
557 GSF_connected_peer_get_identity_ (cp, &pid);
559 GSF_pending_request_test_target_ (pr, &pid))
561 GNUNET_STATISTICS_update (GSF_stats,
562 gettext_noop ("# Loopback routes suppressed"),
567 GSF_plan_add_ (cp, pr);
573 * A peer connected to us. Setup the connected peer
577 * @param peer identity of peer that connected
578 * @param mq message queue for talking to @a peer
579 * @return our internal handle for the peer
582 GSF_peer_connect_handler (void *cls,
583 const struct GNUNET_PeerIdentity *peer,
584 struct GNUNET_MQ_Handle *mq)
586 struct GSF_ConnectedPeer *cp;
589 GNUNET_CRYPTO_cmp_peer_identity (&GSF_my_id,
592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
593 "Connected to peer %s\n",
595 cp = GNUNET_new (struct GSF_ConnectedPeer);
596 cp->ppd.pid = GNUNET_PEER_intern (peer);
599 cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO);
601 GNUNET_ATS_reserve_bandwidth (GSF_ats,
604 &ats_reserve_callback, cp);
605 cp->request_map = GNUNET_CONTAINER_multihashmap_create (128,
607 GNUNET_break (GNUNET_OK ==
608 GNUNET_CONTAINER_multipeermap_put (cp_map,
609 GSF_connected_peer_get_identity2_ (cp),
611 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
612 GNUNET_STATISTICS_set (GSF_stats,
613 gettext_noop ("# peers connected"),
614 GNUNET_CONTAINER_multipeermap_size (cp_map),
616 cp->respect_iterate_req
617 = GNUNET_PEERSTORE_iterate (peerstore,
621 GNUNET_TIME_UNIT_FOREVER_REL,
624 GSF_iterate_pending_requests_ (&consider_peer_for_forwarding,
631 * It may be time to re-start migrating content to this
632 * peer. Check, and if so, restart migration.
634 * @param cls the `struct GSF_ConnectedPeer`
637 revive_migration (void *cls)
639 struct GSF_ConnectedPeer *cp = cls;
640 struct GNUNET_TIME_Relative bt;
642 cp->mig_revive_task = NULL;
643 bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until);
644 if (0 != bt.rel_value_us)
646 /* still time left... */
647 cp->mig_revive_task =
648 GNUNET_SCHEDULER_add_delayed (bt, &revive_migration, cp);
651 GSF_push_start_ (cp);
656 * Get a handle for a connected peer.
658 * @param peer peer's identity
659 * @return NULL if the peer is not currently connected
661 struct GSF_ConnectedPeer *
662 GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer)
666 return GNUNET_CONTAINER_multipeermap_get (cp_map, peer);
671 * Handle P2P #GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP message.
673 * @param cls closure, the `struct GSF_ConnectedPeer`
674 * @param msm the actual message
677 handle_p2p_migration_stop (void *cls,
678 const struct MigrationStopMessage *msm)
680 struct GSF_ConnectedPeer *cp = cls;
681 struct GNUNET_TIME_Relative bt;
683 GNUNET_STATISTICS_update (GSF_stats,
684 gettext_noop ("# migration stop messages received"),
686 bt = GNUNET_TIME_relative_ntoh (msm->duration);
687 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
688 _("Migration of content to peer `%s' blocked for %s\n"),
689 GNUNET_i2s (cp->ppd.peer),
690 GNUNET_STRINGS_relative_time_to_string (bt, GNUNET_YES));
691 cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt);
692 if ( (NULL == cp->mig_revive_task) &&
693 (NULL == cp->respect_iterate_req) )
696 cp->mig_revive_task =
697 GNUNET_SCHEDULER_add_delayed (bt,
698 &revive_migration, cp);
704 * Free resources associated with the given peer request.
706 * @param peerreq request to free
709 free_pending_request (struct PeerRequest *peerreq)
711 struct GSF_ConnectedPeer *cp = peerreq->cp;
712 struct GSF_PendingRequestData *prd;
714 prd = GSF_pending_request_get_data_ (peerreq->pr);
715 if (NULL != peerreq->kill_task)
717 GNUNET_SCHEDULER_cancel (peerreq->kill_task);
718 peerreq->kill_task = NULL;
720 GNUNET_STATISTICS_update (GSF_stats,
721 gettext_noop ("# P2P searches active"),
724 GNUNET_break (GNUNET_YES ==
725 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
728 GNUNET_free (peerreq);
733 * Cancel all requests associated with the peer.
736 * @param query hash code of the request
737 * @param value the `struct GSF_PendingRequest`
738 * @return #GNUNET_YES (continue to iterate)
741 cancel_pending_request (void *cls,
742 const struct GNUNET_HashCode *query,
745 struct PeerRequest *peerreq = value;
746 struct GSF_PendingRequest *pr = peerreq->pr;
748 free_pending_request (peerreq);
749 GSF_pending_request_cancel_ (pr,
756 * Free the given request.
758 * @param cls the request to free
761 peer_request_destroy (void *cls)
763 struct PeerRequest *peerreq = cls;
764 struct GSF_PendingRequest *pr = peerreq->pr;
765 struct GSF_PendingRequestData *prd;
767 peerreq->kill_task = NULL;
768 prd = GSF_pending_request_get_data_ (pr);
769 cancel_pending_request (NULL,
776 * The artificial delay is over, transmit the message now.
778 * @param cls the `struct GSF_DelayedHandle` with the message
781 transmit_delayed_now (void *cls)
783 struct GSF_DelayedHandle *dh = cls;
784 struct GSF_ConnectedPeer *cp = dh->cp;
786 GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
789 cp->delay_queue_size--;
790 GSF_peer_transmit_ (cp,
799 * Get the randomized delay a response should be subjected to.
801 * @return desired delay
803 static struct GNUNET_TIME_Relative
804 get_randomized_delay ()
806 struct GNUNET_TIME_Relative ret;
809 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
810 GNUNET_CRYPTO_random_u32
811 (GNUNET_CRYPTO_QUALITY_WEAK,
812 2 * GSF_avg_latency.rel_value_us + 1));
813 #if INSANE_STATISTICS
814 GNUNET_STATISTICS_update (GSF_stats,
816 ("# artificial delays introduced (ms)"),
817 ret.rel_value_us / 1000LL, GNUNET_NO);
824 * Handle a reply to a pending request. Also called if a request
825 * expires (then with data == NULL). The handler may be called
826 * many times (depending on the request type), but will not be
827 * called during or after a call to GSF_pending_request_cancel
828 * and will also not be called anymore after a call signalling
831 * @param cls `struct PeerRequest` this is an answer for
832 * @param eval evaluation of the result
833 * @param pr handle to the original pending request
834 * @param reply_anonymity_level anonymity level for the reply, UINT32_MAX for "unknown"
835 * @param expiration when does @a data expire?
836 * @param last_transmission when did we last transmit a request for this block
837 * @param type type of the block
838 * @param data response data, NULL on request expiration
839 * @param data_len number of bytes in @a data
842 handle_p2p_reply (void *cls,
843 enum GNUNET_BLOCK_EvaluationResult eval,
844 struct GSF_PendingRequest *pr,
845 uint32_t reply_anonymity_level,
846 struct GNUNET_TIME_Absolute expiration,
847 struct GNUNET_TIME_Absolute last_transmission,
848 enum GNUNET_BLOCK_Type type,
852 struct PeerRequest *peerreq = cls;
853 struct GSF_ConnectedPeer *cp = peerreq->cp;
854 struct GSF_PendingRequestData *prd;
855 struct GNUNET_MQ_Envelope *env;
856 struct PutMessage *pm;
859 GNUNET_assert (data_len + sizeof (struct PutMessage) <
860 GNUNET_MAX_MESSAGE_SIZE);
861 GNUNET_assert (peerreq->pr == pr);
862 prd = GSF_pending_request_get_data_ (pr);
865 free_pending_request (peerreq);
868 GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type);
869 if ((prd->type != type) && (GNUNET_BLOCK_TYPE_ANY != prd->type))
871 GNUNET_STATISTICS_update (GSF_stats,
873 ("# replies dropped due to type mismatch"),
877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
878 "Transmitting result for query `%s' to peer\n",
879 GNUNET_h2s (&prd->query));
880 GNUNET_STATISTICS_update (GSF_stats,
881 gettext_noop ("# replies received for other peers"),
883 msize = sizeof (struct PutMessage) + data_len;
884 if (msize >= GNUNET_MAX_MESSAGE_SIZE)
889 if ((UINT32_MAX != reply_anonymity_level) && (reply_anonymity_level > 1))
891 if (reply_anonymity_level - 1 > GSF_cover_content_count)
893 GNUNET_STATISTICS_update (GSF_stats,
895 ("# replies dropped due to insufficient cover traffic"),
899 GSF_cover_content_count -= (reply_anonymity_level - 1);
902 env = GNUNET_MQ_msg_extra (pm,
904 GNUNET_MESSAGE_TYPE_FS_PUT);
905 pm->type = htonl (type);
906 pm->expiration = GNUNET_TIME_absolute_hton (expiration);
907 GNUNET_memcpy (&pm[1],
910 if ( (UINT32_MAX != reply_anonymity_level) &&
911 (0 != reply_anonymity_level) &&
912 (GNUNET_YES == GSF_enable_randomized_delays) )
914 struct GSF_DelayedHandle *dh;
916 dh = GNUNET_new (struct GSF_DelayedHandle);
920 GNUNET_CONTAINER_DLL_insert (cp->delayed_head,
923 cp->delay_queue_size++;
925 GNUNET_SCHEDULER_add_delayed (get_randomized_delay (),
926 &transmit_delayed_now,
931 GSF_peer_transmit_ (cp,
936 if (GNUNET_BLOCK_EVALUATION_OK_LAST != eval)
938 if (NULL == peerreq->kill_task)
940 GNUNET_STATISTICS_update (GSF_stats,
942 ("# P2P searches destroyed due to ultimate reply"),
946 GNUNET_SCHEDULER_add_now (&peer_request_destroy,
953 * Increase the peer's respect by a value.
955 * @param cp which peer to change the respect value on
956 * @param value is the int value by which the
957 * peer's credit is to be increased or decreased
958 * @returns the actual change in respect (positive or negative)
961 change_peer_respect (struct GSF_ConnectedPeer *cp, int value)
965 GNUNET_assert (NULL != cp);
968 if (cp->ppd.respect + value < cp->ppd.respect)
970 value = UINT32_MAX - cp->ppd.respect;
971 cp->ppd.respect = UINT32_MAX;
974 cp->ppd.respect += value;
978 if (cp->ppd.respect < -value)
980 value = -cp->ppd.respect;
984 cp->ppd.respect += value;
991 * We've received a request with the specified priority. Bound it
992 * according to how much we respect the given peer.
994 * @param prio_in requested priority
995 * @param cp the peer making the request
996 * @return effective priority
999 bound_priority (uint32_t prio_in,
1000 struct GSF_ConnectedPeer *cp)
1002 #define N ((double)128.0)
1007 ld = GSF_test_get_load_too_high_ (0);
1008 if (GNUNET_SYSERR == ld)
1010 #if INSANE_STATISTICS
1011 GNUNET_STATISTICS_update (GSF_stats,
1013 ("# requests done for free (low load)"), 1,
1016 return 0; /* excess resources */
1018 if (prio_in > INT32_MAX)
1019 prio_in = INT32_MAX;
1020 ret = -change_peer_respect (cp, -(int) prio_in);
1023 if (ret > GSF_current_priorities + N)
1024 rret = GSF_current_priorities + N;
1027 GSF_current_priorities = (GSF_current_priorities * (N - 1) + rret) / N;
1029 if ((GNUNET_YES == ld) && (ret > 0))
1031 /* try with charging */
1032 ld = GSF_test_get_load_too_high_ (ret);
1034 if (GNUNET_YES == ld)
1036 GNUNET_STATISTICS_update (GSF_stats,
1038 ("# request dropped, priority insufficient"), 1,
1041 change_peer_respect (cp, (int) ret);
1042 return -1; /* not enough resources */
1046 GNUNET_STATISTICS_update (GSF_stats,
1048 ("# requests done for a price (normal load)"), 1,
1057 * The priority level imposes a bound on the maximum
1058 * value for the ttl that can be requested.
1060 * @param ttl_in requested ttl
1061 * @param prio given priority
1062 * @return @a ttl_in if @a ttl_in is below the limit,
1063 * otherwise the ttl-limit for the given @a prio
1066 bound_ttl (int32_t ttl_in,
1069 unsigned long long allowed;
1073 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1074 if (ttl_in > allowed)
1076 if (allowed >= (1 << 30))
1085 * Closure for #test_exist_cb().
1087 struct TestExistClosure
1091 * Priority of the incoming request.
1096 * Relative TTL of the incoming request.
1101 * Type of the incoming request.
1103 enum GNUNET_BLOCK_Type type;
1106 * Set to #GNUNET_YES if we are done handling the query.
1114 * Test if the query already exists. If so, merge it, otherwise
1115 * keep `finished` at #GNUNET_NO.
1117 * @param cls our `struct TestExistClosure`
1118 * @param hc the key of the query
1119 * @param value the existing `struct PeerRequest`.
1120 * @return #GNUNET_YES to continue to iterate,
1121 * #GNUNET_NO if we successfully merged
1124 test_exist_cb (void *cls,
1125 const struct GNUNET_HashCode *hc,
1128 struct TestExistClosure *tec = cls;
1129 struct PeerRequest *peerreq = value;
1130 struct GSF_PendingRequest *pr;
1131 struct GSF_PendingRequestData *prd;
1134 prd = GSF_pending_request_get_data_ (pr);
1135 if (prd->type != tec->type)
1137 if (prd->ttl.abs_value_us >=
1138 GNUNET_TIME_absolute_get ().abs_value_us + tec->ttl * 1000LL)
1140 /* existing request has higher TTL, drop new one! */
1141 prd->priority += tec->priority;
1142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143 "Have existing request with higher TTL, dropping new request.\n");
1144 GNUNET_STATISTICS_update (GSF_stats,
1146 ("# requests dropped due to higher-TTL request"),
1148 tec->finished = GNUNET_YES;
1151 /* existing request has lower TTL, drop old one! */
1152 tec->priority += prd->priority;
1153 free_pending_request (peerreq);
1154 GSF_pending_request_cancel_ (pr,
1161 * Handle P2P "QUERY" message. Creates the pending request entry
1162 * and sets up all of the data structures to that we will
1163 * process replies properly. Does not initiate forwarding or
1164 * local database lookups.
1166 * @param cls the other peer involved (sender of the message)
1167 * @param gm the GET message
1170 handle_p2p_get (void *cls,
1171 const struct GetMessage *gm)
1173 struct GSF_ConnectedPeer *cps = cls;
1174 struct PeerRequest *peerreq;
1175 struct GSF_PendingRequest *pr;
1176 struct GSF_ConnectedPeer *cp;
1177 const struct GNUNET_PeerIdentity *target;
1178 enum GSF_PendingRequestOptions options;
1181 const struct GNUNET_PeerIdentity *opt;
1184 uint32_t ttl_decrement;
1185 struct TestExistClosure tec;
1186 GNUNET_PEER_Id spid;
1187 const struct GSF_PendingRequestData *prd;
1189 msize = ntohs (gm->header.size);
1190 tec.type = ntohl (gm->type);
1191 bm = ntohl (gm->hash_bitmap);
1199 opt = (const struct GNUNET_PeerIdentity *) &gm[1];
1200 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (struct GNUNET_PeerIdentity);
1201 GNUNET_STATISTICS_update (GSF_stats,
1203 ("# GET requests received (from other peers)"),
1206 GSF_cover_query_count++;
1207 bm = ntohl (gm->hash_bitmap);
1209 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1210 cp = GSF_peer_get_ (&opt[bits++]);
1215 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1217 "Failed to find RETURN-TO peer `%s' in connection set. Dropping query.\n",
1218 GNUNET_i2s (&opt[bits - 1]));
1221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222 "Failed to find peer `%s' in connection set. Dropping query.\n",
1223 GNUNET_i2s (cps->ppd.peer));
1224 GNUNET_STATISTICS_update (GSF_stats,
1226 ("# requests dropped due to missing reverse route"),
1231 unsigned int queue_size = GNUNET_MQ_get_length (cp->mq);
1232 queue_size += cp->ppd.pending_replies + cp->delay_queue_size;
1233 if (queue_size > MAX_QUEUE_PER_PEER)
1235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1236 "Peer `%s' has too many replies queued already. Dropping query.\n",
1237 GNUNET_i2s (cps->ppd.peer));
1238 GNUNET_STATISTICS_update (GSF_stats,
1239 gettext_noop ("# 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 + tec.priority))
1268 || (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) >
1269 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value_us * 2 +
1270 GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)))
1272 /* don't have BW to send to peer, or would likely take longer than we have for it,
1273 * so at best indirect the query */
1275 options |= GSF_PRO_FORWARD_ONLY;
1276 spid = GNUNET_PEER_intern (cps->ppd.peer);
1277 GNUNET_assert (0 != spid);
1279 tec.ttl = bound_ttl (ntohl (gm->ttl),
1281 /* decrement ttl (always) */
1283 2 * TTL_DECREMENT + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1285 if ( (tec.ttl < 0) &&
1286 (((int32_t) (tec.ttl - ttl_decrement)) > 0) )
1288 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1289 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
1290 GNUNET_i2s (cps->ppd.peer),
1293 GNUNET_STATISTICS_update (GSF_stats,
1295 ("# requests dropped due TTL underflow"), 1,
1297 /* integer underflow => drop (should be very rare)! */
1300 tec.ttl -= ttl_decrement;
1302 /* test if the request already exists */
1303 tec.finished = GNUNET_NO;
1304 GNUNET_CONTAINER_multihashmap_get_multiple (cp->request_map,
1308 if (GNUNET_YES == tec.finished)
1309 return; /* merged into existing request, we're done */
1311 peerreq = GNUNET_new (struct PeerRequest);
1313 pr = GSF_pending_request_create_ (options,
1318 ? (const char *) &opt[bits]
1321 ntohl (gm->filter_mutator),
1323 (uint32_t) tec.priority,
1326 GNUNET_PEER_intern (cps->ppd.peer),
1327 NULL, 0, /* replies_seen */
1330 GNUNET_assert (NULL != pr);
1331 prd = GSF_pending_request_get_data_ (pr);
1333 GNUNET_break (GNUNET_OK ==
1334 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
1337 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1338 GNUNET_STATISTICS_update (GSF_stats,
1339 gettext_noop ("# P2P query messages received and processed"),
1342 GNUNET_STATISTICS_update (GSF_stats,
1343 gettext_noop ("# P2P searches active"),
1346 GSF_pending_request_get_data_ (pr)->has_started = GNUNET_YES;
1347 GSF_local_lookup_ (pr,
1348 &GSF_consider_forwarding,
1354 * Transmit a message to the given peer as soon as possible.
1355 * If the peer disconnects before the transmission can happen,
1356 * the callback is invoked with a `NULL` @a buffer.
1358 * @param cp target peer
1359 * @param is_query is this a query (#GNUNET_YES) or content (#GNUNET_NO) or neither (#GNUNET_SYSERR)
1360 * @param priority how important is this request?
1361 * @param timeout when does this request timeout
1362 * @param size number of bytes we would like to send to the peer
1363 * @param env message to send
1366 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1369 struct GNUNET_MQ_Envelope *env)
1371 struct GSF_PeerTransmitHandle *pth;
1372 struct GSF_PeerTransmitHandle *pos;
1373 struct GSF_PeerTransmitHandle *prev;
1375 pth = GNUNET_new (struct GSF_PeerTransmitHandle);
1376 pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1378 pth->is_query = is_query;
1379 pth->priority = priority;
1381 /* insertion sort (by priority, descending) */
1384 while ((NULL != pos) && (pos->priority > priority))
1389 GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1393 if (GNUNET_YES == is_query)
1394 cp->ppd.pending_queries++;
1395 else if (GNUNET_NO == is_query)
1396 cp->ppd.pending_replies++;
1397 schedule_transmission (pth);
1402 * Report on receiving a reply; update the performance record of the given peer.
1404 * @param cp responding peer (will be updated)
1405 * @param request_time time at which the original query was transmitted
1406 * @param request_priority priority of the original request
1409 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1410 struct GNUNET_TIME_Absolute request_time,
1411 uint32_t request_priority)
1413 struct GNUNET_TIME_Relative delay;
1415 delay = GNUNET_TIME_absolute_get_duration (request_time);
1416 cp->ppd.avg_reply_delay.rel_value_us =
1417 (cp->ppd.avg_reply_delay.rel_value_us * (RUNAVG_DELAY_N - 1) +
1418 delay.rel_value_us) / RUNAVG_DELAY_N;
1419 cp->ppd.avg_priority =
1420 (cp->ppd.avg_priority * (RUNAVG_DELAY_N - 1) +
1421 request_priority) / RUNAVG_DELAY_N;
1426 * Report on receiving a reply in response to an initiating client.
1427 * Remember that this peer is good for this client.
1429 * @param cp responding peer (will be updated)
1430 * @param initiator_client local client on responsible for query
1433 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1434 struct GSF_LocalClient *initiator_client)
1436 cp->ppd.last_client_replies[cp->last_client_replies_woff++ %
1437 CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1442 * Report on receiving a reply in response to an initiating peer.
1443 * Remember that this peer is good for this initiating peer.
1445 * @param cp responding peer (will be updated)
1446 * @param initiator_peer other peer responsible for query
1449 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1450 const struct GSF_ConnectedPeer *initiator_peer)
1454 woff = cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE;
1455 GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[woff], -1);
1456 cp->ppd.last_p2p_replies[woff] = initiator_peer->ppd.pid;
1457 GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1458 cp->last_p2p_replies_woff = (woff + 1) % P2P_SUCCESS_LIST_SIZE;
1463 * Write peer-respect information to a file - flush the buffer entry!
1466 * @param key peer identity
1467 * @param value the `struct GSF_ConnectedPeer` to flush
1468 * @return #GNUNET_OK to continue iteration
1471 flush_respect (void *cls,
1472 const struct GNUNET_PeerIdentity *key,
1475 struct GSF_ConnectedPeer *cp = value;
1476 struct GNUNET_PeerIdentity pid;
1478 if (cp->ppd.respect == cp->disk_respect)
1479 return GNUNET_OK; /* unchanged */
1480 GNUNET_assert (0 != cp->ppd.pid);
1481 GNUNET_PEER_resolve (cp->ppd.pid, &pid);
1482 GNUNET_PEERSTORE_store (peerstore, "fs", &pid, "respect", &cp->ppd.respect,
1483 sizeof (cp->ppd.respect),
1484 GNUNET_TIME_UNIT_FOREVER_ABS,
1485 GNUNET_PEERSTORE_STOREOPTION_REPLACE,
1493 * A peer disconnected from us. Tear down the connected peer
1497 * @param peer identity of peer that disconnected
1498 * @param internal_cls the corresponding `struct GSF_ConnectedPeer`
1501 GSF_peer_disconnect_handler (void *cls,
1502 const struct GNUNET_PeerIdentity *peer,
1505 struct GSF_ConnectedPeer *cp = internal_cls;
1506 struct GSF_PeerTransmitHandle *pth;
1507 struct GSF_DelayedHandle *dh;
1510 return; /* must have been disconnect from core with
1511 * 'peer' == my_id, ignore */
1512 flush_respect (NULL,
1515 GNUNET_assert (GNUNET_YES ==
1516 GNUNET_CONTAINER_multipeermap_remove (cp_map,
1519 GNUNET_STATISTICS_set (GSF_stats,
1520 gettext_noop ("# peers connected"),
1521 GNUNET_CONTAINER_multipeermap_size (cp_map),
1523 if (NULL != cp->respect_iterate_req)
1525 GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
1526 cp->respect_iterate_req = NULL;
1530 GNUNET_ATS_reserve_bandwidth_cancel (cp->rc);
1533 if (NULL != cp->rc_delay_task)
1535 GNUNET_SCHEDULER_cancel (cp->rc_delay_task);
1536 cp->rc_delay_task = NULL;
1538 GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1539 &cancel_pending_request,
1541 GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1542 cp->request_map = NULL;
1543 GSF_plan_notify_peer_disconnect_ (cp);
1544 GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1545 GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies,
1546 P2P_SUCCESS_LIST_SIZE);
1547 memset (cp->ppd.last_p2p_replies,
1549 sizeof (cp->ppd.last_p2p_replies));
1550 GSF_push_stop_ (cp);
1551 while (NULL != (pth = cp->pth_head))
1553 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1556 if (GNUNET_YES == pth->is_query)
1557 GNUNET_assert (0 < cp->ppd.pending_queries--);
1558 else if (GNUNET_NO == pth->is_query)
1559 GNUNET_assert (0 < cp->ppd.pending_replies--);
1562 while (NULL != (dh = cp->delayed_head))
1564 GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
1567 GNUNET_MQ_discard (dh->env);
1568 cp->delay_queue_size--;
1569 GNUNET_SCHEDULER_cancel (dh->delay_task);
1572 GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1573 if (NULL != cp->mig_revive_task)
1575 GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1576 cp->mig_revive_task = NULL;
1578 GNUNET_break (0 == cp->ppd.pending_queries);
1579 GNUNET_break (0 == cp->ppd.pending_replies);
1585 * Closure for #call_iterator().
1587 struct IterationContext
1590 * Function to call on each entry.
1592 GSF_ConnectedPeerIterator it;
1595 * Closure for @e it.
1602 * Function that calls the callback for each peer.
1604 * @param cls the `struct IterationContext *`
1605 * @param key identity of the peer
1606 * @param value the `struct GSF_ConnectedPeer *`
1607 * @return #GNUNET_YES to continue iteration
1610 call_iterator (void *cls,
1611 const struct GNUNET_PeerIdentity *key,
1614 struct IterationContext *ic = cls;
1615 struct GSF_ConnectedPeer *cp = value;
1625 * Iterate over all connected peers.
1627 * @param it function to call for each peer
1628 * @param it_cls closure for @a it
1631 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1634 struct IterationContext ic;
1638 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1645 * Obtain the identity of a connected peer.
1647 * @param cp peer to get identity of
1648 * @param id identity to set (written to)
1651 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1652 struct GNUNET_PeerIdentity *id)
1654 GNUNET_assert (0 != cp->ppd.pid);
1655 GNUNET_PEER_resolve (cp->ppd.pid, id);
1660 * Obtain the identity of a connected peer.
1662 * @param cp peer to get identity of
1663 * @return reference to peer identity, valid until peer disconnects (!)
1665 const struct GNUNET_PeerIdentity *
1666 GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp)
1668 GNUNET_assert (0 != cp->ppd.pid);
1669 return GNUNET_PEER_resolve2 (cp->ppd.pid);
1674 * Ask a peer to stop migrating data to us until the given point
1677 * @param cp peer to ask
1678 * @param block_time until when to block
1681 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1682 struct GNUNET_TIME_Absolute block_time)
1684 struct GNUNET_MQ_Envelope *env;
1685 struct MigrationStopMessage *msm;
1687 if (cp->last_migration_block.abs_value_us > block_time.abs_value_us)
1689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690 "Migration already blocked for another %s\n",
1691 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining
1692 (cp->last_migration_block), GNUNET_YES));
1693 return; /* already blocked */
1695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %s\n",
1696 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (block_time),
1698 cp->last_migration_block = block_time;
1699 env = GNUNET_MQ_msg (msm,
1700 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1701 msm->reserved = htonl (0);
1703 = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1704 (cp->last_migration_block));
1705 GNUNET_STATISTICS_update (GSF_stats,
1706 gettext_noop ("# migration stop messages sent"),
1709 GSF_peer_transmit_ (cp,
1717 * Notify core about a preference we have for the given peer
1718 * (to allocate more resources towards it). The change will
1719 * be communicated the next time we reserve bandwidth with
1720 * core (not instantly).
1722 * @param cp peer to reserve bandwidth from
1723 * @param pref preference change
1726 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1729 cp->inc_preference += pref;
1734 * Call this method periodically to flush respect information to disk.
1736 * @param cls closure, not used
1739 cron_flush_respect (void *cls)
1742 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1745 fr_task = GNUNET_SCHEDULER_add_delayed_with_priority (RESPECT_FLUSH_FREQ,
1746 GNUNET_SCHEDULER_PRIORITY_HIGH,
1747 &cron_flush_respect, NULL);
1752 * Initialize peer management subsystem.
1755 GSF_connected_peer_init_ ()
1757 cp_map = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1758 peerstore = GNUNET_PEERSTORE_connect (GSF_cfg);
1759 fr_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1760 &cron_flush_respect, NULL);
1765 * Shutdown peer management subsystem.
1768 GSF_connected_peer_done_ ()
1770 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1773 GNUNET_SCHEDULER_cancel (fr_task);
1775 GNUNET_CONTAINER_multipeermap_destroy (cp_map);
1777 GNUNET_PEERSTORE_disconnect (peerstore,
1784 * Iterator to remove references to LC entry.
1786 * @param cls the `struct GSF_LocalClient *` to look for
1787 * @param key current key code
1788 * @param value value in the hash map (peer entry)
1789 * @return #GNUNET_YES (we should continue to iterate)
1792 clean_local_client (void *cls,
1793 const struct GNUNET_PeerIdentity *key,
1796 const struct GSF_LocalClient *lc = cls;
1797 struct GSF_ConnectedPeer *cp = value;
1800 for (i = 0; i < CS2P_SUCCESS_LIST_SIZE; i++)
1801 if (cp->ppd.last_client_replies[i] == lc)
1802 cp->ppd.last_client_replies[i] = NULL;
1808 * Notification that a local client disconnected. Clean up all of our
1809 * references to the given handle.
1811 * @param lc handle to the local client (henceforth invalid)
1814 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1817 return; /* already cleaned up */
1818 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1819 &clean_local_client,
1824 /* end of gnunet-service-fs_cp.c */