21 "github.com/anacrolix/chansync"
22 "github.com/anacrolix/chansync/events"
23 "github.com/anacrolix/dht/v2"
24 "github.com/anacrolix/dht/v2/krpc"
25 . "github.com/anacrolix/generics"
26 g "github.com/anacrolix/generics"
27 "github.com/anacrolix/log"
28 "github.com/anacrolix/missinggo/perf"
29 "github.com/anacrolix/missinggo/v2"
30 "github.com/anacrolix/missinggo/v2/bitmap"
31 "github.com/anacrolix/missinggo/v2/pproffd"
32 "github.com/anacrolix/sync"
33 "github.com/davecgh/go-spew/spew"
34 "github.com/dustin/go-humanize"
35 gbtree "github.com/google/btree"
36 "github.com/pion/datachannel"
37 "golang.org/x/time/rate"
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"
54 // Clients contain zero or more Torrents. A Client manages a blocklist, the
55 // TCP/UDP protocol ports, and DHT as desired.
57 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
63 closed chansync.SetOnce
69 defaultStorage *storage.Client
73 dhtServers []DhtServer
74 ipBlockList iplist.Ranger
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
84 acceptLimiter map[ipStr]int
85 dialRateLimiter *rate.Limiter
88 websocketTrackers websocketTrackers
90 activeAnnounceLimiter limiter.Instance
91 httpClient *http.Client
96 func (cl *Client) BadPeerIPs() (ips []string) {
98 ips = cl.badPeerIPsLocked()
103 func (cl *Client) badPeerIPsLocked() (ips []string) {
104 ips = make([]string, len(cl.badPeerIPs))
106 for k := range cl.badPeerIPs {
113 func (cl *Client) PeerID() PeerID {
117 // Returns the port number for the first listener that has one. No longer assumes that all port
118 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
120 func (cl *Client) LocalPort() (port int) {
121 for i := 0; i < len(cl.listeners); i += 1 {
122 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
129 func writeDhtServerStatus(w io.Writer, s DhtServer) {
130 dhtStats := s.Stats()
131 fmt.Fprintf(w, " ID: %x\n", s.ID())
132 spew.Fdump(w, dhtStats)
135 // Writes out a human readable status of the client, such as for writing to a
137 func (cl *Client) WriteStatus(_w io.Writer) {
140 w := bufio.NewWriter(_w)
142 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
143 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
144 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
145 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
146 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
147 cl.eachDhtServer(func(s DhtServer) {
148 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
149 writeDhtServerStatus(w, s)
151 dumpStats(w, cl.statsLocked())
152 torrentsSlice := cl.torrentsAsSlice()
153 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
155 sort.Slice(torrentsSlice, func(l, r int) bool {
156 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
158 for _, t := range torrentsSlice {
160 fmt.Fprint(w, "<unknown name>")
162 fmt.Fprint(w, t.name())
168 "%f%% of %d bytes (%s)",
169 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
171 humanize.Bytes(uint64(t.length())))
173 w.WriteString("<missing metainfo>")
181 func (cl *Client) initLogger() {
182 logger := cl.config.Logger
187 logger = logger.FilterLevel(log.Debug)
189 cl.logger = logger.WithValues(cl)
192 func (cl *Client) announceKey() int32 {
193 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
196 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
197 func (cl *Client) init(cfg *ClientConfig) {
199 g.MakeMap(&cl.dopplegangerAddrs)
200 cl.torrents = make(map[metainfo.Hash]*Torrent)
201 cl.dialRateLimiter = rate.NewLimiter(10, 10)
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.
216 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
218 cfg = NewDefaultClientConfig()
224 go cl.acceptLimitClearer()
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)
242 storageImpl = storageImplCloser
244 cl.defaultStorage = storage.NewClient(storageImpl)
246 if cfg.PeerID != "" {
247 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
249 o := copy(cl.peerID[:], cfg.Bep20)
250 _, err = rand.Read(cl.peerID[o:])
252 panic("error generating peer id")
256 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
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)
278 for _, s := range sockets {
279 if pc, ok := s.(net.PacketConn); ok {
280 ds, err := cl.NewAnacrolixDhtServer(pc)
284 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
285 cl.onClose = append(cl.onClose, func() { ds.Close() })
290 cl.websocketTrackers = websocketTrackers{
293 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
296 t, ok := cl.torrents[infoHash]
298 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
300 return t.announceRequest(event), nil
302 Proxy: cl.config.HTTPProxy,
303 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
304 DialContext: cl.config.TrackerDialContext,
305 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
308 t, ok := cl.torrents[dcc.InfoHash]
310 cl.logger.WithDefaultLevel(log.Warning).Printf(
311 "got webrtc conn for unloaded torrent with infohash %x",
317 go t.onWebRtcConn(dc, dcc)
324 func (cl *Client) AddDhtServer(d DhtServer) {
325 cl.dhtServers = append(cl.dhtServers, d)
328 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
329 // given address for any Torrent.
330 func (cl *Client) AddDialer(d Dialer) {
333 cl.dialers = append(cl.dialers, d)
334 for _, t := range cl.torrents {
339 func (cl *Client) Listeners() []Listener {
343 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
345 func (cl *Client) AddListener(l Listener) {
346 cl.listeners = append(cl.listeners, l)
347 if cl.config.AcceptPeerConnections {
348 go cl.acceptConnections(l)
352 func (cl *Client) firewallCallback(net.Addr) bool {
354 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
357 torrent.Add("connections firewalled", 1)
359 torrent.Add("connections not firewalled", 1)
364 func (cl *Client) listenOnNetwork(n network) bool {
365 if n.Ipv4 && cl.config.DisableIPv4 {
368 if n.Ipv6 && cl.config.DisableIPv6 {
371 if n.Tcp && cl.config.DisableTCP {
374 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
380 func (cl *Client) listenNetworks() (ns []network) {
381 for _, n := range allPeerNetworks {
382 if cl.listenOnNetwork(n) {
389 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
390 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
391 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
392 cfg := dht.ServerConfig{
393 IPBlocklist: cl.ipBlockList,
395 OnAnnouncePeer: cl.onDHTAnnouncePeer,
396 PublicIP: func() net.IP {
397 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
398 return cl.config.PublicIp6
400 return cl.config.PublicIp4
402 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
403 OnQuery: cl.config.DHTOnQuery,
406 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
409 s, err = dht.NewServer(&cfg)
411 go s.TableMaintainer()
416 func (cl *Client) Closed() events.Done {
417 return cl.closed.Done()
420 func (cl *Client) eachDhtServer(f func(DhtServer)) {
421 for _, ds := range cl.dhtServers {
426 // Stops the client. All connections to peers are closed and all activity will come to a halt.
427 func (cl *Client) Close() (errs []error) {
428 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
430 for _, t := range cl.torrents {
431 err := t.close(&closeGroup)
433 errs = append(errs, err)
436 for i := range cl.onClose {
437 cl.onClose[len(cl.onClose)-1-i]()
442 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
446 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
447 if cl.ipBlockList == nil {
450 return cl.ipBlockList.Lookup(ip)
453 func (cl *Client) ipIsBlocked(ip net.IP) bool {
454 _, blocked := cl.ipBlockRange(ip)
458 func (cl *Client) wantConns() bool {
459 if cl.config.AlwaysWantConns {
462 for _, t := range cl.torrents {
463 if t.wantIncomingConns() {
470 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
471 func (cl *Client) rejectAccepted(conn net.Conn) error {
473 return errors.New("don't want conns right now")
475 ra := conn.RemoteAddr()
476 if rip := addrIpOrNil(ra); rip != nil {
477 if cl.config.DisableIPv4Peers && rip.To4() != nil {
478 return errors.New("ipv4 peers disabled")
480 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
481 return errors.New("ipv4 disabled")
483 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
484 return errors.New("ipv6 disabled")
486 if cl.rateLimitAccept(rip) {
487 return errors.New("source IP accepted rate limited")
489 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
490 return errors.New("bad source addr")
496 func (cl *Client) acceptConnections(l Listener) {
498 conn, err := l.Accept()
499 torrent.Add("client listener accepts", 1)
500 conn = pproffd.WrapNetConn(conn)
502 closed := cl.closed.IsSet()
504 if !closed && conn != nil {
505 reject = cl.rejectAccepted(conn)
515 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
520 torrent.Add("rejected accepted connections", 1)
521 cl.logger.LazyLog(log.Debug, func() log.Msg {
522 return log.Fmsg("rejecting accepted conn: %v", reject)
526 go cl.incomingConnection(conn)
528 cl.logger.LazyLog(log.Debug, func() log.Msg {
529 return log.Fmsg("accepted %q connection at %q from %q",
535 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
536 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
537 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
542 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
543 func regularNetConnPeerConnConnString(nc net.Conn) string {
544 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
547 func (cl *Client) incomingConnection(nc net.Conn) {
549 if tc, ok := nc.(*net.TCPConn); ok {
552 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
553 c := cl.newConnection(
557 remoteAddr: nc.RemoteAddr(),
558 localPublicAddr: cl.publicAddr(remoteAddr.IP),
559 network: nc.RemoteAddr().Network(),
560 connString: regularNetConnPeerConnConnString(nc),
567 c.Discovery = PeerSourceIncoming
568 cl.runReceivedConn(c)
571 // Returns a handle to the given torrent, if it's present in the client.
572 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
575 t, ok = cl.torrents[ih]
579 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
580 return cl.torrents[ih]
583 type DialResult struct {
588 func countDialResult(err error) {
590 torrent.Add("successful dials", 1)
592 torrent.Add("unsuccessful dials", 1)
596 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
597 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
598 if ret < minDialTimeout {
604 // Returns whether an address is known to connect to a client with our own ID.
605 func (cl *Client) dopplegangerAddr(addr string) bool {
606 _, ok := cl.dopplegangerAddrs[addr]
610 // Returns a connection over UTP or TCP, whichever is first to connect.
611 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
612 return DialFirst(ctx, addr, cl.dialers)
615 // Returns a connection over UTP or TCP, whichever is first to connect.
616 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
618 t := perf.NewTimer(perf.CallerName(0))
621 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
623 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
627 ctx, cancel := context.WithCancel(ctx)
628 // As soon as we return one connection, cancel the others.
631 resCh := make(chan DialResult, left)
632 for _, _s := range dialers {
637 dialFromSocket(ctx, s, addr),
642 // Wait for a successful connection.
644 defer perf.ScopeTimer()()
645 for ; left > 0 && res.Conn == nil; left-- {
649 // There are still uncompleted dials.
651 for ; left > 0; left-- {
652 conn := (<-resCh).Conn
659 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
664 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
665 c, err := s.Dial(ctx, addr)
667 log.Levelf(log.Debug, "error dialing %q: %v", addr, err)
669 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
670 // it now in case we close the connection forthwith. Note this is also done in the TCP dialer
671 // code to increase the chance it's done.
672 if tc, ok := c.(*net.TCPConn); ok {
679 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingConnAttemptKey) {
680 path := t.getHalfOpenPath(addr, attemptKey)
682 panic("should exist")
686 if cl.numHalfOpen < 0 {
687 panic("should not be possible")
689 for _, t := range cl.torrents {
694 func (cl *Client) countHalfOpenFromTorrents() (count int) {
695 for _, t := range cl.torrents {
696 count += t.numHalfOpenAttempts()
701 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
702 // for valid reasons.
703 func (cl *Client) initiateProtocolHandshakes(
708 newConnOpts newConnectionOpts,
710 c *PeerConn, err error,
712 c = cl.newConnection(nc, newConnOpts)
713 c.headerEncrypted = encryptHeader
714 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
716 dl, ok := ctx.Deadline()
720 err = nc.SetDeadline(dl)
724 err = cl.initiateHandshakes(c, t)
728 func (cl *Client) waitForRendezvousConnect(ctx context.Context, rz *utHolepunchRendezvous) error {
731 case rz.gotConnect.IsSet():
733 case len(rz.relays) == 0:
734 return errors.New("all relays failed")
735 case ctx.Err() != nil:
736 return context.Cause(ctx)
738 relayCond := rz.relayCond.Signaled()
741 case <-rz.gotConnect.Done():
749 // Returns nil connection and nil error if no connection could be established for valid reasons.
750 func (cl *Client) initiateRendezvousConnect(
751 t *Torrent, addr PeerRemoteAddr,
752 ) (ok bool, err error) {
753 holepunchAddr, err := addrPortFromPeerRemoteAddr(addr)
759 rz, err := t.startHolepunchRendezvous(holepunchAddr)
767 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
769 err = cl.waitForRendezvousConnect(ctx, rz)
770 delete(t.utHolepunchRendezvous, holepunchAddr)
772 err = fmt.Errorf("waiting for rendezvous connect signal: %w", err)
777 // Returns nil connection and nil error if no connection could be established for valid reasons.
778 func (cl *Client) establishOutgoingConnEx(
779 opts outgoingConnOpts,
780 obfuscatedHeader bool,
782 _ *PeerConn, err error,
787 if !opts.skipHolepunchRendezvous {
788 rzOk, err = cl.initiateRendezvousConnect(t, addr)
790 err = fmt.Errorf("initiating rendezvous connect: %w", err)
793 if opts.requireRendezvous && !rzOk {
799 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
802 return t.dialTimeout()
805 dr := cl.dialFirst(dialCtx, addr.String())
808 if dialCtx.Err() != nil {
809 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
811 return nil, errors.New("dial failed")
813 addrIpPort, _ := tryIpPortFromNetAddr(addr)
814 c, err := cl.initiateProtocolHandshakes(
815 context.Background(), nc, t, obfuscatedHeader,
819 // It would be possible to retrieve a public IP from the dialer used here?
820 localPublicAddr: cl.publicAddr(addrIpPort.IP),
821 network: dr.Dialer.DialerNetwork(),
822 connString: regularNetConnPeerConnConnString(nc),
830 // Returns nil connection and nil error if no connection could be established
831 // for valid reasons.
832 func (cl *Client) establishOutgoingConn(opts outgoingConnOpts) (c *PeerConn, err error) {
833 torrent.Add("establish outgoing connection", 1)
834 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
835 c, err = cl.establishOutgoingConnEx(opts, obfuscatedHeaderFirst)
837 torrent.Add("initiated conn with preferred header obfuscation", 1)
840 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
841 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
842 // We should have just tried with the preferred header obfuscation. If it was required,
843 // there's nothing else to try.
846 // Try again with encryption if we didn't earlier, or without if we did.
847 c, err = cl.establishOutgoingConnEx(opts, !obfuscatedHeaderFirst)
849 torrent.Add("initiated conn with fallback header obfuscation", 1)
851 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
855 type outgoingConnOpts struct {
858 // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
859 requireRendezvous bool
860 // Don't send rendezvous requests to eligible relays.
861 skipHolepunchRendezvous bool
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,
870 attemptKey outgoingConnAttemptKey,
872 cl.dialRateLimiter.Wait(context.Background())
873 c, err := cl.establishOutgoingConn(opts)
875 c.conn.SetWriteDeadline(time.Time{})
879 // Don't release lock between here and addPeerConn, unless it's for
881 cl.noLongerHalfOpen(opts.t, opts.addr.String(), attemptKey)
884 cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", opts.addr, err)
891 opts.t.runHandshookConnLoggingErr(c)
894 // The port number for incoming peer connections. 0 if the client isn't listening.
895 func (cl *Client) incomingPeerPort() int {
896 return cl.LocalPort()
899 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
900 if c.headerEncrypted {
903 rw, c.cryptoMethod, err = mse.InitiateHandshake(
910 cl.config.CryptoProvides,
914 return fmt.Errorf("header obfuscation handshake: %w", err)
917 ih, err := cl.connBtHandshake(c, &t.infoHash)
919 return fmt.Errorf("bittorrent protocol handshake: %w", err)
921 if ih != t.infoHash {
922 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
927 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
928 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
929 func (cl *Client) forSkeys(f func([]byte) bool) {
932 if false { // Emulate the bug from #114
934 for ih := range cl.torrents {
938 for range cl.torrents {
945 for ih := range cl.torrents {
952 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
953 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
959 // Do encryption and bittorrent handshakes as receiver.
960 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
961 defer perf.ScopeTimerErr(&err)()
963 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
965 if err == nil || err == mse.ErrNoSecretKeyMatch {
966 if c.headerEncrypted {
967 torrent.Add("handshakes received encrypted", 1)
969 torrent.Add("handshakes received unencrypted", 1)
972 torrent.Add("handshakes received with error while handling encryption", 1)
975 if err == mse.ErrNoSecretKeyMatch {
980 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
981 err = errors.New("connection does not have required header obfuscation")
984 ih, err := cl.connBtHandshake(c, nil)
986 return nil, fmt.Errorf("during bt handshake: %w", err)
994 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
998 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
999 &successfulPeerWireProtocolHandshakePeerReservedBytes)
1002 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
1003 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
1007 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
1009 c.PeerExtensionBytes = res.PeerExtensionBits
1010 c.PeerID = res.PeerID
1011 c.completedHandshake = time.Now()
1012 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
1018 func (cl *Client) runReceivedConn(c *PeerConn) {
1019 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1023 t, err := cl.receiveHandshakes(c)
1025 cl.logger.LazyLog(log.Debug, func() log.Msg {
1027 "error receiving handshakes on %v: %s", c, err,
1029 "network", c.Network,
1032 torrent.Add("error receiving handshake", 1)
1034 cl.onBadAccept(c.RemoteAddr)
1039 torrent.Add("received handshake for unloaded torrent", 1)
1040 cl.logger.LazyLog(log.Debug, func() log.Msg {
1041 return log.Fmsg("received handshake for unloaded torrent")
1044 cl.onBadAccept(c.RemoteAddr)
1048 torrent.Add("received handshake for loaded torrent", 1)
1049 c.conn.SetWriteDeadline(time.Time{})
1052 t.runHandshookConnLoggingErr(c)
1055 // Client lock must be held before entering this.
1056 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
1058 for i, b := range cl.config.MinPeerExtensions {
1059 if c.PeerExtensionBytes[i]&b != b {
1060 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
1063 if c.PeerID == cl.peerID {
1066 addr := c.RemoteAddr.String()
1067 cl.dopplegangerAddrs[addr] = struct{}{}
1069 // Because the remote address is not necessarily the same as its client's torrent listen
1070 // address, we won't record the remote address as a doppleganger. Instead, the initiator
1071 // can record *us* as the doppleganger.
1073 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1076 c.r = deadlineReader{c.conn, c.r}
1077 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1078 if connIsIpv6(c.conn) {
1079 torrent.Add("completed handshake over ipv6", 1)
1081 if err := t.addPeerConn(c); err != nil {
1082 return fmt.Errorf("adding connection: %w", err)
1084 defer t.dropConnection(c)
1085 c.startMessageWriter()
1086 cl.sendInitialMessages(c, t)
1087 c.initUpdateRequestsTimer()
1088 err := c.mainReadLoop()
1090 return fmt.Errorf("main read loop: %w", err)
1095 func (p *Peer) initUpdateRequestsTimer() {
1097 if p.updateRequestsTimer != nil {
1098 panic(p.updateRequestsTimer)
1101 if enableUpdateRequestsTimer {
1102 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1106 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1108 func (c *Peer) updateRequestsTimerFunc() {
1110 defer c.locker().Unlock()
1111 if c.closed.IsSet() {
1114 if c.isLowOnRequests() {
1115 // If there are no outstanding requests, then a request update should have already run.
1118 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1119 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1120 // already been fired.
1121 torrent.Add("spurious timer requests updates", 1)
1124 c.updateRequests(peerUpdateRequestsTimerReason)
1127 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1128 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1129 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1130 const localClientReqq = 1024
1132 // See the order given in Transmission's tr_peerMsgsNew.
1133 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1134 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1135 conn.write(pp.Message{
1137 ExtendedID: pp.HandshakeExtendedID,
1138 ExtendedPayload: func() []byte {
1139 msg := pp.ExtendedHandshakeMessage{
1140 M: map[pp.ExtensionName]pp.ExtensionNumber{
1141 pp.ExtensionNameMetadata: metadataExtendedId,
1142 utHolepunch.ExtensionName: utHolepunchExtendedId,
1144 V: cl.config.ExtendedHandshakeClientVersion,
1145 Reqq: localClientReqq,
1146 YourIp: pp.CompactIp(conn.remoteIp()),
1147 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1148 Port: cl.incomingPeerPort(),
1149 MetadataSize: torrent.metadataSize(),
1150 // TODO: We can figure these out specific to the socket used.
1151 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1152 Ipv6: cl.config.PublicIp6.To16(),
1154 if !cl.config.DisablePEX {
1155 msg.M[pp.ExtensionNamePex] = pexExtendedId
1157 return bencode.MustMarshal(msg)
1162 if conn.fastEnabled() {
1163 if torrent.haveAllPieces() {
1164 conn.write(pp.Message{Type: pp.HaveAll})
1165 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1167 } else if !torrent.haveAnyPieces() {
1168 conn.write(pp.Message{Type: pp.HaveNone})
1169 conn.sentHaves.Clear()
1175 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1176 conn.write(pp.Message{
1183 func (cl *Client) dhtPort() (ret uint16) {
1184 if len(cl.dhtServers) == 0 {
1187 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1190 func (cl *Client) haveDhtServer() bool {
1191 return len(cl.dhtServers) > 0
1194 // Process incoming ut_metadata message.
1195 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1196 var d pp.ExtendedMetadataRequestMsg
1197 err := bencode.Unmarshal(payload, &d)
1198 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1199 } else if err != nil {
1200 return fmt.Errorf("error unmarshalling bencode: %s", err)
1204 case pp.DataMetadataExtensionMsgType:
1205 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1206 if !c.requestedMetadataPiece(piece) {
1207 return fmt.Errorf("got unexpected piece %d", piece)
1209 c.metadataRequests[piece] = false
1210 begin := len(payload) - d.PieceSize()
1211 if begin < 0 || begin >= len(payload) {
1212 return fmt.Errorf("data has bad offset in payload: %d", begin)
1214 t.saveMetadataPiece(piece, payload[begin:])
1215 c.lastUsefulChunkReceived = time.Now()
1216 err = t.maybeCompleteMetadata()
1218 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1219 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1220 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1221 // log consumers can filter for this message.
1222 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1225 case pp.RequestMetadataExtensionMsgType:
1226 if !t.haveMetadataPiece(piece) {
1227 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1230 start := (1 << 14) * piece
1231 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1232 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1234 case pp.RejectMetadataExtensionMsgType:
1237 return errors.New("unknown msg_type value")
1241 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1242 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1243 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1248 // Returns whether the IP address and port are considered "bad".
1249 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1250 if port == 0 || ip == nil {
1253 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1256 if _, ok := cl.ipBlockRange(ip); ok {
1259 ipAddr, ok := netip.AddrFromSlice(ip)
1263 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1269 // Return a Torrent ready for insertion into a Client.
1270 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1271 return cl.newTorrentOpt(AddTorrentOpts{
1273 Storage: specStorage,
1277 // Return a Torrent ready for insertion into a Client.
1278 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1279 // use provided storage, if provided
1280 storageClient := cl.defaultStorage
1281 if opts.Storage != nil {
1282 storageClient = storage.NewClient(opts.Storage)
1287 infoHash: opts.InfoHash,
1288 peers: prioritizedPeers{
1290 getPrio: func(p PeerInfo) peerPriority {
1292 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1295 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1297 storageOpener: storageClient,
1298 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1300 metadataChanged: sync.Cond{
1303 webSeeds: make(map[string]*Peer),
1304 gotMetainfoC: make(chan struct{}),
1306 t.smartBanCache.Hash = sha1.Sum
1307 t.smartBanCache.Init()
1308 t.networkingEnabled.Set()
1309 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString()).WithDefaultLevel(log.Debug)
1310 t.sourcesLogger = t.logger.WithNames("sources")
1311 if opts.ChunkSize == 0 {
1312 opts.ChunkSize = defaultChunkSize
1314 t.setChunkSize(opts.ChunkSize)
1318 // A file-like handle to some torrent data resource.
1319 type Handle interface {
1326 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1327 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1330 // Adds a torrent by InfoHash with a custom Storage implementation.
1331 // If the torrent already exists then this Storage is ignored and the
1332 // existing torrent returned with `new` set to `false`
1333 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1336 t, ok := cl.torrents[infoHash]
1342 t = cl.newTorrent(infoHash, specStorage)
1343 cl.eachDhtServer(func(s DhtServer) {
1344 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1345 go t.dhtAnnouncer(s)
1348 cl.torrents[infoHash] = t
1349 cl.clearAcceptLimits()
1350 t.updateWantPeersEvent()
1351 // Tickle Client.waitAccept, new torrent may want conns.
1352 cl.event.Broadcast()
1356 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1357 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1358 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1359 infoHash := opts.InfoHash
1362 t, ok := cl.torrents[infoHash]
1368 t = cl.newTorrentOpt(opts)
1369 cl.eachDhtServer(func(s DhtServer) {
1370 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1371 go t.dhtAnnouncer(s)
1374 cl.torrents[infoHash] = t
1375 t.setInfoBytesLocked(opts.InfoBytes)
1376 cl.clearAcceptLimits()
1377 t.updateWantPeersEvent()
1378 // Tickle Client.waitAccept, new torrent may want conns.
1379 cl.event.Broadcast()
1383 type AddTorrentOpts struct {
1385 Storage storage.ClientImpl
1386 ChunkSize pp.Integer
1390 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1391 // Torrent.MergeSpec.
1392 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1393 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1394 InfoHash: spec.InfoHash,
1395 Storage: spec.Storage,
1396 ChunkSize: spec.ChunkSize,
1400 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1402 modSpec.ChunkSize = 0
1404 err = t.MergeSpec(&modSpec)
1405 if err != nil && new {
1411 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1412 // spec.DisallowDataDownload/Upload will be read and applied
1413 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1414 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1415 if spec.DisplayName != "" {
1416 t.SetDisplayName(spec.DisplayName)
1418 if spec.InfoBytes != nil {
1419 err := t.SetInfoBytes(spec.InfoBytes)
1425 cl.AddDhtNodes(spec.DhtNodes)
1426 t.UseSources(spec.Sources)
1429 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1430 for _, url := range spec.Webseeds {
1433 for _, peerAddr := range spec.PeerAddrs {
1435 Addr: StringAddr(peerAddr),
1436 Source: PeerSourceDirect,
1440 if spec.ChunkSize != 0 {
1441 panic("chunk size cannot be changed for existing Torrent")
1443 t.addTrackers(spec.Trackers)
1445 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1446 t.dataUploadDisallowed = spec.DisallowDataUpload
1450 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1451 t, ok := cl.torrents[infoHash]
1453 err = fmt.Errorf("no such torrent")
1457 delete(cl.torrents, infoHash)
1461 func (cl *Client) allTorrentsCompleted() bool {
1462 for _, t := range cl.torrents {
1466 if !t.haveAllPieces() {
1473 // Returns true when all torrents are completely downloaded and false if the
1474 // client is stopped before that.
1475 func (cl *Client) WaitAll() bool {
1478 for !cl.allTorrentsCompleted() {
1479 if cl.closed.IsSet() {
1487 // Returns handles to all the torrents loaded in the Client.
1488 func (cl *Client) Torrents() []*Torrent {
1491 return cl.torrentsAsSlice()
1494 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1495 for _, t := range cl.torrents {
1496 ret = append(ret, t)
1501 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1502 spec, err := TorrentSpecFromMagnetUri(uri)
1506 T, _, err = cl.AddTorrentSpec(spec)
1510 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1511 ts, err := TorrentSpecFromMetaInfoErr(mi)
1515 T, _, err = cl.AddTorrentSpec(ts)
1519 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1520 mi, err := metainfo.LoadFromFile(filename)
1524 return cl.AddTorrent(mi)
1527 func (cl *Client) DhtServers() []DhtServer {
1528 return cl.dhtServers
1531 func (cl *Client) AddDhtNodes(nodes []string) {
1532 for _, n := range nodes {
1533 hmp := missinggo.SplitHostMaybePort(n)
1534 ip := net.ParseIP(hmp.Host)
1536 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1539 ni := krpc.NodeInfo{
1540 Addr: krpc.NodeAddr{
1545 cl.eachDhtServer(func(s DhtServer) {
1551 func (cl *Client) banPeerIP(ip net.IP) {
1552 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1553 // addresses directly to v4on6, which doesn't compare equal with v4.
1554 ipAddr, ok := netip.AddrFromSlice(ip)
1558 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1559 for _, t := range cl.torrents {
1560 t.iterPeers(func(p *Peer) {
1561 if p.remoteIp().Equal(ip) {
1562 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1563 // Should this be a close?
1570 type newConnectionOpts struct {
1572 remoteAddr PeerRemoteAddr
1573 localPublicAddr peerLocalPublicAddr
1578 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1579 if opts.network == "" {
1580 panic(opts.remoteAddr)
1584 outgoing: opts.outgoing,
1587 PeerMaxRequests: 250,
1589 RemoteAddr: opts.remoteAddr,
1590 localPublicAddr: opts.localPublicAddr,
1591 Network: opts.network,
1592 callbacks: &cl.config.Callbacks,
1594 connString: opts.connString,
1597 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1598 c.initRequestState()
1599 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1600 if opts.remoteAddr != nil {
1601 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1603 c.bannableAddr = Some(netipAddrPort.Addr())
1607 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1608 c.setRW(connStatsReadWriter{nc, c})
1609 c.r = &rateLimitedReader{
1610 l: cl.config.DownloadRateLimiter,
1615 "new PeerConn %p [Client %p remoteAddr %v network %v outgoing %t]",
1616 c, cl, opts.remoteAddr, opts.network, opts.outgoing,
1618 for _, f := range cl.config.Callbacks.NewPeer {
1624 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1631 t.addPeers([]PeerInfo{{
1632 Addr: ipPortAddr{ip, port},
1633 Source: PeerSourceDhtAnnouncePeer,
1637 func firstNotNil(ips ...net.IP) net.IP {
1638 for _, ip := range ips {
1646 func (cl *Client) eachListener(f func(Listener) bool) {
1647 for _, s := range cl.listeners {
1654 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1655 for i := 0; i < len(cl.listeners); i += 1 {
1656 if ret = cl.listeners[i]; f(ret) {
1663 func (cl *Client) publicIp(peer net.IP) net.IP {
1664 // TODO: Use BEP 10 to determine how peers are seeing us.
1665 if peer.To4() != nil {
1667 cl.config.PublicIp4,
1668 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1673 cl.config.PublicIp6,
1674 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1678 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1679 l := cl.findListener(
1680 func(l Listener) bool {
1681 return f(addrIpOrNil(l.Addr()))
1687 return addrIpOrNil(l.Addr())
1690 // Our IP as a peer should see it.
1691 func (cl *Client) publicAddr(peer net.IP) IpPort {
1692 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1695 // ListenAddrs addresses currently being listened to.
1696 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1698 ret = make([]net.Addr, len(cl.listeners))
1699 for i := 0; i < len(cl.listeners); i += 1 {
1700 ret[i] = cl.listeners[i].Addr()
1706 func (cl *Client) PublicIPs() (ips []net.IP) {
1707 if ip := cl.config.PublicIp4; ip != nil {
1708 ips = append(ips, ip)
1710 if ip := cl.config.PublicIp6; ip != nil {
1711 ips = append(ips, ip)
1716 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1717 ipa, ok := tryIpPortFromNetAddr(addr)
1721 ip := maskIpForAcceptLimiting(ipa.IP)
1722 if cl.acceptLimiter == nil {
1723 cl.acceptLimiter = make(map[ipStr]int)
1725 cl.acceptLimiter[ipStr(ip.String())]++
1728 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1729 if ip4 := ip.To4(); ip4 != nil {
1730 return ip4.Mask(net.CIDRMask(24, 32))
1735 func (cl *Client) clearAcceptLimits() {
1736 cl.acceptLimiter = nil
1739 func (cl *Client) acceptLimitClearer() {
1742 case <-cl.closed.Done():
1744 case <-time.After(15 * time.Minute):
1746 cl.clearAcceptLimits()
1752 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1753 if cl.config.DisableAcceptRateLimiting {
1756 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1759 func (cl *Client) rLock() {
1763 func (cl *Client) rUnlock() {
1767 func (cl *Client) lock() {
1771 func (cl *Client) unlock() {
1775 func (cl *Client) locker() *lockWithDeferreds {
1779 func (cl *Client) String() string {
1780 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1783 // Returns connection-level aggregate connStats at the Client level. See the comment on
1784 // TorrentStats.ConnStats.
1785 func (cl *Client) ConnStats() ConnStats {
1786 return cl.connStats.Copy()
1789 func (cl *Client) Stats() ClientStats {
1792 return cl.statsLocked()
1795 func (cl *Client) statsLocked() (stats ClientStats) {
1796 stats.ConnStats = cl.connStats.Copy()
1797 stats.ActiveHalfOpenAttempts = cl.numHalfOpen