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