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