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).
156 * NULL if we have successfully reserved 32k, otherwise non-NULL.
158 struct GNUNET_CORE_InformationRequestContext *irc;
161 * Active requests from this neighbour.
163 struct GNUNET_CONTAINER_MultiHashMap *request_map;
166 * Increase in traffic preference still to be submitted
167 * to the core service for this peer.
169 uint64_t inc_preference;
172 * Trust rating for this peer on disk.
177 * Which offset in "last_p2p_replies" will be updated next?
178 * (we go round-robin).
180 unsigned int last_p2p_replies_woff;
183 * Which offset in "last_client_replies" will be updated next?
184 * (we go round-robin).
186 unsigned int last_client_replies_woff;
189 * Current offset into 'last_request_times' ring buffer.
191 unsigned int last_request_times_off;
197 * Map from peer identities to 'struct GSF_ConnectPeer' entries.
199 static struct GNUNET_CONTAINER_MultiHashMap *cp_map;
202 * Where do we store trust information?
204 static char *trustDirectory;
208 * Get the filename under which we would store the GNUNET_HELLO_Message
209 * for the given host and protocol.
210 * @return filename of the form DIRECTORY/HOSTID
213 get_trust_filename (const struct GNUNET_PeerIdentity *id)
215 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
218 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
219 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
225 * Find latency information in 'atsi'.
227 * @param atsi performance data
228 * @return connection latency
230 static struct GNUNET_TIME_Relative
231 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
234 return GNUNET_TIME_UNIT_SECONDS;
235 while ( (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
236 (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY) )
238 if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR)
241 /* how can we not have latency data? */
242 return GNUNET_TIME_UNIT_SECONDS;
244 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
245 ntohl (atsi->value));
250 * Update the performance information kept for the given peer.
252 * @param cp peer record to update
253 * @param atsi transport performance data
256 update_atsi (struct GSF_ConnectedPeer *cp,
257 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
259 struct GNUNET_TIME_Relative latency;
261 latency = get_latency (atsi);
262 GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay,
264 /* LATER: merge atsi into cp's performance data (if we ever care...) */
269 * Return the performance data record for the given peer
271 * @param cp peer to query
272 * @return performance data record for the peer
274 struct GSF_PeerPerformanceData *
275 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
282 * Core is ready to transmit to a peer, get the message.
284 * @param cls the 'struct GSF_PeerTransmitHandle' of the message
285 * @param size number of bytes core is willing to take
286 * @param buf where to copy the message
287 * @return number of bytes copied to buf
290 peer_transmit_ready_cb (void *cls,
294 struct GSF_PeerTransmitHandle *pth = cls;
295 struct GSF_ConnectedPeer *cp;
298 if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
300 GNUNET_SCHEDULER_cancel (pth->timeout_task);
301 pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
304 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
307 if (GNUNET_YES == pth->is_query)
309 cp->ppd.last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
310 GNUNET_assert (0 < cp->ppd.pending_queries--);
312 else if (GNUNET_NO == pth->is_query)
314 GNUNET_assert (0 < cp->ppd.pending_replies--);
316 GNUNET_LOAD_update (cp->ppd.transmission_delay,
317 GNUNET_TIME_absolute_get_duration (pth->transmission_request_start_time).rel_value);
318 ret = pth->gmc (pth->gmc_cls,
326 * Function called by core upon success or failure of our bandwidth reservation request.
328 * @param cls the 'struct GSF_ConnectedPeer' of the peer for which we made the request
329 * @param peer identifies the peer
330 * @param bandwidth_out available amount of outbound bandwidth
331 * @param amount set to the amount that was actually reserved or unreserved;
332 * either the full requested amount or zero (no partial reservations)
333 * @param preference current traffic preference for the given peer
336 core_reserve_callback (void *cls,
337 const struct GNUNET_PeerIdentity *peer,
338 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
342 struct GSF_ConnectedPeer *cp = cls;
343 struct GSF_PeerTransmitHandle *pth;
349 /* failed; retry! (how did we get here!?) */
350 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
351 _("Failed to reserve bandwidth to peer `%s'\n"),
353 ip = cp->inc_preference;
354 cp->inc_preference = 0;
355 cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
357 GNUNET_TIME_UNIT_FOREVER_REL,
358 GNUNET_BANDWIDTH_VALUE_MAX,
361 &core_reserve_callback,
366 if ( (NULL != pth) &&
369 /* reservation success, try transmission now! */
370 pth->cth = GNUNET_CORE_notify_transmit_ready (GSF_core,
373 GNUNET_TIME_absolute_get_remaining (pth->timeout),
376 &peer_transmit_ready_cb,
383 * A peer connected to us. Setup the connected peer
386 * @param peer identity of peer that connected
387 * @param atsi performance data for the connection
388 * @return handle to connected peer entry
390 struct GSF_ConnectedPeer *
391 GSF_peer_connect_handler_ (const struct GNUNET_PeerIdentity *peer,
392 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
394 struct GSF_ConnectedPeer *cp;
398 cp = GNUNET_malloc (sizeof (struct GSF_ConnectedPeer));
399 cp->ppd.pid = GNUNET_PEER_intern (peer);
400 cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO);
401 cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
403 GNUNET_TIME_UNIT_FOREVER_REL,
404 GNUNET_BANDWIDTH_VALUE_MAX,
407 &core_reserve_callback,
409 fn = get_trust_filename (peer);
410 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
411 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
412 cp->disk_trust = cp->ppd.trust = ntohl (trust);
414 cp->request_map = GNUNET_CONTAINER_multihashmap_create (128);
415 GNUNET_break (GNUNET_OK ==
416 GNUNET_CONTAINER_multihashmap_put (cp_map,
419 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
420 update_atsi (cp, atsi);
421 GSF_push_start_ (cp);
427 * It may be time to re-start migrating content to this
428 * peer. Check, and if so, restart migration.
430 * @param cls the 'struct GSF_ConnectedPeer'
431 * @param tc scheduler context
434 revive_migration (void *cls,
435 const struct GNUNET_SCHEDULER_TaskContext *tc)
437 struct GSF_ConnectedPeer *cp = cls;
438 struct GNUNET_TIME_Relative bt;
440 cp->mig_revive_task = GNUNET_SCHEDULER_NO_TASK;
441 bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until);
442 if (0 != bt.rel_value)
444 /* still time left... */
446 = GNUNET_SCHEDULER_add_delayed (bt,
451 GSF_push_start_ (cp);
456 * Get a handle for a connected peer.
458 * @param peer peer's identity
460 struct GSF_ConnectedPeer *
461 GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer)
463 return GNUNET_CONTAINER_multihashmap_get (cp_map,
469 * Handle P2P "MIGRATION_STOP" message.
471 * @param cls closure, always NULL
472 * @param other the other peer involved (sender or receiver, NULL
473 * for loopback messages where we are both sender and receiver)
474 * @param message the actual message
475 * @param atsi performance information
476 * @return GNUNET_OK to keep the connection open,
477 * GNUNET_SYSERR to close it (signal serious error)
480 GSF_handle_p2p_migration_stop_ (void *cls,
481 const struct GNUNET_PeerIdentity *other,
482 const struct GNUNET_MessageHeader *message,
483 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
485 struct GSF_ConnectedPeer *cp;
486 const struct MigrationStopMessage *msm;
487 struct GNUNET_TIME_Relative bt;
489 msm = (const struct MigrationStopMessage*) message;
490 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
497 bt = GNUNET_TIME_relative_ntoh (msm->duration);
498 cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt);
499 if (cp->mig_revive_task == GNUNET_SCHEDULER_NO_TASK)
503 = GNUNET_SCHEDULER_add_delayed (bt,
507 update_atsi (cp, atsi);
513 * Copy reply and free put message.
515 * @param cls the 'struct PutMessage'
516 * @param buf_size number of bytes available in buf
517 * @param buf where to copy the message, NULL on error (peer disconnect)
518 * @return number of bytes copied to 'buf', can be 0 (without indicating an error)
521 copy_reply (void *cls,
525 struct PutMessage *pm = cls;
530 GNUNET_assert (buf_size >= ntohs (pm->header.size));
531 size = ntohs (pm->header.size);
532 memcpy (buf, pm, size);
533 GNUNET_STATISTICS_update (GSF_stats,
534 gettext_noop ("# replies transmitted to other peers"),
541 GNUNET_STATISTICS_update (GSF_stats,
542 gettext_noop ("# replies dropped"),
552 * Handle a reply to a pending request. Also called if a request
553 * expires (then with data == NULL). The handler may be called
554 * many times (depending on the request type), but will not be
555 * called during or after a call to GSF_pending_request_cancel
556 * and will also not be called anymore after a call signalling
559 * @param cls 'struct GSF_ConnectedPeer' of the peer that would
560 * have liked an answer to the request
561 * @param pr handle to the original pending request
562 * @param expiration when does 'data' expire?
563 * @param data response data, NULL on request expiration
564 * @param data_len number of bytes in data
565 * @param more GNUNET_YES if the request remains active (may call
566 * this function again), GNUNET_NO if the request is
567 * finished (client must not call GSF_pending_request_cancel_)
570 handle_p2p_reply (void *cls,
571 struct GSF_PendingRequest *pr,
572 struct GNUNET_TIME_Absolute expiration,
577 struct GSF_ConnectedPeer *cp = cls;
578 struct GSF_PendingRequestData *prd;
579 struct PutMessage *pm;
582 prd = GSF_pending_request_get_data_ (pr);
585 GNUNET_assert (GNUNET_NO == more);
586 GNUNET_STATISTICS_update (GSF_stats,
587 gettext_noop ("# P2P searches active"),
590 GNUNET_break (GNUNET_OK ==
591 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
598 "Transmitting result for query `%s'\n",
601 GNUNET_STATISTICS_update (GSF_stats,
602 gettext_noop ("# replies received for other peers"),
605 msize = sizeof (struct PutMessage) + data_len;
606 pm = GNUNET_malloc (sizeof (msize));
607 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
608 pm->header.size = htons (msize);
609 pm->type = htonl (prd->type);
610 pm->expiration = GNUNET_TIME_absolute_hton (expiration);
611 memcpy (&pm[1], data, data_len);
612 (void) GSF_peer_transmit_ (cp, GNUNET_NO,
622 * Increase the host credit by a value.
624 * @param cp which peer to change the trust value on
625 * @param value is the int value by which the
626 * host credit is to be increased or decreased
627 * @returns the actual change in trust (positive or negative)
630 change_host_trust (struct GSF_ConnectedPeer *cp, int value)
634 GNUNET_assert (cp != NULL);
637 if (cp->ppd.trust + value < cp->ppd.trust)
639 value = UINT32_MAX - cp->ppd.trust;
640 cp->ppd.trust = UINT32_MAX;
643 cp->ppd.trust += value;
647 if (cp->ppd.trust < -value)
649 value = -cp->ppd.trust;
653 cp->ppd.trust += value;
660 * We've received a request with the specified priority. Bound it
661 * according to how much we trust the given peer.
663 * @param prio_in requested priority
664 * @param cp the peer making the request
665 * @return effective priority
668 bound_priority (uint32_t prio_in,
669 struct GSF_ConnectedPeer *cp)
671 #define N ((double)128.0)
676 ld = GSF_test_get_load_too_high_ (0);
677 if (ld == GNUNET_SYSERR)
679 GNUNET_STATISTICS_update (GSF_stats,
680 gettext_noop ("# requests done for free (low load)"),
683 return 0; /* excess resources */
685 if (prio_in > INT32_MAX)
687 ret = - change_host_trust (cp, - (int) prio_in);
690 if (ret > GSF_current_priorities + N)
691 rret = GSF_current_priorities + N;
694 GSF_current_priorities
695 = (GSF_current_priorities * (N-1) + rret)/N;
697 if ( (ld == GNUNET_YES) && (ret > 0) )
699 /* try with charging */
700 ld = GSF_test_get_load_too_high_ (ret);
702 if (ld == GNUNET_YES)
704 GNUNET_STATISTICS_update (GSF_stats,
705 gettext_noop ("# request dropped, priority insufficient"),
709 change_host_trust (cp, (int) ret);
710 return -1; /* not enough resources */
714 GNUNET_STATISTICS_update (GSF_stats,
715 gettext_noop ("# requests done for a price (normal load)"),
725 * The priority level imposes a bound on the maximum
726 * value for the ttl that can be requested.
728 * @param ttl_in requested ttl
729 * @param prio given priority
730 * @return ttl_in if ttl_in is below the limit,
731 * otherwise the ttl-limit for the given priority
734 bound_ttl (int32_t ttl_in, uint32_t prio)
736 unsigned long long allowed;
740 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
741 if (ttl_in > allowed)
743 if (allowed >= (1 << 30))
752 * Handle P2P "QUERY" message. Creates the pending request entry
753 * and sets up all of the data structures to that we will
754 * process replies properly. Does not initiate forwarding or
755 * local database lookups.
757 * @param other the other peer involved (sender or receiver, NULL
758 * for loopback messages where we are both sender and receiver)
759 * @param message the actual message
760 * @return pending request handle, NULL on error
762 struct GSF_PendingRequest *
763 GSF_handle_p2p_query_ (const struct GNUNET_PeerIdentity *other,
764 const struct GNUNET_MessageHeader *message)
766 struct GSF_PendingRequest *pr;
767 struct GSF_PendingRequestData *prd;
768 struct GSF_ConnectedPeer *cp;
769 struct GSF_ConnectedPeer *cps;
770 const GNUNET_HashCode *namespace;
771 const struct GNUNET_PeerIdentity *target;
772 enum GSF_PendingRequestOptions options;
774 const struct GetMessage *gm;
776 const GNUNET_HashCode *opt;
779 uint32_t ttl_decrement;
782 enum GNUNET_BLOCK_Type type;
785 msize = ntohs(message->size);
786 if (msize < sizeof (struct GetMessage))
791 gm = (const struct GetMessage*) message;
793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
794 "Received request for `%s'\n",
795 GNUNET_h2s (&gm->query));
797 type = ntohl (gm->type);
798 bm = ntohl (gm->hash_bitmap);
806 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
811 opt = (const GNUNET_HashCode*) &gm[1];
812 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
813 /* bfsize must be power of 2, check! */
814 if (0 != ( (bfsize - 1) & bfsize))
819 GSF_cover_query_count++;
820 bm = ntohl (gm->hash_bitmap);
822 cps = GNUNET_CONTAINER_multihashmap_get (cp_map,
826 /* peer must have just disconnected */
827 GNUNET_STATISTICS_update (GSF_stats,
828 gettext_noop ("# requests dropped due to initiator not being connected"),
833 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
834 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
841 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
844 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848 "Failed to find peer `%4s' in connection set. Dropping query.\n",
851 GNUNET_STATISTICS_update (GSF_stats,
852 gettext_noop ("# requests dropped due to missing reverse route"),
857 /* note that we can really only check load here since otherwise
858 peers could find out that we are overloaded by not being
859 disconnected after sending us a malformed query... */
860 priority = bound_priority (ntohl (gm->priority), cps);
864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
865 "Dropping query from `%s', this peer is too busy.\n",
871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
873 GNUNET_h2s (&gm->query),
878 namespace = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) ? &opt[bits++] : NULL;
879 target = (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? ((const struct GNUNET_PeerIdentity*) &opt[bits++]) : NULL;
882 if ( (GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1 + priority)) ||
883 (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) >
884 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)) )
886 /* don't have BW to send to peer, or would likely take longer than we have for it,
887 so at best indirect the query */
889 options |= GSF_PRO_FORWARD_ONLY;
890 spid = GNUNET_PEER_intern (other);
892 ttl = bound_ttl (ntohl (gm->ttl), priority);
893 /* decrement ttl (always) */
894 ttl_decrement = 2 * TTL_DECREMENT +
895 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
898 (((int32_t)(ttl - ttl_decrement)) > 0) )
901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
902 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
907 GNUNET_STATISTICS_update (GSF_stats,
908 gettext_noop ("# requests dropped due TTL underflow"),
911 /* integer underflow => drop (should be very rare)! */
914 ttl -= ttl_decrement;
916 /* test if the request already exists */
917 pr = GNUNET_CONTAINER_multihashmap_get (cp->request_map,
921 prd = GSF_pending_request_get_data_ (pr);
922 if ( (prd->type == type) &&
923 ( (type != GNUNET_BLOCK_TYPE_FS_SBLOCK) ||
924 (0 == memcmp (&prd->namespace,
926 sizeof (GNUNET_HashCode))) ) )
928 if (prd->ttl.abs_value >= GNUNET_TIME_absolute_get().abs_value + ttl)
930 /* existing request has higher TTL, drop new one! */
931 prd->priority += priority;
933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934 "Have existing request with higher TTL, dropping new request.\n",
937 GNUNET_STATISTICS_update (GSF_stats,
938 gettext_noop ("# requests dropped due to higher-TTL request"),
943 /* existing request has lower TTL, drop old one! */
944 priority += prd->priority;
945 GSF_pending_request_cancel_ (pr);
946 GNUNET_assert (GNUNET_YES ==
947 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
953 pr = GSF_pending_request_create_ (options,
958 (bfsize > 0) ? (const char*)&opt[bits] : NULL,
960 ntohl (gm->filter_mutator),
965 NULL, 0, /* replies_seen */
968 GNUNET_break (GNUNET_OK ==
969 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
972 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
973 GNUNET_STATISTICS_update (GSF_stats,
974 gettext_noop ("# P2P searches received"),
977 GNUNET_STATISTICS_update (GSF_stats,
978 gettext_noop ("# P2P searches active"),
986 * Function called if there has been a timeout trying to satisfy
987 * a transmission request.
989 * @param cls the 'struct GSF_PeerTransmitHandle' of the request
990 * @param tc scheduler context
993 peer_transmit_timeout (void *cls,
994 const struct GNUNET_SCHEDULER_TaskContext *tc)
996 struct GSF_PeerTransmitHandle *pth = cls;
997 struct GSF_ConnectedPeer *cp;
999 pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1001 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1004 if (GNUNET_YES == pth->is_query)
1005 GNUNET_assert (0 < cp->ppd.pending_queries--);
1006 else if (GNUNET_NO == pth->is_query)
1007 GNUNET_assert (0 < cp->ppd.pending_replies--);
1008 GNUNET_LOAD_update (cp->ppd.transmission_delay,
1010 pth->gmc (pth->gmc_cls,
1017 * Transmit a message to the given peer as soon as possible.
1018 * If the peer disconnects before the transmission can happen,
1019 * the callback is invoked with a 'NULL' buffer.
1021 * @param cp target peer
1022 * @param is_query is this a query (GNUNET_YES) or content (GNUNET_NO) or neither (GNUNET_SYSERR)
1023 * @param priority how important is this request?
1024 * @param timeout when does this request timeout (call gmc with error)
1025 * @param size number of bytes we would like to send to the peer
1026 * @param gmc function to call to get the message
1027 * @param gmc_cls closure for gmc
1028 * @return handle to cancel request
1030 struct GSF_PeerTransmitHandle *
1031 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1034 struct GNUNET_TIME_Relative timeout,
1036 GSF_GetMessageCallback gmc,
1039 struct GSF_PeerTransmitHandle *pth;
1040 struct GSF_PeerTransmitHandle *pos;
1041 struct GSF_PeerTransmitHandle *prev;
1042 struct GNUNET_PeerIdentity target;
1046 pth = GNUNET_malloc (sizeof (struct GSF_PeerTransmitHandle));
1047 pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1048 pth->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1050 pth->gmc_cls = gmc_cls;
1052 pth->is_query = is_query;
1053 pth->priority = priority;
1055 /* insertion sort (by priority, descending) */
1058 while ( (pos != NULL) &&
1059 (pos->priority > priority) )
1065 GNUNET_CONTAINER_DLL_insert (cp->pth_head,
1069 GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1073 GNUNET_PEER_resolve (cp->ppd.pid,
1075 if (GNUNET_YES == is_query)
1077 /* query, need reservation */
1078 cp->ppd.pending_queries++;
1079 if (NULL == cp->irc)
1081 /* reservation already done! */
1082 is_ready = GNUNET_YES;
1083 ip = cp->inc_preference;
1084 cp->inc_preference = 0;
1085 cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
1087 GNUNET_TIME_UNIT_FOREVER_REL,
1088 GNUNET_BANDWIDTH_VALUE_MAX,
1091 &core_reserve_callback,
1096 /* still waiting for reservation */
1097 is_ready = GNUNET_NO;
1100 else if (GNUNET_NO == is_query)
1102 /* no reservation needed for content */
1103 cp->ppd.pending_replies++;
1104 is_ready = GNUNET_YES;
1108 /* not a query or content, no reservation needed */
1109 is_ready = GNUNET_YES;
1113 pth->cth = GNUNET_CORE_notify_transmit_ready (GSF_core,
1119 &peer_transmit_ready_cb,
1121 /* pth->cth could be NULL here, that's OK, we'll try again
1124 if (pth->cth == NULL)
1126 /* if we're waiting for reservation OR if we could not do notify_transmit_ready,
1127 install a timeout task to be on the safe side */
1128 pth->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
1129 &peer_transmit_timeout,
1137 * Cancel an earlier request for transmission.
1139 * @param pth request to cancel
1142 GSF_peer_transmit_cancel_ (struct GSF_PeerTransmitHandle *pth)
1144 struct GSF_ConnectedPeer *cp;
1146 if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1148 GNUNET_SCHEDULER_cancel (pth->timeout_task);
1149 pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1151 if (NULL != pth->cth)
1153 GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
1157 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1160 if (GNUNET_YES == pth->is_query)
1161 GNUNET_assert (0 < cp->ppd.pending_queries--);
1162 else if (GNUNET_NO == pth->is_query)
1163 GNUNET_assert (0 < cp->ppd.pending_replies--);
1169 * Report on receiving a reply; update the performance record of the given peer.
1171 * @param cp responding peer (will be updated)
1172 * @param request_time time at which the original query was transmitted
1173 * @param request_priority priority of the original request
1176 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1177 struct GNUNET_TIME_Absolute request_time,
1178 uint32_t request_priority)
1180 struct GNUNET_TIME_Relative delay;
1182 delay = GNUNET_TIME_absolute_get_duration (request_time);
1183 cp->ppd.avg_reply_delay.rel_value = (cp->ppd.avg_reply_delay.rel_value * (RUNAVG_DELAY_N-1) + delay.rel_value) / RUNAVG_DELAY_N;
1184 cp->ppd.avg_priority = (cp->ppd.avg_priority * (RUNAVG_DELAY_N-1) + request_priority) / RUNAVG_DELAY_N;
1189 * Report on receiving a reply in response to an initiating client.
1190 * Remember that this peer is good for this client.
1192 * @param cp responding peer (will be updated)
1193 * @param initiator_client local client on responsible for query
1196 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1197 struct GSF_LocalClient *initiator_client)
1199 cp->ppd.last_client_replies[cp->last_client_replies_woff++ % CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1204 * Report on receiving a reply in response to an initiating peer.
1205 * Remember that this peer is good for this initiating peer.
1207 * @param cp responding peer (will be updated)
1208 * @param initiator_peer other peer responsible for query
1211 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1212 const struct GSF_ConnectedPeer *initiator_peer)
1214 GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
1215 cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff++ % P2P_SUCCESS_LIST_SIZE] = initiator_peer->ppd.pid;
1216 GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1221 * Method called whenever a given peer has a status change.
1223 * @param cls closure
1224 * @param peer peer identity this notification is about
1225 * @param bandwidth_in available amount of inbound bandwidth
1226 * @param bandwidth_out available amount of outbound bandwidth
1227 * @param timeout absolute time when this peer will time out
1228 * unless we see some further activity from it
1229 * @param atsi status information
1232 GSF_peer_status_handler_ (void *cls,
1233 const struct GNUNET_PeerIdentity *peer,
1234 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1235 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1236 struct GNUNET_TIME_Absolute timeout,
1237 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1239 struct GSF_ConnectedPeer *cp;
1241 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1243 GNUNET_assert (NULL != cp);
1244 update_atsi (cp, atsi);
1249 * Cancel all requests associated with the peer.
1252 * @param query hash code of the request
1253 * @param value the 'struct GSF_PendingRequest'
1254 * @return GNUNET_YES (continue to iterate)
1257 cancel_pending_request (void *cls,
1258 const GNUNET_HashCode *query,
1261 struct GSF_PendingRequest *pr = value;
1263 GSF_pending_request_cancel_ (pr);
1269 * A peer disconnected from us. Tear down the connected peer
1273 * @param peer identity of peer that connected
1276 GSF_peer_disconnect_handler_ (void *cls,
1277 const struct GNUNET_PeerIdentity *peer)
1279 struct GSF_ConnectedPeer *cp;
1280 struct GSF_PeerTransmitHandle *pth;
1282 cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1285 return; /* must have been disconnect from core with
1286 'peer' == my_id, ignore */
1287 GNUNET_CONTAINER_multihashmap_remove (cp_map,
1290 if (NULL != cp->migration_pth)
1292 GSF_peer_transmit_cancel_ (cp->migration_pth);
1293 cp->migration_pth = NULL;
1295 if (NULL != cp->irc)
1297 GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1300 GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1301 &cancel_pending_request,
1303 GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1304 cp->request_map = NULL;
1305 GSF_plan_notify_peer_disconnect_ (cp);
1306 GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1307 GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1308 while (NULL != (pth = cp->pth_head))
1310 if (NULL != pth->cth)
1312 GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
1315 GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1320 GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1321 if (GNUNET_SCHEDULER_NO_TASK != cp->mig_revive_task)
1323 GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1324 cp->mig_revive_task = GNUNET_SCHEDULER_NO_TASK;
1331 * Closure for 'call_iterator'.
1333 struct IterationContext
1336 * Function to call on each entry.
1338 GSF_ConnectedPeerIterator it;
1348 * Function that calls the callback for each peer.
1350 * @param cls the 'struct IterationContext*'
1351 * @param key identity of the peer
1352 * @param value the 'struct GSF_ConnectedPeer*'
1353 * @return GNUNET_YES to continue iteration
1356 call_iterator (void *cls,
1357 const GNUNET_HashCode *key,
1360 struct IterationContext *ic = cls;
1361 struct GSF_ConnectedPeer *cp = value;
1364 (const struct GNUNET_PeerIdentity*) key,
1372 * Iterate over all connected peers.
1374 * @param it function to call for each peer
1375 * @param it_cls closure for it
1378 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1381 struct IterationContext ic;
1385 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1392 * Obtain the identity of a connected peer.
1394 * @param cp peer to reserve bandwidth from
1395 * @param id identity to set (written to)
1398 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1399 struct GNUNET_PeerIdentity *id)
1401 GNUNET_PEER_resolve (cp->ppd.pid,
1407 * Assemble a migration stop message for transmission.
1409 * @param cls the 'struct GSF_ConnectedPeer' to use
1410 * @param size number of bytes we're allowed to write to buf
1411 * @param buf where to copy the message
1412 * @return number of bytes copied to buf
1415 create_migration_stop_message (void *cls,
1419 struct GSF_ConnectedPeer *cp = cls;
1420 struct MigrationStopMessage msm;
1422 cp->migration_pth = NULL;
1425 GNUNET_assert (size > sizeof (struct MigrationStopMessage));
1426 msm.header.size = htons (sizeof (struct MigrationStopMessage));
1427 msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1428 msm.duration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (cp->last_migration_block));
1429 memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1430 return sizeof (struct MigrationStopMessage);
1435 * Ask a peer to stop migrating data to us until the given point
1438 * @param cp peer to ask
1439 * @param block_time until when to block
1442 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1443 struct GNUNET_TIME_Relative block_time)
1445 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value > block_time.rel_value)
1446 return; /* already blocked */
1447 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
1448 if (cp->migration_pth != NULL)
1449 GSF_peer_transmit_cancel_ (cp->migration_pth);
1451 = GSF_peer_transmit_ (cp,
1454 GNUNET_TIME_UNIT_FOREVER_REL,
1455 sizeof (struct MigrationStopMessage),
1456 &create_migration_stop_message,
1462 * Write host-trust information to a file - flush the buffer entry!
1464 * @param cls closure, not used
1465 * @param key host identity
1466 * @param value the 'struct GSF_ConnectedPeer' to flush
1467 * @return GNUNET_OK to continue iteration
1470 flush_trust (void *cls,
1471 const GNUNET_HashCode *key,
1474 struct GSF_ConnectedPeer *cp = value;
1477 struct GNUNET_PeerIdentity pid;
1479 if (cp->ppd.trust == cp->disk_trust)
1480 return GNUNET_OK; /* unchanged */
1481 GNUNET_PEER_resolve (cp->ppd.pid,
1483 fn = get_trust_filename (&pid);
1484 if (cp->ppd.trust == 0)
1486 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1487 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1488 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1492 trust = htonl (cp->ppd.trust);
1493 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1495 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1496 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1497 cp->disk_trust = cp->ppd.trust;
1505 * Notify core about a preference we have for the given peer
1506 * (to allocate more resources towards it). The change will
1507 * be communicated the next time we reserve bandwidth with
1508 * core (not instantly).
1510 * @param cp peer to reserve bandwidth from
1511 * @param pref preference change
1514 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1517 cp->inc_preference += pref;
1522 * Call this method periodically to flush trust information to disk.
1524 * @param cls closure, not used
1525 * @param tc task context, not used
1528 cron_flush_trust (void *cls,
1529 const struct GNUNET_SCHEDULER_TaskContext *tc)
1534 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1539 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1541 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ,
1548 * Initialize peer management subsystem.
1551 GSF_connected_peer_init_ ()
1553 cp_map = GNUNET_CONTAINER_multihashmap_create (128);
1554 GNUNET_assert (GNUNET_OK ==
1555 GNUNET_CONFIGURATION_get_value_filename (GSF_cfg,
1559 GNUNET_DISK_directory_create (trustDirectory);
1560 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1561 &cron_flush_trust, NULL);
1566 * Iterator to free peer entries.
1568 * @param cls closure, unused
1569 * @param key current key code
1570 * @param value value in the hash map (peer entry)
1571 * @return GNUNET_YES (we should continue to iterate)
1574 clean_peer (void *cls,
1575 const GNUNET_HashCode * key,
1578 GSF_peer_disconnect_handler_ (NULL,
1579 (const struct GNUNET_PeerIdentity*) key);
1585 * Shutdown peer management subsystem.
1588 GSF_connected_peer_done_ ()
1590 cron_flush_trust (NULL, NULL);
1591 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1594 GNUNET_CONTAINER_multihashmap_destroy (cp_map);
1596 GNUNET_free (trustDirectory);
1597 trustDirectory = NULL;
1602 * Iterator to remove references to LC entry.
1604 * @param cls the 'struct GSF_LocalClient*' to look for
1605 * @param key current key code
1606 * @param value value in the hash map (peer entry)
1607 * @return GNUNET_YES (we should continue to iterate)
1610 clean_local_client (void *cls,
1611 const GNUNET_HashCode * key,
1614 const struct GSF_LocalClient *lc = cls;
1615 struct GSF_ConnectedPeer *cp = value;
1618 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1619 if (cp->ppd.last_client_replies[i] == lc)
1620 cp->ppd.last_client_replies[i] = NULL;
1626 * Notification that a local client disconnected. Clean up all of our
1627 * references to the given handle.
1629 * @param lc handle to the local client (henceforth invalid)
1632 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1634 GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1635 &clean_local_client,
1640 /* end of gnunet-service-fs_cp.c */