Documentation ¶
Overview ¶
Package torrent implements a torrent client. Goals include:
- Configurable data storage, such as file, mmap, and piece-based.
- Downloading on demand: torrent.Reader will request only the data required to satisfy Reads, which is ideal for streaming and torrentfs.
BitTorrent features implemented include:
- Protocol obfuscation
- DHT
- uTP
- PEX
- Magnet
- IP Blocklists
- Some IPv6
- UDP Trackers
ConfigDir ¶
A Client has a configurable ConfigDir that defaults to $HOME/.config/torrent. Torrent metainfo files are cached at $CONFIGDIR/torrents/$infohash.torrent. Infohashes in $CONFIGDIR/banned_infohashes cannot be added to the Client. A P2P Plaintext Format blocklist is loaded from a file at the location specified by the environment variable TORRENT_BLOCKLIST_FILE if set. otherwise from $CONFIGDIR/blocklist. If $CONFIGDIR/packed-blocklist exists, this is memory- mapped as a packed IP blocklist, saving considerable memory.
Example ¶
package main import ( "log" "github.com/anacrolix/torrent" ) func main() { c, _ := torrent.NewClient(nil) defer c.Close() t, _ := c.AddMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU") <-t.GotInfo() t.DownloadAll() c.WaitAll() log.Print("ermahgerd, torrent downloaded") }
Output:
Example (FileReader) ¶
package main import ( "github.com/anacrolix/missinggo" "github.com/anacrolix/torrent" ) func main() { var ( t torrent.Torrent f torrent.File ) r := t.NewReader() defer r.Close() // Access the parts of the torrent pertaining to f. Data will be // downloaded as required, per the configuration of the torrent.Reader. _ = missinggo.NewSectionReadSeeker(r, f.Offset(), f.Length()) }
Output:
Index ¶
- Constants
- type Client
- func (me *Client) AddMagnet(uri string) (T Torrent, err error)
- func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error)
- func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error)
- func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error)
- func (me *Client) Close()
- func (cl *Client) ConfigDir() string
- func (me *Client) DHT() *dht.Server
- func (me *Client) IPBlockList() iplist.Ranger
- func (me *Client) ListenAddr() (addr net.Addr)
- func (me *Client) PeerID() string
- func (me *Client) SetIPBlockList(list iplist.Ranger)
- func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool)
- func (me *Client) Torrents() (ret []Torrent)
- func (me *Client) WaitAll() bool
- func (cl *Client) WriteStatus(_w io.Writer)
- type Config
- type Data
- type File
- type FilePieceState
- type Handle
- type InfoHash
- type Magnet
- type Peer
- type PieceState
- type PieceStateRun
- type Reader
- type Torrent
- func (t Torrent) AddPeers(pp []Peer) error
- func (t Torrent) BytesCompleted() int64
- func (t Torrent) DownloadAll()
- func (t Torrent) DownloadPieces(begin, end int)
- func (t Torrent) Drop()
- func (t Torrent) Files() (ret []File)
- func (t Torrent) GotInfo() <-chan struct{}
- func (t Torrent) Info() *metainfo.Info
- func (t Torrent) InfoHash() InfoHash
- func (t Torrent) Length() int64
- func (t Torrent) MetaInfo() *metainfo.MetaInfo
- func (t Torrent) Name() string
- func (t Torrent) NewReader() (ret *Reader)
- func (t Torrent) NumPieces() int
- func (t Torrent) PieceStateRuns() []PieceStateRun
- func (t Torrent) Seeding() bool
- func (t Torrent) SetDisplayName(dn string)
- func (t Torrent) SubscribePieceStateChanges() *pubsub.Subscription
- type TorrentDataOpener
- type TorrentSpec
Examples ¶
Constants ¶
const ( PiecePriorityNone piecePriority = iota // Not wanted. PiecePriorityNormal // Wanted. PiecePriorityReadahead // May be required soon. PiecePriorityNext // Succeeds a piece where a read occurred. PiecePriorityNow // A read occurred in this piece. )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Clients contain zero or more Torrents. A client manages a blocklist, the TCP/UDP protocol ports, and DHT as desired.
func (*Client) AddTorrent ¶
func (*Client) AddTorrentFromFile ¶
func (*Client) AddTorrentSpec ¶
func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error)
Add or merge a torrent spec. If the torrent is already present, the trackers will be merged with the existing ones. If the Info isn't yet known, it will be set. The display name is replaced if the new spec provides one. Returns new if the torrent wasn't already in the client.
func (*Client) Close ¶
func (me *Client) Close()
Stops the client. All connections to peers are closed and all activity will come to a halt.
func (*Client) ConfigDir ¶
The directory where the Client expects to find and store configuration data. Defaults to $HOME/.config/torrent.
func (*Client) IPBlockList ¶
func (*Client) ListenAddr ¶
func (*Client) SetIPBlockList ¶
func (*Client) WaitAll ¶
Returns true when all torrents are completely downloaded and false if the client is stopped before that.
func (*Client) WriteStatus ¶
Writes out a human readable status of the client, such as for writing to a HTTP status page.
type Config ¶
type Config struct { // Store torrent file data in this directory unless TorrentDataOpener is // specified. DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"` // The address to listen for new uTP and TCP bittorrent protocol // connections. DHT shares a UDP socket with uTP unless configured // otherwise. ListenAddr string `long:"listen-addr" value-name:"HOST:PORT"` // Don't announce to trackers. This only leaves DHT to discover peers. DisableTrackers bool `long:"disable-trackers"` DisablePEX bool `long:"disable-pex"` // Don't create a DHT. NoDHT bool `long:"disable-dht"` // Overrides the default DHT configuration. DHTConfig dht.ServerConfig // Don't ever 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. Seed bool `long:"seed"` // User-provided Client peer ID. If not present, one is generated automatically. PeerID string // For the bittorrent protocol. DisableUTP bool // For the bittorrent protocol. DisableTCP bool `long:"disable-tcp"` // Don't automatically load "$ConfigDir/blocklist". NoDefaultBlocklist bool // Defaults to "$HOME/.config/torrent". This is where "blocklist", // "torrents" and other operational files are stored. ConfigDir string // Don't save or load to a cache of torrent files stored in // "$ConfigDir/torrents". DisableMetainfoCache bool // Called to instantiate storage for each added torrent. Provided backends // are in $REPO/data. If not set, the "file" implementation is used. TorrentDataOpener DisableEncryption bool `long:"disable-encryption"` IPBlocklist *iplist.IPList DisableIPv6 bool `long:"disable-ipv6"` // Perform logging and any other behaviour that will help debug. Debug bool `help:"enable debug logging"` }
Override Client defaults.
type Data ¶
type Data interface { io.ReaderAt io.WriterAt // Bro, do you even io.Closer? Close() // If the data isn't available, err should be io.ErrUnexpectedEOF. WriteSectionTo(w io.Writer, off, n int64) (written int64, err error) // We believe the piece data will pass a hash check. PieceCompleted(index int) error // Returns true if the piece is complete. PieceComplete(index int) bool }
Represents data storage for a Torrent.
type File ¶
type File struct {
// contains filtered or unexported fields
}
Provides access to regions of torrent data that correspond to its files.
func (*File) DisplayPath ¶
The relative file path for a multi-file torrent, and the torrent name for a single-file torrent.
func (*File) State ¶
func (f *File) State() (ret []FilePieceState)
Returns the state of pieces in this file.
type FilePieceState ¶
type FilePieceState struct { Bytes int64 // Bytes within the piece that are part of this File. PieceState }
type Magnet ¶
func ParseMagnetURI ¶
ParseMagnetURI parses Magnet-formatted URIs into a Magnet instance
type PieceState ¶
type PieceState struct { Priority piecePriority // The piece is available in its entirety. Complete bool // The piece is being hashed, or is queued for hash. Checking bool // Some of the piece has been obtained. Partial bool }
The current state of a piece.
type PieceStateRun ¶
type PieceStateRun struct { PieceState Length int // How many consecutive pieces have this state. }
Represents a series of consecutive pieces with the same state.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Accesses torrent data via a client.
func (*Reader) SetReadahead ¶
Configure the number of bytes ahead of a read that should also be prioritized in preparation for further reads.
func (*Reader) SetResponsive ¶
func (r *Reader) SetResponsive()
Don't wait for pieces to complete and be verified. Read calls return as soon as they can when the underlying chunks become available.
type Torrent ¶
type Torrent struct {
// contains filtered or unexported fields
}
The public handle to a live torrent within a Client.
func (Torrent) BytesCompleted ¶
Number of bytes of the entire torrent we have completed.
func (Torrent) DownloadAll ¶
func (t Torrent) DownloadAll()
Marks the entire torrent for download. Requires the info first, see GotInfo.
func (Torrent) DownloadPieces ¶
func (Torrent) Files ¶
Returns handles to the files in the torrent. This requires the metainfo is available first.
func (Torrent) GotInfo ¶
func (t Torrent) GotInfo() <-chan struct{}
Closed when the info (.Info()) for the torrent has become available. Using features of Torrent that require the info before it is available will have undefined behaviour.
func (Torrent) InfoHash ¶
The torrent's infohash. This is fixed and cannot change. It uniquely identifies a torrent.
func (Torrent) MetaInfo ¶
Returns a run-time generated metainfo for the torrent that includes the info bytes and announce-list as currently known to the client.
func (Torrent) Name ¶
The current working name for the torrent. Either the name in the info dict, or a display name given such as by the dn value in a magnet link, or "".
func (Torrent) NewReader ¶
Returns a Reader bound to the torrent's data. All read calls block until the data requested is actually available.
func (Torrent) NumPieces ¶
The number of pieces in the torrent. This requires that the info has been obtained first.
func (Torrent) PieceStateRuns ¶
func (t Torrent) PieceStateRuns() []PieceStateRun
Returns the state of pieces of the torrent. They are grouped into runs of same state. The sum of the state run lengths is the number of pieces in the torrent.
func (Torrent) Seeding ¶
Returns true if the torrent is currently being seeded. This occurs when the client is willing to upload without wanting anything in return.
func (Torrent) SetDisplayName ¶
Clobbers the torrent display name. The display name is used as the torrent name if the metainfo is not available.
func (Torrent) SubscribePieceStateChanges ¶
func (t Torrent) SubscribePieceStateChanges() *pubsub.Subscription
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.
type TorrentDataOpener ¶
type TorrentSpec ¶
type TorrentSpec struct { // The tiered tracker URIs. Trackers [][]string InfoHash InfoHash Info *metainfo.InfoEx // The name to use if the Name field from the Info isn't available. DisplayName string // The chunk size to use for outbound requests. Defaults to 16KiB if not // set. ChunkSize int }
Specifies a new torrent for adding to a client. There are helpers for magnet URIs and torrent metainfo files.
func TorrentSpecFromMagnetURI ¶
func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error)
func TorrentSpecFromMetaInfo ¶
func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec)
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
dht-ping
Pings DHT nodes with the given network addresses.
|
Pings DHT nodes with the given network addresses. |
magnet-metainfo
Converts magnet URIs and info hashes into torrent metainfo files.
|
Converts magnet URIs and info hashes into torrent metainfo files. |
torrent
Downloads torrents from the command-line.
|
Downloads torrents from the command-line. |
torrent-pick
Downloads torrents from the command-line.
|
Downloads torrents from the command-line. |
torrentfs
Mounts a FUSE filesystem backed by torrents and magnet links.
|
Mounts a FUSE filesystem backed by torrents and magnet links. |
data
|
|
Standard use involves creating a Server, and calling Announce on it with the details of your local torrent client and infohash of interest.
|
Standard use involves creating a Server, and calling Announce on it with the details of your local torrent client and infohash of interest. |
internal
|
|
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. |
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. |