torrent

package module
v0.0.0-...-90f5931 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2025 License: MPL-2.0 Imports: 60 Imported by: 2

README

torrent

GoDoc

This repository is a refactor of anacrolix's, to simplify the API of the library, use more idiomatic code, improve horizontal scalability, remove extraneous dependencies, and to add in some extended functionality.

improvements implemented by library

  • smaller API surface. simplifying use, while still maintaining almost full functionality provided (some read ahead logic is broken, which is risky anyways due to the data being unvalidated).
  • refactored the single lock used for all torrents out. this means the torrents do not contend with each other for the singe lock.
  • removed a number of panic making the code safer to use (more to do here).
  • ability to use arbitrary socket implementations, as long as they are IP/Port based.

improvements planned

  • performance enhancements.

Installation

Install the library package with go get -u github.com/james-lawrence/torrent, or the provided cmds with go get -u github.com/james-lawrence/torrent/cmd/....

Library examples

There are some small examples in the package documentation.

Help

Communication about the project is through the issue tracker.

torrent

Downloads torrents from the command-line. This first example does not use godo.

$ go get github.com/james-lawrence/torrent/cmd/torrent
# Now 'torrent' should be in $GOPATH/bin, which should be in $PATH.
$ torrent 'magnet:?xt=urn:btih:KRWPCX3SJUM4IMM4YF5RPHL6ANPYTQPU'
ubuntu-14.04.2-desktop-amd64.iso [===================================================================>]  99% downloading (1.0 GB/1.0 GB)
2015/04/01 02:08:20 main.go:137: downloaded ALL the torrents
$ md5sum ubuntu-14.04.2-desktop-amd64.iso
1b305d585b1918f297164add46784116  ubuntu-14.04.2-desktop-amd64.iso
$ echo such amaze
wow
torrentfs

torrentfs mounts a FUSE filesystem at -mountDir. The contents are the torrents described by the torrent files and magnet links at -metainfoDir. Data for read requests is fetched only as required from the torrent network, and stored at -downloadDir.

$ mkdir mnt torrents
$ godo github.com/james-lawrence/torrent/cmd/torrentfs -mountDir=mnt -metainfoDir=torrents &
$ cd torrents
$ wget http://releases.ubuntu.com/14.04.2/ubuntu-14.04.2-desktop-amd64.iso.torrent
$ cd ..
$ ls mnt
ubuntu-14.04.2-desktop-amd64.iso
$ pv mnt/ubuntu-14.04.2-desktop-amd64.iso | md5sum
996MB 0:04:40 [3.55MB/s] [========================================>] 100%
1b305d585b1918f297164add46784116  -
torrent-magnet

Creates a magnet link from a torrent file. Note the extracted trackers, display name, and info hash.

$ godo github.com/james-lawrence/torrent/cmd/torrent-magnet < ubuntu-14.04.2-desktop-amd64.iso.torrent
magnet:?xt=urn:btih:546cf15f724d19c4319cc17b179d7e035f89c1f4&dn=ubuntu-14.04.2-desktop-amd64.iso&tr=http%3A%2F%2Ftorrent.ubuntu.com%3A6969%2Fannounce&tr=http%3A%2F%2Fipv6.torrent.ubuntu.com%3A6969%2Fannounce

Documentation

Overview

Package torrent implements a torrent client

  • simple api.
  • performant.

BitTorrent features implemented include:

  • Protocol obfuscation
  • DHT
  • uTP
  • PEX
  • Magnet links
  • IP Blocklists
  • Some IPv6
  • HTTP and UDP tracker clients
  • BEPs:
  • 3: Basic BitTorrent protocol
  • 5: DHT
  • 6: Fast Extension (have all/none only)
  • 7: IPv6 Tracker Extension
  • 9: ut_metadata
  • 10: Extension protocol
  • 11: PEX
  • 12: Multitracker metadata extension
  • 15: UDP Tracker Protocol
  • 20: Peer ID convention ("-GTnnnn-")
  • 23: Tracker Returns Compact Peer Lists
  • 27: Private torrents
  • 29: uTorrent transport protocol
  • 41: UDP Tracker Protocol Extensions
  • 42: DHT Security extension
  • 43: Read-only DHT Nodes
Example (CustomNetworkProtocols)
package main

