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