]> Sergey Matveev's repositories - btrtrc.git/blob - config.go
Add OnQuery Hook
[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"
10         "github.com/anacrolix/dht/krpc"
11         "github.com/anacrolix/missinggo"
12         "github.com/anacrolix/missinggo/conntrack"
13         "github.com/anacrolix/missinggo/expect"
14         "github.com/anacrolix/torrent/iplist"
15         "github.com/anacrolix/torrent/storage"
16         "golang.org/x/time/rate"
17 )
18
19 var DefaultHTTPUserAgent = "Go-Torrent/1.0"
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
27         // connections. DHT shares a UDP socket with uTP unless configured
28         // otherwise.
29         ListenHost              func(network string) string
30         ListenPort              int
31         NoDefaultPortForwarding bool
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 dht.StartingNodesGetter
39         // Never send chunks to peers.
40         NoUpload bool `long:"no-upload"`
41         // Disable uploading even when it isn't fair.
42         DisableAggressiveUpload bool `long:"disable-aggressive-upload"`
43         // Upload even after there's nothing in it for us. By default uploading is
44         // not altruistic, we'll only upload to encourage the peer to reciprocate.
45         Seed bool `long:"seed"`
46         // Only applies to chunks uploaded to peers, to maintain responsiveness
47         // communicating local Client state to peers. Each limiter token
48         // represents one byte. The Limiter's burst must be large enough to fit a
49         // whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
50         UploadRateLimiter *rate.Limiter
51         // Rate limits all reads from connections to peers. Each limiter token
52         // represents one byte. The Limiter's burst must be bigger than the
53         // largest Read performed on a the underlying rate-limiting io.Reader
54         // minus one. This is likely to be the larger of the main read loop buffer
55         // (~4096), and the requested chunk size (~16KiB, see
56         // TorrentSpec.ChunkSize).
57         DownloadRateLimiter *rate.Limiter
58
59         // User-provided Client peer ID. If not present, one is generated automatically.
60         PeerID string
61         // For the bittorrent protocol.
62         DisableUTP bool
63         // For the bittorrent protocol.
64         DisableTCP bool `long:"disable-tcp"`
65         // Called to instantiate storage for each added torrent. Builtin backends
66         // are in the storage package. If not set, the "file" implementation is
67         // used.
68         DefaultStorage storage.ClientImpl
69
70         EncryptionPolicy
71
72         // Sets usage of Socks5 Proxy. Authentication should be included in the url if needed.
73         // Examples: socks5://demo:demo@192.168.99.100:1080
74         //                       http://proxy.domain.com:3128
75         ProxyURL string
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
84         // HTTPProxy defines proxy for HTTP requests.
85         // Format: func(*Request) (*url.URL, error),
86         // or result of http.ProxyURL(HTTPProxy).
87         // By default, it is composed from ClientConfig.ProxyURL,
88         // if not set explicitly in ClientConfig struct
89         HTTPProxy func(*http.Request) (*url.URL, error)
90         // HTTPUserAgent changes default UserAgent for HTTP requests
91         HTTPUserAgent string
92         // Updated occasionally to when there's been some changes to client
93         // behaviour in case other clients are assuming anything of us. See also
94         // `bep20`.
95         ExtendedHandshakeClientVersion string
96         // Peer ID client identifier prefix. We'll update this occasionally to
97         // reflect changes to client behaviour that other clients may depend on.
98         // Also see `extendedHandshakeClientVersion`.
99         Bep20 string
100
101         // Peer dial timeout to use when there are limited peers.
102         NominalDialTimeout time.Duration
103         // Minimum peer dial timeout to use (even if we have lots of peers).
104         MinDialTimeout             time.Duration
105         EstablishedConnsPerTorrent int
106         HalfOpenConnsPerTorrent    int
107         // Maximum number of peer addresses in reserve.
108         TorrentPeersHighWater int
109         // Minumum number of peers before effort is made to obtain more peers.
110         TorrentPeersLowWater int
111
112         // Limit how long handshake can take. This is to reduce the lingering
113         // impact of a few bad apples. 4s loses 1% of successful handshakes that
114         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
115         HandshakesTimeout time.Duration
116
117         // The IP addresses as our peers should see them. May differ from the
118         // local interfaces due to NAT or other network configurations.
119         PublicIp4 net.IP
120         PublicIp6 net.IP
121
122         DisableAcceptRateLimiting bool
123         // Don't add connections that have the same peer ID as an existing
124         // connection for a given Torrent.
125         dropDuplicatePeerIds bool
126
127         ConnTracker *conntrack.Instance
128
129         // OnQuery hook func
130         DHTOnQuery func(query *krpc.Msg, source net.Addr) (propagate bool)
131 }
132
133 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
134         host, port, err := missinggo.ParseHostPort(addr)
135         expect.Nil(err)
136         cfg.ListenHost = func(string) string { return host }
137         cfg.ListenPort = port
138         return cfg
139 }
140
141 func NewDefaultClientConfig() *ClientConfig {
142         cc := &ClientConfig{
143                 HTTPUserAgent:                  DefaultHTTPUserAgent,
144                 ExtendedHandshakeClientVersion: "go.torrent dev 20181121",
145                 Bep20:                          "-GT0002-",
146                 NominalDialTimeout:             20 * time.Second,
147                 MinDialTimeout:                 3 * time.Second,
148                 EstablishedConnsPerTorrent:     50,
149                 HalfOpenConnsPerTorrent:        25,
150                 TorrentPeersHighWater:          500,
151                 TorrentPeersLowWater:           50,
152                 HandshakesTimeout:              4 * time.Second,
153                 DhtStartingNodes:               dht.GlobalBootstrapAddrs,
154                 ListenHost:                     func(string) string { return "" },
155                 UploadRateLimiter:              unlimited,
156                 DownloadRateLimiter:            unlimited,
157                 ConnTracker:                    conntrack.NewInstance(),
158         }
159         cc.ConnTracker.SetNoMaxEntries()
160         cc.ConnTracker.Timeout = func(conntrack.Entry) time.Duration { return 0 }
161         return cc
162 }
163
164 type EncryptionPolicy struct {
165         DisableEncryption  bool
166         ForceEncryption    bool // Don't allow unobfuscated connections.
167         PreferNoEncryption bool
168 }