2 This file is part of GNUnet.
3 (C) 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file fs/gnunet-service-fs_cp.c
23 * @brief API to handle 'connected peers'
24 * @author Christian Grothoff
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"
35 * How often do we flush trust values to disk?
37 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
40 * After how long do we discard a reply?
42 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
46 * Handle to cancel a transmission request.
48 struct GSF_PeerTransmitHandle
52 * Kept in a doubly-linked list.
54 struct GSF_PeerTransmitHandle *next;
57 * Kept in a doubly-linked list.
59 struct GSF_PeerTransmitHandle *prev;
62 * Handle for an active request for transmission to this
63 * peer, or NULL (if core queue was full).
65 struct GNUNET_CORE_TransmitHandle *cth;
68 * Time when this transmission request was issued.
70 struct GNUNET_TIME_Absolute transmission_request_start_time;
73 * Timeout for this request.
75 struct GNUNET_TIME_Absolute timeout;
78 * Task called on timeout, or 0 for none.
80 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
83 * Function to call to get the actual message.
85 GSF_GetMessageCallback gmc;
88 * Peer this request targets.
90 struct GSF_ConnectedPeer *cp;
98 * Size of the message to be transmitted.
103 * GNUNET_YES if this is a query, GNUNET_NO for content.
108 * Priority of this request.
118 struct GSF_ConnectedPeer
122 * Performance data for this peer.
124 struct GSF_PeerPerformanceData ppd;
127 * Time until when we blocked this peer from migrating
130 struct GNUNET_TIME_Absolute last_migration_block;
133 * Task scheduled to revive migration to this peer.
135 GNUNET_SCHEDULER_TaskIdentifier mig_revive_task;
138 * Messages (replies, queries, content migration) we would like to
139 * send to this peer in the near future. Sorted by priority, head.
141 struct GSF_PeerTransmitHandle *pth_head;
144 * Messages (replies, queries, content migration) we would like to
145 * send to this peer in the near future. Sorted by priority, tail.
147 struct GSF_PeerTransmitHandle *pth_tail;
150 * Migration stop message in our queue, or NULL if we have none pending.
152 struct GSF_PeerTransmitHandle *migration_pth;
155 * Context of our GNUNET_CORE_peer_change_preference call (or NULL).
157 struct GNUNET_CORE_InformationRequestContext *irc;
160 * Task scheduled if we need to retry bandwidth reservation later.
162 GNUNET_SCHEDULER_TaskIdentifier irc_delay_task;
165 * Active requests from this neighbour.
167 struct GNUNET_CONTAINER_MultiHashMap *request_map;
170 * Increase in traffic preference still to be submitted
171 * to the core service for this peer.
173 uint64_t inc_preference;
176 * Trust rating for this peer on disk.
181 * Which offset in "last_p2p_replies" will be updated next?
182 * (we go round-robin).
184 unsigned int last_p2p_replies_woff;
187 * Which offset in "last_client_replies" will be updated next?
188 * (we go round-robin).
190 unsigned int last_client_replies_woff;
193 * Current offset into 'last_request_times' ring buffer.
195 unsigned int last_request_times_off;
198 * GNUNET_YES if we did successfully reserve 32k bandwidth,
207 * Map from peer identities to 'struct GSF_ConnectPeer' entries.
209 static struct GNUNET_CONTAINER_MultiHashMap *cp_map;
212 * Where do we store trust information?
214 static char *trustDirectory;
218 * Get the filename under which we would store the GNUNET_HELLO_Message
219 * for the given host and protocol.
220 * @return filename of the form DIRECTORY/HOSTID
223 get_trust_filename (const struct GNUNET_PeerIdentity *id)
225 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
228 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
229 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
235 * Find latency information in 'atsi'.
237 * @param atsi performance data
238 * @return connection latency
240 static struct GNUNET_TIME_Relative
241 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
244 return GNUNET_TIME_UNIT_SECONDS;
245 while ( (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
246 (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY) )
248 if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR)
251 /* how can we not have latency data? */
252 return GNUNET_TIME_UNIT_SECONDS;
254 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
255 ntohl (atsi->value));
260 * Update the performance information kept for the given peer.
262 * @param cp peer record to update
263 * @param atsi transport performance data
266 update_atsi (struct GSF_ConnectedPeer *cp,
267 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
269 struct GNUNET_TIME_Relative latency;
271 latency = get_latency (atsi);
272 GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay,
274 /* LATER: merge atsi into cp's performance data (if we ever care...) */
279 * Return the performance data record for the given peer
281 * @param cp peer to query
282 * @return performance data record for the peer
284 struct GSF_PeerPerformanceData *
285 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
292 * Core is ready to transmit to a peer, get the message.
294 * @param cls the 'struct GSF_PeerTransmitHandle' of the message
295 * @param size number of bytes core is willing to take
296 * @param buf where to copy the message
297 * @return number of bytes copied to buf
300 peer_transmit_ready_cb (void *cls,
304 struct GSF_PeerTransmitHandle *pth = cls;
305 struct GSF_ConnectedPeer *cp;
308 if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
310 GNUNET_SCHEDULER_cancel (pth->timeout_task);
311 pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
314 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
317 if (GNUNET_YES == pth->is_query)
319 cp->ppd.last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
320 GNUNET_assert (0 < cp->ppd.pending_queries--);
322 else if (GNUNET_NO == pth->is_query)
324 GNUNET_assert (0 < cp->ppd.pending_replies--);
326 GNUNET_LOAD_update (cp->ppd.transmission_delay,
327 GNUNET_TIME_absolute_get_duration (pth->transmission_request_start_time).rel_value);
328 ret = pth->gmc (pth->gmc_cls,
336 * Function called by core upon success or failure of our bandwidth reservation request.
338 * @param cls the 'struct GSF_ConnectedPeer' of the peer for which we made the request
339 * @param peer identifies the peer
340 * @param bandwidth_out available amount of outbound bandwidth
341 * @param amount set to the amount that was actually reserved or unreserved;
342 * either the full requested amount or zero (no partial reservations)
343 * @param res_delay if the reservation could not be satisfied (amount was 0), how
344 * long should the client wait until re-trying?
345 * @param preference current traffic preference for the given peer
348 core_reserve_callback (void *cls,
349 const struct GNUNET_PeerIdentity *peer,
350 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
352 struct GNUNET_TIME_Relative res_delay,
353 uint64_t preference);
357 * (re)try to reserve bandwidth from the given peer.
359 * @param cls the 'struct GSF_ConnectedPeer' to reserve from
360 * @param tc scheduler context
363 retry_reservation (void *cls,
364 const struct GNUNET_SCHEDULER_TaskContext *tc)
366 struct GSF_ConnectedPeer *cp = cls;
368 struct GNUNET_PeerIdentity target;
370 GNUNET_PEER_resolve (cp->ppd.pid,
372 cp->irc_delay_task = GNUNET_SCHEDULER_NO_TASK;
373 ip = cp->inc_preference;
374 cp->inc_preference = 0;
375 cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
377 GNUNET_TIME_UNIT_FOREVER_REL,
378 GNUNET_BANDWIDTH_VALUE_MAX,
381 &core_reserve_callback,
387 * Function called by core upon success or failure of our bandwidth reservation request.
389 * @param cls the 'struct GSF_ConnectedPeer' of the peer for which we made the request
390 * @param peer identifies the peer
391 * @param bandwidth_out available amount of outbound bandwidth
392 * @param amount set to the amount that was actually reserved or unreserved;
393 * either the full requested amount or zero (no partial reservations)
394 * @param res_delay if the reservation could not be satisfied (amount was 0), how
395 * long should the client wait until re-trying?
396 * @param preference current traffic preference for the given peer
399 core_reserve_callback (void *cls,
400 const struct GNUNET_PeerIdentity *peer,
401 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
403 struct GNUNET_TIME_Relative res_delay,
406 struct GSF_ConnectedPeer *cp = cls;
407 struct GSF_PeerTransmitHandle *pth;
412 cp->irc_delay_task = GNUNET_SCHEDULER_add_delayed (res_delay,
417 cp->did_reserve = GNUNET_YES;
419 if ( (NULL != pth) &&
422 /* reservation success, try transmission now! */
423 pth->cth = GNUNET_CORE_notify_transmit_ready (GSF_core,
426 GNUNET_TIME_absolute_get_remaining (pth->timeout),
429 &peer_transmit_ready_cb,
436 * A peer connected to us. Setup the connected peer
439 * @param peer identity of peer that connected
440 * @param atsi performance data for the connection
441 * @return handle to connected peer entry
443 struct GSF_ConnectedPeer *
444 GSF_peer_connect_handler_ (const struct GNUNET_PeerIdentity *peer,
445 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
447 struct GSF_ConnectedPeer *cp;
451 cp = GNUNET_malloc (sizeof (struct GSF_ConnectedPeer));
452 cp->ppd.pid = GNUNET_PEER_intern (peer);
453 cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO);
454 cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
456 GNUNET_TIME_UNIT_FOREVER_REL,
457 GNUNET_BANDWIDTH_VALUE_MAX,
460 &core_reserve_callback,
462 fn = get_trust_filename (peer);
463 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
464 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
465 cp->disk_trust = cp->ppd.trust = ntohl (trust);
467 cp->request_map = GNUNET_CONTAINER_multihashmap_create (128);
468 GNUNET_break (GNUNET_OK ==
469 GNUNET_CONTAINER_multihashmap_put (cp_map,
472 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
473 update_atsi (cp, atsi);
474 GSF_push_start_ (cp);
480 * It may be time to re-start migrating content to this
481 * peer. Check, and if so, restart migration.
483 * @param cls the 'struct GSF_ConnectedPeer'
484 * @param tc scheduler context
487 revive_migration (void *cls,
488 const struct GNUNET_SCHEDULER_TaskContext *tc)
490 struct GSF_ConnectedPeer *cp = cls;
491 struct GNUNET_TIME_Relative bt;
493 cp->mig_revive_task = GNUNET_SCHEDULER_NO_TASK;
494 bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until);
495 if (0 != bt.rel_value)
497 /* still time left... */
499 = GNUNET_SCHEDULER_add_delayed (bt,
504 GSF_push_start_ (cp);
509 * Get a handle for a connected peer.
511 * @param peer peer's identity
512 * @return NULL if the peer is not currently connected
514 struct GSF_ConnectedPeer *
515 GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer)
517 return GNUNET_CONTAINER_multihashmap_get (cp_map,
523 * Handle P2P "MIGRATION_STOP" message.
525 * @param cls closure, always NULL
526 * @param other the other peer involved (sender or receiver, NULL
527 * for loopback messages where we are both sender and receiver)
528 * @param message the actual message
529 * @param atsi performance information
530 * @return GNUNET_OK to keep the connection open,
531 * GNUNET_SYSERR to close it (signal serious error)
534 GSF_handle_p2p_migration_stop_ (void *cls,
535 const struct GNUNET_PeerIdentity *other,
536 const struct GNUNET_MessageHeader *message,
537 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
539 struct GSF_ConnectedPeer *cp;
540 const struct MigrationStopMessage *msm;
541 struct GNUNET_TIME_Relative bt;
543 msm = (const struct MigrationStopMessage*) message;
544 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
551 bt = GNUNET_TIME_relative_ntoh (msm->duration);
552 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
553 _("Migration of content to peer `%s' blocked for %llu ms\n"),
555 (unsigned long long) bt.rel_value);
556 cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt);
557 if (cp->mig_revive_task == GNUNET_SCHEDULER_NO_TASK)
561 = GNUNET_SCHEDULER_add_delayed (bt,
565 update_atsi (cp, atsi);
571 * Copy reply and free put message.
573 * @param cls the 'struct PutMessage'
574 * @param buf_size number of bytes available in buf
575 * @param buf where to copy the message, NULL on error (peer disconnect)
576 * @return number of bytes copied to 'buf', can be 0 (without indicating an error)
579 copy_reply (void *cls,
583 struct PutMessage *pm = cls;
588 GNUNET_assert (buf_size >= ntohs (pm->header.size));
589 size = ntohs (pm->header.size);
590 memcpy (buf, pm, size);
591 GNUNET_STATISTICS_update (GSF_stats,
592 gettext_noop ("# replies transmitted to other peers"),
599 GNUNET_STATISTICS_update (GSF_stats,
600 gettext_noop ("# replies dropped"),
610 * Handle a reply to a pending request. Also called if a request
611 * expires (then with data == NULL). The handler may be called
612 * many times (depending on the request type), but will not be
613 * called during or after a call to GSF_pending_request_cancel
614 * and will also not be called anymore after a call signalling
617 * @param cls 'struct GSF_ConnectedPeer' of the peer that would
618 * have liked an answer to the request
619 * @param pr handle to the original pending request
620 * @param expiration when does 'data' expire?
621 * @param type type of the block
622 * @param data response data, NULL on request expiration
623 * @param data_len number of bytes in data
626 handle_p2p_reply (void *cls,
627 struct GSF_PendingRequest *pr,
628 struct GNUNET_TIME_Absolute expiration,
629 enum GNUNET_BLOCK_Type type,
633 struct GSF_ConnectedPeer *cp = cls;
634 struct GSF_PendingRequestData *prd;
635 struct PutMessage *pm;
638 GNUNET_assert (data_len < GNUNET_SERVER_MAX_MESSAGE_SIZE);
639 prd = GSF_pending_request_get_data_ (pr);
642 GNUNET_STATISTICS_update (GSF_stats,
643 gettext_noop ("# P2P searches active"),
646 GNUNET_break (GNUNET_OK ==
647 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
652 GNUNET_break (type != GNUNET_BLOCK_TYPE_ANY);
653 if ( (prd->type != type) &&
654 (prd->type != GNUNET_BLOCK_TYPE_ANY) )
660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
661 "Transmitting result for query `%s' to peer\n",
662 GNUNET_h2s (&prd->query));
664 GNUNET_STATISTICS_update (GSF_stats,
665 gettext_noop ("# replies received for other peers"),
668 msize = sizeof (struct PutMessage) + data_len;
669 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
674 pm = GNUNET_malloc (msize);
675 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
676 pm->header.size = htons (msize);
677 pm->type = htonl (type);
678 pm->expiration = GNUNET_TIME_absolute_hton (expiration);
679 memcpy (&pm[1], data, data_len);
680 (void) GSF_peer_transmit_ (cp, GNUNET_NO,
690 * Increase the host credit by a value.
692 * @param cp which peer to change the trust value on
693 * @param value is the int value by which the
694 * host credit is to be increased or decreased
695 * @returns the actual change in trust (positive or negative)
698 change_host_trust (struct GSF_ConnectedPeer *cp, int value)
702 GNUNET_assert (cp != NULL);
705 if (cp->ppd.trust + value < cp->ppd.trust)
707 value = UINT32_MAX - cp->ppd.trust;
708 cp->ppd.trust = UINT32_MAX;
711 cp->ppd.trust += value;
715 if (cp->ppd.trust < -value)
717 value = -cp->ppd.trust;
721 cp->ppd.trust += value;
728 * We've received a request with the specified priority. Bound it
729 * according to how much we trust the given peer.
731 * @param prio_in requested priority
732 * @param cp the peer making the request
733 * @return effective priority
736 bound_priority (uint32_t prio_in,
737 struct GSF_ConnectedPeer *cp)
739 #define N ((double)128.0)
744 ld = GSF_test_get_load_too_high_ (0);
745 if (ld == GNUNET_SYSERR)
747 GNUNET_STATISTICS_update (GSF_stats,
748 gettext_noop ("# requests done for free (low load)"),
751 return 0; /* excess resources */
753 if (prio_in > INT32_MAX)
755 ret = - change_host_trust (cp, - (int) prio_in);
758 if (ret > GSF_current_priorities + N)
759 rret = GSF_current_priorities + N;
762 GSF_current_priorities
763 = (GSF_current_priorities * (N-1) + rret)/N;
765 if ( (ld == GNUNET_YES) && (ret > 0) )
767 /* try with charging */
768 ld = GSF_test_get_load_too_high_ (ret);
770 if (ld == GNUNET_YES)
772 GNUNET_STATISTICS_update (GSF_stats,
773 gettext_noop ("# request dropped, priority insufficient"),
777 change_host_trust (cp, (int) ret);
778 return -1; /* not enough resources */
782 GNUNET_STATISTICS_update (GSF_stats,
783 gettext_noop ("# requests done for a price (normal load)"),
793 * The priority level imposes a bound on the maximum
794 * value for the ttl that can be requested.
796 * @param ttl_in requested ttl
797 * @param prio given priority
798 * @return ttl_in if ttl_in is below the limit,
799 * otherwise the ttl-limit for the given priority
802 bound_ttl (int32_t ttl_in, uint32_t prio)
804 unsigned long long allowed;
808 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
809 if (ttl_in > allowed)
811 if (allowed >= (1 << 30))
820 * Handle P2P "QUERY" message. Creates the pending request entry
821 * and sets up all of the data structures to that we will
822 * process replies properly. Does not initiate forwarding or
823 * local database lookups.
825 * @param other the other peer involved (sender or receiver, NULL
826 * for loopback messages where we are both sender and receiver)
827 * @param message the actual message
828 * @return pending request handle, NULL on error
830 struct GSF_PendingRequest *
831 GSF_handle_p2p_query_ (const struct GNUNET_PeerIdentity *other,
832 const struct GNUNET_MessageHeader *message)
834 struct GSF_PendingRequest *pr;
835 struct GSF_PendingRequestData *prd;
836 struct GSF_ConnectedPeer *cp;
837 struct GSF_ConnectedPeer *cps;
838 const GNUNET_HashCode *namespace;
839 const struct GNUNET_PeerIdentity *target;
840 enum GSF_PendingRequestOptions options;
842 const struct GetMessage *gm;
844 const GNUNET_HashCode *opt;
847 uint32_t ttl_decrement;
850 enum GNUNET_BLOCK_Type type;
853 msize = ntohs(message->size);
854 if (msize < sizeof (struct GetMessage))
859 gm = (const struct GetMessage*) message;
861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
862 "Received request for `%s' from `%s'\n",
863 GNUNET_h2s (&gm->query),
866 type = ntohl (gm->type);
867 bm = ntohl (gm->hash_bitmap);
875 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
880 opt = (const GNUNET_HashCode*) &gm[1];
881 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
882 /* bfsize must be power of 2, check! */
883 if (0 != ( (bfsize - 1) & bfsize))
888 GSF_cover_query_count++;
889 bm = ntohl (gm->hash_bitmap);
891 cps = GNUNET_CONTAINER_multihashmap_get (cp_map,
895 /* peer must have just disconnected */
896 GNUNET_STATISTICS_update (GSF_stats,
897 gettext_noop ("# requests dropped due to initiator not being connected"),
902 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
903 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
910 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
912 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
913 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
917 "Failed to find peer `%4s' in connection set. Dropping query.\n",
920 GNUNET_STATISTICS_update (GSF_stats,
921 gettext_noop ("# requests dropped due to missing reverse route"),
926 /* note that we can really only check load here since otherwise
927 peers could find out that we are overloaded by not being
928 disconnected after sending us a malformed query... */
929 priority = bound_priority (ntohl (gm->priority), cps);
933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934 "Dropping query from `%s', this peer is too busy.\n",
940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
942 GNUNET_h2s (&gm->query),
947 namespace = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) ? &opt[bits++] : NULL;
948 if ( (type == GNUNET_BLOCK_TYPE_FS_SBLOCK) &&
949 (namespace == NULL) )
954 if ( (type != GNUNET_BLOCK_TYPE_FS_SBLOCK) &&
955 (namespace != NULL) )
960 target = (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? ((const struct GNUNET_PeerIdentity*) &opt[bits++]) : NULL;
963 if ( (GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1 + priority)) ||
964 (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) >
965 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)) )
967 /* don't have BW to send to peer, or would likely take longer than we have for it,
968 so at best indirect the query */
970 options |= GSF_PRO_FORWARD_ONLY;
971 spid = GNUNET_PEER_intern (other);
973 ttl = bound_ttl (ntohl (gm->ttl), priority);
974 /* decrement ttl (always) */
975 ttl_decrement = 2 * TTL_DECREMENT +
976 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
979 (((int32_t)(ttl - ttl_decrement)) > 0) )
982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
983 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
988 GNUNET_STATISTICS_update (GSF_stats,
989 gettext_noop ("# requests dropped due TTL underflow"),
992 /* integer underflow => drop (should be very rare)! */
995 ttl -= ttl_decrement;
997 /* test if the request already exists */
998 pr = GNUNET_CONTAINER_multihashmap_get (cp->request_map,
1002 prd = GSF_pending_request_get_data_ (pr);
1003 if ( (prd->type == type) &&
1004 ( (type != GNUNET_BLOCK_TYPE_FS_SBLOCK) ||
1005 (0 == memcmp (&prd->namespace,
1007 sizeof (GNUNET_HashCode))) ) )
1009 if (prd->ttl.abs_value >= GNUNET_TIME_absolute_get().abs_value + ttl)
1011 /* existing request has higher TTL, drop new one! */
1012 prd->priority += priority;
1014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1015 "Have existing request with higher TTL, dropping new request.\n",
1016 GNUNET_i2s (other));
1018 GNUNET_STATISTICS_update (GSF_stats,
1019 gettext_noop ("# requests dropped due to higher-TTL request"),
1024 /* existing request has lower TTL, drop old one! */
1025 priority += prd->priority;
1026 GSF_pending_request_cancel_ (pr);
1027 GNUNET_assert (GNUNET_YES ==
1028 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
1034 pr = GSF_pending_request_create_ (options,
1039 (bfsize > 0) ? (const char*)&opt[bits] : NULL,
1041 ntohl (gm->filter_mutator),
1043 (uint32_t) priority,
1046 NULL, 0, /* replies_seen */
1049 GNUNET_break (GNUNET_OK ==
1050 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
1053 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1054 GNUNET_STATISTICS_update (GSF_stats,
1055 gettext_noop ("# P2P searches received"),
1058 GNUNET_STATISTICS_update (GSF_stats,
1059 gettext_noop ("# P2P searches active"),
1067 * Function called if there has been a timeout trying to satisfy
1068 * a transmission request.
1070 * @param cls the 'struct GSF_PeerTransmitHandle' of the request
1071 * @param tc scheduler context
1074 peer_transmit_timeout (void *cls,
1075 const struct GNUNET_SCHEDULER_TaskContext *tc)
1077 struct GSF_PeerTransmitHandle *pth = cls;
1078 struct GSF_ConnectedPeer *cp;
1081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082 "Timeout trying to transmit to other peer\n");
1084 pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1086 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1089 if (GNUNET_YES == pth->is_query)
1090 GNUNET_assert (0 < cp->ppd.pending_queries--);
1091 else if (GNUNET_NO == pth->is_query)
1092 GNUNET_assert (0 < cp->ppd.pending_replies--);
1093 GNUNET_LOAD_update (cp->ppd.transmission_delay,
1095 pth->gmc (pth->gmc_cls,
1102 * Transmit a message to the given peer as soon as possible.
1103 * If the peer disconnects before the transmission can happen,
1104 * the callback is invoked with a 'NULL' buffer.
1106 * @param cp target peer
1107 * @param is_query is this a query (GNUNET_YES) or content (GNUNET_NO) or neither (GNUNET_SYSERR)
1108 * @param priority how important is this request?
1109 * @param timeout when does this request timeout (call gmc with error)
1110 * @param size number of bytes we would like to send to the peer
1111 * @param gmc function to call to get the message
1112 * @param gmc_cls closure for gmc
1113 * @return handle to cancel request
1115 struct GSF_PeerTransmitHandle *
1116 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1119 struct GNUNET_TIME_Relative timeout,
1121 GSF_GetMessageCallback gmc,
1124 struct GSF_PeerTransmitHandle *pth;
1125 struct GSF_PeerTransmitHandle *pos;
1126 struct GSF_PeerTransmitHandle *prev;
1127 struct GNUNET_PeerIdentity target;
1131 pth = GNUNET_malloc (sizeof (struct GSF_PeerTransmitHandle));
1132 pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1133 pth->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1135 pth->gmc_cls = gmc_cls;
1137 pth->is_query = is_query;
1138 pth->priority = priority;
1140 /* insertion sort (by priority, descending) */
1143 while ( (pos != NULL) &&
1144 (pos->priority > priority) )
1150 GNUNET_CONTAINER_DLL_insert (cp->pth_head,
1154 GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1158 GNUNET_PEER_resolve (cp->ppd.pid,
1160 if (GNUNET_YES == is_query)
1162 /* query, need reservation */
1163 cp->ppd.pending_queries++;
1164 if (GNUNET_YES == cp->did_reserve)
1166 cp->did_reserve = GNUNET_NO;
1167 /* reservation already done! */
1168 is_ready = GNUNET_YES;
1169 ip = cp->inc_preference;
1170 cp->inc_preference = 0;
1171 cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
1173 GNUNET_TIME_UNIT_FOREVER_REL,
1174 GNUNET_BANDWIDTH_VALUE_MAX,
1177 &core_reserve_callback,
1182 /* still waiting for reservation */
1183 is_ready = GNUNET_NO;
1186 else if (GNUNET_NO == is_query)
1188 /* no reservation needed for content */
1189 cp->ppd.pending_replies++;
1190 is_ready = GNUNET_YES;
1194 /* not a query or content, no reservation needed */
1195 is_ready = GNUNET_YES;
1199 pth->cth = GNUNET_CORE_notify_transmit_ready (GSF_core,
1205 &peer_transmit_ready_cb,
1207 /* pth->cth could be NULL here, that's OK, we'll try again
1213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214 "Not ready to ask for transmission to `%s'\n",
1215 GNUNET_i2s (&target));
1218 if (pth->cth == NULL)
1221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222 "No transmission task scheduled, creating timeout task (%llu ms)\n",
1223 (unsigned long long) timeout.rel_value);
1225 /* if we're waiting for reservation OR if we could not do notify_transmit_ready,
1226 install a timeout task to be on the safe side */
1227 pth->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
1228 &peer_transmit_timeout,
1236 * Cancel an earlier request for transmission.
1238 * @param pth request to cancel
1241 GSF_peer_transmit_cancel_ (struct GSF_PeerTransmitHandle *pth)
1243 struct GSF_ConnectedPeer *cp;
1245 if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1247 GNUNET_SCHEDULER_cancel (pth->timeout_task);
1248 pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1250 if (NULL != pth->cth)
1252 GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
1256 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1259 if (GNUNET_YES == pth->is_query)
1260 GNUNET_assert (0 < cp->ppd.pending_queries--);
1261 else if (GNUNET_NO == pth->is_query)
1262 GNUNET_assert (0 < cp->ppd.pending_replies--);
1268 * Report on receiving a reply; update the performance record of the given peer.
1270 * @param cp responding peer (will be updated)
1271 * @param request_time time at which the original query was transmitted
1272 * @param request_priority priority of the original request
1275 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1276 struct GNUNET_TIME_Absolute request_time,
1277 uint32_t request_priority)
1279 struct GNUNET_TIME_Relative delay;
1281 delay = GNUNET_TIME_absolute_get_duration (request_time);
1282 cp->ppd.avg_reply_delay.rel_value = (cp->ppd.avg_reply_delay.rel_value * (RUNAVG_DELAY_N-1) + delay.rel_value) / RUNAVG_DELAY_N;
1283 cp->ppd.avg_priority = (cp->ppd.avg_priority * (RUNAVG_DELAY_N-1) + request_priority) / RUNAVG_DELAY_N;
1288 * Report on receiving a reply in response to an initiating client.
1289 * Remember that this peer is good for this client.
1291 * @param cp responding peer (will be updated)
1292 * @param initiator_client local client on responsible for query
1295 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1296 struct GSF_LocalClient *initiator_client)
1298 cp->ppd.last_client_replies[cp->last_client_replies_woff++ % CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1303 * Report on receiving a reply in response to an initiating peer.
1304 * Remember that this peer is good for this initiating peer.
1306 * @param cp responding peer (will be updated)
1307 * @param initiator_peer other peer responsible for query
1310 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1311 const struct GSF_ConnectedPeer *initiator_peer)
1313 GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
1314 cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff++ % P2P_SUCCESS_LIST_SIZE] = initiator_peer->ppd.pid;
1315 GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1320 * Method called whenever a given peer has a status change.
1322 * @param cls closure
1323 * @param peer peer identity this notification is about
1324 * @param bandwidth_in available amount of inbound bandwidth
1325 * @param bandwidth_out available amount of outbound bandwidth
1326 * @param timeout absolute time when this peer will time out
1327 * unless we see some further activity from it
1328 * @param atsi status information
1331 GSF_peer_status_handler_ (void *cls,
1332 const struct GNUNET_PeerIdentity *peer,
1333 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1334 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1335 struct GNUNET_TIME_Absolute timeout,
1336 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1338 struct GSF_ConnectedPeer *cp;
1340 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1342 GNUNET_assert (NULL != cp);
1343 update_atsi (cp, atsi);
1348 * Cancel all requests associated with the peer.
1351 * @param query hash code of the request
1352 * @param value the 'struct GSF_PendingRequest'
1353 * @return GNUNET_YES (continue to iterate)
1356 cancel_pending_request (void *cls,
1357 const GNUNET_HashCode *query,
1360 struct GSF_PendingRequest *pr = value;
1362 GSF_pending_request_cancel_ (pr);
1368 * A peer disconnected from us. Tear down the connected peer
1372 * @param peer identity of peer that connected
1375 GSF_peer_disconnect_handler_ (void *cls,
1376 const struct GNUNET_PeerIdentity *peer)
1378 struct GSF_ConnectedPeer *cp;
1379 struct GSF_PeerTransmitHandle *pth;
1381 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1384 return; /* must have been disconnect from core with
1385 'peer' == my_id, ignore */
1386 GNUNET_CONTAINER_multihashmap_remove (cp_map,
1389 if (NULL != cp->migration_pth)
1391 GSF_peer_transmit_cancel_ (cp->migration_pth);
1392 cp->migration_pth = NULL;
1394 if (NULL != cp->irc)
1396 GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1399 if (GNUNET_SCHEDULER_NO_TASK != cp->irc_delay_task)
1401 GNUNET_SCHEDULER_cancel (cp->irc_delay_task);
1402 cp->irc_delay_task = GNUNET_SCHEDULER_NO_TASK;
1404 GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1405 &cancel_pending_request,
1407 GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1408 cp->request_map = NULL;
1409 GSF_plan_notify_peer_disconnect_ (cp);
1410 GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1411 GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1412 while (NULL != (pth = cp->pth_head))
1414 if (NULL != pth->cth)
1416 GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
1419 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1424 GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1425 if (GNUNET_SCHEDULER_NO_TASK != cp->mig_revive_task)
1427 GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1428 cp->mig_revive_task = GNUNET_SCHEDULER_NO_TASK;
1435 * Closure for 'call_iterator'.
1437 struct IterationContext
1440 * Function to call on each entry.
1442 GSF_ConnectedPeerIterator it;
1452 * Function that calls the callback for each peer.
1454 * @param cls the 'struct IterationContext*'
1455 * @param key identity of the peer
1456 * @param value the 'struct GSF_ConnectedPeer*'
1457 * @return GNUNET_YES to continue iteration
1460 call_iterator (void *cls,
1461 const GNUNET_HashCode *key,
1464 struct IterationContext *ic = cls;
1465 struct GSF_ConnectedPeer *cp = value;
1468 (const struct GNUNET_PeerIdentity*) key,
1476 * Iterate over all connected peers.
1478 * @param it function to call for each peer
1479 * @param it_cls closure for it
1482 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1485 struct IterationContext ic;
1489 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1496 * Obtain the identity of a connected peer.
1498 * @param cp peer to reserve bandwidth from
1499 * @param id identity to set (written to)
1502 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1503 struct GNUNET_PeerIdentity *id)
1505 GNUNET_PEER_resolve (cp->ppd.pid,
1511 * Assemble a migration stop message for transmission.
1513 * @param cls the 'struct GSF_ConnectedPeer' to use
1514 * @param size number of bytes we're allowed to write to buf
1515 * @param buf where to copy the message
1516 * @return number of bytes copied to buf
1519 create_migration_stop_message (void *cls,
1523 struct GSF_ConnectedPeer *cp = cls;
1524 struct MigrationStopMessage msm;
1526 cp->migration_pth = NULL;
1529 GNUNET_assert (size >= sizeof (struct MigrationStopMessage));
1530 msm.header.size = htons (sizeof (struct MigrationStopMessage));
1531 msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1532 msm.reserved = htonl (0);
1533 msm.duration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (cp->last_migration_block));
1534 memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1535 return sizeof (struct MigrationStopMessage);
1540 * Ask a peer to stop migrating data to us until the given point
1543 * @param cp peer to ask
1544 * @param block_time until when to block
1547 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1548 struct GNUNET_TIME_Relative block_time)
1550 if (GNUNET_TIME_absolute_get_remaining (cp->last_migration_block).rel_value > block_time.rel_value)
1553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1554 "Migration already blocked for another %llu ms\n",
1555 (unsigned long long) GNUNET_TIME_absolute_get_remaining (cp->last_migration_block).rel_value);
1557 return; /* already blocked */
1560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1561 "Asking to stop migration for %llu ms\n",
1562 (unsigned long long) block_time.rel_value);
1564 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
1565 if (cp->migration_pth != NULL)
1566 GSF_peer_transmit_cancel_ (cp->migration_pth);
1568 = GSF_peer_transmit_ (cp,
1571 GNUNET_TIME_UNIT_FOREVER_REL,
1572 sizeof (struct MigrationStopMessage),
1573 &create_migration_stop_message,
1579 * Write host-trust information to a file - flush the buffer entry!
1581 * @param cls closure, not used
1582 * @param key host identity
1583 * @param value the 'struct GSF_ConnectedPeer' to flush
1584 * @return GNUNET_OK to continue iteration
1587 flush_trust (void *cls,
1588 const GNUNET_HashCode *key,
1591 struct GSF_ConnectedPeer *cp = value;
1594 struct GNUNET_PeerIdentity pid;
1596 if (cp->ppd.trust == cp->disk_trust)
1597 return GNUNET_OK; /* unchanged */
1598 GNUNET_PEER_resolve (cp->ppd.pid,
1600 fn = get_trust_filename (&pid);
1601 if (cp->ppd.trust == 0)
1603 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1604 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1605 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1609 trust = htonl (cp->ppd.trust);
1610 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1612 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1613 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1614 cp->disk_trust = cp->ppd.trust;
1622 * Notify core about a preference we have for the given peer
1623 * (to allocate more resources towards it). The change will
1624 * be communicated the next time we reserve bandwidth with
1625 * core (not instantly).
1627 * @param cp peer to reserve bandwidth from
1628 * @param pref preference change
1631 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1634 cp->inc_preference += pref;
1639 * Call this method periodically to flush trust information to disk.
1641 * @param cls closure, not used
1642 * @param tc task context, not used
1645 cron_flush_trust (void *cls,
1646 const struct GNUNET_SCHEDULER_TaskContext *tc)
1651 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1656 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1658 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ,
1665 * Initialize peer management subsystem.
1668 GSF_connected_peer_init_ ()
1670 cp_map = GNUNET_CONTAINER_multihashmap_create (128);
1671 GNUNET_assert (GNUNET_OK ==
1672 GNUNET_CONFIGURATION_get_value_filename (GSF_cfg,
1676 GNUNET_DISK_directory_create (trustDirectory);
1677 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1678 &cron_flush_trust, NULL);
1683 * Iterator to free peer entries.
1685 * @param cls closure, unused
1686 * @param key current key code
1687 * @param value value in the hash map (peer entry)
1688 * @return GNUNET_YES (we should continue to iterate)
1691 clean_peer (void *cls,
1692 const GNUNET_HashCode * key,
1695 GSF_peer_disconnect_handler_ (NULL,
1696 (const struct GNUNET_PeerIdentity*) key);
1702 * Shutdown peer management subsystem.
1705 GSF_connected_peer_done_ ()
1707 cron_flush_trust (NULL, NULL);
1708 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1711 GNUNET_CONTAINER_multihashmap_destroy (cp_map);
1713 GNUNET_free (trustDirectory);
1714 trustDirectory = NULL;
1719 * Iterator to remove references to LC entry.
1721 * @param cls the 'struct GSF_LocalClient*' to look for
1722 * @param key current key code
1723 * @param value value in the hash map (peer entry)
1724 * @return GNUNET_YES (we should continue to iterate)
1727 clean_local_client (void *cls,
1728 const GNUNET_HashCode * key,
1731 const struct GSF_LocalClient *lc = cls;
1732 struct GSF_ConnectedPeer *cp = value;
1735 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1736 if (cp->ppd.last_client_replies[i] == lc)
1737 cp->ppd.last_client_replies[i] = NULL;
1743 * Notification that a local client disconnected. Clean up all of our
1744 * references to the given handle.
1746 * @param lc handle to the local client (henceforth invalid)
1749 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1752 return; /* already cleaned up */
1753 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1754 &clean_local_client,
1759 /* end of gnunet-service-fs_cp.c */