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