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