]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Use new anacrolix/multiless, and incorporate Peer.Trusted into peer prioritization
[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 var DefaultHTTPUserAgent = "Go-Torrent/1.0"
23
24 // Probably not safe to modify this after it's given to a Client.
25 type ClientConfig struct {
26         // Store torrent file data in this directory unless .DefaultStorage is
27         // specified.
28         DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`
29         // The address to listen for new uTP and TCP bittorrent protocol
30         // connections. DHT shares a UDP socket with uTP unless configured
31         // otherwise.
32         ListenHost              func(network string) string
33         ListenPort              int
34         NoDefaultPortForwarding bool
35         UpnpID                  string
36         // Don't announce to trackers. This only leaves DHT to discover peers.
37         DisableTrackers bool `long:"disable-trackers"`
38         DisablePEX      bool `long:"disable-pex"`
39
40         // Don't create a DHT.
41         NoDHT            bool `long:"disable-dht"`
42         DhtStartingNodes dht.StartingNodesGetter
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.
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         // Sets usage of Socks5 Proxy. Authentication should be included in the url if needed.
81         // Examples: socks5://demo:demo@192.168.99.100:1080
82         //                       http://proxy.domain.com:3128
83         ProxyURL string
84
85         IPBlocklist      iplist.Ranger
86         DisableIPv6      bool `long:"disable-ipv6"`
87         DisableIPv4      bool
88         DisableIPv4Peers bool
89         // Perform logging and any other behaviour that will help debug.
90         Debug  bool `help:"enable debugging"`
91         Logger log.Logger
92
93         // HTTPProxy defines proxy for HTTP requests.
94         // Format: func(*Request) (*url.URL, error),
95         // or result of http.ProxyURL(HTTPProxy).
96         // By default, it is composed from ClientConfig.ProxyURL,
97         // if not set explicitly in ClientConfig struct
98         HTTPProxy func(*http.Request) (*url.URL, error)
99         // HTTPUserAgent changes default UserAgent for HTTP requests
100         HTTPUserAgent string
101         // Updated occasionally to when there's been some changes to client
102         // behaviour in case other clients are assuming anything of us. See also
103         // `bep20`.
104         ExtendedHandshakeClientVersion string
105         // Peer ID client identifier prefix. We'll update this occasionally to
106         // reflect changes to client behaviour that other clients may depend on.
107         // Also see `extendedHandshakeClientVersion`.
108         Bep20 string
109
110         // Peer dial timeout to use when there are limited peers.
111         NominalDialTimeout time.Duration
112         // Minimum peer dial timeout to use (even if we have lots of peers).
113         MinDialTimeout             time.Duration
114         EstablishedConnsPerTorrent int
115         HalfOpenConnsPerTorrent    int
116         // Maximum number of peer addresses in reserve.
117         TorrentPeersHighWater int
118         // Minumum number of peers before effort is made to obtain more peers.
119         TorrentPeersLowWater int
120
121         // Limit how long handshake can take. This is to reduce the lingering
122         // impact of a few bad apples. 4s loses 1% of successful handshakes that
123         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
124         HandshakesTimeout time.Duration
125
126         // The IP addresses as our peers should see them. May differ from the
127         // local interfaces due to NAT or other network configurations.
128         PublicIp4 net.IP
129         PublicIp6 net.IP
130
131         DisableAcceptRateLimiting bool
132         // Don't add connections that have the same peer ID as an existing
133         // connection for a given Torrent.
134         dropDuplicatePeerIds bool
135
136         ConnTracker *conntrack.Instance
137
138         // OnQuery hook func
139         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
140 }
141
142 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
143         host, port, err := missinggo.ParseHostPort(addr)
144         expect.Nil(err)
145         cfg.ListenHost = func(string) string { return host }
146         cfg.ListenPort = port
147         return cfg
148 }
149
150 func NewDefaultClientConfig() *ClientConfig {
151         cc := &ClientConfig{
152                 HTTPUserAgent:                  DefaultHTTPUserAgent,
153                 ExtendedHandshakeClientVersion: "go.torrent dev 20181121",
154                 Bep20:                          "-GT0002-",
155                 UpnpID:                         "anacrolix/torrent",
156                 NominalDialTimeout:             20 * time.Second,
157                 MinDialTimeout:                 3 * time.Second,
158                 EstablishedConnsPerTorrent:     50,
159                 HalfOpenConnsPerTorrent:        25,
160                 TorrentPeersHighWater:          500,
161                 TorrentPeersLowWater:           50,
162                 HandshakesTimeout:              4 * time.Second,
163                 DhtStartingNodes:               dht.GlobalBootstrapAddrs,
164                 ListenHost:                     func(string) string { return "" },
165                 UploadRateLimiter:              unlimited,
166                 DownloadRateLimiter:            unlimited,
167                 ConnTracker:                    conntrack.NewInstance(),
168                 HeaderObfuscationPolicy: HeaderObfuscationPolicy{
169                         Preferred:        true,
170                         RequirePreferred: false,
171                 },
172                 CryptoSelector: mse.DefaultCryptoSelector,
173                 CryptoProvides: mse.AllSupportedCrypto,
174                 ListenPort:     42069,
175                 Logger:         log.Default,
176         }
177         //cc.ConnTracker.SetNoMaxEntries()
178         //cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
179         return cc
180 }
181
182 type HeaderObfuscationPolicy struct {
183         RequirePreferred bool // Whether the value of Preferred is a strict requirement.
184         Preferred        bool // Whether header obfuscation is preferred.
185 }