import (
	"context"
	"io"
	"log"
	"net"

	"github.com/anacrolix/utp"
	"github.com/james-lawrence/torrent"
	"github.com/james-lawrence/torrent/sockets"
)

func main() {
	var (
		err      error
		metadata torrent.Metadata
	)

	l, err := utp.NewSocket("udp", "0.0.0.0:0")
	if err != nil {
		log.Fatalln(err)
		return
	}
	defer l.Close()

	s := sockets.New(l, &net.Dialer{LocalAddr: l.Addr()})
	c, _ := torrent.NewSocketsBind(s).Bind(torrent.NewClient(torrent.NewDefaultClientConfig(torrent.ClientConfigBootstrapGlobal)))
	defer c.Close()

	if metadata, err = torrent.NewFromMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU"); err != nil {
		log.Fatalln(err)
		return
	}

	dl, _, err := c.Start(metadata)
	if err != nil {
		log.Fatalln(err)
		return
	}

	if _, err = torrent.DownloadInto(context.Background(), io.Discard, dl); err != nil {
		log.Fatalln(err)
		return
	}

	log.Print("torrent downloaded")
}
Output:

Example (Download)
package main

import (
	"context"
	"io"
	"log"

	"github.com/james-lawrence/torrent"
	"github.com/james-lawrence/torrent/autobind"
)

func main() {
	var (
		err      error
		metadata torrent.Metadata
	)

	c, _ := autobind.NewDefaultClient()
	defer c.Close()

	if metadata, err = torrent.NewFromMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU"); err != nil {
		log.Fatalln(err)
		return
	}
	dl, _, err := c.Start(metadata)
	if err != nil {
		log.Fatalln(err)
		return
	}

	if _, err = torrent.DownloadInto(context.Background(), io.Discard, dl); err != nil {
		// if _, err = c.DownloadInto(context.Background(), metadata, io.Discard); err != nil {
		log.Fatalln(err)
		return
	}

	log.Print("torrent downloaded")
}
Output:

Example (FileReader)
package main

import (
	"github.com/james-lawrence/torrent"
)

func main() {
	var f torrent.File
	// Accesses the parts of the torrent pertaining to f. Data will be
	// downloaded as required, per the configuration of the torrent.Reader.
	r := f.NewReader()
	defer r.Close()
}
Output:

Index

Examples

Constants

View Source
const DefaultHTTPUserAgent = "Go-Torrent/1.0"

DefaultHTTPUserAgent ...

View Source
const ErrNoPeers = errorsx.String("failed to locate any peers for torrent")

Variables

This section is empty.

Functions

func ClientConfigBootstrapGlobal

func ClientConfigBootstrapGlobal(c *ClientConfig)

func ClientConfigNoop

func ClientConfigNoop(c *ClientConfig)

useful for default noop configurations.

func DownloadInto

func DownloadInto(ctx context.Context, dst io.Writer, m Torrent, options ...Tuner) (n int64, err error)

Download a torrent into a writer blocking until completion.

func ErrTorrentClosed

func ErrTorrentClosed() error

func NewMagnet

func NewMagnet(md Metadata) metainfo.Magnet

func OptionNoop

func OptionNoop(t *Metadata)

OptionNoop does nothing, stand in during configurations.

func TrackerAnnounceUntil

func TrackerAnnounceUntil(ctx context.Context, t *torrent, donefn func() bool, options ...tracker.AnnounceOption)

func TrackerEvent

func TrackerEvent(ctx context.Context, l Torrent, announceuri string, options ...tracker.AnnounceOption) (ret *tracker.AnnounceResponse, err error)

func TuneAnnounceUntilComplete

func TuneAnnounceUntilComplete(t *torrent)

func TuneAutoDownload

func TuneAutoDownload(t *torrent)

used after info has been received to mark all chunks missing. will only happen if missing and completed are zero.

func TuneNewConns

func TuneNewConns(t *torrent)

force new connections to be found

func TuneVerifyFull

func TuneVerifyFull(t *torrent)

Verify the entirety of the torrent. will block

func Verify

func Verify(ctx context.Context, t Torrent) error

Types

type Binder

type Binder interface {
	// Bind to the given client if err is nil.
	Bind(cl *Client, err error) (*Client, error)
}

Binder binds network sockets to the client.

func NewSocketsBind

func NewSocketsBind(s ...socket) Binder

