peerWire

package
v1.64.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MPL-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package peerWire holds what can be known about a BitTorrent peer purely from the wire messages exchanged with it. It has no knowledge of Client or Torrent, so the rules for each message can be tested in isolation. Side effects on the rest of the client (piece availability, request updates, metrics) are left to the caller, which is told what changed.

Index

Constants

View Source
const (
	// BEP 11: "Clients must batch updates to send no more than 1 PEX message per minute." We allow
	// some slack.
	PexMinRecvInterval = 45 * time.Second
	// Most added peers used from each address family of a received PEX message. BEP 11 asks
	// senders for no more than 50 per message.
	MaxPexAddedPerMessage = 100
	// Most live connections recorded as purported by the peer.
	MaxPexRemoteLiveConns = 1000
)
View Source
const (
	PexSendInterval = time.Minute
	// Most peers we track having advertised to one peer. Past this, further peers aren't added.
	MaxPexAdvertised = 10000
)
View Source
const MaxHashRequestLength = 512

BEP 52: "Length SHOULD NOT be greater than 512."

View Source
const MaxPeerAllowedFast = 256

Most pieces a peer may allow us while choked. BEP 6 doesn't bound the Allowed Fast set, but it's generated as a small set (libtorrent and others use around 10), and without a bound a peer could grow the set without limit before we know the piece count.

View Source
const MaxSentRendezvous = 64

Most rendezvous awaiting a reply through one relay. The BEP says the relay SHOULD reply, so this bounds what a relay that doesn't can make us hold.

Variables

View Source
var ErrDuplicateRequest = errors.New("received duplicate request with fast enabled")
View Source
var ErrUnexpectedChunk = errors.New("received unexpected chunk")
View Source
var ErrUnrequestedPiece = errors.New("piece doesn't match an outstanding request from the peer")

Functions

func CheckHashRequest

func CheckHashRequest(hr HashRequest, baseLayer pp.Integer) error

CheckHashRequest applies the BEP 52 rules to a hash request: "Length MUST be equal-to-or-greater-than two and a power of two", "Index MUST be a multiple of length", and length SHOULD NOT exceed 512. We only serve baseLayer, the piece layer, and no proof layers. An error means the request should be rejected with Hash Reject.

func IsTransmission

func IsTransmission(id types.PeerID) bool

IsTransmission returns whether the peer ID uses Transmission's -TRxyzb- scheme (https://github.com/transmission/transmission/blob/7ec7607bbcf0fa99bd4b157b9b0f0c411d59f45d/CMakeLists.txt#L128-L149).

func MeetsMinExtensions

func MeetsMinExtensions(have, min pp.PeerExtensionBits) bool

MeetsMinExtensions returns whether have sets every bit set in min.

func RecvExtendedHandshake

func RecvExtendedHandshake(
	h *ExtendedHandshake,
	d *pp.ExtendedHandshakeMessage,
	maxNames int,
) (newNames []pp.ExtensionName)

RecvExtendedHandshake applies an extended handshake to h. The handshake can be repeated, and later ones update earlier ones. Extension names are peer-controlled, so at most maxNames are tracked. It returns the names seen for the first time. metadata_size isn't handled here because the caller validates it before calling State.RecvMetadataSize.

func RecvHandshake

func RecvHandshake(h *Handshake, res pp.HandshakeResult)

RecvHandshake records the peer's half of a completed handshake.

func RejectsCancels

func RejectsCancels(id types.PeerID, fastEnabled bool) bool

RejectsCancels returns whether a peer with the fast extension enabled answers our Cancel with a Reject or the Piece, as BEP 6 requires. Transmission before 4.0.0 didn't (https://github.com/transmission/transmission/pull/2275).

func UsesOwnExtensionIDs

func UsesOwnExtensionIDs(id types.PeerID) bool

UsesOwnExtensionIDs returns whether the peer ID belongs to a client known to send extended messages with its own extension IDs rather than ours (BEP 10), so they can't be decoded.

Types

