torrent

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2020 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package torrent implements the BitTorrent protocol. It is designed to be simple and easy to use. A common workflow is to create a Client, add a torrent and then download it.

cl, _ := torrent.NewClient(nil)
t, _ := cl.AddFromFile("example.torrent")
<-t.InfoC
t.StartDataTransfer()
<-t.DownloadedDataC
fmt.Println("torrent downloaded!")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client manages multiple torrents

func NewClient

func NewClient(cfg *Config) (*Client, error)

NewClient creates a new Client with the provided configuration. Use `NewClient(nil)` for the default configuration.

func (*Client) AddFromFile

func (cl *Client) AddFromFile(filename string) (*Torrent, error)

AddFromFile creates a torrent based on the contents of filename. The Torrent returned maybe be in seeding mode if all the data is already downloaded.

func (*Client) AddFromInfoHash

func (cl *Client) AddFromInfoHash(infohash [20]byte) (*Torrent, error)

AddFromInfoHash creates a torrent based on it's infohash

func (*Client) AddFromMagnet

func (cl *Client) AddFromMagnet(uri string) (*Torrent, error)

AddFromMagnet creates a torrent based on the magnet link provided

func (*Client) AddFromParser

func (cl *Client) AddFromParser(p metainfo.Parser) (*Torrent, error)

AddFromParser creates a torrent from the provided parser. See metainfo package for more.

func (*Client) Close

func (cl *Client) Close()

Close calls torrent.Close for all the torrents managed by the client.

func (*Client) ID

func (cl *Client) ID() []byte

ID returns the Client's random ID

func (*Client) ListenPort

func (cl *Client) ListenPort() int

ListenPort returns the port that the client listens for new connections

func (*Client) Torrents

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

Torrents returns all torrents that the client manages.

type Config

type Config struct {
	//Returns a new PieceSelector instantiated for each torrent the client manages
	SelectorF func() PieceSelector
	//Max outstanding requests per connection we allow for a peer to have
	MaxOnFlightReqs int
	//Max active/established connections per torrent
	MaxEstablishedConns int
	//This option disables DHT also.
	RejectIncomingConnections bool
	DisableTrackers           bool
	DisableDHT                bool
	//Directory to store the data
	BaseDir string
	//Function to open the storage.Provide your own for a custom storage implementation
	OpenStorage storage.Open
	//Dials for new connections will fail after this duration
	DialTimeout time.Duration
	//BitTorrent handshakes will fail after this duration
	HandshakeTiemout time.Duration
}

Config provides configuration for a Client.

func DefaultConfig

func DefaultConfig() (*Config, error)

DefaultConfig returns the default configuration for a client

type DefaultPieceSelector

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

func (*DefaultPieceSelector) Less

func (dfs *DefaultPieceSelector) Less(p1, p2 *Piece) bool

Less is the default Less func. Pieces that have more pending and completed blocks have the highest priority. If the two pieces have both all blocks unrequested then: i) If no other piece in the Torrent has been downloaded, then we prioritize randomly. ii) Otherwise, by comparing their rarities. The one that is more rare gets prioritized.

func (*DefaultPieceSelector) OnPieceDownload

func (dfs *DefaultPieceSelector) OnPieceDownload(_ int)

func (*DefaultPieceSelector) SetTorrent

func (dfs *DefaultPieceSelector) SetTorrent(_ *Torrent)

type Peer

type Peer struct {
	P      tracker.Peer
	Source PeerSource
}

Holds basic information about a peer

type PeerSource

type PeerSource byte

Which source informed us about that peer

const (
	//The user manually added this peer
	SourceUser PeerSource = iota
	//It was an incoming connection
	SourceIncoming
	//The peer was given to us by DHT
	SourceDHT
	//The peer was given to us by a tracker
	SourceTracker
)

type Piece

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

Piece represents a single bitTorrent piece. A piece is divided in blocks. A piece's block can be at one of the following three states: unrequested,pending or completed. All blocks are initially unrequested.When we request a block, then it becomes pending and when we download it it becomes completed.

func (*Piece) Blocks

func (p *Piece) Blocks() int

Blocks returns the total blocks of the piece

func (*Piece) CompletedBlocks

func (p *Piece) CompletedBlocks() int

CompletedBlocks returns the number of completed blocks of p.

func (*Piece) Data

func (p *Piece) Data() (b []byte, err error)

Data Returns the data of the piece. Requires that the piece has been downloaded otherwise an error is returned.

func (*Piece) Index

func (p *Piece) Index() int

Index return the piece's index

func (*Piece) PendingBlocks

func (p *Piece) PendingBlocks() int

PendingBlocks returns the number of pendingBlocks blocks of p.

func (*Piece) Rarity

func (p *Piece) Rarity() int

Rarity returns how many peers in the swarm have been known to own this piece. Note that is only an approximation and we can't know for sure the exact number of peers owning a piece.

func (*Piece) Torrent

