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