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 "golang.org/x/time/rate"
40 "github.com/anacrolix/torrent/bencode"
41 "github.com/anacrolix/torrent/internal/check"
42 "github.com/anacrolix/torrent/internal/limiter"
43 "github.com/anacrolix/torrent/iplist"
44 "github.com/anacrolix/torrent/metainfo"
45 "github.com/anacrolix/torrent/mse"
46 pp "github.com/anacrolix/torrent/peer_protocol"
47 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
48 request_strategy "github.com/anacrolix/torrent/request-strategy"
49 "github.com/anacrolix/torrent/storage"
50 "github.com/anacrolix/torrent/tracker"
51 "github.com/anacrolix/torrent/types/infohash"
52 "github.com/anacrolix/torrent/webtorrent"
55 // Clients contain zero or more Torrents. A Client manages a blocklist, the
56 // TCP/UDP protocol ports, and DHT as desired.
58 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
64 closed chansync.SetOnce
70 defaultStorage *storage.Client
74 dhtServers []DhtServer
75 ipBlockList iplist.Ranger
77 // Set of addresses that have our client ID. This intentionally will
78 // include ourselves if we end up trying to connect to our own address
79 // through legitimate channels.
80 dopplegangerAddrs map[string]struct{}
81 badPeerIPs map[netip.Addr]struct{}
82 torrents map[InfoHash]*Torrent
83 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
85 acceptLimiter map[ipStr]int
86 dialRateLimiter *rate.Limiter
89 websocketTrackers websocketTrackers
91 activeAnnounceLimiter limiter.Instance
92 httpClient *http.Client
94 clientHolepunchAddrSets
99 func (cl *Client) BadPeerIPs() (ips []string) {
101 ips = cl.badPeerIPsLocked()
106 func (cl *Client) badPeerIPsLocked() (ips []string) {
107 ips = make([]string, len(cl.badPeerIPs))
109 for k := range cl.badPeerIPs {
116 func (cl *Client) PeerID() PeerID {
120 // Returns the port number for the first listener that has one. No longer assumes that all port
121 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
123 func (cl *Client) LocalPort() (port int) {
124 for i := 0; i < len(cl.listeners); i += 1 {
125 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
132 func writeDhtServerStatus(w io.Writer, s DhtServer) {
133 dhtStats := s.Stats()
134 fmt.Fprintf(w, " ID: %x\n", s.ID())
135 spew.Fdump(w, dhtStats)
138 // Writes out a human readable status of the client, such as for writing to a
140 func (cl *Client) WriteStatus(_w io.Writer) {
143 w := bufio.NewWriter(_w)
145 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
146 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
147 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
148 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
149 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
150 cl.eachDhtServer(func(s DhtServer) {
151 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
152 writeDhtServerStatus(w, s)
154 dumpStats(w, cl.statsLocked())
155 torrentsSlice := cl.torrentsAsSlice()
156 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
158 sort.Slice(torrentsSlice, func(l, r int) bool {
159 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
161 for _, t := range torrentsSlice {
163 fmt.Fprint(w, "<unknown name>")
165 fmt.Fprint(w, t.name())
171 "%f%% of %d bytes (%s)",
172 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
174 humanize.Bytes(uint64(t.length())))
176 w.WriteString("<missing metainfo>")
184 func (cl *Client) initLogger() {
185 logger := cl.config.Logger
190 logger = logger.FilterLevel(log.Debug)
192 cl.logger = logger.WithValues(cl)
195 func (cl *Client) announceKey() int32 {
196 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
199 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
200 func (cl *Client) init(cfg *ClientConfig) {
202 g.MakeMap(&cl.dopplegangerAddrs)
203 cl.torrents = make(map[metainfo.Hash]*Torrent)
204 cl.dialRateLimiter = rate.NewLimiter(10, 10)
205 cl.activeAnnounceLimiter.SlotsPerKey = 2
206 cl.event.L = cl.locker()
207 cl.ipBlockList = cfg.IPBlocklist
208 cl.httpClient = &http.Client{
209 Transport: &http.Transport{
210 Proxy: cfg.HTTPProxy,
211 DialContext: cfg.HTTPDialContext,
212 // I think this value was observed from some webseeds. It seems reasonable to extend it
213 // to other uses of HTTP from the client.
219 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
221 cfg = NewDefaultClientConfig()
227 go cl.acceptLimitClearer()
236 storageImpl := cfg.DefaultStorage
237 if storageImpl == nil {
238 // We'd use mmap by default but HFS+ doesn't support sparse files.
239 storageImplCloser := storage.NewFile(cfg.DataDir)
240 cl.onClose = append(cl.onClose, func() {
241 if err := storageImplCloser.Close(); err != nil {
242 cl.logger.Printf("error closing default storage: %s", err)
245 storageImpl = storageImplCloser
247 cl.defaultStorage = storage.NewClient(storageImpl)
249 if cfg.PeerID != "" {
250 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
252 o := copy(cl.peerID[:], cfg.Bep20)
253 _, err = rand.Read(cl.peerID[o:])
255 panic("error generating peer id")
259 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
267 for _, _s := range sockets {
268 s := _s // Go is fucking retarded.
269 cl.onClose = append(cl.onClose, func() { go s.Close() })
270 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
271 cl.dialers = append(cl.dialers, s)
272 cl.listeners = append(cl.listeners, s)
273 if cl.config.AcceptPeerConnections {
274 go cl.acceptConnections(s)
281 for _, s := range sockets {
282 if pc, ok := s.(net.PacketConn); ok {
283 ds, err := cl.NewAnacrolixDhtServer(pc)
287 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
288 cl.onClose = append(cl.onClose, func() { ds.Close() })
293 cl.websocketTrackers = websocketTrackers{
296 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
299 t, ok := cl.torrents[infoHash]
301 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
303 return t.announceRequest(event), nil
305 Proxy: cl.config.HTTPProxy,
306 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
307 DialContext: cl.config.TrackerDialContext,
308 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
311 t, ok := cl.torrents[dcc.InfoHash]
313 cl.logger.WithDefaultLevel(log.Warning).Printf(
314 "got webrtc conn for unloaded torrent with infohash %x",
320 go t.onWebRtcConn(dc, dcc)
327 func (cl *Client) AddDhtServer(d DhtServer) {
328 cl.dhtServers = append(cl.dhtServers, d)
331 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
332 // given address for any Torrent.
333 func (cl *Client) AddDialer(d Dialer) {
336 cl.dialers = append(cl.dialers, d)
337 for _, t := range cl.torrents {
342 func (cl *Client) Listeners() []Listener {
346 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
348 func (cl *Client) AddListener(l Listener) {
349 cl.listeners = append(cl.listeners, l)
350 if cl.config.AcceptPeerConnections {
351 go cl.acceptConnections(l)
355 func (cl *Client) firewallCallback(net.Addr) bool {
357 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
360 torrent.Add("connections firewalled", 1)
362 torrent.Add("connections not firewalled", 1)
367 func (cl *Client) listenOnNetwork(n network) bool {
368 if n.Ipv4 && cl.config.DisableIPv4 {
371 if n.Ipv6 && cl.config.DisableIPv6 {
374 if n.Tcp && cl.config.DisableTCP {
377 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
383 func (cl *Client) listenNetworks() (ns []network) {
384 for _, n := range allPeerNetworks {
385 if cl.listenOnNetwork(n) {
392 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
393 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
394 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
395 cfg := dht.ServerConfig{
396 IPBlocklist: cl.ipBlockList,
398 OnAnnouncePeer: cl.onDHTAnnouncePeer,
399 PublicIP: func() net.IP {
400 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
401 return cl.config.PublicIp6
403 return cl.config.PublicIp4
405 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
406 OnQuery: cl.config.DHTOnQuery,
409 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
412 s, err = dht.NewServer(&cfg)
414 go s.TableMaintainer()
419 func (cl *Client) Closed() events.Done {
420 return cl.closed.Done()
423 func (cl *Client) eachDhtServer(f func(DhtServer)) {
424 for _, ds := range cl.dhtServers {
429 // Stops the client. All connections to peers are closed and all activity will come to a halt.
430 func (cl *Client) Close() (errs []error) {
431 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
433 for _, t := range cl.torrents {
434 err := t.close(&closeGroup)
436 errs = append(errs, err)
439 for i := range cl.onClose {
440 cl.onClose[len(cl.onClose)-1-i]()
445 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
449 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
450 if cl.ipBlockList == nil {
453 return cl.ipBlockList.Lookup(ip)
456 func (cl *Client) ipIsBlocked(ip net.IP) bool {
457 _, blocked := cl.ipBlockRange(ip)
461 func (cl *Client) wantConns() bool {
462 if cl.config.AlwaysWantConns {
465 for _, t := range cl.torrents {
466 if t.wantIncomingConns() {
473 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
474 func (cl *Client) rejectAccepted(conn net.Conn) error {
476 return errors.New("don't want conns right now")
478 ra := conn.RemoteAddr()
479 if rip := addrIpOrNil(ra); rip != nil {
480 if cl.config.DisableIPv4Peers && rip.To4() != nil {
481 return errors.New("ipv4 peers disabled")
483 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
484 return errors.New("ipv4 disabled")
486 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
487 return errors.New("ipv6 disabled")
489 if cl.rateLimitAccept(rip) {
490 return errors.New("source IP accepted rate limited")
492 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
493 return errors.New("bad source addr")
499 func (cl *Client) acceptConnections(l Listener) {
501 conn, err := l.Accept()
502 torrent.Add("client listener accepts", 1)
503 conn = pproffd.WrapNetConn(conn)
505 closed := cl.closed.IsSet()
507 if !closed && conn != nil {
508 reject = cl.rejectAccepted(conn)
518 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
522 holepunchAddr, holepunchErr := addrPortFromPeerRemoteAddr(conn.RemoteAddr())
523 if holepunchErr == nil {
526 cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
529 g.MakeMapIfNil(&cl.probablyOnlyConnectedDueToHolepunch)
530 g.MapInsert(cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr, struct{}{})
537 torrent.Add("rejected accepted connections", 1)
538 cl.logger.LazyLog(log.Debug, func() log.Msg {
539 return log.Fmsg("rejecting accepted conn: %v", reject)
543 go cl.incomingConnection(conn)
545 cl.logger.LazyLog(log.Debug, func() log.Msg {
546 return log.Fmsg("accepted %q connection at %q from %q",
552 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
553 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
554 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
559 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
560 func regularNetConnPeerConnConnString(nc net.Conn) string {
561 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
564 func (cl *Client) incomingConnection(nc net.Conn) {
566 if tc, ok := nc.(*net.TCPConn); ok {
569 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
570 c := cl.newConnection(
574 remoteAddr: nc.RemoteAddr(),
575 localPublicAddr: cl.publicAddr(remoteAddr.IP),
576 network: nc.RemoteAddr().Network(),
577 connString: regularNetConnPeerConnConnString(nc),
584 c.Discovery = PeerSourceIncoming
585 cl.runReceivedConn(c)
588 // Returns a handle to the given torrent, if it's present in the client.
589 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
592 t, ok = cl.torrents[ih]
596 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
597 return cl.torrents[ih]
600 type DialResult struct {
605 func countDialResult(err error) {
607 torrent.Add("successful dials", 1)
609 torrent.Add("unsuccessful dials", 1)
613 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
614 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
615 if ret < minDialTimeout {
621 // Returns whether an address is known to connect to a client with our own ID.
622 func (cl *Client) dopplegangerAddr(addr string) bool {
623 _, ok := cl.dopplegangerAddrs[addr]
627 // Returns a connection over UTP or TCP, whichever is first to connect.
628 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
629 return DialFirst(ctx, addr, cl.dialers)
632 // Returns a connection over UTP or TCP, whichever is first to connect.
633 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
637 defer pool.startDrainer()
638 for _, _s := range dialers {
641 return pool.getFirst()
644 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
645 c, err := s.Dial(ctx, addr)
647 log.Levelf(log.Debug, "error dialing %q: %v", addr, err)
649 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
650 // it now in case we close the connection forthwith. Note this is also done in the TCP dialer
651 // code to increase the chance it's done.
652 if tc, ok := c.(*net.TCPConn); ok {
659 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingConnAttemptKey) {
660 path := t.getHalfOpenPath(addr, attemptKey)
662 panic("should exist")
666 if cl.numHalfOpen < 0 {
667 panic("should not be possible")
669 for _, t := range cl.torrents {
674 func (cl *Client) countHalfOpenFromTorrents() (count int) {
675 for _, t := range cl.torrents {
676 count += t.numHalfOpenAttempts()
681 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
682 // for valid reasons.
683 func (cl *Client) initiateProtocolHandshakes(
688 newConnOpts newConnectionOpts,
690 c *PeerConn, err error,
692 c = cl.newConnection(nc, newConnOpts)
693 c.headerEncrypted = encryptHeader
694 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
696 dl, ok := ctx.Deadline()
700 err = nc.SetDeadline(dl)
704 err = cl.initiateHandshakes(c, t)
708 func doProtocolHandshakeOnDialResult(
710 obfuscatedHeader bool,
714 c *PeerConn, err error,
718 addrIpPort, _ := tryIpPortFromNetAddr(addr)
719 c, err = cl.initiateProtocolHandshakes(
720 context.Background(), nc, t, obfuscatedHeader,
724 // It would be possible to retrieve a public IP from the dialer used here?
725 localPublicAddr: cl.publicAddr(addrIpPort.IP),
726 network: dr.Dialer.DialerNetwork(),
727 connString: regularNetConnPeerConnConnString(nc),
735 // Returns nil connection and nil error if no connection could be established for valid reasons.
736 func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn, err error) {
737 torrent.Add("establish outgoing connection", 1)
738 addr := opts.peerInfo.Addr
739 dialPool := dialPool{
740 resCh: make(chan DialResult),
743 defer dialPool.startDrainer()
744 dialTimeout := opts.t.getDialTimeoutUnlocked()
746 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
748 for _, d := range cl.dialers {
752 holepunchAddr, holepunchAddrErr := addrPortFromPeerRemoteAddr(addr)
753 if holepunchAddrErr == nil && opts.receivedHolepunchConnect {
755 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
756 g.MakeMapIfNilAndSet(
757 &cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
764 headerObfuscationPolicy := opts.HeaderObfuscationPolicy
765 obfuscatedHeaderFirst := headerObfuscationPolicy.Preferred
766 firstDialResult := dialPool.getFirst()
767 if firstDialResult.Conn == nil {
768 // No dialers worked. Try to initiate a holepunching rendezvous.
769 if holepunchAddrErr == nil {
771 if !opts.receivedHolepunchConnect {
772 g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
774 if !opts.skipHolepunchRendezvous {
775 opts.t.trySendHolepunchRendezvous(holepunchAddr)
779 err = fmt.Errorf("all initial dials failed")
782 if opts.receivedHolepunchConnect && holepunchAddrErr == nil {
784 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
785 g.MakeMapIfNilAndSet(&cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
787 g.MakeMapIfNil(&cl.dialedSuccessfullyAfterHolepunchConnect)
788 g.MapInsert(cl.dialedSuccessfullyAfterHolepunchConnect, holepunchAddr, struct{}{})
791 c, err = doProtocolHandshakeOnDialResult(
793 obfuscatedHeaderFirst,
798 torrent.Add("initiated conn with preferred header obfuscation", 1)
801 // We should have just tried with the preferred header obfuscation. If it was required, there's nothing else to try.
802 if headerObfuscationPolicy.RequirePreferred {
805 // Reuse the dialer that returned already but failed to handshake.
807 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
809 dialPool.add(ctx, firstDialResult.Dialer)
811 secondDialResult := dialPool.getFirst()
812 if secondDialResult.Conn == nil {
815 c, err = doProtocolHandshakeOnDialResult(
817 !obfuscatedHeaderFirst,
822 torrent.Add("initiated conn with fallback header obfuscation", 1)
828 type outgoingConnOpts struct {
831 // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
832 requireRendezvous bool
833 // Don't send rendezvous requests to eligible relays.
834 skipHolepunchRendezvous bool
835 // Outgoing connection attempt is in response to holepunch connect message.
836 receivedHolepunchConnect bool
837 HeaderObfuscationPolicy HeaderObfuscationPolicy
840 // Called to dial out and run a connection. The addr we're given is already
841 // considered half-open.
842 func (cl *Client) outgoingConnection(
843 opts outgoingConnOpts,
844 attemptKey outgoingConnAttemptKey,
846 cl.dialRateLimiter.Wait(context.Background())
847 c, err := cl.dialAndCompleteHandshake(opts)
849 c.conn.SetWriteDeadline(time.Time{})
853 // Don't release lock between here and addPeerConn, unless it's for failure.
854 cl.noLongerHalfOpen(opts.t, opts.peerInfo.Addr.String(), attemptKey)
859 "error establishing outgoing connection to %v: %v",
867 c.Discovery = opts.peerInfo.Source
868 c.trusted = opts.peerInfo.Trusted
869 opts.t.runHandshookConnLoggingErr(c)
872 // The port number for incoming peer connections. 0 if the client isn't listening.
873 func (cl *Client) incomingPeerPort() int {
874 return cl.LocalPort()
877 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
878 if c.headerEncrypted {
881 rw, c.cryptoMethod, err = mse.InitiateHandshake(
888 cl.config.CryptoProvides,
892 return fmt.Errorf("header obfuscation handshake: %w", err)
895 ih, err := cl.connBtHandshake(c, &t.infoHash)
897 return fmt.Errorf("bittorrent protocol handshake: %w", err)
899 if ih != t.infoHash {
900 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
905 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
906 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
907 func (cl *Client) forSkeys(f func([]byte) bool) {
910 if false { // Emulate the bug from #114
912 for ih := range cl.torrents {
916 for range cl.torrents {
923 for ih := range cl.torrents {
930 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
931 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
937 // Do encryption and bittorrent handshakes as receiver.
938 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
939 defer perf.ScopeTimerErr(&err)()
941 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
943 if err == nil || err == mse.ErrNoSecretKeyMatch {
944 if c.headerEncrypted {
945 torrent.Add("handshakes received encrypted", 1)
947 torrent.Add("handshakes received unencrypted", 1)
950 torrent.Add("handshakes received with error while handling encryption", 1)
953 if err == mse.ErrNoSecretKeyMatch {
958 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
959 err = errors.New("connection does not have required header obfuscation")
962 ih, err := cl.connBtHandshake(c, nil)
964 return nil, fmt.Errorf("during bt handshake: %w", err)
972 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
976 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
977 &successfulPeerWireProtocolHandshakePeerReservedBytes)
980 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
981 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
985 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(
986 hex.EncodeToString(res.PeerExtensionBits[:]), 1)
988 c.PeerExtensionBytes = res.PeerExtensionBits
989 c.PeerID = res.PeerID
990 c.completedHandshake = time.Now()
991 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
997 func (cl *Client) runReceivedConn(c *PeerConn) {
998 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1002 t, err := cl.receiveHandshakes(c)
1004 cl.logger.LazyLog(log.Debug, func() log.Msg {
1006 "error receiving handshakes on %v: %s", c, err,
1008 "network", c.Network,
1011 torrent.Add("error receiving handshake", 1)
1013 cl.onBadAccept(c.RemoteAddr)
1018 torrent.Add("received handshake for unloaded torrent", 1)
1019 cl.logger.LazyLog(log.Debug, func() log.Msg {
1020 return log.Fmsg("received handshake for unloaded torrent")
1023 cl.onBadAccept(c.RemoteAddr)
1027 torrent.Add("received handshake for loaded torrent", 1)
1028 c.conn.SetWriteDeadline(time.Time{})
1031 t.runHandshookConnLoggingErr(c)
1034 // Client lock must be held before entering this.
1035 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
1037 for i, b := range cl.config.MinPeerExtensions {
1038 if c.PeerExtensionBytes[i]&b != b {
1039 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
1042 if c.PeerID == cl.peerID {
1045 addr := c.RemoteAddr.String()
1046 cl.dopplegangerAddrs[addr] = struct{}{}
1048 // Because the remote address is not necessarily the same as its client's torrent listen
1049 // address, we won't record the remote address as a doppleganger. Instead, the initiator
1050 // can record *us* as the doppleganger.
1052 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1055 c.r = deadlineReader{c.conn, c.r}
1056 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1057 if connIsIpv6(c.conn) {
1058 torrent.Add("completed handshake over ipv6", 1)
1060 if err := t.addPeerConn(c); err != nil {
1061 return fmt.Errorf("adding connection: %w", err)
1063 defer t.dropConnection(c)
1064 c.startMessageWriter()
1065 cl.sendInitialMessages(c, t)
1066 c.initUpdateRequestsTimer()
1067 err := c.mainReadLoop()
1069 return fmt.Errorf("main read loop: %w", err)
1074 func (p *Peer) initUpdateRequestsTimer() {
1076 if p.updateRequestsTimer != nil {
1077 panic(p.updateRequestsTimer)
1080 if enableUpdateRequestsTimer {
1081 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1085 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1087 func (c *Peer) updateRequestsTimerFunc() {
1089 defer c.locker().Unlock()
1090 if c.closed.IsSet() {
1093 if c.isLowOnRequests() {
1094 // If there are no outstanding requests, then a request update should have already run.
1097 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1098 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1099 // already been fired.
1100 torrent.Add("spurious timer requests updates", 1)
1103 c.updateRequests(peerUpdateRequestsTimerReason)
1106 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1107 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1108 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1109 const localClientReqq = 1024
1111 // See the order given in Transmission's tr_peerMsgsNew.
1112 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1113 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1114 conn.write(pp.Message{
1116 ExtendedID: pp.HandshakeExtendedID,
1117 ExtendedPayload: func() []byte {
1118 msg := pp.ExtendedHandshakeMessage{
1119 M: map[pp.ExtensionName]pp.ExtensionNumber{
1120 pp.ExtensionNameMetadata: metadataExtendedId,
1121 utHolepunch.ExtensionName: utHolepunchExtendedId,
1123 V: cl.config.ExtendedHandshakeClientVersion,
1124 Reqq: localClientReqq,
1125 YourIp: pp.CompactIp(conn.remoteIp()),
1126 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1127 Port: cl.incomingPeerPort(),
1128 MetadataSize: torrent.metadataSize(),
1129 // TODO: We can figure these out specific to the socket used.
1130 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1131 Ipv6: cl.config.PublicIp6.To16(),
1133 if !cl.config.DisablePEX {
1134 msg.M[pp.ExtensionNamePex] = pexExtendedId
1136 return bencode.MustMarshal(msg)
1141 if conn.fastEnabled() {
1142 if torrent.haveAllPieces() {
1143 conn.write(pp.Message{Type: pp.HaveAll})
1144 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1146 } else if !torrent.haveAnyPieces() {
1147 conn.write(pp.Message{Type: pp.HaveNone})
1148 conn.sentHaves.Clear()
1154 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1155 conn.write(pp.Message{
1162 func (cl *Client) dhtPort() (ret uint16) {
1163 if len(cl.dhtServers) == 0 {
1166 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1169 func (cl *Client) haveDhtServer() bool {
1170 return len(cl.dhtServers) > 0
1173 // Process incoming ut_metadata message.
1174 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1175 var d pp.ExtendedMetadataRequestMsg
1176 err := bencode.Unmarshal(payload, &d)
1177 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1178 } else if err != nil {
1179 return fmt.Errorf("error unmarshalling bencode: %s", err)
1183 case pp.DataMetadataExtensionMsgType:
1184 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1185 if !c.requestedMetadataPiece(piece) {
1186 return fmt.Errorf("got unexpected piece %d", piece)
1188 c.metadataRequests[piece] = false
1189 begin := len(payload) - d.PieceSize()
1190 if begin < 0 || begin >= len(payload) {
1191 return fmt.Errorf("data has bad offset in payload: %d", begin)
1193 t.saveMetadataPiece(piece, payload[begin:])
1194 c.lastUsefulChunkReceived = time.Now()
1195 err = t.maybeCompleteMetadata()
1197 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1198 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1199 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1200 // log consumers can filter for this message.
1201 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1204 case pp.RequestMetadataExtensionMsgType:
1205 if !t.haveMetadataPiece(piece) {
1206 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1209 start := (1 << 14) * piece
1210 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1211 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1213 case pp.RejectMetadataExtensionMsgType:
1216 return errors.New("unknown msg_type value")
1220 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1221 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1222 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1227 // Returns whether the IP address and port are considered "bad".
1228 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1229 if port == 0 || ip == nil {
1232 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1235 if _, ok := cl.ipBlockRange(ip); ok {
1238 ipAddr, ok := netip.AddrFromSlice(ip)
1242 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1248 // Return a Torrent ready for insertion into a Client.
1249 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1250 return cl.newTorrentOpt(AddTorrentOpts{
1252 Storage: specStorage,
1256 // Return a Torrent ready for insertion into a Client.
1257 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1258 // use provided storage, if provided
1259 storageClient := cl.defaultStorage
1260 if opts.Storage != nil {
1261 storageClient = storage.NewClient(opts.Storage)
1266 infoHash: opts.InfoHash,
1267 peers: prioritizedPeers{
1269 getPrio: func(p PeerInfo) peerPriority {
1271 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1274 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1276 storageOpener: storageClient,
1277 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1279 metadataChanged: sync.Cond{
1282 webSeeds: make(map[string]*Peer),
1283 gotMetainfoC: make(chan struct{}),
1285 t.smartBanCache.Hash = sha1.Sum
1286 t.smartBanCache.Init()
1287 t.networkingEnabled.Set()
1288 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString()).WithDefaultLevel(log.Debug)
1289 t.sourcesLogger = t.logger.WithNames("sources")
1290 if opts.ChunkSize == 0 {
1291 opts.ChunkSize = defaultChunkSize
1293 t.setChunkSize(opts.ChunkSize)
1297 // A file-like handle to some torrent data resource.
1298 type Handle interface {
1305 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1306 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1309 // Adds a torrent by InfoHash with a custom Storage implementation.
1310 // If the torrent already exists then this Storage is ignored and the
1311 // existing torrent returned with `new` set to `false`
1312 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1315 t, ok := cl.torrents[infoHash]
1321 t = cl.newTorrent(infoHash, specStorage)
1322 cl.eachDhtServer(func(s DhtServer) {
1323 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1324 go t.dhtAnnouncer(s)
1327 cl.torrents[infoHash] = t
1328 cl.clearAcceptLimits()
1329 t.updateWantPeersEvent()
1330 // Tickle Client.waitAccept, new torrent may want conns.
1331 cl.event.Broadcast()
1335 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1336 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1337 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1338 infoHash := opts.InfoHash
1341 t, ok := cl.torrents[infoHash]
1347 t = cl.newTorrentOpt(opts)
1348 cl.eachDhtServer(func(s DhtServer) {
1349 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1350 go t.dhtAnnouncer(s)
1353 cl.torrents[infoHash] = t
1354 t.setInfoBytesLocked(opts.InfoBytes)
1355 cl.clearAcceptLimits()
1356 t.updateWantPeersEvent()
1357 // Tickle Client.waitAccept, new torrent may want conns.
1358 cl.event.Broadcast()
1362 type AddTorrentOpts struct {
1364 Storage storage.ClientImpl
1365 ChunkSize pp.Integer
1369 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1370 // Torrent.MergeSpec.
1371 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1372 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1373 InfoHash: spec.InfoHash,
1374 Storage: spec.Storage,
1375 ChunkSize: spec.ChunkSize,
1379 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1381 modSpec.ChunkSize = 0
1383 err = t.MergeSpec(&modSpec)
1384 if err != nil && new {
1390 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1391 // spec.DisallowDataDownload/Upload will be read and applied
1392 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1393 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1394 if spec.DisplayName != "" {
1395 t.SetDisplayName(spec.DisplayName)
1397 if spec.InfoBytes != nil {
1398 err := t.SetInfoBytes(spec.InfoBytes)
1404 cl.AddDhtNodes(spec.DhtNodes)
1405 t.UseSources(spec.Sources)
1408 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1409 for _, url := range spec.Webseeds {
1412 for _, peerAddr := range spec.PeerAddrs {
1414 Addr: StringAddr(peerAddr),
1415 Source: PeerSourceDirect,
1419 if spec.ChunkSize != 0 {
1420 panic("chunk size cannot be changed for existing Torrent")
1422 t.addTrackers(spec.Trackers)
1424 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1425 t.dataUploadDisallowed = spec.DisallowDataUpload
1429 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1430 t, ok := cl.torrents[infoHash]
1432 err = fmt.Errorf("no such torrent")
1436 delete(cl.torrents, infoHash)
1440 func (cl *Client) allTorrentsCompleted() bool {
1441 for _, t := range cl.torrents {
1445 if !t.haveAllPieces() {
1452 // Returns true when all torrents are completely downloaded and false if the
1453 // client is stopped before that.
1454 func (cl *Client) WaitAll() bool {
1457 for !cl.allTorrentsCompleted() {
1458 if cl.closed.IsSet() {
1466 // Returns handles to all the torrents loaded in the Client.
1467 func (cl *Client) Torrents() []*Torrent {
1470 return cl.torrentsAsSlice()
1473 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1474 for _, t := range cl.torrents {
1475 ret = append(ret, t)
1480 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1481 spec, err := TorrentSpecFromMagnetUri(uri)
1485 T, _, err = cl.AddTorrentSpec(spec)
1489 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1490 ts, err := TorrentSpecFromMetaInfoErr(mi)
1494 T, _, err = cl.AddTorrentSpec(ts)
1498 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1499 mi, err := metainfo.LoadFromFile(filename)
1503 return cl.AddTorrent(mi)
1506 func (cl *Client) DhtServers() []DhtServer {
1507 return cl.dhtServers
1510 func (cl *Client) AddDhtNodes(nodes []string) {
1511 for _, n := range nodes {
1512 hmp := missinggo.SplitHostMaybePort(n)
1513 ip := net.ParseIP(hmp.Host)
1515 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1518 ni := krpc.NodeInfo{
1519 Addr: krpc.NodeAddr{
1524 cl.eachDhtServer(func(s DhtServer) {
1530 func (cl *Client) banPeerIP(ip net.IP) {
1531 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1532 // addresses directly to v4on6, which doesn't compare equal with v4.
1533 ipAddr, ok := netip.AddrFromSlice(ip)
1537 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1538 for _, t := range cl.torrents {
1539 t.iterPeers(func(p *Peer) {
1540 if p.remoteIp().Equal(ip) {
1541 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1542 // Should this be a close?
1549 type newConnectionOpts struct {
1551 remoteAddr PeerRemoteAddr
1552 localPublicAddr peerLocalPublicAddr
1557 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1558 if opts.network == "" {
1559 panic(opts.remoteAddr)
1563 outgoing: opts.outgoing,
1566 PeerMaxRequests: 250,
1568 RemoteAddr: opts.remoteAddr,
1569 localPublicAddr: opts.localPublicAddr,
1570 Network: opts.network,
1571 callbacks: &cl.config.Callbacks,
1573 connString: opts.connString,
1576 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1577 c.initRequestState()
1578 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1579 if opts.remoteAddr != nil {
1580 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1582 c.bannableAddr = Some(netipAddrPort.Addr())
1586 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1587 c.logger = c.logger.WithContextText(fmt.Sprintf("%T %p", c, c))
1588 c.setRW(connStatsReadWriter{nc, c})
1589 c.r = &rateLimitedReader{
1590 l: cl.config.DownloadRateLimiter,
1595 "new PeerConn %p [Client %p remoteAddr %v network %v outgoing %t]",
1596 c, cl, opts.remoteAddr, opts.network, opts.outgoing,
1598 for _, f := range cl.config.Callbacks.NewPeer {
1604 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1611 t.addPeers([]PeerInfo{{
1612 Addr: ipPortAddr{ip, port},
1613 Source: PeerSourceDhtAnnouncePeer,
1617 func firstNotNil(ips ...net.IP) net.IP {
1618 for _, ip := range ips {
1626 func (cl *Client) eachListener(f func(Listener) bool) {
1627 for _, s := range cl.listeners {
1634 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1635 for i := 0; i < len(cl.listeners); i += 1 {
1636 if ret = cl.listeners[i]; f(ret) {
1643 func (cl *Client) publicIp(peer net.IP) net.IP {
1644 // TODO: Use BEP 10 to determine how peers are seeing us.
1645 if peer.To4() != nil {
1647 cl.config.PublicIp4,
1648 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1653 cl.config.PublicIp6,
1654 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1658 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1659 l := cl.findListener(
1660 func(l Listener) bool {
1661 return f(addrIpOrNil(l.Addr()))
1667 return addrIpOrNil(l.Addr())
1670 // Our IP as a peer should see it.
1671 func (cl *Client) publicAddr(peer net.IP) IpPort {
1672 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1675 // ListenAddrs addresses currently being listened to.
1676 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1678 ret = make([]net.Addr, len(cl.listeners))
1679 for i := 0; i < len(cl.listeners); i += 1 {
1680 ret[i] = cl.listeners[i].Addr()
1686 func (cl *Client) PublicIPs() (ips []net.IP) {
1687 if ip := cl.config.PublicIp4; ip != nil {
1688 ips = append(ips, ip)
1690 if ip := cl.config.PublicIp6; ip != nil {
1691 ips = append(ips, ip)
1696 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1697 ipa, ok := tryIpPortFromNetAddr(addr)
1701 ip := maskIpForAcceptLimiting(ipa.IP)
1702 if cl.acceptLimiter == nil {
1703 cl.acceptLimiter = make(map[ipStr]int)
1705 cl.acceptLimiter[ipStr(ip.String())]++
1708 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1709 if ip4 := ip.To4(); ip4 != nil {
1710 return ip4.Mask(net.CIDRMask(24, 32))
1715 func (cl *Client) clearAcceptLimits() {
1716 cl.acceptLimiter = nil
1719 func (cl *Client) acceptLimitClearer() {
1722 case <-cl.closed.Done():
1724 case <-time.After(15 * time.Minute):
1726 cl.clearAcceptLimits()
1732 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1733 if cl.config.DisableAcceptRateLimiting {
1736 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1739 func (cl *Client) rLock() {
1743 func (cl *Client) rUnlock() {
1747 func (cl *Client) lock() {
1751 func (cl *Client) unlock() {
1755 func (cl *Client) locker() *lockWithDeferreds {
1759 func (cl *Client) String() string {
1760 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1763 // Returns connection-level aggregate connStats at the Client level. See the comment on
1764 // TorrentStats.ConnStats.
1765 func (cl *Client) ConnStats() ConnStats {
1766 return cl.connStats.Copy()
1769 func (cl *Client) Stats() ClientStats {
1772 return cl.statsLocked()