bittorrent

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: BSD-2-Clause Imports: 12 Imported by: 0

Documentation

Overview

Package bittorrent implements all of the abstractions used to decouple the protocol of a BitTorrent tracker from the logic of handling Announces and Scrapes.

Index

Constants

View Source
const (
	// None is the event when a BitTorrent client announces due to time lapsed
	// since the previous announce.
	None Event = iota

	// Started is the event sent by a BitTorrent client when it joins a swarm.
	Started

	// Stopped is the event sent by a BitTorrent client when it leaves a swarm.
	Stopped

	// Completed is the event sent by a BitTorrent client when it finishes
	// downloading all of the required chunks.
	Completed

	// NoneStr string representation of None event
	NoneStr = "none"

	// StartedStr string representation of Started event
	StartedStr = "started"

	// StoppedStr string representation of Stopped event
	StoppedStr = "stopped"

	// CompletedStr string representation of Completed event
	CompletedStr = "completed"
)
View Source
const (
	// InfoHashV1Len is the same as sha1.Size
	InfoHashV1Len = sha1.Size
	// InfoHashV2Len ... sha256.Size
	InfoHashV2Len = sha256.Size
)
View Source
const PeerIDLen = 20

PeerIDLen is length of peer id field in bytes

Variables

View Source
var (

	// ErrInvalidIP indicates an invalid IP for an Announce.
	ErrInvalidIP = ClientError("invalid IP")

	// ErrInvalidPort indicates an invalid Port for an Announce.
	ErrInvalidPort = ClientError("invalid port")
)
View Source
var ErrInvalidHashSize = fmt.Errorf("info hash must be either %d (for torrent V1) or %d (V2) bytes or same sizes x2 (if HEX encoded)", InfoHashV1Len, InfoHashV2Len)

ErrInvalidHashSize holds error about invalid InfoHash size

View Source
var ErrInvalidPeerIDSize = fmt.Errorf("peer ID must be %d bytes", PeerIDLen)

ErrInvalidPeerIDSize holds error about invalid PeerID size

View Source
var ErrUnknownEvent = ClientError("unknown event")

ErrUnknownEvent is returned when New fails to return an event.

View Source
var RouteParamsKey = routeParamsKey{}

RouteParamsKey is a key for the context of a request that contains the named parameters from the http router.

Functions

func InjectRouteParamsToContext added in v0.0.4

func InjectRouteParamsToContext(ctx context.Context, rp RouteParams) context.Context

InjectRouteParamsToContext returns new context with specified RouteParams placed in RouteParamsKey key

func RemapRouteParamsToBgContext added in v0.0.4

func RemapRouteParamsToBgContext(inCtx context.Context) context.Context

RemapRouteParamsToBgContext returns new context with context.Background parent and copied RouteParams from inCtx

func SanitizeAnnounce

func SanitizeAnnounce(r *AnnounceRequest, maxNumWant, defaultNumWant uint32, filterPrivate bool) error

SanitizeAnnounce enforces a max and default NumWant and coerces the peer's IP address into the proper format.

func SanitizeScrape

func SanitizeScrape(r *ScrapeRequest, maxScrapeInfoHashes uint32, filterPrivate bool) error

SanitizeScrape enforces a max number of infohashes for a single scrape request and checks if addresses are valid.

Types

type AnnounceRequest

type AnnounceRequest struct {
	Event           Event
	InfoHash        InfoHash
	EventProvided   bool
	NumWantProvided bool
	NumWant         uint32
	Left            uint64
	Downloaded      uint64
	Uploaded        uint64

	RequestPeer
	Params
}

AnnounceRequest represents the parsed parameters from an announce request.

func (AnnounceRequest) MarshalZerologObject

func (r AnnounceRequest) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type AnnounceResponse

type AnnounceResponse struct {
	Complete    uint32
	Incomplete  uint32
	Interval    time.Duration
	MinInterval time.Duration
	IPv4Peers   Peers
	IPv6Peers   Peers
}

AnnounceResponse represents the parameters used to create an announce response.

