]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
package expect fix (#524)
[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/v2"
13         "github.com/anacrolix/missinggo/expect"
14         "golang.org/x/time/rate"
15
16         "github.com/anacrolix/torrent/iplist"
17         "github.com/anacrolix/torrent/mse"
18         "github.com/anacrolix/torrent/storage"
19 )
20
21 // Probably not safe to modify this after it's given to a Client.
22 type ClientConfig struct {
23         // Store torrent file data in this directory unless .DefaultStorage is
24         // specified.
25         DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`
26         // The address to listen for new uTP and TCP BitTorrent protocol connections. DHT shares a UDP
27         // socket with uTP unless configured otherwise.
28         ListenHost              func(network string) string
29         ListenPort              int
30         NoDefaultPortForwarding bool
31         UpnpID                  string
32         // Don't announce to trackers. This only leaves DHT to discover peers.
33         DisableTrackers bool `long:"disable-trackers"`
34         DisablePEX      bool `long:"disable-pex"`
35
36         // Don't create a DHT.
37         NoDHT            bool `long:"disable-dht"`
38         DhtStartingNodes func(network string) dht.StartingNodesGetter
39         // Called for each anacrolix/dht Server created for the Client.
40         ConfigureAnacrolixDhtServer       func(*dht.ServerConfig)
41         PeriodicallyAnnounceTorrentsToDht bool
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         // Maximum unverified bytes across all torrents. Not used if zero.
63         MaxUnverifiedBytes int64
64
65         // User-provided Client peer ID. If not present, one is generated automatically.
66         PeerID string
67         // For the bittorrent protocol.
68         DisableUTP bool
69         // For the bittorrent protocol.
70         DisableTCP bool `long:"disable-tcp"`
71         // Called to instantiate storage for each added torrent. Builtin backends
72         // are in the storage package. If not set, the "file" implementation is
73         // used (and Closed when the Client is Closed).
74         DefaultStorage storage.ClientImpl
75
76         HeaderObfuscationPolicy HeaderObfuscationPolicy
77         // The crypto methods to offer when initiating connections with header obfuscation.
78         CryptoProvides mse.CryptoMethod
79         // Chooses the crypto method to use when receiving connections with header obfuscation.
80         CryptoSelector mse.CryptoSelector
81
82         IPBlocklist      iplist.Ranger
83         DisableIPv6      bool `long:"disable-ipv6"`
84         DisableIPv4      bool
85         DisableIPv4Peers bool
86         // Perform logging and any other behaviour that will help debug.
87         Debug  bool `help:"enable debugging"`
88         Logger log.Logger
89
90         // Defines proxy for HTTP requests, such as for trackers. It's commonly set from the result of
91         // "net/http".ProxyURL(HTTPProxy).
92         HTTPProxy func(*http.Request) (*url.URL, error)
93         // HTTPUserAgent changes default UserAgent for HTTP requests
94         HTTPUserAgent string
95         // Updated occasionally to when there's been some changes to client
96         // behaviour in case other clients are assuming anything of us. See also
97         // `bep20`.
98         ExtendedHandshakeClientVersion string
99         // Peer ID client identifier prefix. We'll update this occasionally to
100         // reflect changes to client behaviour that other clients may depend on.
101         // Also see `extendedHandshakeClientVersion`.
102         Bep20 string
103
104         // Peer dial timeout to use when there are limited peers.
105         NominalDialTimeout time.Duration
106         // Minimum peer dial timeout to use (even if we have lots of peers).
107         MinDialTimeout             time.Duration
108         EstablishedConnsPerTorrent int
109         HalfOpenConnsPerTorrent    int
110         TotalHalfOpenConns         int
111         // Maximum number of peer addresses in reserve.
112         TorrentPeersHighWater int
113         // Minumum number of peers before effort is made to obtain more peers.
114         TorrentPeersLowWater int
115
116         // Limit how long handshake can take. This is to reduce the lingering
117         // impact of a few bad apples. 4s loses 1% of successful handshakes that
118         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
119         HandshakesTimeout time.Duration
120
121         // The IP addresses as our peers should see them. May differ from the
122         // local interfaces due to NAT or other network configurations.
123         PublicIp4 net.IP
124         PublicIp6 net.IP
125
126         // Accept rate limiting affects excessive connection attempts from IPs that fail during
127         // handshakes or request torrents that we don't have.
128         DisableAcceptRateLimiting bool
129         // Don't add connections that have the same peer ID as an existing
130         // connection for a given Torrent.
131         DropDuplicatePeerIds bool
132         // Drop peers that are complete if we are also complete and have no use for the peer. This is a
133         // bit of a special case, since a peer could also be useless if they're just not interested, or
134         // we don't intend to obtain all of a torrent's data.
135         DropMutuallyCompletePeers bool
136         // Whether to accept peer connections at all.
137         AcceptPeerConnections bool
138
139         // OnQuery hook func
140         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
141
142         Extensions PeerExtensionBits
143
144         DisableWebtorrent bool
145         DisableWebseeds   bool
146
147         Callbacks Callbacks
148 }
149
150 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
151         host, port, err := missinggo.ParseHostPort(addr)
152         expect.Nil(err)
153         cfg.ListenHost = func(string) string { return host }
154         cfg.ListenPort = port
155         return cfg
156 }
157
158 func NewDefaultClientConfig() *ClientConfig {
159         cc := &ClientConfig{
160                 HTTPUserAgent:                  "Go-Torrent/1.0",
161                 ExtendedHandshakeClientVersion: "go.torrent dev 20181121",
162                 Bep20:                          "-GT0002-",
163                 UpnpID:                         "anacrolix/torrent",
164                 NominalDialTimeout:             20 * time.Second,
165                 MinDialTimeout:                 3 * time.Second,
166                 EstablishedConnsPerTorrent:     50,
167                 HalfOpenConnsPerTorrent:        25,
168                 TotalHalfOpenConns:             100,
169                 TorrentPeersHighWater:          500,
170                 TorrentPeersLowWater:           50,
171                 HandshakesTimeout:              4 * time.Second,
172                 DhtStartingNodes: func(network string) dht.StartingNodesGetter {
173                         return func() ([]dht.Addr, error) { return dht.GlobalBootstrapAddrs(network) }
174                 },
175                 PeriodicallyAnnounceTorrentsToDht: true,
176                 ListenHost:                        func(string) string { return "" },
177                 UploadRateLimiter:                 unlimited,
178                 DownloadRateLimiter:               unlimited,
179                 DisableAcceptRateLimiting:         true,
180                 DropMutuallyCompletePeers:         true,
181                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
182                         Preferred:        true,
183                         RequirePreferred: false,
184                 },
185                 CryptoSelector:        mse.DefaultCryptoSelector,
186                 CryptoProvides:        mse.AllSupportedCrypto,
187                 ListenPort:            42069,
188                 Extensions:            defaultPeerExtensionBytes(),
189                 AcceptPeerConnections: true,
190         }
191         //cc.ConnTracker.SetNoMaxEntries()
192         //cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
193         return cc
194 }
195
196 type HeaderObfuscationPolicy struct {
197         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
198         Preferred        bool // Whether header obfuscation is preferred.
199 }