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