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