]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
Implement reading piece hashes from peers
[btrtrc.git] / client.go
1 package torrent
2
3 import (
4         "bufio"
5         "context"
6         "crypto/rand"
7         "encoding/binary"
8         "encoding/hex"
9         "errors"
10         "expvar"
11         "fmt"
12         "io"
13         "math"
14         "net"
15         "net/http"
16         "net/netip"
17         "sort"
18         "strconv"
19         "time"
20
21         "github.com/anacrolix/chansync"
22         "github.com/anacrolix/chansync/events"
23         "github.com/anacrolix/dht/v2"
24         "github.com/anacrolix/dht/v2/krpc"
25         . "github.com/anacrolix/generics"
26         g "github.com/anacrolix/generics"
27         "github.com/anacrolix/log"
28         "github.com/anacrolix/missinggo/perf"
29         "github.com/anacrolix/missinggo/v2"
30         "github.com/anacrolix/missinggo/v2/bitmap"
31         "github.com/anacrolix/missinggo/v2/pproffd"
32         "github.com/anacrolix/sync"
33         "github.com/cespare/xxhash"
34         "github.com/davecgh/go-spew/spew"
35         "github.com/dustin/go-humanize"
36         gbtree "github.com/google/btree"
37         "github.com/pion/datachannel"
38
39         "github.com/anacrolix/torrent/bencode"
40         "github.com/anacrolix/torrent/internal/check"
41         "github.com/anacrolix/torrent/internal/limiter"
42         "github.com/anacrolix/torrent/iplist"
43         "github.com/anacrolix/torrent/metainfo"
44         "github.com/anacrolix/torrent/mse"
45         pp "github.com/anacrolix/torrent/peer_protocol"
46         request_strategy "github.com/anacrolix/torrent/request-strategy"
47         "github.com/anacrolix/torrent/storage"
48         "github.com/anacrolix/torrent/tracker"
49         "github.com/anacrolix/torrent/types/infohash"
50         infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2"
51         "github.com/anacrolix/torrent/webtorrent"
52 )
53
54 // Clients contain zero or more Torrents. A Client manages a blocklist, the
55 // TCP/UDP protocol ports, and DHT as desired.
56 type Client struct {
57         // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
58         // fields. See #262.
59         connStats ConnStats
60
61         _mu    lockWithDeferreds
62         event  sync.Cond
63         closed chansync.SetOnce
64
65         config *ClientConfig
66         logger log.Logger
67
68         peerID         PeerID
69         defaultStorage *storage.Client
70         onClose        []func()
71         dialers        []Dialer
72         listeners      []Listener
73         dhtServers     []DhtServer
74         ipBlockList    iplist.Ranger
75
76         // Set of addresses that have our client ID. This intentionally will
77         // include ourselves if we end up trying to connect to our own address
78         // through legitimate channels.
79         dopplegangerAddrs map[string]struct{}
80         badPeerIPs        map[netip.Addr]struct{}
81         torrents          map[InfoHash]*Torrent
82         pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
83
84         acceptLimiter map[ipStr]int
85         numHalfOpen   int
86
87         websocketTrackers websocketTrackers
88
89         activeAnnounceLimiter limiter.Instance
90         httpClient            *http.Client
91
92         clientHolepunchAddrSets
93
94         defaultLocalLtepProtocolMap LocalLtepProtocolMap
95 }
96
97 type ipStr string
98
99 func (cl *Client) BadPeerIPs() (ips []string) {
100         cl.rLock()
101         ips = cl.badPeerIPsLocked()
102         cl.rUnlock()
103         return
104 }
105
106 func (cl *Client) badPeerIPsLocked() (ips []string) {
107         ips = make([]string, len(cl.badPeerIPs))
108         i := 0
109         for k := range cl.badPeerIPs {
110                 ips[i] = k.String()
111                 i += 1
112         }
113         return
114 }
115
116 func (cl *Client) PeerID() PeerID {
117         return cl.peerID
118 }
119
120 // Returns the port number for the first listener that has one. No longer assumes that all port
121 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
122 // found.
123 func (cl *Client) LocalPort() (port int) {
124         for i := 0; i < len(cl.listeners); i += 1 {
125                 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
126                         return
127                 }
128         }
129         return
130 }
131
132 func writeDhtServerStatus(w io.Writer, s DhtServer) {
133         dhtStats := s.Stats()
134         fmt.Fprintf(w, " ID: %x\n", s.ID())
135         spew.Fdump(w, dhtStats)
136 }
137
138 // Writes out a human readable status of the client, such as for writing to a
139 // HTTP status page.
140 func (cl *Client) WriteStatus(_w io.Writer) {
141         cl.rLock()
142         defer cl.rUnlock()
143         w := bufio.NewWriter(_w)
144         defer w.Flush()
145         fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
146         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
147         fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
148         fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
149         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
150         cl.eachDhtServer(func(s DhtServer) {
151                 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
152                 writeDhtServerStatus(w, s)
153         })
154         dumpStats(w, cl.statsLocked())
155         torrentsSlice := cl.torrentsAsSlice()
156         fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
157         fmt.Fprintln(w)
158         sort.Slice(torrentsSlice, func(l, r int) bool {
159                 return torrentsSlice[l].canonicalShortInfohash().AsString() < torrentsSlice[r].canonicalShortInfohash().AsString()
160         })
161         for _, t := range torrentsSlice {
162                 if t.name() == "" {
163                         fmt.Fprint(w, "<unknown name>")
164                 } else {
165                         fmt.Fprint(w, t.name())
166                 }
167                 fmt.Fprint(w, "\n")
168                 if t.info != nil {
169                         fmt.Fprintf(
170                                 w,
171                                 "%f%% of %d bytes (%s)",
172                                 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
173                                 t.length(),
174                                 humanize.Bytes(uint64(t.length())))
175                 } else {
176                         w.WriteString("<missing metainfo>")
177                 }
178                 fmt.Fprint(w, "\n")
179                 t.writeStatus(w)
180                 fmt.Fprintln(w)
181         }
182 }
183
184 func (cl *Client) initLogger() {
185         logger := cl.config.Logger
186         if logger.IsZero() {
187                 logger = log.Default
188         }
189         if cl.config.Debug {
190                 logger = logger.FilterLevel(log.Debug)
191         }
192         cl.logger = logger.WithValues(cl)
193 }
194
195 func (cl *Client) announceKey() int32 {
196         return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
197 }
198
199 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
200 func (cl *Client) init(cfg *ClientConfig) {
201         cl.config = cfg
202         g.MakeMap(&cl.dopplegangerAddrs)
203         cl.torrents = make(map[metainfo.Hash]*Torrent)
204         cl.activeAnnounceLimiter.SlotsPerKey = 2
205         cl.event.L = cl.locker()
206         cl.ipBlockList = cfg.IPBlocklist
207         cl.httpClient = &http.Client{
208                 Transport: cfg.WebTransport,
209         }
210         if cl.httpClient.Transport == nil {
211                 cl.httpClient.Transport = &http.Transport{
212                         Proxy:       cfg.HTTPProxy,
213                         DialContext: cfg.HTTPDialContext,
214                         // I think this value was observed from some webseeds. It seems reasonable to extend it
215                         // to other uses of HTTP from the client.
216                         MaxConnsPerHost: 10,
217                 }
218         }
219         cl.defaultLocalLtepProtocolMap = makeBuiltinLtepProtocols(!cfg.DisablePEX)
220 }
221
222 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
223         if cfg == nil {
224                 cfg = NewDefaultClientConfig()
225                 cfg.ListenPort = 0
226         }
227         cl = &Client{}
228         cl.init(cfg)
229         go cl.acceptLimitClearer()
230         cl.initLogger()
231         defer func() {
232                 if err != nil {
233                         cl.Close()
234                         cl = nil
235                 }
236         }()
237
238         storageImpl := cfg.DefaultStorage
239         if storageImpl == nil {
240                 // We'd use mmap by default but HFS+ doesn't support sparse files.
241                 storageImplCloser := storage.NewFile(cfg.DataDir)
242                 cl.onClose = append(cl.onClose, func() {
243                         if err := storageImplCloser.Close(); err != nil {
244                                 cl.logger.Printf("error closing default storage: %s", err)
245                         }
246                 })
247                 storageImpl = storageImplCloser
248         }
249         cl.defaultStorage = storage.NewClient(storageImpl)
250
251         if cfg.PeerID != "" {
252                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
253         } else {
254                 o := copy(cl.peerID[:], cfg.Bep20)
255                 _, err = rand.Read(cl.peerID[o:])
256                 if err != nil {
257                         panic("error generating peer id")
258                 }
259         }
260
261         builtinListenNetworks := cl.listenNetworks()
262         sockets, err := listenAll(
263                 builtinListenNetworks,
264                 cl.config.ListenHost,
265                 cl.config.ListenPort,
266                 cl.firewallCallback,
267                 cl.logger,
268         )
269         if err != nil {
270                 return
271         }
272         if len(sockets) == 0 && len(builtinListenNetworks) != 0 {
273                 err = fmt.Errorf("no sockets created for networks %v", builtinListenNetworks)
274                 return
275         }
276
277         // Check for panics.
278         cl.LocalPort()
279
280         for _, _s := range sockets {
281                 s := _s // Go is fucking retarded.
282                 cl.onClose = append(cl.onClose, func() { go s.Close() })
283                 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
284                         cl.dialers = append(cl.dialers, s)
285                         cl.listeners = append(cl.listeners, s)
286                         if cl.config.AcceptPeerConnections {
287                                 go cl.acceptConnections(s)
288                         }
289                 }
290         }
291
292         go cl.forwardPort()
293         if !cfg.NoDHT {
294                 for _, s := range sockets {
295                         if pc, ok := s.(net.PacketConn); ok {
296                                 ds, err := cl.NewAnacrolixDhtServer(pc)
297                                 if err != nil {
298                                         panic(err)
299                                 }
300                                 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
301                                 cl.onClose = append(cl.onClose, func() { ds.Close() })
302                         }
303                 }
304         }
305
306         cl.websocketTrackers = websocketTrackers{
307                 PeerId: cl.peerID,
308                 Logger: cl.logger,
309                 GetAnnounceRequest: func(
310                         event tracker.AnnounceEvent, infoHash [20]byte,
311                 ) (
312                         tracker.AnnounceRequest, error,
313                 ) {
314                         cl.lock()
315                         defer cl.unlock()
316                         t, ok := cl.torrents[infoHash]
317                         if !ok {
318                                 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
319                         }
320                         return t.announceRequest(event, infoHash), nil
321                 },
322                 Proxy:                      cl.config.HTTPProxy,
323                 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
324                 ICEServers:                 cl.config.ICEServers,
325                 DialContext:                cl.config.TrackerDialContext,
326                 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
327                         cl.lock()
328                         defer cl.unlock()
329                         t, ok := cl.torrents[dcc.InfoHash]
330                         if !ok {
331                                 cl.logger.WithDefaultLevel(log.Warning).Printf(
332                                         "got webrtc conn for unloaded torrent with infohash %x",
333                                         dcc.InfoHash,
334                                 )
335                                 dc.Close()
336                                 return
337                         }
338                         go t.onWebRtcConn(dc, dcc)
339                 },
340         }
341
342         return
343 }
344
345 func (cl *Client) AddDhtServer(d DhtServer) {
346         cl.dhtServers = append(cl.dhtServers, d)
347 }
348
349 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
350 // given address for any Torrent.
351 func (cl *Client) AddDialer(d Dialer) {
352         cl.lock()
353         defer cl.unlock()
354         cl.dialers = append(cl.dialers, d)
355         for _, t := range cl.torrents {
356                 t.openNewConns()
357         }
358 }
359
360 func (cl *Client) Listeners() []Listener {
361         return cl.listeners
362 }
363
364 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
365 // yourself.
366 func (cl *Client) AddListener(l Listener) {
367         cl.listeners = append(cl.listeners, l)
368         if cl.config.AcceptPeerConnections {
369                 go cl.acceptConnections(l)
370         }
371 }
372
373 func (cl *Client) firewallCallback(net.Addr) bool {
374         cl.rLock()
375         block := !cl.wantConns() || !cl.config.AcceptPeerConnections
376         cl.rUnlock()
377         if block {
378                 torrent.Add("connections firewalled", 1)
379         } else {
380                 torrent.Add("connections not firewalled", 1)
381         }
382         return block
383 }
384
385 func (cl *Client) listenOnNetwork(n network) bool {
386         if n.Ipv4 && cl.config.DisableIPv4 {
387                 return false
388         }
389         if n.Ipv6 && cl.config.DisableIPv6 {
390                 return false
391         }
392         if n.Tcp && cl.config.DisableTCP {
393                 return false
394         }
395         if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
396                 return false
397         }
398         return true
399 }
400
401 func (cl *Client) listenNetworks() (ns []network) {
402         for _, n := range allPeerNetworks {
403                 if cl.listenOnNetwork(n) {
404                         ns = append(ns, n)
405                 }
406         }
407         return
408 }
409
410 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
411 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
412         logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
413         cfg := dht.ServerConfig{
414                 IPBlocklist:    cl.ipBlockList,
415                 Conn:           conn,
416                 OnAnnouncePeer: cl.onDHTAnnouncePeer,
417                 PublicIP: func() net.IP {
418                         if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
419                                 return cl.config.PublicIp6
420                         }
421                         return cl.config.PublicIp4
422                 }(),
423                 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
424                 OnQuery:       cl.config.DHTOnQuery,
425                 Logger:        logger,
426         }
427         if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
428                 f(&cfg)
429         }
430         s, err = dht.NewServer(&cfg)
431         if err == nil {
432                 go s.TableMaintainer()
433         }
434         return
435 }
436
437 func (cl *Client) Closed() events.Done {
438         return cl.closed.Done()
439 }
440
441 func (cl *Client) eachDhtServer(f func(DhtServer)) {
442         for _, ds := range cl.dhtServers {
443                 f(ds)
444         }
445 }
446
447 // Stops the client. All connections to peers are closed and all activity will come to a halt.
448 func (cl *Client) Close() (errs []error) {
449         var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
450         cl.lock()
451         for _, t := range cl.torrents {
452                 err := t.close(&closeGroup)
453                 if err != nil {
454                         errs = append(errs, err)
455                 }
456         }
457         for i := range cl.onClose {
458                 cl.onClose[len(cl.onClose)-1-i]()
459         }
460         cl.closed.Set()
461         cl.unlock()
462         cl.event.Broadcast()
463         closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
464         return
465 }
466
467 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
468         if cl.ipBlockList == nil {
469                 return
470         }
471         return cl.ipBlockList.Lookup(ip)
472 }
473
474 func (cl *Client) ipIsBlocked(ip net.IP) bool {
475         _, blocked := cl.ipBlockRange(ip)
476         return blocked
477 }
478
479 func (cl *Client) wantConns() bool {
480         if cl.config.AlwaysWantConns {
481                 return true
482         }
483         for _, t := range cl.torrents {
484                 if t.wantIncomingConns() {
485                         return true
486                 }
487         }
488         return false
489 }
490
491 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
492 func (cl *Client) rejectAccepted(conn net.Conn) error {
493         if !cl.wantConns() {
494                 return errors.New("don't want conns right now")
495         }
496         ra := conn.RemoteAddr()
497         if rip := addrIpOrNil(ra); rip != nil {
498                 if cl.config.DisableIPv4Peers && rip.To4() != nil {
499                         return errors.New("ipv4 peers disabled")
500                 }
501                 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
502                         return errors.New("ipv4 disabled")
503                 }
504                 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
505                         return errors.New("ipv6 disabled")
506                 }
507                 if cl.rateLimitAccept(rip) {
508                         return errors.New("source IP accepted rate limited")
509                 }
510                 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
511                         return errors.New("bad source addr")
512                 }
513         }
514         return nil
515 }
516
517 func (cl *Client) acceptConnections(l Listener) {
518         for {
519                 conn, err := l.Accept()
520                 torrent.Add("client listener accepts", 1)
521                 if err == nil {
522                         holepunchAddr, holepunchErr := addrPortFromPeerRemoteAddr(conn.RemoteAddr())
523                         if holepunchErr == nil {
524                                 cl.lock()
525                                 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
526                                         setAdd(&cl.accepted, holepunchAddr)
527                                 }
528                                 if g.MapContains(
529                                         cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
530                                         holepunchAddr,
531                                 ) {
532                                         setAdd(&cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
533                                 }
534                                 cl.unlock()
535                         }
536                 }
537                 conn = pproffd.WrapNetConn(conn)
538                 cl.rLock()
539                 closed := cl.closed.IsSet()
540                 var reject error
541                 if !closed && conn != nil {
542                         reject = cl.rejectAccepted(conn)
543                 }
544                 cl.rUnlock()
545                 if closed {
546                         if conn != nil {
547                                 conn.Close()
548                         }
549                         return
550                 }
551                 if err != nil {
552                         log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
553                         continue
554                 }
555                 go func() {
556                         if reject != nil {
557                                 torrent.Add("rejected accepted connections", 1)
558                                 cl.logger.LazyLog(log.Debug, func() log.Msg {
559                                         return log.Fmsg("rejecting accepted conn: %v", reject)
560                                 })
561                                 conn.Close()
562                         } else {
563                                 go cl.incomingConnection(conn)
564                         }
565                         cl.logger.LazyLog(log.Debug, func() log.Msg {
566                                 return log.Fmsg("accepted %q connection at %q from %q",
567                                         l.Addr().Network(),
568                                         conn.LocalAddr(),
569                                         conn.RemoteAddr(),
570                                 )
571                         })
572                         torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
573                         torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
574                         torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
575                 }()
576         }
577 }
578
579 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
580 func regularNetConnPeerConnConnString(nc net.Conn) string {
581         return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
582 }
583
584 func (cl *Client) incomingConnection(nc net.Conn) {
585         defer nc.Close()
586         if tc, ok := nc.(*net.TCPConn); ok {
587                 tc.SetLinger(0)
588         }
589         remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
590         c := cl.newConnection(
591                 nc,
592                 newConnectionOpts{
593                         outgoing:        false,
594                         remoteAddr:      nc.RemoteAddr(),
595                         localPublicAddr: cl.publicAddr(remoteAddr.IP),
596                         network:         nc.RemoteAddr().Network(),
597                         connString:      regularNetConnPeerConnConnString(nc),
598                 })
599         defer func() {
600                 cl.lock()
601                 defer cl.unlock()
602                 c.close()
603         }()
604         c.Discovery = PeerSourceIncoming
605         cl.runReceivedConn(c)
606 }
607
608 // Returns a handle to the given torrent, if it's present in the client.
609 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
610         cl.rLock()
611         defer cl.rUnlock()
612         t, ok = cl.torrents[ih]
613         return
614 }
615
616 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
617         return cl.torrents[ih]
618 }
619
620 type DialResult struct {
621         Conn   net.Conn
622         Dialer Dialer
623 }
624
625 func countDialResult(err error) {
626         if err == nil {
627                 torrent.Add("successful dials", 1)
628         } else {
629                 torrent.Add("unsuccessful dials", 1)
630         }
631 }
632
633 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
634         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
635         if ret < minDialTimeout {
636                 ret = minDialTimeout
637         }
638         return
639 }
640
641 // Returns whether an address is known to connect to a client with our own ID.
642 func (cl *Client) dopplegangerAddr(addr string) bool {
643         _, ok := cl.dopplegangerAddrs[addr]
644         return ok
645 }
646
647 // Returns a connection over UTP or TCP, whichever is first to connect.
648 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
649         return DialFirst(ctx, addr, cl.dialers)
650 }
651
652 // Returns a connection over UTP or TCP, whichever is first to connect.
653 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
654         pool := dialPool{
655                 addr: addr,
656         }
657         defer pool.startDrainer()
658         for _, _s := range dialers {
659                 pool.add(ctx, _s)
660         }
661         return pool.getFirst()
662 }
663
664 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
665         c, err := s.Dial(ctx, addr)
666         if err != nil {
667                 log.Levelf(log.Debug, "error dialing %q: %v", addr, err)
668         }
669         // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
670         // it now in case we close the connection forthwith. Note this is also done in the TCP dialer
671         // code to increase the chance it's done.
672         if tc, ok := c.(*net.TCPConn); ok {
673                 tc.SetLinger(0)
674         }
675         countDialResult(err)
676         return c
677 }
678
679 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingConnAttemptKey) {
680         path := t.getHalfOpenPath(addr, attemptKey)
681         if !path.Exists() {
682                 panic("should exist")
683         }
684         path.Delete()
685         cl.numHalfOpen--
686         if cl.numHalfOpen < 0 {
687                 panic("should not be possible")
688         }
689         for _, t := range cl.torrents {
690                 t.openNewConns()
691         }
692 }
693
694 func (cl *Client) countHalfOpenFromTorrents() (count int) {
695         for _, t := range cl.torrents {
696                 count += t.numHalfOpenAttempts()
697         }
698         return
699 }
700
701 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
702 // for valid reasons.
703 func (cl *Client) initiateProtocolHandshakes(
704         ctx context.Context,
705         nc net.Conn,
706         t *Torrent,
707         encryptHeader bool,
708         newConnOpts newConnectionOpts,
709 ) (
710         c *PeerConn, err error,
711 ) {
712         c = cl.newConnection(nc, newConnOpts)
713         c.headerEncrypted = encryptHeader
714         ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
715         defer cancel()
716         dl, ok := ctx.Deadline()
717         if !ok {
718                 panic(ctx)
719         }
720         err = nc.SetDeadline(dl)
721         if err != nil {
722                 panic(err)
723         }
724         err = cl.initiateHandshakes(c, t)
725         return
726 }
727
728 func doProtocolHandshakeOnDialResult(
729         t *Torrent,
730         obfuscatedHeader bool,
731         addr PeerRemoteAddr,
732         dr DialResult,
733 ) (
734         c *PeerConn, err error,
735 ) {
736         cl := t.cl
737         nc := dr.Conn
738         addrIpPort, _ := tryIpPortFromNetAddr(addr)
739         c, err = cl.initiateProtocolHandshakes(
740                 context.Background(), nc, t, obfuscatedHeader,
741                 newConnectionOpts{
742                         outgoing:   true,
743                         remoteAddr: addr,
744                         // It would be possible to retrieve a public IP from the dialer used here?
745                         localPublicAddr: cl.publicAddr(addrIpPort.IP),
746                         network:         dr.Dialer.DialerNetwork(),
747                         connString:      regularNetConnPeerConnConnString(nc),
748                 })
749         if err != nil {
750                 nc.Close()
751         }
752         return c, err
753 }
754
755 // Returns nil connection and nil error if no connection could be established for valid reasons.
756 func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn, err error) {
757         // It would be better if dial rate limiting could be tested when considering to open connections
758         // instead. Doing it here means if the limit is low, and the half-open limit is high, we could
759         // end up with lots of outgoing connection attempts pending that were initiated on stale data.
760         {
761                 dialReservation := cl.config.DialRateLimiter.Reserve()
762                 if !opts.receivedHolepunchConnect {
763                         if !dialReservation.OK() {
764                                 err = errors.New("can't make dial limit reservation")
765                                 return
766                         }
767                         time.Sleep(dialReservation.Delay())
768                 }
769         }
770         torrent.Add("establish outgoing connection", 1)
771         addr := opts.peerInfo.Addr
772         dialPool := dialPool{
773                 resCh: make(chan DialResult),
774                 addr:  addr.String(),
775         }
776         defer dialPool.startDrainer()
777         dialTimeout := opts.t.getDialTimeoutUnlocked()
778         {
779                 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
780                 defer cancel()
781                 for _, d := range cl.dialers {
782                         dialPool.add(ctx, d)
783                 }
784         }
785         holepunchAddr, holepunchAddrErr := addrPortFromPeerRemoteAddr(addr)
786         headerObfuscationPolicy := opts.HeaderObfuscationPolicy
787         obfuscatedHeaderFirst := headerObfuscationPolicy.Preferred
788         firstDialResult := dialPool.getFirst()
789         if firstDialResult.Conn == nil {
790                 // No dialers worked. Try to initiate a holepunching rendezvous.
791                 if holepunchAddrErr == nil {
792                         cl.lock()
793                         if !opts.receivedHolepunchConnect {
794                                 g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
795                         }
796                         if !opts.skipHolepunchRendezvous {
797                                 opts.t.trySendHolepunchRendezvous(holepunchAddr)
798                         }
799                         cl.unlock()
800                 }
801                 err = fmt.Errorf("all initial dials failed")
802                 return
803         }
804         if opts.receivedHolepunchConnect && holepunchAddrErr == nil {
805                 cl.lock()
806                 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
807                         g.MakeMapIfNilAndSet(&cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
808                 }
809                 g.MakeMapIfNil(&cl.dialedSuccessfullyAfterHolepunchConnect)
810                 g.MapInsert(cl.dialedSuccessfullyAfterHolepunchConnect, holepunchAddr, struct{}{})
811                 cl.unlock()
812         }
813         c, err = doProtocolHandshakeOnDialResult(
814                 opts.t,
815                 obfuscatedHeaderFirst,
816                 addr,
817                 firstDialResult,
818         )
819         if err == nil {
820                 torrent.Add("initiated conn with preferred header obfuscation", 1)
821                 return
822         }
823         c.logger.Levelf(
824                 log.Debug,
825                 "error doing protocol handshake with header obfuscation %v",
826                 obfuscatedHeaderFirst,
827         )
828         firstDialResult.Conn.Close()
829         // We should have just tried with the preferred header obfuscation. If it was required, there's nothing else to try.
830         if headerObfuscationPolicy.RequirePreferred {
831                 return
832         }
833         // Reuse the dialer that returned already but failed to handshake.
834         {
835                 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
836                 defer cancel()
837                 dialPool.add(ctx, firstDialResult.Dialer)
838         }
839         secondDialResult := dialPool.getFirst()
840         if secondDialResult.Conn == nil {
841                 return
842         }
843         c, err = doProtocolHandshakeOnDialResult(
844                 opts.t,
845                 !obfuscatedHeaderFirst,
846                 addr,
847                 secondDialResult,
848         )
849         if err == nil {
850                 torrent.Add("initiated conn with fallback header obfuscation", 1)
851                 return
852         }
853         c.logger.Levelf(
854                 log.Debug,
855                 "error doing protocol handshake with header obfuscation %v",
856                 !obfuscatedHeaderFirst,
857         )
858         secondDialResult.Conn.Close()
859         return
860 }
861
862 type outgoingConnOpts struct {
863         peerInfo PeerInfo
864         t        *Torrent
865         // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
866         requireRendezvous bool
867         // Don't send rendezvous requests to eligible relays.
868         skipHolepunchRendezvous bool
869         // Outgoing connection attempt is in response to holepunch connect message.
870         receivedHolepunchConnect bool
871         HeaderObfuscationPolicy  HeaderObfuscationPolicy
872 }
873
874 // Called to dial out and run a connection. The addr we're given is already
875 // considered half-open.
876 func (cl *Client) outgoingConnection(
877         opts outgoingConnOpts,
878         attemptKey outgoingConnAttemptKey,
879 ) {
880         c, err := cl.dialAndCompleteHandshake(opts)
881         if err == nil {
882                 c.conn.SetWriteDeadline(time.Time{})
883         }
884         cl.lock()
885         defer cl.unlock()
886         // Don't release lock between here and addPeerConn, unless it's for failure.
887         cl.noLongerHalfOpen(opts.t, opts.peerInfo.Addr.String(), attemptKey)
888         if err != nil {
889                 if cl.config.Debug {
890                         cl.logger.Levelf(
891                                 log.Debug,
892                                 "error establishing outgoing connection to %v: %v",
893                                 opts.peerInfo.Addr,
894                                 err,
895                         )
896                 }
897                 return
898         }
899         defer c.close()
900         c.Discovery = opts.peerInfo.Source
901         c.trusted = opts.peerInfo.Trusted
902         opts.t.runHandshookConnLoggingErr(c)
903 }
904
905 // The port number for incoming peer connections. 0 if the client isn't listening.
906 func (cl *Client) incomingPeerPort() int {
907         return cl.LocalPort()
908 }
909
910 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) (err error) {
911         if c.headerEncrypted {
912                 var rw io.ReadWriter
913                 rw, c.cryptoMethod, err = mse.InitiateHandshake(
914                         struct {
915                                 io.Reader
916                                 io.Writer
917                         }{c.r, c.w},
918                         t.canonicalShortInfohash().Bytes(),
919                         nil,
920                         cl.config.CryptoProvides,
921                 )
922                 c.setRW(rw)
923                 if err != nil {
924                         return fmt.Errorf("header obfuscation handshake: %w", err)
925                 }
926         }
927         ih, err := cl.connBtHandshake(c, t.canonicalShortInfohash())
928         if err != nil {
929                 return fmt.Errorf("bittorrent protocol handshake: %w", err)
930         }
931         if g.Some(ih) == t.infoHash {
932                 return nil
933         }
934         if t.infoHashV2.Ok && *t.infoHashV2.Value.ToShort() == ih {
935                 c.v2 = true
936                 return nil
937         }
938         err = errors.New("bittorrent protocol handshake: peer infohash didn't match")
939         return
940 }
941
942 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
943 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
944 func (cl *Client) forSkeys(f func([]byte) bool) {
945         cl.rLock()
946         defer cl.rUnlock()
947         if false { // Emulate the bug from #114
948                 var firstIh InfoHash
949                 for ih := range cl.torrents {
950                         firstIh = ih
951                         break
952                 }
953                 for range cl.torrents {
954                         if !f(firstIh[:]) {
955                                 break
956                         }
957                 }
958                 return
959         }
960         for ih := range cl.torrents {
961                 if !f(ih[:]) {
962                         break
963                 }
964         }
965 }
966
967 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
968         if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
969                 return ret
970         }
971         return cl.forSkeys
972 }
973
974 // Do encryption and bittorrent handshakes as receiver.
975 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
976         defer perf.ScopeTimerErr(&err)()
977         var rw io.ReadWriter
978         rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
979         c.setRW(rw)
980         if err == nil || err == mse.ErrNoSecretKeyMatch {
981                 if c.headerEncrypted {
982                         torrent.Add("handshakes received encrypted", 1)
983                 } else {
984                         torrent.Add("handshakes received unencrypted", 1)
985                 }
986         } else {
987                 torrent.Add("handshakes received with error while handling encryption", 1)
988         }
989         if err != nil {
990                 if err == mse.ErrNoSecretKeyMatch {
991                         err = nil
992                 }
993                 return
994         }
995         if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
996                 err = errors.New("connection does not have required header obfuscation")
997                 return
998         }
999         ih, err := cl.connBtHandshake(c, nil)
1000         if err != nil {
1001                 return nil, fmt.Errorf("during bt handshake: %w", err)
1002         }
1003         cl.lock()
1004         t = cl.torrents[ih]
1005         cl.unlock()
1006         return
1007 }
1008
1009 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
1010
1011 func init() {
1012         torrent.Set(
1013                 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
1014                 &successfulPeerWireProtocolHandshakePeerReservedBytes)
1015 }
1016
1017 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
1018         res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
1019         if err != nil {
1020                 return
1021         }
1022         successfulPeerWireProtocolHandshakePeerReservedBytes.Add(
1023                 hex.EncodeToString(res.PeerExtensionBits[:]), 1)
1024         ret = res.Hash
1025         c.PeerExtensionBytes = res.PeerExtensionBits
1026         c.PeerID = res.PeerID
1027         c.completedHandshake = time.Now()
1028         if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
1029                 cb(c, res.Hash)
1030         }
1031         return
1032 }
1033
1034 func (cl *Client) runReceivedConn(c *PeerConn) {
1035         err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1036         if err != nil {
1037                 panic(err)
1038         }
1039         t, err := cl.receiveHandshakes(c)
1040         if err != nil {
1041                 cl.logger.LazyLog(log.Debug, func() log.Msg {
1042                         return log.Fmsg(
1043                                 "error receiving handshakes on %v: %s", c, err,
1044                         ).Add(
1045                                 "network", c.Network,
1046                         )
1047                 })
1048                 torrent.Add("error receiving handshake", 1)
1049                 cl.lock()
1050                 cl.onBadAccept(c.RemoteAddr)
1051                 cl.unlock()
1052                 return
1053         }
1054         if t == nil {
1055                 torrent.Add("received handshake for unloaded torrent", 1)
1056                 cl.logger.LazyLog(log.Debug, func() log.Msg {
1057                         return log.Fmsg("received handshake for unloaded torrent")
1058                 })
1059                 cl.lock()
1060                 cl.onBadAccept(c.RemoteAddr)
1061                 cl.unlock()
1062                 return
1063         }
1064         torrent.Add("received handshake for loaded torrent", 1)
1065         c.conn.SetWriteDeadline(time.Time{})
1066         cl.lock()
1067         defer cl.unlock()
1068         t.runHandshookConnLoggingErr(c)
1069 }
1070
1071 // Client lock must be held before entering this.
1072 func (t *Torrent) runHandshookConn(pc *PeerConn) error {
1073         pc.setTorrent(t)
1074         cl := t.cl
1075         for i, b := range cl.config.MinPeerExtensions {
1076                 if pc.PeerExtensionBytes[i]&b != b {
1077                         return fmt.Errorf("peer did not meet minimum peer extensions: %x", pc.PeerExtensionBytes[:])
1078                 }
1079         }
1080         if pc.PeerID == cl.peerID {
1081                 if pc.outgoing {
1082                         connsToSelf.Add(1)
1083                         addr := pc.RemoteAddr.String()
1084                         cl.dopplegangerAddrs[addr] = struct{}{}
1085                 } /* else {
1086                         // Because the remote address is not necessarily the same as its client's torrent listen
1087                         // address, we won't record the remote address as a doppleganger. Instead, the initiator
1088                         // can record *us* as the doppleganger.
1089                 } */
1090                 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1091                 return nil
1092         }
1093         pc.r = deadlineReader{pc.conn, pc.r}
1094         completedHandshakeConnectionFlags.Add(pc.connectionFlags(), 1)
1095         if connIsIpv6(pc.conn) {
1096                 torrent.Add("completed handshake over ipv6", 1)
1097         }
1098         if err := t.addPeerConn(pc); err != nil {
1099                 return fmt.Errorf("adding connection: %w", err)
1100         }
1101         defer t.dropConnection(pc)
1102         pc.addBuiltinLtepProtocols(!cl.config.DisablePEX)
1103         for _, cb := range pc.callbacks.PeerConnAdded {
1104                 cb(pc)
1105         }
1106         pc.startMessageWriter()
1107         pc.sendInitialMessages()
1108         pc.initUpdateRequestsTimer()
1109         err := pc.mainReadLoop()
1110         if err != nil {
1111                 return fmt.Errorf("main read loop: %w", err)
1112         }
1113         return nil
1114 }
1115
1116 func (p *Peer) initUpdateRequestsTimer() {
1117         if check.Enabled {
1118                 if p.updateRequestsTimer != nil {
1119                         panic(p.updateRequestsTimer)
1120                 }
1121         }
1122         if enableUpdateRequestsTimer {
1123                 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1124         }
1125 }
1126
1127 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1128
1129 func (c *Peer) updateRequestsTimerFunc() {
1130         c.locker().Lock()
1131         defer c.locker().Unlock()
1132         if c.closed.IsSet() {
1133                 return
1134         }
1135         if c.isLowOnRequests() {
1136                 // If there are no outstanding requests, then a request update should have already run.
1137                 return
1138         }
1139         if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1140                 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1141                 // already been fired.
1142                 torrent.Add("spurious timer requests updates", 1)
1143                 return
1144         }
1145         c.updateRequests(peerUpdateRequestsTimerReason)
1146 }
1147
1148 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1149 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1150 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1151 const localClientReqq = 1024
1152
1153 // See the order given in Transmission's tr_peerMsgsNew.
1154 func (pc *PeerConn) sendInitialMessages() {
1155         t := pc.t
1156         cl := t.cl
1157         if pc.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1158                 pc.write(pp.Message{
1159                         Type:       pp.Extended,
1160                         ExtendedID: pp.HandshakeExtendedID,
1161                         ExtendedPayload: func() []byte {
1162                                 msg := pp.ExtendedHandshakeMessage{
1163                                         V:            cl.config.ExtendedHandshakeClientVersion,
1164                                         Reqq:         localClientReqq,
1165                                         YourIp:       pp.CompactIp(pc.remoteIp()),
1166                                         Encryption:   cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1167                                         Port:         cl.incomingPeerPort(),
1168                                         MetadataSize: t.metadataSize(),
1169                                         // TODO: We can figure these out specific to the socket used.
1170                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1171                                         Ipv6: cl.config.PublicIp6.To16(),
1172                                 }
1173                                 msg.M = pc.LocalLtepProtocolMap.toSupportedExtensionDict()
1174                                 return bencode.MustMarshal(msg)
1175                         }(),
1176                 })
1177         }
1178         func() {
1179                 if pc.fastEnabled() {
1180                         if t.haveAllPieces() {
1181                                 pc.write(pp.Message{Type: pp.HaveAll})
1182                                 pc.sentHaves.AddRange(0, bitmap.BitRange(pc.t.NumPieces()))
1183                                 return
1184                         } else if !t.haveAnyPieces() {
1185                                 pc.write(pp.Message{Type: pp.HaveNone})
1186                                 pc.sentHaves.Clear()
1187                                 return
1188                         }
1189                 }
1190                 pc.postBitfield()
1191         }()
1192         if pc.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1193                 pc.write(pp.Message{
1194                         Type: pp.Port,
1195                         Port: cl.dhtPort(),
1196                 })
1197         }
1198 }
1199
1200 func (cl *Client) dhtPort() (ret uint16) {
1201         if len(cl.dhtServers) == 0 {
1202                 return
1203         }
1204         return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1205 }
1206
1207 func (cl *Client) haveDhtServer() bool {
1208         return len(cl.dhtServers) > 0
1209 }
1210
1211 // Process incoming ut_metadata message.
1212 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1213         var d pp.ExtendedMetadataRequestMsg
1214         err := bencode.Unmarshal(payload, &d)
1215         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1216         } else if err != nil {
1217                 return fmt.Errorf("error unmarshalling bencode: %s", err)
1218         }
1219         piece := d.Piece
1220         switch d.Type {
1221         case pp.DataMetadataExtensionMsgType:
1222                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1223                 if !c.requestedMetadataPiece(piece) {
1224                         return fmt.Errorf("got unexpected piece %d", piece)
1225                 }
1226                 c.metadataRequests[piece] = false
1227                 begin := len(payload) - d.PieceSize()
1228                 if begin < 0 || begin >= len(payload) {
1229                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1230                 }
1231                 t.saveMetadataPiece(piece, payload[begin:])
1232                 c.lastUsefulChunkReceived = time.Now()
1233                 err = t.maybeCompleteMetadata()
1234                 if err != nil {
1235                         // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1236                         // don't know who to blame. TODO: Also errors can be returned here that aren't related
1237                         // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1238                         // log consumers can filter for this message.
1239                         t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1240                 }
1241                 return err
1242         case pp.RequestMetadataExtensionMsgType:
1243                 if !t.haveMetadataPiece(piece) {
1244                         c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1245                         return nil
1246                 }
1247                 start := (1 << 14) * piece
1248                 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1249                 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1250                 return nil
1251         case pp.RejectMetadataExtensionMsgType:
1252                 return nil
1253         default:
1254                 return errors.New("unknown msg_type value")
1255         }
1256 }
1257
1258 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1259         if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1260                 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1261         }
1262         return false
1263 }
1264
1265 // Returns whether the IP address and port are considered "bad".
1266 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1267         if port == 0 || ip == nil {
1268                 return true
1269         }
1270         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1271                 return true
1272         }
1273         if _, ok := cl.ipBlockRange(ip); ok {
1274                 return true
1275         }
1276         ipAddr, ok := netip.AddrFromSlice(ip)
1277         if !ok {
1278                 panic(ip)
1279         }
1280         if _, ok := cl.badPeerIPs[ipAddr]; ok {
1281                 return true
1282         }
1283         return false
1284 }
1285
1286 // Return a Torrent ready for insertion into a Client.
1287 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1288         return cl.newTorrentOpt(AddTorrentOpts{
1289                 InfoHash: ih,
1290                 Storage:  specStorage,
1291         })
1292 }
1293
1294 // Return a Torrent ready for insertion into a Client.
1295 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1296         var v1InfoHash g.Option[infohash.T]
1297         if !opts.InfoHash.IsZero() {
1298                 v1InfoHash.Set(opts.InfoHash)
1299         }
1300         if !v1InfoHash.Ok && !opts.InfoHashV2.Ok {
1301                 panic("v1 infohash must be nonzero or v2 infohash must be set")
1302         }
1303         // use provided storage, if provided
1304         storageClient := cl.defaultStorage
1305         if opts.Storage != nil {
1306                 storageClient = storage.NewClient(opts.Storage)
1307         }
1308
1309         t = &Torrent{
1310                 cl:         cl,
1311                 infoHash:   v1InfoHash,
1312                 infoHashV2: opts.InfoHashV2,
1313                 peers: prioritizedPeers{
1314                         om: gbtree.New(32),
1315                         getPrio: func(p PeerInfo) peerPriority {
1316                                 ipPort := p.addr()
1317                                 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1318                         },
1319                 },
1320                 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1321
1322                 storageOpener:       storageClient,
1323                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1324
1325                 metadataChanged: sync.Cond{
1326                         L: cl.locker(),
1327                 },
1328                 webSeeds:     make(map[string]*Peer),
1329                 gotMetainfoC: make(chan struct{}),
1330         }
1331         var salt [8]byte
1332         rand.Read(salt[:])
1333         t.smartBanCache.Hash = func(b []byte) uint64 {
1334                 h := xxhash.New()
1335                 h.Write(salt[:])
1336                 h.Write(b)
1337                 return h.Sum64()
1338         }
1339         t.smartBanCache.Init()
1340         t.networkingEnabled.Set()
1341         t.logger = cl.logger.WithDefaultLevel(log.Debug)
1342         t.sourcesLogger = t.logger.WithNames("sources")
1343         if opts.ChunkSize == 0 {
1344                 opts.ChunkSize = defaultChunkSize
1345         }
1346         t.setChunkSize(opts.ChunkSize)
1347         return
1348 }
1349
1350 // A file-like handle to some torrent data resource.
1351 type Handle interface {
1352         io.Reader
1353         io.Seeker
1354         io.Closer
1355         io.ReaderAt
1356 }
1357
1358 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1359         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1360 }
1361
1362 // Deprecated. Adds a torrent by InfoHash with a custom Storage implementation.
1363 // If the torrent already exists then this Storage is ignored and the
1364 // existing torrent returned with `new` set to `false`
1365 func (cl *Client) AddTorrentInfoHashWithStorage(
1366         infoHash metainfo.Hash,
1367         specStorage storage.ClientImpl,
1368 ) (t *Torrent, new bool) {
1369         cl.lock()
1370         defer cl.unlock()
1371         t, ok := cl.torrents[infoHash]
1372         if ok {
1373                 return
1374         }
1375         new = true
1376
1377         t = cl.newTorrent(infoHash, specStorage)
1378         cl.eachDhtServer(func(s DhtServer) {
1379                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1380                         go t.dhtAnnouncer(s)
1381                 }
1382         })
1383         cl.torrents[infoHash] = t
1384         cl.clearAcceptLimits()
1385         t.updateWantPeersEvent()
1386         // Tickle Client.waitAccept, new torrent may want conns.
1387         cl.event.Broadcast()
1388         return
1389 }
1390
1391 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1392 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1393 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1394         infoHash := opts.InfoHash
1395         cl.lock()
1396         defer cl.unlock()
1397         t, ok := cl.torrents[infoHash]
1398         if ok {
1399                 return
1400         }
1401         new = true
1402
1403         t = cl.newTorrentOpt(opts)
1404         cl.eachDhtServer(func(s DhtServer) {
1405                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1406                         go t.dhtAnnouncer(s)
1407                 }
1408         })
1409         cl.torrents[infoHash] = t
1410         t.setInfoBytesLocked(opts.InfoBytes)
1411         cl.clearAcceptLimits()
1412         t.updateWantPeersEvent()
1413         // Tickle Client.waitAccept, new torrent may want conns.
1414         cl.event.Broadcast()
1415         return
1416 }
1417
1418 type AddTorrentOpts struct {
1419         InfoHash   infohash.T
1420         InfoHashV2 g.Option[infohash_v2.T]
1421         Storage    storage.ClientImpl
1422         ChunkSize  pp.Integer
1423         InfoBytes  []byte
1424 }
1425
1426 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1427 // Torrent.MergeSpec.
1428 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1429         t, new = cl.AddTorrentOpt(AddTorrentOpts{
1430                 InfoHash:   spec.InfoHash,
1431                 InfoHashV2: spec.InfoHashV2,
1432                 Storage:    spec.Storage,
1433                 ChunkSize:  spec.ChunkSize,
1434         })
1435         modSpec := *spec
1436         if new {
1437                 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1438                 // it.
1439                 modSpec.ChunkSize = 0
1440         }
1441         err = t.MergeSpec(&modSpec)
1442         if err != nil && new {
1443                 t.Drop()
1444         }
1445         return
1446 }
1447
1448 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1449 // spec.DisallowDataDownload/Upload will be read and applied
1450 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1451 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1452         if spec.DisplayName != "" {
1453                 t.SetDisplayName(spec.DisplayName)
1454         }
1455         if spec.InfoBytes != nil {
1456                 err := t.SetInfoBytes(spec.InfoBytes)
1457                 if err != nil {
1458                         return err
1459                 }
1460         }
1461         cl := t.cl
1462         cl.AddDhtNodes(spec.DhtNodes)
1463         t.UseSources(spec.Sources)
1464         cl.lock()
1465         defer cl.unlock()
1466         t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1467         for _, url := range spec.Webseeds {
1468                 t.addWebSeed(url)
1469         }
1470         for _, peerAddr := range spec.PeerAddrs {
1471                 t.addPeer(PeerInfo{
1472                         Addr:    StringAddr(peerAddr),
1473                         Source:  PeerSourceDirect,
1474                         Trusted: true,
1475                 })
1476         }
1477         if spec.ChunkSize != 0 {
1478                 panic("chunk size cannot be changed for existing Torrent")
1479         }
1480         t.addTrackers(spec.Trackers)
1481         t.maybeNewConns()
1482         t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1483         t.dataUploadDisallowed = spec.DisallowDataUpload
1484         return t.AddPieceLayers(spec.PieceLayers)
1485 }
1486
1487 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1488         t, ok := cl.torrents[infoHash]
1489         if !ok {
1490                 err = fmt.Errorf("no such torrent")
1491                 return
1492         }
1493         err = t.close(wg)
1494         delete(cl.torrents, infoHash)
1495         return
1496 }
1497
1498 func (cl *Client) allTorrentsCompleted() bool {
1499         for _, t := range cl.torrents {
1500                 if !t.haveInfo() {
1501                         return false
1502                 }
1503                 if !t.haveAllPieces() {
1504                         return false
1505                 }
1506         }
1507         return true
1508 }
1509
1510 // Returns true when all torrents are completely downloaded and false if the
1511 // client is stopped before that.
1512 func (cl *Client) WaitAll() bool {
1513         cl.lock()
1514         defer cl.unlock()
1515         for !cl.allTorrentsCompleted() {
1516                 if cl.closed.IsSet() {
1517                         return false
1518                 }
1519                 cl.event.Wait()
1520         }
1521         return true
1522 }
1523
1524 // Returns handles to all the torrents loaded in the Client.
1525 func (cl *Client) Torrents() []*Torrent {
1526         cl.rLock()
1527         defer cl.rUnlock()
1528         return cl.torrentsAsSlice()
1529 }
1530
1531 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1532         for _, t := range cl.torrents {
1533                 ret = append(ret, t)
1534         }
1535         return
1536 }
1537
1538 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1539         spec, err := TorrentSpecFromMagnetUri(uri)
1540         if err != nil {
1541                 return
1542         }
1543         T, _, err = cl.AddTorrentSpec(spec)
1544         return
1545 }
1546
1547 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1548         ts, err := TorrentSpecFromMetaInfoErr(mi)
1549         if err != nil {
1550                 return
1551         }
1552         T, _, err = cl.AddTorrentSpec(ts)
1553         return
1554 }
1555
1556 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1557         mi, err := metainfo.LoadFromFile(filename)
1558         if err != nil {
1559                 return
1560         }
1561         return cl.AddTorrent(mi)
1562 }
1563
1564 func (cl *Client) DhtServers() []DhtServer {
1565         return cl.dhtServers
1566 }
1567
1568 func (cl *Client) AddDhtNodes(nodes []string) {
1569         for _, n := range nodes {
1570                 hmp := missinggo.SplitHostMaybePort(n)
1571                 ip := net.ParseIP(hmp.Host)
1572                 if ip == nil {
1573                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1574                         continue
1575                 }
1576                 ni := krpc.NodeInfo{
1577                         Addr: krpc.NodeAddr{
1578                                 IP:   ip,
1579                                 Port: hmp.Port,
1580                         },
1581                 }
1582                 cl.eachDhtServer(func(s DhtServer) {
1583                         s.AddNode(ni)
1584                 })
1585         }
1586 }
1587
1588 func (cl *Client) banPeerIP(ip net.IP) {
1589         // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1590         // addresses directly to v4on6, which doesn't compare equal with v4.
1591         ipAddr, ok := netip.AddrFromSlice(ip)
1592         if !ok {
1593                 panic(ip)
1594         }
1595         g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1596         for _, t := range cl.torrents {
1597                 t.iterPeers(func(p *Peer) {
1598                         if p.remoteIp().Equal(ip) {
1599                                 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1600                                 // Should this be a close?
1601                                 p.drop()
1602                         }
1603                 })
1604         }
1605 }
1606
1607 type newConnectionOpts struct {
1608         outgoing        bool
1609         remoteAddr      PeerRemoteAddr
1610         localPublicAddr peerLocalPublicAddr
1611         network         string
1612         connString      string
1613 }
1614
1615 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1616         if opts.network == "" {
1617                 panic(opts.remoteAddr)
1618         }
1619         c = &PeerConn{
1620                 Peer: Peer{
1621                         outgoing:        opts.outgoing,
1622                         choking:         true,
1623                         peerChoking:     true,
1624                         PeerMaxRequests: 250,
1625
1626                         RemoteAddr:      opts.remoteAddr,
1627                         localPublicAddr: opts.localPublicAddr,
1628                         Network:         opts.network,
1629                         callbacks:       &cl.config.Callbacks,
1630                 },
1631                 connString: opts.connString,
1632                 conn:       nc,
1633         }
1634         c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1635         c.initRequestState()
1636         // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1637         if opts.remoteAddr != nil {
1638                 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1639                 if err == nil {
1640                         c.bannableAddr = Some(netipAddrPort.Addr())
1641                 }
1642         }
1643         c.peerImpl = c
1644         c.logger = cl.logger.WithDefaultLevel(log.Warning)
1645         c.logger = c.logger.WithContextText(fmt.Sprintf("%T %p", c, c))
1646         c.setRW(connStatsReadWriter{nc, c})
1647         c.r = &rateLimitedReader{
1648                 l: cl.config.DownloadRateLimiter,
1649                 r: c.r,
1650         }
1651         c.logger.Levelf(
1652                 log.Debug,
1653                 "inited with remoteAddr %v network %v outgoing %t",
1654                 opts.remoteAddr, opts.network, opts.outgoing,
1655         )
1656         for _, f := range cl.config.Callbacks.NewPeer {
1657                 f(&c.Peer)
1658         }
1659         return
1660 }
1661
1662 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1663         cl.lock()
1664         defer cl.unlock()
1665         t := cl.torrent(ih)
1666         if t == nil {
1667                 return
1668         }
1669         t.addPeers([]PeerInfo{{
1670                 Addr:   ipPortAddr{ip, port},
1671                 Source: PeerSourceDhtAnnouncePeer,
1672         }})
1673 }
1674
1675 func firstNotNil(ips ...net.IP) net.IP {
1676         for _, ip := range ips {
1677                 if ip != nil {
1678                         return ip
1679                 }
1680         }
1681         return nil
1682 }
1683
1684 func (cl *Client) eachListener(f func(Listener) bool) {
1685         for _, s := range cl.listeners {
1686                 if !f(s) {
1687                         break
1688                 }
1689         }
1690 }
1691
1692 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1693         for i := 0; i < len(cl.listeners); i += 1 {
1694                 if ret = cl.listeners[i]; f(ret) {
1695                         return
1696                 }
1697         }
1698         return nil
1699 }
1700
1701 func (cl *Client) publicIp(peer net.IP) net.IP {
1702         // TODO: Use BEP 10 to determine how peers are seeing us.
1703         if peer.To4() != nil {
1704                 return firstNotNil(
1705                         cl.config.PublicIp4,
1706                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1707                 )
1708         }
1709
1710         return firstNotNil(
1711                 cl.config.PublicIp6,
1712                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1713         )
1714 }
1715
1716 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1717         l := cl.findListener(
1718                 func(l Listener) bool {
1719                         return f(addrIpOrNil(l.Addr()))
1720                 },
1721         )
1722         if l == nil {
1723                 return nil
1724         }
1725         return addrIpOrNil(l.Addr())
1726 }
1727
1728 // Our IP as a peer should see it.
1729 func (cl *Client) publicAddr(peer net.IP) IpPort {
1730         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1731 }
1732
1733 // ListenAddrs addresses currently being listened to.
1734 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1735         cl.lock()
1736         ret = make([]net.Addr, len(cl.listeners))
1737         for i := 0; i < len(cl.listeners); i += 1 {
1738                 ret[i] = cl.listeners[i].Addr()
1739         }
1740         cl.unlock()
1741         return
1742 }
1743
1744 func (cl *Client) PublicIPs() (ips []net.IP) {
1745         if ip := cl.config.PublicIp4; ip != nil {
1746                 ips = append(ips, ip)
1747         }
1748         if ip := cl.config.PublicIp6; ip != nil {
1749                 ips = append(ips, ip)
1750         }
1751         return
1752 }
1753
1754 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1755         ipa, ok := tryIpPortFromNetAddr(addr)
1756         if !ok {
1757                 return
1758         }
1759         ip := maskIpForAcceptLimiting(ipa.IP)
1760         if cl.acceptLimiter == nil {
1761                 cl.acceptLimiter = make(map[ipStr]int)
1762         }
1763         cl.acceptLimiter[ipStr(ip.String())]++
1764 }
1765
1766 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1767         if ip4 := ip.To4(); ip4 != nil {
1768                 return ip4.Mask(net.CIDRMask(24, 32))
1769         }
1770         return ip
1771 }
1772
1773 func (cl *Client) clearAcceptLimits() {
1774         cl.acceptLimiter = nil
1775 }
1776
1777 func (cl *Client) acceptLimitClearer() {
1778         for {
1779                 select {
1780                 case <-cl.closed.Done():
1781                         return
1782                 case <-time.After(15 * time.Minute):
1783                         cl.lock()
1784                         cl.clearAcceptLimits()
1785                         cl.unlock()
1786                 }
1787         }
1788 }
1789
1790 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1791         if cl.config.DisableAcceptRateLimiting {
1792                 return false
1793         }
1794         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1795 }
1796
1797 func (cl *Client) rLock() {
1798         cl._mu.RLock()
1799 }
1800
1801 func (cl *Client) rUnlock() {
1802         cl._mu.RUnlock()
1803 }
1804
1805 func (cl *Client) lock() {
1806         cl._mu.Lock()
1807 }
1808
1809 func (cl *Client) unlock() {
1810         cl._mu.Unlock()
1811 }
1812
1813 func (cl *Client) locker() *lockWithDeferreds {
1814         return &cl._mu
1815 }
1816
1817 func (cl *Client) String() string {
1818         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1819 }
1820
1821 // Returns connection-level aggregate connStats at the Client level. See the comment on
1822 // TorrentStats.ConnStats.
1823 func (cl *Client) ConnStats() ConnStats {
1824         return cl.connStats.Copy()
1825 }
1826
1827 func (cl *Client) Stats() ClientStats {
1828         cl.rLock()
1829         defer cl.rUnlock()
1830         return cl.statsLocked()
1831 }