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