NewSocketsBind binds a set of sockets to the client. it bypasses any disable checks (tcp,udp, ip4/6) from the configuration.

type Client

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

Client contain zero or more Torrents. A Client manages a blocklist, the TCP/UDP protocol ports, and DHT as desired.

func NewClient

func NewClient(cfg *ClientConfig) (_ *Client, err error)

NewClient create a new client from the provided config. nil is acceptable.

func (*Client) AddDHTNodes

func (cl *Client) AddDHTNodes(nodes []string)

AddDHTNodes adds nodes to the DHT servers.

func (*Client) Bind

func (cl *Client) Bind(s socket) (err error)

Bind the socket to this client.

func (*Client) Close

func (cl *Client) Close()

Close stops the client. All connections to peers are closed and all activity will come to a halt.

func (*Client) Closed

func (cl *Client) Closed() <-chan struct{}

Closed returns a channel to detect when the client is closed.

func (*Client) Config

func (cl *Client) Config() *ClientConfig

Config underlying configuration for the client.

func (*Client) DhtServers

func (cl *Client) DhtServers() []*dht.Server

DhtServers returns the set of DHT servers.

func (*Client) Info

func (cl *Client) Info(ctx context.Context, m Metadata, options ...Tuner) (i *metainfo.Info, err error)

Query torrent info from the dht

func (*Client) ListenAddrs

func (cl *Client) ListenAddrs() (ret []net.Addr)

ListenAddrs addresses currently being listened to.

func (*Client) LocalPort

func (cl *Client) LocalPort() (port int)

LocalPort returns the local port being listened on. WARNING: this method can panic. this is method is odd given a client can be attached to multiple ports on different listeners.

func (*Client) MaybeStart

func (cl *Client) MaybeStart(t Metadata, failed error, options ...Tuner) (dl Torrent, added bool, err error)

MaybeStart is a convience method that consumes the return types of the torrent creation methods: New, NewFromFile, etc. it is all respects identical to the Start method.

func (*Client) PeerID

func (cl *Client) PeerID() PeerID

PeerID ...

func (*Client) Start

func (cl *Client) Start(t Metadata, options ...Tuner) (dl Torrent, added bool, err error)

Start the specified torrent. Start adds starts up the torrent within the client downloading the missing pieces as needed. if you want to wait until the torrent is completed use Download.

func (*Client) Stop

func (cl *Client) Stop(t Metadata) (err error)

Stop the specified torrent, this halts all network activity around the torrent for this client.

func (*Client) String

func (cl *Client) String() string

func (*Client) Torrent

func (cl *Client) Torrent(ih metainfo.Hash) (t Torrent, ok bool)

Torrent returns a handle to the given torrent, if it's present in the client.

func (*Client) Torrents

func (cl *Client) Torrents() []Torrent

Torrents returns handles to all the torrents loaded in the Client.

func (*Client) WaitAll

func (cl *Client) WaitAll() bool

WaitAll returns true when all torrents are completely downloaded and false if the client is stopped before that.

func (*Client) WriteStatus

func (cl *Client) WriteStatus(_w io.Writer)

WriteStatus writes out a human readable status of the client, such as for writing to a HTTP status page.

type ClientConfig