type ExtendedHandshake

type ExtendedHandshake struct {
	// The peer's extension map, as sent in their extended handshake.
	PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
	// The 'v' field from the extended handshake, as a string.
	PeerClientName atomic.Value
	// The 'p' field from the extended handshake.
	PeerListenPort int
	// As indicated by 'e' field in extension handshake.
	PeerPrefersEncryption bool
	// Maximum pending requests the peer allows. The 'reqq' field from the extended handshake if
	// given, otherwise a default chosen by the caller.
	PeerMaxRequests int
}

ExtendedHandshake is what the peer has told us in its BEP 10 extended handshakes. The fields are exported because they're promoted into torrent.PeerConn's public API. Update it with RecvExtendedHandshake.

type Handshake

type Handshake struct {
	PeerID             types.PeerID
	PeerExtensionBytes pp.PeerExtensionBits
}

Handshake is what the peer told us in its BEP 3 handshake. The fields are exported because they're promoted into torrent.PeerConn's public API. Set it with RecvHandshake.

type HashRequest

type HashRequest struct {
	PiecesRoot                            [32]byte
	BaseLayer, Index, Length, ProofLayers pp.Integer
}

HashRequest is the payload of a BEP 52 hash request, hashes or hash reject message.

func HashRequestFromMessage

func HashRequestFromMessage(m *pp.Message) HashRequest

func (HashRequest) Message

func (hr HashRequest) Message(t pp.MessageType) pp.Message

Message returns the message of type t with the request's payload.

type PeerRequestAction

type PeerRequestAction int

PeerRequestAction is what to do about a Request from the peer.

const (
	// The request is outstanding. Serve it, or send a Reject and call SentReject.
	PeerRequestServe PeerRequestAction = iota
	// Do nothing.
	PeerRequestIgnore
	// Send a Reject. The request was never outstanding.
	PeerRequestReject
	// Close the connection.
	PeerRequestError
)

type PeerRequestCheck

type PeerRequestCheck int

PeerRequestCheck is the protocol rule a Request from the peer met. See RecvRequest.

const (
	// The request is accepted, subject to the caller's own checks.
	PeerRequestOk PeerRequestCheck = iota
	// The request is already outstanding. With the fast extension that's a protocol error,
	// otherwise it's ignored.
	PeerRequestDuplicate
	// We're choking the peer. It's rejected with the fast extension, otherwise ignored.
	PeerRequestWhileChoking
	// Too many requests are outstanding. It's rejected with the fast extension, otherwise
	// ignored. BEP 6 allows closing the connection.
	PeerRequestQueueFull
)

type PexRecv

type PexRecv struct {
	// Added peers past MaxPexAddedPerMessage for their address family.
	DroppedPastLimit int
	// Added peers that mayDial refused.
	DroppedForScope int
}

PexRecv counts what RecvPex dropped from a message.

type PiecesChange

type PiecesChange struct {
	// The peer had all pieces before the message.
	WasAll bool
	// The peer has all pieces after the message.
	NowAll bool
	// Pieces that are now claimed individually and weren't claimed before.
	Gained roaring.Bitmap
	// Pieces that were claimed individually before and no longer are.
	Lost roaring.Bitmap
}

PiecesChange describes how the pieces a peer claims changed after a Bitfield, HaveAll or HaveNone message. While the peer has all pieces they aren't tracked individually, so moving in or out of that state is reported separately from Gained and Lost.

type Request

type Request = types.Request

Request is a request for a chunk, as sent over the wire.

type State

type State struct {
	// contains filtered or unexported fields
}

State is the per-connection state derived from messages sent to and received from a peer. The zero value is a peer that isn't choking us and hasn't claimed any pieces, which is what non-BitTorrent peers like webseeds want. BitTorrent connections start with NewState.

Piece counts are passed in as g.Option because a peer can send piece messages before we have the torrent info.

func NewState

func NewState() State

NewState returns the state of a BitTorrent connection before any messages: both sides are choking (BEP 3).

func (*State) BestPeerNumPieces

