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