func (p *Piece) Torrent() *Torrent

Torrent returns the underlying Torrent of the piece

func (*Piece) UnrequestedBlocks

func (p *Piece) UnrequestedBlocks() int

UnrequestedBlocks returns the number of unrequested blocks of p.

func (*Piece) Verified

func (p *Piece) Verified() bool

Verified returns wheter the piece is downloaded and verified or not

type PieceSelector

type PieceSelector interface {
	// Less reports whether p1 should be prioritized over p2.
	// p1 and p2 have both unrequested blocks.
	// Less will be executed every time the client wants to request pieces from a
	// remote peer so it's important that its execution time is short.
	// Moreover, Less should not call any of the torrent's methods because it will
	// cause deadlock - it is called with the torrent's internall lock acquired,
	// another reason to keep its execution time short-.
	Less(p1, p2 *Piece) bool
	// This is called when a piece is fully downloaded (and verified).
	// i is the index of the downloaded piece.
	// Useful if PieceSelector wants to change state after such an event.
	OnPieceDownload(i int)
	// Called when the PieceSelector is associated with a specific Torrent.
	// Maybe useful for some initial setup.
	SetTorrent(t *Torrent)
}

PieceSelector is responsible for selecting the order in which the torrent's pieces will be requested. Note that this is not the order in which they will be downloaded.

func NewDefaultPieceSelector

func NewDefaultPieceSelector() PieceSelector

type Stats

type Stats struct {
	//Number of blocks/chunks downloaded (not necessarily verified)
	BlocksDownloaded int
	//Number of blocks/chunks uploaded
	BlocksUploaded int
	//Remainings bytes to download (bytes that are downloaded but not verified are not included)
	BytesLeft int
	//Number of verified bytes we have downloaded
	BytesDownloaded int
	//Number of bytes we have uploaded
	BytesUploaded int
}

Stats contains statistics about a Torrent

func (*Stats) String

func (s *Stats) String() string

type Torrent

type Torrent struct {

	//closes when the Torrent closes
	ClosedC chan struct{}

	//closes when all pieces have been downloaded
	DownloadedDataC chan struct{}
	//closes when we get the info dictionary.
	InfoC chan struct{}
	// contains filtered or unexported fields
}

Torrent represents a torrent and maintains state about it.Multiple goroutines may invoke methods on a Torrent simultaneously.

func (*Torrent) AddPeers

func (t *Torrent) AddPeers(peers ...Peer) error

AddPeers adds peers to the Torrent and (if needed) tries to establish connections with them. Returns error if the torrent is closed.

func (*Torrent) Close

func (t *Torrent) Close()

Close removes the torrent from the Client and closes all connections with peers. Close is safe to be called multiple times on the same torrent.

func (*Torrent) Closed

func (t *Torrent) Closed() bool

Closed returns whether the torrent is closed or not.

func (*Torrent) DisableDataDownload

func (t *Torrent) DisableDataDownload() error

DisableDataDownload pauses the process of downloading the torrent's data. It is an error to call this before calling StartDataTransfer.

func (*Torrent) EnableDataDownload

func (t *Torrent) EnableDataDownload() error

EnableDataDownload re-enables downloading the torrent's data. To bootstrap the data downloading, one should call TransferData first. It is an error to call this before calling StartDataTransfer. Usually EnableDataDownload is called after a call to DisableDataDownload.

func (*Torrent) HaveAllPieces

func (t *Torrent) HaveAllPieces() bool

HaveAllPieces returns whether all torrent's data has been downloaded

func (*Torrent) Info

func (t *Torrent) Info() *metainfo.InfoDict

Info returns the info of the torrent or nil of its not available.

func (*Torrent) Metainfo

func (t *Torrent) Metainfo() *metainfo.MetaInfo

Metainfo returns the metainfo of the torrent.

func (*Torrent) Pieces

func (t *Torrent) Pieces() []Piece

Pieces returns all pieces of the torrent. If Info is not available or t is closed it returns nil.

func (*Torrent) Seeding

func (t *Torrent) Seeding() bool

Seeding returns true if `HaveAllPieces` returns true and a call to `Download` has been made for this torrent

func (*Torrent) StartDataTransfer

func (t *Torrent) StartDataTransfer() error

StartDataTransfer enables downloading/uploading the torrent's data. It should be called once for each Torrent. It requires the info first i.e one should ensure that t.InfoC is closed After the download is complete, the Torrent transits in seeding mode (i.e altruistically upload) until it's closed. If the data are already there, StartDataTransfer returns immediatly and seeds the torrent.

func (*Torrent) Stats

func (t *Torrent) Stats() Stats

func (*Torrent) Swarm

func (t *Torrent) Swarm() []Peer

Swarm returns all known peers associated with this torrent.

func (*Torrent) WriteStatus

func (t *Torrent) WriteStatus(w io.Writer)

WriteStatus writes to w a human readable message about the status of the Torrent.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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