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