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