]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Add ability to set DialContext/ListenPacket for tracker announcements (#760)
[btrtrc.git] / config.go
1 package torrent
2
3 import (
4         "context"
5         "net"
6         "net/http"
7         "net/url"
8         "time"
9
10         "github.com/anacrolix/dht/v2"
11         "github.com/anacrolix/dht/v2/krpc"
12         "github.com/anacrolix/log"
13         "github.com/anacrolix/missinggo/v2"
14         "github.com/anacrolix/torrent/version"
15         "golang.org/x/time/rate"
16
17         "github.com/anacrolix/torrent/iplist"
18         "github.com/anacrolix/torrent/mse"
19         "github.com/anacrolix/torrent/storage"
20 )
21
22 // Probably not safe to modify this after it's given to a Client.
23 type ClientConfig struct {
24         // Store torrent file data in this directory unless .DefaultStorage is
25         // specified.
26         DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`
27         // The address to listen for new uTP and TCP BitTorrent protocol connections. DHT shares a UDP
28         // socket with uTP unless configured otherwise.
29         ListenHost              func(network string) string
30         ListenPort              int
31         NoDefaultPortForwarding bool
32         UpnpID                  string
33         // Don't announce to trackers. This only leaves DHT to discover peers.
34         DisableTrackers bool `long:"disable-trackers"`
35         DisablePEX      bool `long:"disable-pex"`
36
37         // Don't create a DHT.
38         NoDHT            bool `long:"disable-dht"`
39         DhtStartingNodes func(network string) dht.StartingNodesGetter
40         // Called for each anacrolix/dht Server created for the Client.
41         ConfigureAnacrolixDhtServer       func(*dht.ServerConfig)
42         PeriodicallyAnnounceTorrentsToDht bool
43
44         // Never send chunks to peers.
45         NoUpload bool `long:"no-upload"`
46         // Disable uploading even when it isn't fair.
47         DisableAggressiveUpload bool `long:"disable-aggressive-upload"`
48         // Upload even after there's nothing in it for us. By default uploading is
49         // not altruistic, we'll only upload to encourage the peer to reciprocate.
50         Seed bool `long:"seed"`
51         // Only applies to chunks uploaded to peers, to maintain responsiveness
52         // communicating local Client state to peers. Each limiter token
53         // represents one byte. The Limiter's burst must be large enough to fit a
54         // whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
55         UploadRateLimiter *rate.Limiter
56         // Rate limits all reads from connections to peers. Each limiter token
57         // represents one byte. The Limiter's burst must be bigger than the
58         // largest Read performed on a the underlying rate-limiting io.Reader
59         // minus one. This is likely to be the larger of the main read loop buffer
60         // (~4096), and the requested chunk size (~16KiB, see
61         // TorrentSpec.ChunkSize).
62         DownloadRateLimiter *rate.Limiter
63         // Maximum unverified bytes across all torrents. Not used if zero.
64         MaxUnverifiedBytes int64
65
66         // User-provided Client peer ID. If not present, one is generated automatically.
67         PeerID string
68         // For the bittorrent protocol.
69         DisableUTP bool
70         // For the bittorrent protocol.
71         DisableTCP bool `long:"disable-tcp"`
72         // Called to instantiate storage for each added torrent. Builtin backends
73         // are in the storage package. If not set, the "file" implementation is
74         // used (and Closed when the Client is Closed).
75         DefaultStorage storage.ClientImpl
76
77         HeaderObfuscationPolicy HeaderObfuscationPolicy
78         // The crypto methods to offer when initiating connections with header obfuscation.
79         CryptoProvides mse.CryptoMethod
80         // Chooses the crypto method to use when receiving connections with header obfuscation.
81         CryptoSelector mse.CryptoSelector
82
83         IPBlocklist      iplist.Ranger
84         DisableIPv6      bool `long:"disable-ipv6"`
85         DisableIPv4      bool
86         DisableIPv4Peers bool
87         // Perform logging and any other behaviour that will help debug.
88         Debug  bool `help:"enable debugging"`
89         Logger log.Logger
90
91         // Defines proxy for HTTP requests, such as for trackers. It's commonly set from the result of
92         // "net/http".ProxyURL(HTTPProxy).
93         HTTPProxy func(*http.Request) (*url.URL, error)
94         // Defines DialContext func to use for HTTP tracker announcements
95         TrackerDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
96         // Defines ListenPacket func to use for UDP tracker announcements
97         TrackerListenPacket func(network, addr string) (net.PacketConn, error)
98         // Takes a tracker's hostname and requests DNS A and AAAA records.
99         // Used in case DNS lookups require a special setup (i.e., dns-over-https)
100         LookupTrackerIp func(*url.URL) ([]net.IP, error)
101         // HTTPUserAgent changes default UserAgent for HTTP requests
102         HTTPUserAgent string
103         // Updated occasionally to when there's been some changes to client
104         // behaviour in case other clients are assuming anything of us. See also
105         // `bep20`.
106         ExtendedHandshakeClientVersion string
107         // Peer ID client identifier prefix. We'll update this occasionally to
108         // reflect changes to client behaviour that other clients may depend on.
109         // Also see `extendedHandshakeClientVersion`.
110         Bep20 string
111
112         // Peer dial timeout to use when there are limited peers.
113         NominalDialTimeout time.Duration
114         // Minimum peer dial timeout to use (even if we have lots of peers).
115         MinDialTimeout             time.Duration
116         EstablishedConnsPerTorrent int
117         HalfOpenConnsPerTorrent    int
118         TotalHalfOpenConns         int
119         // Maximum number of peer addresses in reserve.
120         TorrentPeersHighWater int
121         // Minumum number of peers before effort is made to obtain more peers.
122         TorrentPeersLowWater int
123
124         // Limit how long handshake can take. This is to reduce the lingering
125         // impact of a few bad apples. 4s loses 1% of successful handshakes that
126         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
127         HandshakesTimeout time.Duration
128         // How long between writes before sending a keep alive message on a peer connection that we want
129         // to maintain.
130         KeepAliveTimeout time.Duration
131
132         // The IP addresses as our peers should see them. May differ from the
133         // local interfaces due to NAT or other network configurations.
134         PublicIp4 net.IP
135         PublicIp6 net.IP
136
137         // Accept rate limiting affects excessive connection attempts from IPs that fail during
138         // handshakes or request torrents that we don't have.
139         DisableAcceptRateLimiting bool
140         // Don't add connections that have the same peer ID as an existing
141         // connection for a given Torrent.
142         DropDuplicatePeerIds bool
143         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
144         // bit of a special case, since a peer could also be useless if they're just not interested, or
145         // we don't intend to obtain all of a torrent's data.
146         DropMutuallyCompletePeers bool
147         // Whether to accept peer connections at all.
148         AcceptPeerConnections bool
149         // Whether a Client should want conns without delegating to any attached Torrents. This is
150         // useful when torrents might be added dynmically in callbacks for example.
151         AlwaysWantConns bool
152
153         // OnQuery hook func
154         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
155
156         Extensions PeerExtensionBits
157         // Bits that peers must have set to proceed past handshakes.
158         MinPeerExtensions PeerExtensionBits
159
160         DisableWebtorrent bool
161         DisableWebseeds   bool
162
163         Callbacks Callbacks
164 }
165
166 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
167         host, port, err := missinggo.ParseHostPort(addr)
168         if err != nil {
169                 panic(err)
170         }
171         cfg.ListenHost = func(string) string { return host }
172         cfg.ListenPort = port
173         return cfg
174 }
175
176 func NewDefaultClientConfig() *ClientConfig {
177         cc := &ClientConfig{
178                 HTTPUserAgent:                  version.DefaultHttpUserAgent,
179                 ExtendedHandshakeClientVersion: version.DefaultExtendedHandshakeClientVersion,
180                 Bep20:                          version.DefaultBep20Prefix,
181                 UpnpID:                         version.DefaultUpnpId,
182                 NominalDialTimeout:             20 * time.Second,
183                 MinDialTimeout:                 3 * time.Second,
184                 EstablishedConnsPerTorrent:     50,
185                 HalfOpenConnsPerTorrent:        25,
186                 TotalHalfOpenConns:             100,
187                 TorrentPeersHighWater:          500,
188                 TorrentPeersLowWater:           50,
189                 HandshakesTimeout:              4 * time.Second,
190                 KeepAliveTimeout:               time.Minute,
191                 DhtStartingNodes: func(network string) dht.StartingNodesGetter {
192                         return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
193                 },
194                 PeriodicallyAnnounceTorrentsToDht: true,
195                 ListenHost:                        func(string) string { return "" },
196                 UploadRateLimiter:                 unlimited,
197                 DownloadRateLimiter:               unlimited,
198                 DisableAcceptRateLimiting:         true,
199                 DropMutuallyCompletePeers:         true,
200                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
201                         Preferred:        true,
202                         RequirePreferred: false,
203                 },
204                 CryptoSelector:        mse.DefaultCryptoSelector,
205                 CryptoProvides:        mse.AllSupportedCrypto,
206                 ListenPort:            42069,
207                 Extensions:            defaultPeerExtensionBytes(),
208                 AcceptPeerConnections: true,
209                 MaxUnverifiedBytes:    64 << 20,
210         }
211         return cc
212 }
213
214 type HeaderObfuscationPolicy struct {
215         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
216         Preferred        bool // Whether header obfuscation is preferred.
217 }