type ClientConfig struct {
	// Store torrent file data in this directory unless .DefaultStorage is
	// specified.
	DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`

	NoDefaultPortForwarding bool
	UpnpID                  string

	DisablePEX bool `long:"disable-pex"`

	// Don't create a DHT.
	NoDHT            bool `long:"disable-dht"`
	DhtStartingNodes func(network string) dht.StartingNodesGetter
	// Never send chunks to peers.
	NoUpload bool `long:"no-upload"`

	// Upload even after there's nothing in it for us. By default uploading is
	// not altruistic, we'll only upload to encourage the peer to reciprocate.
	Seed bool `long:"seed"`
	// Only applies to chunks uploaded to peers, to maintain responsiveness
	// communicating local Client state to peers. Each limiter token
	// represents one byte. The Limiter's burst must be large enough to fit a
	// whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
	UploadRateLimiter *rate.Limiter
	// Rate limits all reads from connections to peers. Each limiter token
	// represents one byte. The Limiter's burst must be bigger than the
	// largest Read performed on a the underlying rate-limiting io.Reader
	// minus one. This is likely to be the larger of the main read loop buffer
	// (~4096), and the requested chunk size (~16KiB, see
	// TorrentSpec.ChunkSize).
	DownloadRateLimiter *rate.Limiter

	// User-provided Client peer ID. If not present, one is generated automatically.
	PeerID string

	HeaderObfuscationPolicy HeaderObfuscationPolicy
	// The crypto methods to offer when initiating connections with header obfuscation.
	CryptoProvides mse.CryptoMethod
	// Chooses the crypto method to use when receiving connections with header obfuscation.
	CryptoSelector mse.CryptoSelector

	// Sets usage of Socks5 Proxy. Authentication should be included in the url if needed.
	// Examples: socks5://demo:demo@192.168.99.100:1080
	// 			 http://proxy.domain.com:3128
	ProxyURL string

	DisableIPv4Peers bool
	Logger           logger // standard logging for errors, defaults to stderr
	Warn             logger // warn logging
	Debug            logger // debug logging, defaults to discard

	// HTTPProxy defines proxy for HTTP requests.
	// Format: func(*Request) (*url.URL, error),
	// or result of http.ProxyURL(HTTPProxy).
	// By default, it is composed from ClientConfig.ProxyURL,
	// if not set explicitly in ClientConfig struct
	HTTPProxy func(*http.Request) (*url.URL, error)
	// HTTPUserAgent changes default UserAgent for HTTP requests
	HTTPUserAgent string
	// Updated occasionally to when there's been some changes to client
	// behaviour in case other clients are assuming anything of us. See also
	// `bep20`.
	ExtendedHandshakeClientVersion string
	// Peer ID client identifier prefix. We'll update this occasionally to
	// reflect changes to client behaviour that other clients may depend on.
	// Also see `extendedHandshakeClientVersion`.
	Bep20 string

	// Peer dial timeout to use when there are limited peers.
	NominalDialTimeout time.Duration
	// Minimum peer dial timeout to use (even if we have lots of peers).
	MinDialTimeout             time.Duration
	EstablishedConnsPerTorrent int
	HalfOpenConnsPerTorrent    int
	// Maximum number of peer addresses in reserve.
	TorrentPeersHighWater int
	// Minumum number of peers before effort is made to obtain more peers.
	TorrentPeersLowWater int

	// Limit how long handshake can take. This is to reduce the lingering
	// impact of a few bad apples. 4s loses 1% of successful handshakes that
	// are obtained with 60s timeout, and 5% of unsuccessful handshakes.
	HandshakesTimeout time.Duration

	// The IP addresses as our peers should see them. May differ from the
	// local interfaces due to NAT or other network configurations.
	PublicIP4 net.IP
	PublicIP6 net.IP

	DisableAcceptRateLimiting bool

	ConnTracker *conntrack.Instance

	connections.Handshaker

	// OnQuery hook func
	DHTOnQuery      func(query *krpc.Msg, source net.Addr) (propagate bool)
	DHTAnnouncePeer func(ih metainfo.Hash, ip net.IP, port int, portOk bool)
	DHTMuxer        dht.Muxer

	ConnectionClosed func(ih metainfo.Hash, stats ConnStats)
	// contains filtered or unexported fields
}

ClientConfig not safe to modify this after it's given to a Client.

func NewDefaultClientConfig

func NewDefaultClientConfig(options ...ClientConfigOption) *ClientConfig

NewDefaultClientConfig default client configuration.

type ClientConfigOption

type ClientConfigOption func(*ClientConfig)

ClientConfigOption options for the client configuration

func ClientConfigBootstrapFn

func ClientConfigBootstrapFn(fn func(n string) dht.StartingNodesGetter) ClientConfigOption

func ClientConfigBootstrapPeerFile

func ClientConfigBootstrapPeerFile(path string) ClientConfigOption

Bootstrap from a file written by dht.WriteNodesToFile

func ClientConfigBucketLimit

func ClientConfigBucketLimit(i int) ClientConfigOption

func ClientConfigCompose

func ClientConfigCompose(options ...ClientConfigOption) ClientConfigOption

func ClientConfigConnectionClosed

func ClientConfigConnectionClosed(fn func(ih metainfo.Hash, stats ConnStats)) ClientConfigOption

func ClientConfigDialRateLimit

func ClientConfigDialRateLimit(l *rate.Limiter) ClientConfigOption

func ClientConfigHTTPUserAgent

func ClientConfigHTTPUserAgent(s string) ClientConfigOption

func ClientConfigInfoLogger

func ClientConfigInfoLogger(l *log.Logger) ClientConfigOption

ClientConfigInfoLogger set the info logger

func ClientConfigMuxer

func ClientConfigMuxer(m dht.Muxer) ClientConfigOption

configure what endpoints the dht's will support.

func ClientConfigPeerID

func ClientConfigPeerID(s string) ClientConfigOption

func ClientConfigSeed

func ClientConfigSeed(b bool) ClientConfigOption

ClientConfigSeed enable/disable seeding

type ConnStats

type ConnStats struct {
	// Total bytes on the wire. Includes handshakes and encryption.
	BytesWritten     count
	BytesWrittenData count

	BytesRead           count
	BytesReadData       count
	BytesReadUsefulData count

	ChunksWritten count

	ChunksRead       count
	ChunksReadUseful count
	ChunksReadWasted count

	MetadataChunksRead count

	// Number of pieces data was written to, that subsequently passed verification.
	PiecesDirtiedGood count
	// Number of pieces data was written to, that subsequently failed
	// verification. Note that a connection may not have been the sole dirtier
	// of a piece.
	PiecesDirtiedBad count

	DHTAnnounce count
}

ConnStats various connection-level metrics. At the Torrent level these are aggregates. Chunks are messages with data payloads. Data is actual torrent content without any overhead. Useful is something we needed locally. Unwanted is something we didn't ask for (but may still be useful). Written is things sent to the peer, and Read is stuff received from them.

func (*ConnStats) Copy

func (t *ConnStats) Copy() (ret ConnStats)

Copy returns a copy of the connection stats.

func (ConnStats) ResetTransferMetrics

func (t ConnStats) ResetTransferMetrics() ConnStats

type File

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

File provides access to regions of torrent data that correspond to its files.

func (*File) BytesCompleted

func (f *File) BytesCompleted() int64

BytesCompleted number of bytes of the entire file we have completed. This is the sum of completed pieces, and dirtied chunks of incomplete pieces.

func (*File) DisplayPath

func (f *File) DisplayPath() string

DisplayPath the relative file path for a multi-file torrent, and the torrent name for a single-file torrent.

func (File) FileInfo

func (f File) FileInfo() metainfo.FileInfo

FileInfo from the metainfo.Info to which this file corresponds.

func (*File) Length

func (f *File) Length() int64

Length the file's length in bytes.

func (*File) NewReader

func (f *File) NewReader() Reader

NewReader returns a reader for the file.

func (*File) Offset

func (f *File) Offset() int64

Offset data for this file begins this many bytes into the Torrent.

func (File) Path

func (f File) Path() string

Path the file's path components joined by '/'.

func (*File) Torrent

func (f *File) Torrent() Torrent

Torrent returns the associated torrent

type Handle

type Handle interface {
	io.Reader
	io.Seeker
	io.Closer
	io.ReaderAt
}

Handle a file-like handle to some torrent data resource.

type HeaderObfuscationPolicy

type HeaderObfuscationPolicy struct {
	RequirePreferred bool // Whether the value of Preferred is a strict requirement.
	Preferred        bool // Whether header obfuscation is preferred.
}

HeaderObfuscationPolicy ...

type IpPort

type IpPort = missinggo.IpPort

type Metadata

type Metadata struct {
	// The tiered tracker URIs.
	Trackers  []string
	ID        metainfo.Hash
	InfoBytes []byte
	// The name to use if the Name field from the Info isn't available.
	DisplayName string
	Webseeds    []string
	DHTNodes    []string
	// The chunk size to use for outbound requests. Defaults to 16KiB if not
	// set.
	ChunkSize int
	Storage   storage.ClientImpl
}

Metadata specifies the metadata of a torrent for adding to a client. There are helpers for magnet URIs and torrent metainfo files.

func New

func New(info metainfo.Hash, options ...Option) (t Metadata, err error)

New create a torrent from the metainfo.MetaInfo and any additional options.

func NewFromFile

func NewFromFile(path string, options ...Option) (t Metadata, err error)

NewFromFile convience method to create a torrent directly from a file.

func NewFromInfo

func NewFromInfo(i metainfo.Info, options ...Option) (t Metadata, err error)

NewFromInfo creates a torrent from metainfo.Info

func NewFromMagnet

func NewFromMagnet(uri string, options ...Option) (t Metadata, err error)

NewFromMagnet creates a torrent from a magnet uri.

func NewFromMetaInfo

func NewFromMetaInfo(mi *metainfo.MetaInfo, options ...Option) (t Metadata, err error)

NewFromMetaInfo create a torrent from metainfo

func NewFromMetaInfoFile

func NewFromMetaInfoFile(path string, options ...Option) (t Metadata, err error)

NewFromMetaInfoFile loads torrent metadata stored in a file.

func (Metadata) Announce

func (t Metadata) Announce() string

grabs random tracker from available.

func (Metadata) Merge

func (t Metadata) Merge(options ...Option) Metadata

Merge Metadata options into the current metadata.

func (Metadata) Metainfo

func (t Metadata) Metainfo() metainfo.MetaInfo

Metainfo generate metainfo from the metadata.

type Option

type Option func(*Metadata)

Option for the torrent.

func OptionChunk

func OptionChunk(s int) Option

OptionChunk sets the size of the chunks to use for outbound requests

func OptionDisplayName

func OptionDisplayName(dn string) Option

OptionDisplayName set the display name for the torrent.

func OptionInfo

func OptionInfo(i []byte) Option

OptionInfo set the info bytes for the torrent.

func OptionNodes

func OptionNodes(nodes ...string) Option

OptionNodes supplimental nodes to add to the dht of the client.

func OptionStorage

func OptionStorage(s storage.ClientImpl) Option

OptionStorage set the storage implementation for the torrent.

func OptionTrackers

func OptionTrackers(trackers ...string) Option

OptionTrackers set the trackers for the torrent.

func OptionWebseeds

func OptionWebseeds(seeds []string) Option

OptionWebseeds set the webseed hosts for the torrent.

type Peer

type Peer struct {
	ID     [20]byte
	IP     net.IP
	Port   int
	Source peerSource
	// Peer is known to support encryption.
	SupportsEncryption bool
	btprotocol.PexPeerFlags
	// Whether we can ignore poor or bad behaviour from the peer.
	Trusted bool
}

Peer connection info, handed about publicly.

func (*Peer) FromPex

func (me *Peer) FromPex(na krpc.NodeAddr, fs btprotocol.PexPeerFlags)

FromPex generate Peer from peer exchange

type PeerExtensionBits

type PeerExtensionBits = pp.ExtensionBits

PeerExtensionBits define what extensions are available.

type PeerID

type PeerID [20]byte

PeerID client ID.

type Peers

type Peers []Peer

func TrackerAnnounceOnce

func TrackerAnnounceOnce(ctx context.Context, l Torrent, uri string, options ...tracker.AnnounceOption) (delay time.Duration, peers Peers, err error)

func (*Peers) AppendFromPex

func (me *Peers) AppendFromPex(nas []krpc.NodeAddr, fs []btprotocol.PexPeerFlags)

func (Peers) AppendFromTracker

func (ret Peers) AppendFromTracker(ps []tracker.Peer) Peers

type Reader

type Reader interface {
	io.Reader
	io.Seeker
	io.Closer
}

Reader for a torrent

func NewReader

func NewReader(t Torrent) Reader

type Stats

type Stats struct {
	// Aggregates stats over all connections past and present. Some values may
	// not have much meaning in the aggregate context.
	ConnStats

	// metrics marking the progress of the torrent
	// these are in chunks.
	Missing     int
	Outstanding int
	Unverified  int
	Failed      int
	Completed   int

	// Ordered by expected descending quantities (if all is well).
	MaximumAllowedPeers int
	TotalPeers          int
	PendingPeers        int
	ActivePeers         int
	HalfOpenPeers       int

	Seeding bool
}

Stats high level stats about the torrent.

type Torrent

type Torrent interface {
	Metadata() Metadata
	Tune(...Tuner) error
	Stats() Stats
	BytesCompleted() int64        // TODO: maybe should be pulled from torrent, it has a reference to the storage implementation. or maybe part of the Stats call?
	Info() *metainfo.Info         // TODO: remove, this should be pulled from Metadata()
	GotInfo() <-chan struct{}     // TODO: remove, torrents should never be returned if they don't have the meta info.
	Storage() storage.TorrentImpl // temporary replacement for reader.
}

Torrent represents the state of a torrent within a client. interface is currently being used to ease the transition of to a cleaner API. Many methods should not be called before the info is available, see .Info and .GotInfo.

type Tuner

type Tuner func(*torrent)

Tuner runtime tuning of an actively running torrent.

func TuneAnnounceOnce

func TuneAnnounceOnce(options ...tracker.AnnounceOption) Tuner

Announce to trackers looking for at least one successful request that returns peers.

func TuneClientPeer

func TuneClientPeer(cl *Client) Tuner

TuneClientPeer adds a trusted, pending peer for each of the Client's addresses. used for tests.

func TuneMaxConnections

func TuneMaxConnections(m int) Tuner

TuneMaxConnections adjust the maximum connections allowed for a torrent.

func TunePeers

func TunePeers(peers ...Peer) Tuner

TunePeers add peers to the torrent.

func TunePublicTrackers

func TunePublicTrackers(trackers ...string) Tuner

func TuneReadAnnounce

func TuneReadAnnounce(v *tracker.Announce) Tuner

func TuneReadHashID

func TuneReadHashID(id *int160.T) Tuner

func TuneReadPeerID

func TuneReadPeerID(id *int160.T) Tuner

Extract the peer id from the torrent

func TuneReadPort

func TuneReadPort(v *int) Tuner

func TuneReadPublicIPv4

func TuneReadPublicIPv4(v net.IP) Tuner

func TuneReadPublicIPv6

func TuneReadPublicIPv6(v net.IP) Tuner

func TuneReadUserAgent

func TuneReadUserAgent(v *string) Tuner

func TuneResetTrackingStats

func TuneResetTrackingStats(s *Stats) Tuner

Reset tracking data for tracker events

func TuneSubscribe

func TuneSubscribe(sub *pubsub.Subscription) Tuner

The subscription emits as (int) the index of pieces as their state changes. A state change is when the PieceState for a piece alters in value.

func TuneTrackers

func TuneTrackers(trackers ...string) Tuner

add trackers to the torrent.

Directories

Path Synopsis
Package autobind for automically binding on the local server this package is only for convience and it's suggested to use torrent.NewSocketsBind instead.
Package autobind for automically binding on the local server this package is only for convience and it's suggested to use torrent.NewSocketsBind instead.
Package bep0051 implements DHT infohash indexing https://www.bittorrent.org/beps/bep_0051.html
Package bep0051 implements DHT infohash indexing https://www.bittorrent.org/beps/bep_0051.html
dht
Package dht implements a Distributed Hash Table (DHT) part of the BitTorrent protocol, as specified by BEP 5: http://www.bittorrent.org/beps/bep_0005.html
Package dht implements a Distributed Hash Table (DHT) part of the BitTorrent protocol, as specified by BEP 5: http://www.bittorrent.org/beps/bep_0005.html
internal
langx
Package langx provides small utility functions to extend the standard golang language.
Package langx provides small utility functions to extend the standard golang language.
testutil
Package testutil contains stuff for testing torrent-related behaviour.
Package testutil contains stuff for testing torrent-related behaviour.
Package iplist handles the P2P Plaintext Format described by https://en.wikipedia.org/wiki/PeerGuardian#P2P_plaintext_format.
Package iplist handles the P2P Plaintext Format described by https://en.wikipedia.org/wiki/PeerGuardian#P2P_plaintext_format.
cmd/pack-blocklist
Takes P2P blocklist text format in stdin, and outputs the packed format from the iplist package.
Takes P2P blocklist text format in stdin, and outputs the packed format from the iplist package.
Package logonce implements an io.Writer facade that only performs distinct writes.
Package logonce implements an io.Writer facade that only performs distinct writes.
mse
Package sockets implements examples of how to write sockets for the torrent client.
Package sockets implements examples of how to write sockets for the torrent client.
Package storage implements storage backends for package torrent.
Package storage implements storage backends for package torrent.
util
dirwatch
Package dirwatch provides filesystem-notification based tracking of torrent info files and magnet URIs in a directory.
Package dirwatch provides filesystem-notification based tracking of torrent info files and magnet URIs in a directory.
x

Jump to

Keyboard shortcuts

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