func (s *State) BestPeerNumPieces(numPieces g.Option[int]) int

BestPeerNumPieces returns the best guess at the number of pieces in the torrent.

func (*State) Choking

func (s *State) Choking() bool

Choking returns whether we are choking the peer.

func (*State) ExpectChunk

func (s *State) ExpectChunk(req Request)

ExpectChunk records that a Piece answering req is acceptable, without making a request. Each call allows one Piece. SentRequest does this itself, so this is only for setting up tests.

func (*State) ExpectingChunk

func (s *State) ExpectingChunk(req Request) bool

ExpectingChunk returns whether a Piece answering req would be accepted. Chunks stay acceptable after their request is dropped, since the peer may already have sent them.

func (*State) ExpectsCancelReplies

func (s *State) ExpectsCancelReplies() bool

ExpectsCancelReplies returns whether the peer answers our Cancel with a Reject or the Piece, as BEP 6 requires with the fast extension. Some clients don't: see RejectsCancels.

func (*State) Fast

func (s *State) Fast() bool

Fast returns whether the fast extension (BEP 6) is enabled, which is when both sides set its bit in the handshake.

func (*State) GotInfo

func (s *State) GotInfo(numPieces int)

GotInfo records that we learned the torrent's piece count from its info. Pieces claimed or allowed fast by the peer past the end are dropped. They were never counted towards availability, since that needs the info.

func (*State) Handshook

func (s *State) Handshook(ours pp.PeerExtensionBits, peer Handshake)

Handshook records the completed BEP 3 handshake: the reserved bits we sent, and what the peer sent.

func (*State) HashRequestSent

func (s *State) HashRequestSent(hr HashRequest) bool

HashRequestSent returns whether we've sent hr, answered or not.

func (*State) HaveAnnounced

func (s *State) HaveAnnounced(piece int) bool

HaveAnnounced returns whether we've told the peer we have the piece.

func (*State) HavePeerRequest

func (s *State) HavePeerRequest(r Request) bool

HavePeerRequest returns whether the peer's request is outstanding.

func (*State) Interested

func (s *State) Interested() bool

Interested returns whether we've told the peer we're interested.

func (*State) LowOnRequests

func (s *State) LowOnRequests() bool

LowOnRequests returns whether there's nothing outstanding with the peer, including cancels awaiting a response.

func (*State) MetadataPieceRequested

func (s *State) MetadataPieceRequested(index int) bool

MetadataPieceRequested returns whether we requested a ut_metadata piece and haven't had the response.

func (*State) NoHavesAnnounced

func (s *State) NoHavesAnnounced() bool

NoHavesAnnounced returns whether we haven't told the peer about any pieces.

func (*State) NumCancelled

func (s *State) NumCancelled() int

NumCancelled returns the number of cancels awaiting a reply.

func (*State) NumFilesReceivingHashes

func (s *State) NumFilesReceivingHashes() int

NumFilesReceivingHashes returns the number of files we have some but not all hashes for.

func (*State) NumPeerPexLiveConns

func (s *State) NumPeerPexLiveConns() int

NumPeerPexLiveConns returns how many live connections the peer has told us of over PEX.

func (*State) NumPeerRequests

func (s *State) NumPeerRequests() int

NumPeerRequests returns how many of the peer's requests are outstanding.

func (*State) NumRequests

func (s *State) NumRequests() int

NumRequests returns the number of outstanding requests, not counting cancelled ones.

func (*State) OutstandingHashRequests

func (s *State) OutstandingHashRequests() iter.Seq[HashRequest]

OutstandingHashRequests iterates our hash requests awaiting a reply. Don't modify the state while iterating.

func (*State) PeerAllowedFast

func (s *State) PeerAllowedFast() *typedRoaring.Bitmap[int]

PeerAllowedFast returns the pieces the peer allows us to request while choked. Don't modify it.

func (*State) PeerChoking

func (s *State) PeerChoking() bool

PeerChoking returns whether the peer is choking us.

