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