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