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.
16 * @file fs/gnunet-service-fs_cp.c
17 * @brief API to handle 'connected peers'
18 * @author Christian Grothoff
21 #include "gnunet_util_lib.h"
22 #include "gnunet_load_lib.h"
23 #include "gnunet-service-fs.h"
24 #include "gnunet-service-fs_cp.h"
25 #include "gnunet-service-fs_pe.h"
26 #include "gnunet-service-fs_pr.h"
27 #include "gnunet-service-fs_push.h"
28 #include "gnunet_peerstore_service.h"
32 * Ratio for moving average delay calculation. The previous
33 * average goes in with a factor of (n-1) into the calculation.
36 #define RUNAVG_DELAY_N 16
39 * How often do we flush respect values to disk?
41 #define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
44 * After how long do we discard a reply?
46 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
49 * Collect an instane number of statistics? May cause excessive IPC.
51 #define INSANE_STATISTICS GNUNET_NO
55 * Handle to cancel a transmission request.
57 struct GSF_PeerTransmitHandle
61 * Kept in a doubly-linked list.
63 struct GSF_PeerTransmitHandle *next;
66 * Kept in a doubly-linked list.
68 struct GSF_PeerTransmitHandle *prev;
71 * Time when this transmission request was issued.
73 struct GNUNET_TIME_Absolute transmission_request_start_time;
76 * Envelope with the actual message.
78 struct GNUNET_MQ_Envelope *env;
81 * Peer this request targets.
83 struct GSF_ConnectedPeer *cp;
86 * #GNUNET_YES if this is a query, #GNUNET_NO for content.
91 * Did we get a reservation already?
96 * Priority of this request.
104 * Handle for an entry in our delay list.
106 struct GSF_DelayedHandle
110 * Kept in a doubly-linked list.
112 struct GSF_DelayedHandle *next;
115 * Kept in a doubly-linked list.
117 struct GSF_DelayedHandle *prev;
120 * Peer this transmission belongs to.
122 struct GSF_ConnectedPeer *cp;
125 * Envelope of the message that was delayed.
127 struct GNUNET_MQ_Envelope *env;
130 * Task for the delay.
132 struct GNUNET_SCHEDULER_Task *delay_task;
135 * Size of the message.
143 * Information per peer and request.
149 * Handle to generic request (generic: from peer or local client).
151 struct GSF_PendingRequest *pr;
154 * Which specific peer issued this request?
156 struct GSF_ConnectedPeer *cp;
159 * Task for asynchronous stopping of this request.
161 struct GNUNET_SCHEDULER_Task *kill_task;
169 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;
281 * Map from peer identities to `struct GSF_ConnectPeer` entries.
283 static struct GNUNET_CONTAINER_MultiPeerMap *cp_map;
286 * Handle to peerstore service.
288 static struct GNUNET_PEERSTORE_Handle *peerstore;
291 * Task used to flush respect values to disk.
293 static struct GNUNET_SCHEDULER_Task *fr_task;
297 * Update the latency information kept for the given peer.
299 * @param id peer record to update
300 * @param latency current latency value
303 GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id,
304 struct GNUNET_TIME_Relative latency)
306 struct GSF_ConnectedPeer *cp;
308 cp = GSF_peer_get_ (id);
310 return; /* we're not yet connected at the core level, ignore */
311 GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay,
317 * Return the performance data record for the given peer
319 * @param cp peer to query
320 * @return performance data record for the peer
322 struct GSF_PeerPerformanceData *
323 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
330 * Core is ready to transmit to a peer, get the message.
332 * @param cp which peer to send a message to
335 peer_transmit (struct GSF_ConnectedPeer *cp);
339 * Function called by core upon success or failure of our bandwidth reservation request.
341 * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
342 * @param peer identifies the peer
343 * @param amount set to the amount that was actually reserved or unreserved;
344 * either the full requested amount or zero (no partial reservations)
345 * @param res_delay if the reservation could not be satisfied (amount was 0), how
346 * long should the client wait until re-trying?
349 ats_reserve_callback (void *cls,
350 const struct GNUNET_PeerIdentity *peer,
352 struct GNUNET_TIME_Relative res_delay);
356 * If ready (bandwidth reserved), try to schedule transmission via
357 * core for the given handle.
359 * @param pth transmission handle to schedule
362 schedule_transmission (struct GSF_PeerTransmitHandle *pth)
364 struct GSF_ConnectedPeer *cp;
365 struct GNUNET_PeerIdentity target;
368 GNUNET_assert (0 != cp->ppd.pid);
369 GNUNET_PEER_resolve (cp->ppd.pid, &target);
371 if (0 != cp->inc_preference)
373 GNUNET_ATS_performance_change_preference (GSF_ats,
375 GNUNET_ATS_PREFERENCE_BANDWIDTH,
376 (double) cp->inc_preference,
377 GNUNET_ATS_PREFERENCE_END);
378 cp->inc_preference = 0;
381 if ( (GNUNET_YES == pth->is_query) &&
382 (GNUNET_YES != pth->was_reserved) )
384 /* query, need reservation */
385 if (GNUNET_YES != cp->did_reserve)
386 return; /* not ready */
387 cp->did_reserve = GNUNET_NO;
388 /* reservation already done! */
389 pth->was_reserved = GNUNET_YES;
390 cp->rc = GNUNET_ATS_reserve_bandwidth (GSF_ats,
393 &ats_reserve_callback,
402 * Core is ready to transmit to a peer, get the message.
404 * @param cp which peer to send a message to
407 peer_transmit (struct GSF_ConnectedPeer *cp)
409 struct GSF_PeerTransmitHandle *pth = cp->pth_head;
410 struct GSF_PeerTransmitHandle *pos;
414 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
417 if (GNUNET_YES == pth->is_query)
419 cp->ppd.last_request_times[(cp->last_request_times_off++) %
420 MAX_QUEUE_PER_PEER] =
421 GNUNET_TIME_absolute_get ();
422 GNUNET_assert (0 < cp->ppd.pending_queries--);
424 else if (GNUNET_NO == pth->is_query)
426 GNUNET_assert (0 < cp->ppd.pending_replies--);
428 GNUNET_LOAD_update (cp->ppd.transmission_delay,
429 GNUNET_TIME_absolute_get_duration
430 (pth->transmission_request_start_time).rel_value_us);
431 GNUNET_MQ_send (cp->mq,
434 if (NULL != (pos = cp->pth_head))
436 GNUNET_assert (pos != pth);
437 schedule_transmission (pos);
443 * (re)try to reserve bandwidth from the given peer.
445 * @param cls the `struct GSF_ConnectedPeer` to reserve from
448 retry_reservation (void *cls)
450 struct GSF_ConnectedPeer *cp = cls;
451 struct GNUNET_PeerIdentity target;
453 GNUNET_PEER_resolve (cp->ppd.pid, &target);
454 cp->rc_delay_task = NULL;
456 GNUNET_ATS_reserve_bandwidth (GSF_ats,
459 &ats_reserve_callback, cp);
464 * Function called by core upon success or failure of our bandwidth reservation request.
466 * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
467 * @param peer identifies the peer
468 * @param amount set to the amount that was actually reserved or unreserved;
469 * either the full requested amount or zero (no partial reservations)
470 * @param res_delay if the reservation could not be satisfied (amount was 0), how
471 * long should the client wait until re-trying?
474 ats_reserve_callback (void *cls,
475 const struct GNUNET_PeerIdentity *peer,
477 struct GNUNET_TIME_Relative res_delay)
479 struct GSF_ConnectedPeer *cp = cls;
480 struct GSF_PeerTransmitHandle *pth;
482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
483 "Reserved %d bytes / need to wait %s for reservation\n",
485 GNUNET_STRINGS_relative_time_to_string (res_delay, GNUNET_YES));
490 GNUNET_SCHEDULER_add_delayed (res_delay,
495 cp->did_reserve = GNUNET_YES;
499 /* reservation success, try transmission now! */
506 * Function called by PEERSTORE with peer respect record
508 * @param cls handle to connected peer entry
509 * @param record peerstore record information
510 * @param emsg error message, or NULL if no errors
513 peer_respect_cb (void *cls,
514 const struct GNUNET_PEERSTORE_Record *record,
517 struct GSF_ConnectedPeer *cp = cls;
519 GNUNET_assert (NULL != cp->respect_iterate_req);
520 if ( (NULL != record) &&
521 (sizeof (cp->disk_respect) == record->value_size))
523 cp->disk_respect = *((uint32_t *)record->value);
524 cp->ppd.respect += *((uint32_t *)record->value);
526 GSF_push_start_ (cp);
528 GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
529 cp->respect_iterate_req = NULL;
534 * Function called for each pending request whenever a new
535 * peer connects, giving us a chance to decide about submitting
536 * the existing request to the new peer.
538 * @param cls the `struct GSF_ConnectedPeer` of the new peer
539 * @param key query for the request
540 * @param pr handle to the pending request
541 * @return #GNUNET_YES to continue to iterate
544 consider_peer_for_forwarding (void *cls,
545 const struct GNUNET_HashCode *key,
546 struct GSF_PendingRequest *pr)
548 struct GSF_ConnectedPeer *cp = cls;
549 struct GNUNET_PeerIdentity pid;
552 GSF_pending_request_test_active_ (pr))
553 return GNUNET_YES; /* request is not actually active, skip! */
554 GSF_connected_peer_get_identity_ (cp, &pid);
556 GSF_pending_request_test_target_ (pr, &pid))
558 GNUNET_STATISTICS_update (GSF_stats,
559 gettext_noop ("# Loopback routes suppressed"),
564 GSF_plan_add_ (cp, pr);
570 * A peer connected to us. Setup the connected peer
574 * @param peer identity of peer that connected
575 * @param mq message queue for talking to @a peer
576 * @return our internal handle for the peer
579 GSF_peer_connect_handler (void *cls,
580 const struct GNUNET_PeerIdentity *peer,
581 struct GNUNET_MQ_Handle *mq)
583 struct GSF_ConnectedPeer *cp;
586 GNUNET_CRYPTO_cmp_peer_identity (&GSF_my_id,
589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
590 "Connected to peer %s\n",
592 cp = GNUNET_new (struct GSF_ConnectedPeer);
593 cp->ppd.pid = GNUNET_PEER_intern (peer);
596 cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO);
598 GNUNET_ATS_reserve_bandwidth (GSF_ats,
601 &ats_reserve_callback, cp);
602 cp->request_map = GNUNET_CONTAINER_multihashmap_create (128,
604 GNUNET_break (GNUNET_OK ==
605 GNUNET_CONTAINER_multipeermap_put (cp_map,
606 GSF_connected_peer_get_identity2_ (cp),
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,
618 GNUNET_TIME_UNIT_FOREVER_REL,
621 GSF_iterate_pending_requests_ (&consider_peer_for_forwarding,
628 * It may be time to re-start migrating content to this
629 * peer. Check, and if so, restart migration.
631 * @param cls the `struct GSF_ConnectedPeer`
634 revive_migration (void *cls)
636 struct GSF_ConnectedPeer *cp = cls;
637 struct GNUNET_TIME_Relative bt;
639 cp->mig_revive_task = NULL;
640 bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until);
641 if (0 != bt.rel_value_us)
643 /* still time left... */
644 cp->mig_revive_task =
645 GNUNET_SCHEDULER_add_delayed (bt, &revive_migration, cp);
648 GSF_push_start_ (cp);
653 * Get a handle for a connected peer.
655 * @param peer peer's identity
656 * @return NULL if the peer is not currently connected
658 struct GSF_ConnectedPeer *
659 GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer)
663 return GNUNET_CONTAINER_multipeermap_get (cp_map, peer);
668 * Handle P2P #GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP message.
670 * @param cls closure, the `struct GSF_ConnectedPeer`
671 * @param msm the actual message
674 handle_p2p_migration_stop (void *cls,
675 const struct MigrationStopMessage *msm)
677 struct GSF_ConnectedPeer *cp = cls;
678 struct GNUNET_TIME_Relative bt;
680 GNUNET_STATISTICS_update (GSF_stats,
681 gettext_noop ("# migration stop messages received"),
683 bt = GNUNET_TIME_relative_ntoh (msm->duration);
684 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
685 _("Migration of content to peer `%s' blocked for %s\n"),
686 GNUNET_i2s (cp->ppd.peer),
687 GNUNET_STRINGS_relative_time_to_string (bt, GNUNET_YES));
688 cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt);
689 if ( (NULL == cp->mig_revive_task) &&
690 (NULL == cp->respect_iterate_req) )
693 cp->mig_revive_task =
694 GNUNET_SCHEDULER_add_delayed (bt,
695 &revive_migration, cp);
701 * Free resources associated with the given peer request.
703 * @param peerreq request to free
706 free_pending_request (struct PeerRequest *peerreq)
708 struct GSF_ConnectedPeer *cp = peerreq->cp;
709 struct GSF_PendingRequestData *prd;
711 prd = GSF_pending_request_get_data_ (peerreq->pr);
712 if (NULL != peerreq->kill_task)
714 GNUNET_SCHEDULER_cancel (peerreq->kill_task);
715 peerreq->kill_task = NULL;
717 GNUNET_STATISTICS_update (GSF_stats,
718 gettext_noop ("# P2P searches active"),
721 GNUNET_break (GNUNET_YES ==
722 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
725 GNUNET_free (peerreq);
730 * Cancel all requests associated with the peer.
733 * @param query hash code of the request
734 * @param value the `struct GSF_PendingRequest`
735 * @return #GNUNET_YES (continue to iterate)
738 cancel_pending_request (void *cls,
739 const struct GNUNET_HashCode *query,
742 struct PeerRequest *peerreq = value;
743 struct GSF_PendingRequest *pr = peerreq->pr;
745 free_pending_request (peerreq);
746 GSF_pending_request_cancel_ (pr,
753 * Free the given request.
755 * @param cls the request to free
758 peer_request_destroy (void *cls)
760 struct PeerRequest *peerreq = cls;
761 struct GSF_PendingRequest *pr = peerreq->pr;
762 struct GSF_PendingRequestData *prd;
764 peerreq->kill_task = NULL;
765 prd = GSF_pending_request_get_data_ (pr);
766 cancel_pending_request (NULL,
773 * The artificial delay is over, transmit the message now.
775 * @param cls the `struct GSF_DelayedHandle` with the message
778 transmit_delayed_now (void *cls)
780 struct GSF_DelayedHandle *dh = cls;
781 struct GSF_ConnectedPeer *cp = dh->cp;
783 GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
786 cp->delay_queue_size--;
787 GSF_peer_transmit_ (cp,
796 * Get the randomized delay a response should be subjected to.
798 * @return desired delay
800 static struct GNUNET_TIME_Relative
801 get_randomized_delay ()
803 struct GNUNET_TIME_Relative ret;
806 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
807 GNUNET_CRYPTO_random_u32
808 (GNUNET_CRYPTO_QUALITY_WEAK,
809 2 * GSF_avg_latency.rel_value_us + 1));
810 #if INSANE_STATISTICS
811 GNUNET_STATISTICS_update (GSF_stats,
813 ("# artificial delays introduced (ms)"),
814 ret.rel_value_us / 1000LL, GNUNET_NO);
821 * Handle a reply to a pending request. Also called if a request
822 * expires (then with data == NULL). The handler may be called
823 * many times (depending on the request type), but will not be
824 * called during or after a call to GSF_pending_request_cancel
825 * and will also not be called anymore after a call signalling
828 * @param cls `struct PeerRequest` this is an answer for
829 * @param eval evaluation of the result
830 * @param pr handle to the original pending request
831 * @param reply_anonymity_level anonymity level for the reply, UINT32_MAX for "unknown"
832 * @param expiration when does @a data expire?
833 * @param last_transmission when did we last transmit a request for this block
834 * @param type type of the block
835 * @param data response data, NULL on request expiration
836 * @param data_len number of bytes in @a data
839 handle_p2p_reply (void *cls,
840 enum GNUNET_BLOCK_EvaluationResult eval,
841 struct GSF_PendingRequest *pr,
842 uint32_t reply_anonymity_level,
843 struct GNUNET_TIME_Absolute expiration,
844 struct GNUNET_TIME_Absolute last_transmission,
845 enum GNUNET_BLOCK_Type type,
849 struct PeerRequest *peerreq = cls;
850 struct GSF_ConnectedPeer *cp = peerreq->cp;
851 struct GSF_PendingRequestData *prd;
852 struct GNUNET_MQ_Envelope *env;
853 struct PutMessage *pm;
856 GNUNET_assert (data_len + sizeof (struct PutMessage) <
857 GNUNET_MAX_MESSAGE_SIZE);
858 GNUNET_assert (peerreq->pr == pr);
859 prd = GSF_pending_request_get_data_ (pr);
862 free_pending_request (peerreq);
865 GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type);
866 if ((prd->type != type) && (GNUNET_BLOCK_TYPE_ANY != prd->type))
868 GNUNET_STATISTICS_update (GSF_stats,
870 ("# replies dropped due to type mismatch"),
874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
875 "Transmitting result for query `%s' to peer\n",
876 GNUNET_h2s (&prd->query));
877 GNUNET_STATISTICS_update (GSF_stats,
878 gettext_noop ("# replies received for other peers"),
880 msize = sizeof (struct PutMessage) + data_len;
881 if (msize >= GNUNET_MAX_MESSAGE_SIZE)
886 if ((UINT32_MAX != reply_anonymity_level) && (reply_anonymity_level > 1))
888 if (reply_anonymity_level - 1 > GSF_cover_content_count)
890 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,
939 ("# P2P searches destroyed due to ultimate reply"),
943 GNUNET_SCHEDULER_add_now (&peer_request_destroy,
950 * Increase the peer's respect by a value.
952 * @param cp which peer to change the respect value on
953 * @param value is the int value by which the
954 * peer's credit is to be increased or decreased
955 * @returns the actual change in respect (positive or negative)
958 change_peer_respect (struct GSF_ConnectedPeer *cp, int value)
962 GNUNET_assert (NULL != cp);
965 if (cp->ppd.respect + value < cp->ppd.respect)
967 value = UINT32_MAX - cp->ppd.respect;
968 cp->ppd.respect = UINT32_MAX;
971 cp->ppd.respect += value;
975 if (cp->ppd.respect < -value)
977 value = -cp->ppd.respect;
981 cp->ppd.respect += value;
988 * We've received a request with the specified priority. Bound it
989 * according to how much we respect the given peer.
991 * @param prio_in requested priority
992 * @param cp the peer making the request
993 * @return effective priority
996 bound_priority (uint32_t prio_in,
997 struct GSF_ConnectedPeer *cp)
999 #define N ((double)128.0)
1004 ld = GSF_test_get_load_too_high_ (0);
1005 if (GNUNET_SYSERR == ld)
1007 #if INSANE_STATISTICS
1008 GNUNET_STATISTICS_update (GSF_stats,
1010 ("# requests done for free (low load)"), 1,
1013 return 0; /* excess resources */
1015 if (prio_in > INT32_MAX)
1016 prio_in = INT32_MAX;
1017 ret = -change_peer_respect (cp, -(int) prio_in);
1020 if (ret > GSF_current_priorities + N)
1021 rret = GSF_current_priorities + N;
1024 GSF_current_priorities = (GSF_current_priorities * (N - 1) + rret) / N;
1026 if ((GNUNET_YES == ld) && (ret > 0))
1028 /* try with charging */
1029 ld = GSF_test_get_load_too_high_ (ret);
1031 if (GNUNET_YES == ld)
1033 GNUNET_STATISTICS_update (GSF_stats,
1035 ("# request dropped, priority insufficient"), 1,
1038 change_peer_respect (cp, (int) ret);
1039 return -1; /* not enough resources */
1043 GNUNET_STATISTICS_update (GSF_stats,
1045 ("# requests done for a price (normal load)"), 1,
1054 * The priority level imposes a bound on the maximum
1055 * value for the ttl that can be requested.
1057 * @param ttl_in requested ttl
1058 * @param prio given priority
1059 * @return @a ttl_in if @a ttl_in is below the limit,
1060 * otherwise the ttl-limit for the given @a prio
1063 bound_ttl (int32_t ttl_in,
1066 unsigned long long allowed;
1070 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1071 if (ttl_in > allowed)
1073 if (allowed >= (1 << 30))
1082 * Closure for #test_exist_cb().
1084 struct TestExistClosure
1088 * Priority of the incoming request.
1093 * Relative TTL of the incoming request.
1098 * Type of the incoming request.
1100 enum GNUNET_BLOCK_Type type;
1103 * 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 GNUNET_PeerIdentity);
1198 GNUNET_STATISTICS_update (GSF_stats,
1200 ("# GET requests received (from other peers)"),
1203 GSF_cover_query_count++;
1204 bm = ntohl (gm->hash_bitmap);
1206 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1207 cp = GSF_peer_get_ (&opt[bits++]);
1212 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214 "Failed to find RETURN-TO peer `%s' in connection set. Dropping query.\n",
1215 GNUNET_i2s (&opt[bits - 1]));
1218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1219 "Failed to find peer `%s' in connection set. Dropping query.\n",
1220 GNUNET_i2s (cps->ppd.peer));
1221 GNUNET_STATISTICS_update (GSF_stats,
1223 ("# requests dropped due to missing reverse route"),
1228 unsigned int queue_size = GNUNET_MQ_get_length (cp->mq);
1229 queue_size += cp->ppd.pending_replies + cp->delay_queue_size;
1230 if (queue_size > MAX_QUEUE_PER_PEER)
1232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233 "Peer `%s' has too many replies queued already. Dropping query.\n",
1234 GNUNET_i2s (cps->ppd.peer));
1235 GNUNET_STATISTICS_update (GSF_stats,
1236 gettext_noop ("# requests dropped due to full reply queue"),
1241 /* note that we can really only check load here since otherwise
1242 * peers could find out that we are overloaded by not being
1243 * disconnected after sending us a malformed query... */
1244 tec.priority = bound_priority (ntohl (gm->priority),
1246 if (tec.priority < 0)
1248 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1249 "Dropping query from `%s', this peer is too busy.\n",
1250 GNUNET_i2s (cps->ppd.peer));
1253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1254 "Received request for `%s' of type %u from peer `%s' with flags %u\n",
1255 GNUNET_h2s (&gm->query),
1256 (unsigned int) tec.type,
1257 GNUNET_i2s (cps->ppd.peer),
1261 (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? (&opt[bits++]) : NULL;
1262 options = GSF_PRO_DEFAULTS;
1264 if ((GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1 + tec.priority))
1265 || (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) >
1266 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value_us * 2 +
1267 GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)))
1269 /* don't have BW to send to peer, or would likely take longer than we have for it,
1270 * so at best indirect the query */
1272 options |= GSF_PRO_FORWARD_ONLY;
1273 spid = GNUNET_PEER_intern (cps->ppd.peer);
1274 GNUNET_assert (0 != spid);
1276 tec.ttl = bound_ttl (ntohl (gm->ttl),
1278 /* decrement ttl (always) */
1280 2 * TTL_DECREMENT + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1282 if ( (tec.ttl < 0) &&
1283 (((int32_t) (tec.ttl - ttl_decrement)) > 0) )
1285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1286 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
1287 GNUNET_i2s (cps->ppd.peer),
1290 GNUNET_STATISTICS_update (GSF_stats,
1292 ("# requests dropped due TTL underflow"), 1,
1294 /* integer underflow => drop (should be very rare)! */
1297 tec.ttl -= ttl_decrement;
1299 /* test if the request already exists */
1300 tec.finished = GNUNET_NO;
1301 GNUNET_CONTAINER_multihashmap_get_multiple (cp->request_map,
1305 if (GNUNET_YES == tec.finished)
1306 return; /* merged into existing request, we're done */
1308 peerreq = GNUNET_new (struct PeerRequest);
1310 pr = GSF_pending_request_create_ (options,
1315 ? (const char *) &opt[bits]
1318 ntohl (gm->filter_mutator),
1320 (uint32_t) tec.priority,
1323 GNUNET_PEER_intern (cps->ppd.peer),
1324 NULL, 0, /* replies_seen */
1327 GNUNET_assert (NULL != pr);
1328 prd = GSF_pending_request_get_data_ (pr);
1330 GNUNET_break (GNUNET_OK ==
1331 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
1334 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1335 GNUNET_STATISTICS_update (GSF_stats,
1336 gettext_noop ("# P2P query messages received and processed"),
1339 GNUNET_STATISTICS_update (GSF_stats,
1340 gettext_noop ("# P2P searches active"),
1343 GSF_pending_request_get_data_ (pr)->has_started = GNUNET_YES;
1344 GSF_local_lookup_ (pr,
1345 &GSF_consider_forwarding,
1351 * Transmit a message to the given peer as soon as possible.
1352 * If the peer disconnects before the transmission can happen,
1353 * the callback is invoked with a `NULL` @a buffer.
1355 * @param cp target peer
1356 * @param is_query is this a query (#GNUNET_YES) or content (#GNUNET_NO) or neither (#GNUNET_SYSERR)
1357 * @param priority how important is this request?
1358 * @param timeout when does this request timeout
1359 * @param size number of bytes we would like to send to the peer
1360 * @param env message to send
1363 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1366 struct GNUNET_MQ_Envelope *env)
1368 struct GSF_PeerTransmitHandle *pth;
1369 struct GSF_PeerTransmitHandle *pos;
1370 struct GSF_PeerTransmitHandle *prev;
1372 pth = GNUNET_new (struct GSF_PeerTransmitHandle);
1373 pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1375 pth->is_query = is_query;
1376 pth->priority = priority;
1378 /* insertion sort (by priority, descending) */
1381 while ((NULL != pos) && (pos->priority > priority))
1386 GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1390 if (GNUNET_YES == is_query)
1391 cp->ppd.pending_queries++;
1392 else if (GNUNET_NO == is_query)
1393 cp->ppd.pending_replies++;
1394 schedule_transmission (pth);
1399 * Report on receiving a reply; update the performance record of the given peer.
1401 * @param cp responding peer (will be updated)
1402 * @param request_time time at which the original query was transmitted
1403 * @param request_priority priority of the original request
1406 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1407 struct GNUNET_TIME_Absolute request_time,
1408 uint32_t request_priority)
1410 struct GNUNET_TIME_Relative delay;
1412 delay = GNUNET_TIME_absolute_get_duration (request_time);
1413 cp->ppd.avg_reply_delay.rel_value_us =
1414 (cp->ppd.avg_reply_delay.rel_value_us * (RUNAVG_DELAY_N - 1) +
1415 delay.rel_value_us) / RUNAVG_DELAY_N;
1416 cp->ppd.avg_priority =
1417 (cp->ppd.avg_priority * (RUNAVG_DELAY_N - 1) +
1418 request_priority) / RUNAVG_DELAY_N;
1423 * Report on receiving a reply in response to an initiating client.
1424 * Remember that this peer is good for this client.
1426 * @param cp responding peer (will be updated)
1427 * @param initiator_client local client on responsible for query
1430 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1431 struct GSF_LocalClient *initiator_client)
1433 cp->ppd.last_client_replies[cp->last_client_replies_woff++ %
1434 CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1439 * Report on receiving a reply in response to an initiating peer.
1440 * Remember that this peer is good for this initiating peer.
1442 * @param cp responding peer (will be updated)
1443 * @param initiator_peer other peer responsible for query
1446 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1447 const struct GSF_ConnectedPeer *initiator_peer)
1451 woff = cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE;
1452 GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[woff], -1);
1453 cp->ppd.last_p2p_replies[woff] = initiator_peer->ppd.pid;
1454 GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1455 cp->last_p2p_replies_woff = (woff + 1) % P2P_SUCCESS_LIST_SIZE;
1460 * Write peer-respect information to a file - flush the buffer entry!
1463 * @param key peer identity
1464 * @param value the `struct GSF_ConnectedPeer` to flush
1465 * @return #GNUNET_OK to continue iteration
1468 flush_respect (void *cls,
1469 const struct GNUNET_PeerIdentity *key,
1472 struct GSF_ConnectedPeer *cp = value;
1473 struct GNUNET_PeerIdentity pid;
1475 if (cp->ppd.respect == cp->disk_respect)
1476 return GNUNET_OK; /* unchanged */
1477 GNUNET_assert (0 != cp->ppd.pid);
1478 GNUNET_PEER_resolve (cp->ppd.pid, &pid);
1479 GNUNET_PEERSTORE_store (peerstore, "fs", &pid, "respect", &cp->ppd.respect,
1480 sizeof (cp->ppd.respect),
1481 GNUNET_TIME_UNIT_FOREVER_ABS,
1482 GNUNET_PEERSTORE_STOREOPTION_REPLACE,
1490 * A peer disconnected from us. Tear down the connected peer
1494 * @param peer identity of peer that disconnected
1495 * @param internal_cls the corresponding `struct GSF_ConnectedPeer`
1498 GSF_peer_disconnect_handler (void *cls,
1499 const struct GNUNET_PeerIdentity *peer,
1502 struct GSF_ConnectedPeer *cp = internal_cls;
1503 struct GSF_PeerTransmitHandle *pth;
1504 struct GSF_DelayedHandle *dh;
1507 return; /* must have been disconnect from core with
1508 * 'peer' == my_id, ignore */
1509 flush_respect (NULL,
1512 GNUNET_assert (GNUNET_YES ==
1513 GNUNET_CONTAINER_multipeermap_remove (cp_map,
1516 GNUNET_STATISTICS_set (GSF_stats,
1517 gettext_noop ("# peers connected"),
1518 GNUNET_CONTAINER_multipeermap_size (cp_map),
1520 if (NULL != cp->respect_iterate_req)
1522 GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
1523 cp->respect_iterate_req = NULL;
1527 GNUNET_ATS_reserve_bandwidth_cancel (cp->rc);
1530 if (NULL != cp->rc_delay_task)
1532 GNUNET_SCHEDULER_cancel (cp->rc_delay_task);
1533 cp->rc_delay_task = NULL;
1535 GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1536 &cancel_pending_request,
1538 GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1539 cp->request_map = NULL;
1540 GSF_plan_notify_peer_disconnect_ (cp);
1541 GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1542 GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies,
1543 P2P_SUCCESS_LIST_SIZE);
1544 memset (cp->ppd.last_p2p_replies,
1546 sizeof (cp->ppd.last_p2p_replies));
1547 GSF_push_stop_ (cp);
1548 while (NULL != (pth = cp->pth_head))
1550 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1553 if (GNUNET_YES == pth->is_query)
1554 GNUNET_assert (0 < cp->ppd.pending_queries--);
1555 else if (GNUNET_NO == pth->is_query)
1556 GNUNET_assert (0 < cp->ppd.pending_replies--);
1559 while (NULL != (dh = cp->delayed_head))
1561 GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
1564 GNUNET_MQ_discard (dh->env);
1565 cp->delay_queue_size--;
1566 GNUNET_SCHEDULER_cancel (dh->delay_task);
1569 GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1570 if (NULL != cp->mig_revive_task)
1572 GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1573 cp->mig_revive_task = NULL;
1575 GNUNET_break (0 == cp->ppd.pending_queries);
1576 GNUNET_break (0 == cp->ppd.pending_replies);
1582 * Closure for #call_iterator().
1584 struct IterationContext
1587 * Function to call on each entry.
1589 GSF_ConnectedPeerIterator it;
1592 * Closure for @e it.
1599 * Function that calls the callback for each peer.
1601 * @param cls the `struct IterationContext *`
1602 * @param key identity of the peer
1603 * @param value the `struct GSF_ConnectedPeer *`
1604 * @return #GNUNET_YES to continue iteration
1607 call_iterator (void *cls,
1608 const struct GNUNET_PeerIdentity *key,
1611 struct IterationContext *ic = cls;
1612 struct GSF_ConnectedPeer *cp = value;
1622 * Iterate over all connected peers.
1624 * @param it function to call for each peer
1625 * @param it_cls closure for @a it
1628 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1631 struct IterationContext ic;
1635 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1642 * Obtain the identity of a connected peer.
1644 * @param cp peer to get identity of
1645 * @param id identity to set (written to)
1648 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1649 struct GNUNET_PeerIdentity *id)
1651 GNUNET_assert (0 != cp->ppd.pid);
1652 GNUNET_PEER_resolve (cp->ppd.pid, id);
1657 * Obtain the identity of a connected peer.
1659 * @param cp peer to get identity of
1660 * @return reference to peer identity, valid until peer disconnects (!)
1662 const struct GNUNET_PeerIdentity *
1663 GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp)
1665 GNUNET_assert (0 != cp->ppd.pid);
1666 return GNUNET_PEER_resolve2 (cp->ppd.pid);
1671 * Ask a peer to stop migrating data to us until the given point
1674 * @param cp peer to ask
1675 * @param block_time until when to block
1678 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1679 struct GNUNET_TIME_Absolute block_time)
1681 struct GNUNET_MQ_Envelope *env;
1682 struct MigrationStopMessage *msm;
1684 if (cp->last_migration_block.abs_value_us > block_time.abs_value_us)
1686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1687 "Migration already blocked for another %s\n",
1688 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining
1689 (cp->last_migration_block), GNUNET_YES));
1690 return; /* already blocked */
1692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %s\n",
1693 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (block_time),
1695 cp->last_migration_block = block_time;
1696 env = GNUNET_MQ_msg (msm,
1697 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1698 msm->reserved = htonl (0);
1700 = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1701 (cp->last_migration_block));
1702 GNUNET_STATISTICS_update (GSF_stats,
1703 gettext_noop ("# migration stop messages sent"),
1706 GSF_peer_transmit_ (cp,
1714 * Notify core about a preference we have for the given peer
1715 * (to allocate more resources towards it). The change will
1716 * be communicated the next time we reserve bandwidth with
1717 * core (not instantly).
1719 * @param cp peer to reserve bandwidth from
1720 * @param pref preference change
1723 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1726 cp->inc_preference += pref;
1731 * Call this method periodically to flush respect information to disk.
1733 * @param cls closure, not used
1736 cron_flush_respect (void *cls)
1739 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1742 fr_task = GNUNET_SCHEDULER_add_delayed_with_priority (RESPECT_FLUSH_FREQ,
1743 GNUNET_SCHEDULER_PRIORITY_HIGH,
1744 &cron_flush_respect, NULL);
1749 * Initialize peer management subsystem.
1752 GSF_connected_peer_init_ ()
1754 cp_map = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1755 peerstore = GNUNET_PEERSTORE_connect (GSF_cfg);
1756 fr_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1757 &cron_flush_respect, NULL);
1762 * Shutdown peer management subsystem.
1765 GSF_connected_peer_done_ ()
1767 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1770 GNUNET_SCHEDULER_cancel (fr_task);
1772 GNUNET_CONTAINER_multipeermap_destroy (cp_map);
1774 GNUNET_PEERSTORE_disconnect (peerstore,
1781 * Iterator to remove references to LC entry.
1783 * @param cls the `struct GSF_LocalClient *` to look for
1784 * @param key current key code
1785 * @param value value in the hash map (peer entry)
1786 * @return #GNUNET_YES (we should continue to iterate)
1789 clean_local_client (void *cls,
1790 const struct GNUNET_PeerIdentity *key,
1793 const struct GSF_LocalClient *lc = cls;
1794 struct GSF_ConnectedPeer *cp = value;
1797 for (i = 0; i < CS2P_SUCCESS_LIST_SIZE; i++)
1798 if (cp->ppd.last_client_replies[i] == lc)
1799 cp->ppd.last_client_replies[i] = NULL;
1805 * Notification that a local client disconnected. Clean up all of our
1806 * references to the given handle.
1808 * @param lc handle to the local client (henceforth invalid)
1811 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1814 return; /* already cleaned up */
1815 GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1816 &clean_local_client,
1821 /* end of gnunet-service-fs_cp.c */