func (AnnounceResponse) MarshalZerologObject

func (r AnnounceResponse) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type ClientError

type ClientError string

ClientError represents an error that should be exposed to the client over the BitTorrent protocol implementation.

func (ClientError) Error

func (c ClientError) Error() string

Error implements the error interface for ClientError.

type Event

type Event uint8

Event represents an event done by a BitTorrent client.

func NewEvent

func NewEvent(eventStr string) (evt Event, err error)

NewEvent returns the proper Event given a string.

func (Event) String

func (e Event) String() (s string)

String implements Stringer for an event.

type InfoHash

type InfoHash string

InfoHash represents an infohash.

func NewInfoHash

func NewInfoHash(data []byte) (InfoHash, error)

NewInfoHash creates an InfoHash from raw/hex byte slice.

func NewInfoHashString added in v0.0.4

func NewInfoHashString(data string) (InfoHash, error)

NewInfoHashString creates an InfoHash from raw/hex string.

func (InfoHash) Bytes added in v0.0.4

func (i InfoHash) Bytes() []byte

Bytes returns slice of bytes represents this InfoHash

func (InfoHash) RawString

func (i InfoHash) RawString() string

RawString returns a string of the raw bytes of the InfoHash.

func (InfoHash) String

func (i InfoHash) String() string

String implements fmt.Stringer, returning the base16 encoded InfoHash.

func (InfoHash) TruncateV1

func (i InfoHash) TruncateV1() InfoHash

TruncateV1 returns truncated to 20-bytes length array of the corresponding InfoHash. If InfoHash is V2 (32 bytes), it will be truncated to 20 bytes according to BEP52.

type InfoHashes

type InfoHashes []InfoHash

InfoHashes wrapper of array of InfoHash-es

func (InfoHashes) MarshalZerologArray

func (i InfoHashes) MarshalZerologArray(a *zerolog.Array)

MarshalZerologArray writes array elements to zerolog event

type Params

type Params interface {
	// GetString returns a string parsed from a query. Every key can be
	// returned as a string because they are encoded in the URL as strings.
	GetString(key string) (string, bool)

	zerolog.LogObjectMarshaler
}

Params is used to fetch (optional) request parameters from an Announce. For HTTP Announces this includes the request path and parsed query, for UDP Announces this is the extracted path and parsed query from optional URLData as specified in BEP41.

See ParseURLData for specifics on parsing and limitations.

type Peer

type Peer struct {
	ID PeerID
	netip.AddrPort
}

Peer represents the connection details of a peer that is returned in an announce response.

func (Peer) Addr

func (p Peer) Addr() netip.Addr

Addr returns unmapped peer's IP address

func (Peer) MarshalZerologObject

func (p Peer) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type PeerID

type PeerID [PeerIDLen]byte

PeerID represents a peer ID.

func NewPeerID

func NewPeerID(b []byte) (PeerID, error)

NewPeerID creates a PeerID from a byte slice.

It panics if b is not 20 bytes long.

func (PeerID) Bytes added in v0.0.4

func (p PeerID) Bytes() []byte

Bytes returns slice of bytes represents this PeerID

func (PeerID) RawString

func (p PeerID) RawString() string

RawString returns a 20-byte string of the raw bytes of the ID.

func (PeerID) String

func (p PeerID) String() string

String implements fmt.Stringer, returning the base16 encoded PeerID.

type Peers

type Peers []Peer

Peers wrapper of array of Peer-s

func (Peers) MarshalZerologArray

func (p Peers) MarshalZerologArray(a *zerolog.Array)

MarshalZerologArray writes array elements to zerolog event

type RequestAddress

type RequestAddress struct {
	netip.Addr
	Provided bool
}

RequestAddress wrapper for netip.Addr with Provided flag. Used in RequestAddresses to determine addresses priority

func (RequestAddress) IsValid added in v0.0.3

func (a RequestAddress) IsValid() bool

IsValid checks if netip.Addr is valid, not unspecified and not multicast

func (RequestAddress) MarshalZerologObject

func (a RequestAddress) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type RequestAddresses