func (*State) PeerHasAllPieces

func (s *State) PeerHasAllPieces(numPieces g.Option[int]) (all, known bool)

PeerHasAllPieces returns whether the peer has every piece. known is false if that can't be determined without the number of pieces.

func (*State) PeerHasPiece

func (s *State) PeerHasPiece(piece int, numPieces g.Option[int]) bool

PeerHasPiece returns whether the peer has claimed the piece.

func (*State) PeerInterested

func (s *State) PeerInterested() bool

PeerInterested returns whether the peer has said it is interested in us.

func (*State) PeerMetadataSize

func (s *State) PeerMetadataSize() int

PeerMetadataSize returns the metadata_size from the peer's extended handshake, or 0.

func (*State) PeerMinPieces

func (s *State) PeerMinPieces() int

PeerMinPieces returns the lowest number of pieces the torrent can have, given the pieces the peer has claimed.

func (*State) PeerPexLiveConn

func (s *State) PeerPexLiveConn(addrPort netip.AddrPort) (flags pp.PexPeerFlags, ok bool)

PeerPexLiveConn returns whether the peer has told us over PEX that it's connected to addrPort, and the flags it gave, which are zero if it didn't give any.

func (*State) PeerPieces

func (s *State) PeerPieces() *typedRoaring.Bitmap[int]

PeerPieces returns the pieces the peer has claimed individually. It's empty if the peer sent HaveAll. Don't modify it.

func (*State) PeerRequests

func (s *State) PeerRequests() iter.Seq[Request]

PeerRequests iterates the peer's outstanding requests, in no particular order. Don't modify the state while iterating.

func (*State) PeerSentHaveAll

func (s *State) PeerSentHaveAll() bool

PeerSentHaveAll returns whether the peer's pieces are tracked as "all" rather than individually.

func (*State) PexAdvertised

func (s *State) PexAdvertised(addrPort netip.AddrPort) bool

PexAdvertised returns whether we've told the peer about addrPort and not dropped it since.

func (*State) PexSendWait

func (s *State) PexSendWait(now time.Time) time.Duration

PexSendWait returns how long until a PEX message may be sent to the peer at now.

func (*State) RecvAllowedFast

func (s *State) RecvAllowedFast(piece int, numPieces g.Option[int]) (added bool)

RecvAllowedFast handles an AllowedFast message (BEP 6), which "MAY list pieces that the message sender does not have". Pieces outside the torrent, or past MaxPeerAllowedFast, are ignored and added is false.

func (*State) RecvBitfield

func (s *State) RecvBitfield(bf []bool, numPieces g.Option[int]) (change PiecesChange, err error)

RecvBitfield handles a Bitfield message. bf is the decoded bitfield, which is a whole number of bytes long. Bits past the end of a torrent with known size are ignored.

func (*State) RecvCancel

func (s *State) RecvCancel(r Request) (known, sendReject bool)

RecvCancel handles a Cancel from the peer. known is false if the request wasn't outstanding. It isn't outstanding after this either way. With the fast extension every request gets exactly one reply (BEP 6), so sendReject says to answer the cancel with a Reject.

func (*State) RecvChoke

func (s *State) RecvChoke() (changed bool, droppedRequests []Request)

RecvChoke handles a Choke message. changed is false if the peer was already choking us. Without the fast extension the peer discards our requests (BEP 3), so they're no longer outstanding and are returned as deleted. With it, they stay outstanding until the peer rejects or serves them.

func (*State) RecvChunk

func (s *State) RecvChunk(req Request) (requested, intended bool, err error)

RecvChunk handles a Piece. req is the index, begin and data length of the Piece, which must be exactly what was requested. requested is true if the request was outstanding, and intended is true if it was outstanding or cancelled. A Piece we weren't expecting is an error (BEP 6 says to close the connection).

func (*State) RecvHashReject

func (s *State) RecvHashReject(hr HashRequest) error

RecvHashReject handles a Hash Reject. It's an error if it doesn't answer an outstanding request. The request isn't made again.

