]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Pass tests with new full-client request strategy implementation
[btrtrc.git] / config.go
1 package torrent
2
3 import (
4         "net"
5         "net/http"
6         "net/url"
7         "time"
8
9         "github.com/anacrolix/dht/v2"
10         "github.com/anacrolix/dht/v2/krpc"
11         "github.com/anacrolix/log"
12         "github.com/anacrolix/missinggo"
13         "github.com/anacrolix/missinggo/expect"
14         "github.com/anacrolix/missinggo/v2/conntrack"
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
43         // Never send chunks to peers.
44         NoUpload bool `long:"no-upload"`
45         // Disable uploading even when it isn't fair.
46         DisableAggressiveUpload bool `long:"disable-aggressive-upload"`
47         // Upload even after there's nothing in it for us. By default uploading is
48         // not altruistic, we'll only upload to encourage the peer to reciprocate.
49         Seed bool `long:"seed"`
50         // Only applies to chunks uploaded to peers, to maintain responsiveness
51         // communicating local Client state to peers. Each limiter token
52         // represents one byte. The Limiter's burst must be large enough to fit a
53         // whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
54         UploadRateLimiter *rate.Limiter
55         // Rate limits all reads from connections to peers. Each limiter token
56         // represents one byte. The Limiter's burst must be bigger than the
57         // largest Read performed on a the underlying rate-limiting io.Reader
58         // minus one. This is likely to be the larger of the main read loop buffer
59         // (~4096), and the requested chunk size (~16KiB, see
60         // TorrentSpec.ChunkSize).
61         DownloadRateLimiter *rate.Limiter
62
63         // User-provided Client peer ID. If not present, one is generated automatically.
64         PeerID string
65         // For the bittorrent protocol.
66         DisableUTP bool
67         // For the bittorrent protocol.
68         DisableTCP bool `long:"disable-tcp"`
69         // Called to instantiate storage for each added torrent. Builtin backends
70         // are in the storage package. If not set, the "file" implementation is
71         // used (and Closed when the Client is Closed).
72         DefaultStorage storage.ClientImpl
73
74         HeaderObfuscationPolicy HeaderObfuscationPolicy
75         // The crypto methods to offer when initiating connections with header obfuscation.
76         CryptoProvides mse.CryptoMethod
77         // Chooses the crypto method to use when receiving connections with header obfuscation.
78         CryptoSelector mse.CryptoSelector
79
80         IPBlocklist      iplist.Ranger
81         DisableIPv6      bool `long:"disable-ipv6"`
82         DisableIPv4      bool
83         DisableIPv4Peers bool
84         // Perform logging and any other behaviour that will help debug.
85         Debug  bool `help:"enable debugging"`
86         Logger log.Logger
87
88         // Defines proxy for HTTP requests, such as for trackers. It's commonly set from the result of
89         // "net/http".ProxyURL(HTTPProxy).
90         HTTPProxy func(*http.Request) (*url.URL, error)
91         // HTTPUserAgent changes default UserAgent for HTTP requests
92         HTTPUserAgent string
93         // Updated occasionally to when there's been some changes to client
94         // behaviour in case other clients are assuming anything of us. See also
95         // `bep20`.
96         ExtendedHandshakeClientVersion string
97         // Peer ID client identifier prefix. We'll update this occasionally to
98         // reflect changes to client behaviour that other clients may depend on.
99         // Also see `extendedHandshakeClientVersion`.
100         Bep20 string
101
102         // Peer dial timeout to use when there are limited peers.
103         NominalDialTimeout time.Duration
104         // Minimum peer dial timeout to use (even if we have lots of peers).
105         MinDialTimeout             time.Duration
106         EstablishedConnsPerTorrent int
107         HalfOpenConnsPerTorrent    int
108         TotalHalfOpenConns         int
109         // Maximum number of peer addresses in reserve.
110         TorrentPeersHighWater int
111         // Minumum number of peers before effort is made to obtain more peers.
112         TorrentPeersLowWater int
113
114         // Limit how long handshake can take. This is to reduce the lingering
115         // impact of a few bad apples. 4s loses 1% of successful handshakes that
116         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
117         HandshakesTimeout time.Duration
118
119         // The IP addresses as our peers should see them. May differ from the
120         // local interfaces due to NAT or other network configurations.
121         PublicIp4 net.IP
122         PublicIp6 net.IP
123
124         // Accept rate limiting affects excessive connection attempts from IPs that fail during
125         // handshakes or request torrents that we don't have.
126         DisableAcceptRateLimiting bool
127         // Don't add connections that have the same peer ID as an existing
128         // connection for a given Torrent.
129         DropDuplicatePeerIds bool
130         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
131         // bit of a special case, since a peer could also be useless if they're just not interested, or
132         // we don't intend to obtain all of a torrent's data.
133         DropMutuallyCompletePeers bool
134
135         ConnTracker *conntrack.Instance
136
137         // OnQuery hook func
138         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
139
140         Extensions PeerExtensionBits
141
142         DisableWebtorrent bool
143         DisableWebseeds   bool
144
145         Callbacks Callbacks
146 }
147
148 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
149         host, port, err := missinggo.ParseHostPort(addr)
150         expect.Nil(err)
151         cfg.ListenHost = func(string) string { return host }
152         cfg.ListenPort = port
153         return cfg
154 }
155
156 func NewDefaultClientConfig() *ClientConfig {
157         cc := &ClientConfig{
158                 HTTPUserAgent:                  "Go-Torrent/1.0",
159                 ExtendedHandshakeClientVersion: "go.torrent dev 20181121",
160                 Bep20:                          "-GT0002-",
161                 UpnpID:                         "anacrolix/torrent",
162                 NominalDialTimeout:             20 * time.Second,
163                 MinDialTimeout:                 3 * time.Second,
164                 EstablishedConnsPerTorrent:     50,
165                 HalfOpenConnsPerTorrent:        25,
166                 TotalHalfOpenConns:             100,
167                 TorrentPeersHighWater:          500,
168                 TorrentPeersLowWater:           50,
169                 HandshakesTimeout:              4 * time.Second,
170                 DhtStartingNodes: func(network string) dht.StartingNodesGetter {
171                         return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
172                 },
173                 ListenHost:                func(string) string { return "" },
174                 UploadRateLimiter:         unlimited,
175                 DownloadRateLimiter:       unlimited,
176                 ConnTracker:               conntrack.NewInstance(),
177                 DisableAcceptRateLimiting: true,
178                 DropMutuallyCompletePeers: true,
179                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
180                         Preferred:        true,
181                         RequirePreferred: false,
182                 },
183                 CryptoSelector: mse.DefaultCryptoSelector,
184                 CryptoProvides: mse.AllSupportedCrypto,
185                 ListenPort:     42069,
186                 Extensions:     defaultPeerExtensionBytes(),
187         }
188         //cc.ConnTracker.SetNoMaxEntries()
189         //cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
190         return cc
191 }
192
193 type HeaderObfuscationPolicy struct {
194         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
195         Preferred        bool // Whether header obfuscation is preferred.
196 }