type RequestAddresses []RequestAddress

RequestAddresses is an array of RequestAddress used mainly for sort.Interface implementation. Frontends may determine peer's address from connections info or from provided values or combine these addresses to fetch maximum connection information about peer

func (*RequestAddresses) Add

func (aa *RequestAddresses) Add(a RequestAddress)

Add checks if provided RequestAddress is valid and adds unmapped netip.Addr to array

func (*RequestAddresses) GetFirst

func (aa *RequestAddresses) GetFirst() netip.Addr

GetFirst returns first address from array or empty netip.Addr if array is empty

func (*RequestAddresses) Len

func (aa *RequestAddresses) Len() int

func (*RequestAddresses) Less

func (aa *RequestAddresses) Less(i, j int) bool

Less returns true only if i-th RequestAddress is marked as RequestAddress.Provided and j-th is not (provided address has higher priority)

func (*RequestAddresses) MarshalZerologArray

func (aa *RequestAddresses) MarshalZerologArray(a *zerolog.Array)

MarshalZerologArray writes array elements to zerolog event

func (*RequestAddresses) Sanitize added in v0.0.3

func (aa *RequestAddresses) Sanitize(ignorePrivate bool) bool

Sanitize checks if array is not empty and at least one RequestAddress is valid, then make them unique and sorts with RequestAddresses.Less rule. If ignorePrivate set to true, function will preserve only global unicast and non-private (see netip.IsGlobalUnicast and netip.IsPrivate) addresses. If there are no valid and global (if ignorePrivate checked) addresses in array, function returns false and empty receiver.

func (*RequestAddresses) Swap

func (aa *RequestAddresses) Swap(i, j int)

type RequestPeer

type RequestPeer struct {
	ID   PeerID
	Port uint16
	RequestAddresses
}

RequestPeer is bundle of peer ID, provided or determined addresses and net port

func (RequestPeer) MarshalZerologObject

func (rp RequestPeer) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

func (RequestPeer) Peers

func (rp RequestPeer) Peers() (peers Peers)

Peers constructs array of Peer-s with the same ID and Port for every RequestAddress array.

type RouteParam

type RouteParam struct {
	Key   string
	Value string
}

RouteParam is a type that contains the values from the named parameters on the route.

type RouteParams

type RouteParams []RouteParam

RouteParams is a collection of RouteParam instances.

func (RouteParams) ByName

func (rp RouteParams) ByName(name string) string

ByName returns the value of the first RouteParam that matches the given name. If no matching RouteParam is found, an empty string is returned. In the event that a "catch-all" parameter is provided on the route and no value is matched, an empty string is returned. For example: a route of "/announce/*param" matches on "/announce/". However, ByName("param") will return an empty string.

type Scrape

type Scrape struct {
	InfoHash   InfoHash
	Snatches   uint32
	Complete   uint32
	Incomplete uint32
}

Scrape represents the state of a swarm that is returned in a scrape response.

func (Scrape) MarshalZerologObject

func (s Scrape) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type ScrapeRequest

type ScrapeRequest struct {
	// RequestAddresses not used in internal logic,
	// but MAY be used in middleware (per-ip block etc.)
	RequestAddresses
	InfoHashes InfoHashes
	Params     Params
}

ScrapeRequest represents the parsed parameters from a scrape request.

func (ScrapeRequest) MarshalZerologObject

func (r ScrapeRequest) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type ScrapeResponse

type ScrapeResponse struct {
	Data Scrapes
}

ScrapeResponse represents the parameters used to create a scrape response.

The Scrapes must be in the same order as the InfoHashes in the corresponding ScrapeRequest.

func (ScrapeResponse) MarshalZerologObject

func (sr ScrapeResponse) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject writes fields into zerolog event

type Scrapes

type Scrapes []Scrape

Scrapes wrapper of array of Scrape-s

func (Scrapes) MarshalZerologArray

func (s Scrapes) MarshalZerologArray(a *zerolog.Array)

MarshalZerologArray writes array elements to zerolog event

Jump to

Keyboard shortcuts

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