func (*State) RecvHashes

func (s *State) RecvHashes(
	hr HashRequest,
	hashes [][32]byte,
	numPieces int,
) (complete [][32]byte, err error)

RecvHashes handles a Hashes message answering hr, for a file with numPieces pieces, which the caller looks up by the pieces root. Once every piece hash for the file has arrived, they're returned for the caller to verify against the pieces root, and forgotten here.

func (*State) RecvHave

func (s *State) RecvHave(piece int, numPieces g.Option[int]) (added bool, err error)

RecvHave handles a Have message. It returns false if the peer already had the piece.

func (*State) RecvHaveAll

func (s *State) RecvHaveAll() PiecesChange

RecvHaveAll handles a HaveAll message (BEP 6).

func (*State) RecvHaveNone

func (s *State) RecvHaveNone() (change PiecesChange)

RecvHaveNone handles a HaveNone message (BEP 6).

func (*State) RecvHolepunchConnect

func (s *State) RecvHolepunchConnect(addr netip.AddrPort) (initiated bool)

RecvHolepunchConnect handles a Connect for addr. initiated is true if it answers our Rendezvous. Otherwise we're the target of someone else's, which needs no prior message.

func (*State) RecvHolepunchError

func (s *State) RecvHolepunchError(addr netip.AddrPort) (solicited bool)

RecvHolepunchError handles an Error for addr. solicited is false if we have no Rendezvous for addr through the peer, since only a relay answering one sends Error.

func (*State) RecvInterested

func (s *State) RecvInterested(interested bool)

RecvInterested handles Interested and NotInterested messages. Requests from the peer aren't cleared on NotInterested since the spec doesn't say to. Choking them does that.

func (*State) RecvMetadataPiece

func (s *State) RecvMetadataPiece(index int) (requested bool)

RecvMetadataPiece records the response to a ut_metadata request. It returns false if we didn't request the piece.

func (*State) RecvMetadataSize

func (s *State) RecvMetadataSize(size int)

RecvMetadataSize records the metadata_size from the peer's extended handshake. The caller validates it.

func (*State) RecvPex

func (s *State) RecvPex(
	rx *pp.PexMsg,
	now time.Time,
	mayDial func(netip.Addr) bool,
) (res PexRecv, err error)

RecvPex applies a PEX message received at now. It's an error if the previous one was less than PexMinRecvInterval earlier, and the message is then ignored. Otherwise rx's added peers are cut to MaxPexAddedPerMessage per family and filtered by mayDial, in place, with flags kept aligned, and the peer's live connections are updated from what remains and from the dropped peers.

func (*State) RecvPort

func (s *State) RecvPort() (first bool)

RecvPort handles a Port message. It returns true only for the first one, so a peer can't make us act on it repeatedly.

func (*State) RecvReject

func (s *State) RecvReject(req Request) (outstanding, ok bool)

RecvReject handles a Reject, which names the request it rejects (BEP 6). outstanding is true if the request hadn't been cancelled. ok is false if we have no such request or cancel, which is a protocol error.

func (*State) RecvRequest

func (s *State) RecvRequest(r Request, maxOutstanding int) (check PeerRequestCheck, action PeerRequestAction)

RecvRequest handles a Request from the peer, applying the protocol rules in order: duplicates, then choking, then at most maxOutstanding outstanding. If the request is accepted it's outstanding until SentPiece, SentReject, RecvCancel or SentChoke.

func (*State) RecvUnchoke

func (s *State) RecvUnchoke() (changed bool)

RecvUnchoke handles an Unchoke message. It returns false if the peer wasn't choking us. Some clients do this, and it isn't treated as an error.

func (*State) RemotePieceCount

func (s *State) RemotePieceCount(numPieces g.Option[int]) int

RemotePieceCount returns how many pieces we think the peer has.

func (*State) RendezvousSent

func (s *State) RendezvousSent(target netip.AddrPort) bool

RendezvousSent returns whether a Rendezvous for target through the peer awaits a reply.

