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