func (*State) RequestCancelled

func (s *State) RequestCancelled(req Request) bool

RequestCancelled returns whether we sent a cancel for the request and are waiting for the peer to reject it or send it anyway.

func (*State) RequestOutstanding

func (s *State) RequestOutstanding(req Request) bool

RequestOutstanding returns whether we have requested a chunk and not had a response, or cancelled the request, or had it dropped.

func (*State) SendPex

func (s *State) SendPex(msg *pp.PexMsg, now time.Time) (send bool)

SendPex prepares msg to be sent to the peer at now, replacing its fields with filtered copies: added peers we've already advertised and dropped peers we haven't are removed, as are duplicates and peers both added and dropped. If anything is left, it's recorded as sent and send is true. It returns false without changing anything if PexSendWait isn't zero.

func (*State) SentBitfield

func (s *State) SentBitfield(pieces *roaring.Bitmap) error

SentBitfield records that we sent Bitfield with the given pieces. It must be the first have-related message.

func (*State) SentCancel

func (s *State) SentCancel(req Request) bool

SentCancel records that we're sending a Cancel for an outstanding request. If the peer acknowledges cancels with Reject or the Piece (BEP 6, see ExpectsCancelReplies), we wait for that before the chunk can be requested again. It returns false if the request wasn't outstanding, in which case there's nothing to send.

func (*State) SentChoke

func (s *State) SentChoke() (changed, droppedPeerRequests bool)

SentChoke records that we're choking the peer. changed is false if we already were, in which case there's nothing to send. Without the fast extension, choking discards the peer's requests (BEP 3), and droppedPeerRequests is true: none are outstanding now.

func (*State) SentHashRequest

func (s *State) SentHashRequest(hr HashRequest) (added bool)

SentHashRequest records that we sent hr. It returns false if it was sent before, whether or not it has been answered, in which case it shouldn't be sent again.

func (*State) SentHave

func (s *State) SentHave(piece int) (added bool)

SentHave records that we're sending Have for a piece. It returns false if the peer already knows, in which case there's nothing to send.

func (*State) SentHaveAll

func (s *State) SentHaveAll(numPieces int)

SentHaveAll records that we sent HaveAll.

func (*State) SentHaveNone

func (s *State) SentHaveNone()

SentHaveNone records that we sent HaveNone.

func (*State) SentInterested

func (s *State) SentInterested(interested bool) (changed bool)

SentInterested records that we're sending Interested or NotInterested. It returns false if that was already the state, in which case there is nothing to send.

func (*State) SentMetadataRequest

func (s *State) SentMetadataRequest(index int) (added bool)

SentMetadataRequest records that we're sending a ut_metadata request for a piece. It returns false if one is already pending.

func (*State) SentPiece

func (s *State) SentPiece(piece Request) error

SentPiece records that we're sending a Piece. piece is its index, begin and data length, which must be exactly one of the peer's outstanding requests, which it then answers. Otherwise it's an error and the Piece mustn't be sent.

func (*State) SentReject

func (s *State) SentReject(r Request) (wasOutstanding bool)

SentReject records that we sent a Reject (BEP 6), which needs the fast extension. It returns whether the request was outstanding: a request can be rejected before it's accepted.

func (*State) SentRendezvous

func (s *State) SentRendezvous(target netip.AddrPort) (ok bool)

SentRendezvous records that we're sending a Rendezvous for target through the peer. It returns false if there are already MaxSentRendezvous awaiting a reply, in which case don't send it. A repeat for the same target is allowed.

func (*State) SentRequest

func (s *State) SentRequest(req Request) (added bool)

SentRequest records that we're sending req. It returns false if it's already outstanding, in which case there's nothing to send. A request can't be sent again while a cancel for it awaits a reply, since the reply would be ambiguous.

func (*State) SentUnchoke

func (s *State) SentUnchoke() (changed bool)

SentUnchoke records that we're unchoking the peer. It returns false if we weren't choking them, in which case there's nothing to send.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL