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"
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
87 websocketTrackers websocketTrackers
89 activeAnnounceLimiter limiter.Instance
90 httpClient *http.Client
92 clientHolepunchAddrSets
97 func (cl *Client) BadPeerIPs() (ips []string) {
99 ips = cl.badPeerIPsLocked()
104 func (cl *Client) badPeerIPsLocked() (ips []string) {
105 ips = make([]string, len(cl.badPeerIPs))
107 for k := range cl.badPeerIPs {
114 func (cl *Client) PeerID() PeerID {
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
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 {
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)
136 // Writes out a human readable status of the client, such as for writing to a
138 func (cl *Client) WriteStatus(_w io.Writer) {
141 w := bufio.NewWriter(_w)
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)
152 dumpStats(w, cl.statsLocked())
153 torrentsSlice := cl.torrentsAsSlice()
154 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
156 sort.Slice(torrentsSlice, func(l, r int) bool {
157 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
159 for _, t := range torrentsSlice {
161 fmt.Fprint(w, "<unknown name>")
163 fmt.Fprint(w, t.name())
169 "%f%% of %d bytes (%s)",
170 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
172 humanize.Bytes(uint64(t.length())))
174 w.WriteString("<missing metainfo>")
182 func (cl *Client) initLogger() {
183 logger := cl.config.Logger
188 logger = logger.FilterLevel(log.Debug)
190 cl.logger = logger.WithValues(cl)
193 func (cl *Client) announceKey() int32 {
194 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
197 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
198 func (cl *Client) init(cfg *ClientConfig) {
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.
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 ICEServers: cl.config.ICEServers,
305 DialContext: cl.config.TrackerDialContext,
306 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
309 t, ok := cl.torrents[dcc.InfoHash]
311 cl.logger.WithDefaultLevel(log.Warning).Printf(
312 "got webrtc conn for unloaded torrent with infohash %x",
318 go t.onWebRtcConn(dc, dcc)
325 func (cl *Client) AddDhtServer(d DhtServer) {
326 cl.dhtServers = append(cl.dhtServers, d)
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) {
334 cl.dialers = append(cl.dialers, d)
335 for _, t := range cl.torrents {
340 func (cl *Client) Listeners() []Listener {
344 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
346 func (cl *Client) AddListener(l Listener) {
347 cl.listeners = append(cl.listeners, l)
348 if cl.config.AcceptPeerConnections {
349 go cl.acceptConnections(l)
353 func (cl *Client) firewallCallback(net.Addr) bool {
355 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
358 torrent.Add("connections firewalled", 1)
360 torrent.Add("connections not firewalled", 1)
365 func (cl *Client) listenOnNetwork(n network) bool {
366 if n.Ipv4 && cl.config.DisableIPv4 {
369 if n.Ipv6 && cl.config.DisableIPv6 {
372 if n.Tcp && cl.config.DisableTCP {
375 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
381 func (cl *Client) listenNetworks() (ns []network) {
382 for _, n := range allPeerNetworks {
383 if cl.listenOnNetwork(n) {
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,
396 OnAnnouncePeer: cl.onDHTAnnouncePeer,
397 PublicIP: func() net.IP {
398 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
399 return cl.config.PublicIp6
401 return cl.config.PublicIp4
403 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
404 OnQuery: cl.config.DHTOnQuery,
407 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
410 s, err = dht.NewServer(&cfg)
412 go s.TableMaintainer()
417 func (cl *Client) Closed() events.Done {
418 return cl.closed.Done()
421 func (cl *Client) eachDhtServer(f func(DhtServer)) {
422 for _, ds := range cl.dhtServers {
427 // Stops the client. All connections to peers are closed and all activity will come to a halt.
428 func (cl *Client) Close() (errs []error) {
429 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
431 for _, t := range cl.torrents {
432 err := t.close(&closeGroup)
434 errs = append(errs, err)
437 for i := range cl.onClose {
438 cl.onClose[len(cl.onClose)-1-i]()
443 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
447 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
448 if cl.ipBlockList == nil {
451 return cl.ipBlockList.Lookup(ip)
454 func (cl *Client) ipIsBlocked(ip net.IP) bool {
455 _, blocked := cl.ipBlockRange(ip)
459 func (cl *Client) wantConns() bool {
460 if cl.config.AlwaysWantConns {
463 for _, t := range cl.torrents {
464 if t.wantIncomingConns() {
471 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
472 func (cl *Client) rejectAccepted(conn net.Conn) error {
474 return errors.New("don't want conns right now")
476 ra := conn.RemoteAddr()
477 if rip := addrIpOrNil(ra); rip != nil {
478 if cl.config.DisableIPv4Peers && rip.To4() != nil {
479 return errors.New("ipv4 peers disabled")
481 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
482 return errors.New("ipv4 disabled")
484 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
485 return errors.New("ipv6 disabled")
487 if cl.rateLimitAccept(rip) {
488 return errors.New("source IP accepted rate limited")
490 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
491 return errors.New("bad source addr")
497 func (cl *Client) acceptConnections(l Listener) {
499 conn, err := l.Accept()
500 torrent.Add("client listener accepts", 1)
501 conn = pproffd.WrapNetConn(conn)
503 closed := cl.closed.IsSet()
505 if !closed && conn != nil {
506 reject = cl.rejectAccepted(conn)
516 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
520 holepunchAddr, holepunchErr := addrPortFromPeerRemoteAddr(conn.RemoteAddr())
521 if holepunchErr == nil {
524 cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
527 g.MakeMapIfNil(&cl.probablyOnlyConnectedDueToHolepunch)
528 g.MapInsert(cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr, struct{}{})
535 torrent.Add("rejected accepted connections", 1)
536 cl.logger.LazyLog(log.Debug, func() log.Msg {
537 return log.Fmsg("rejecting accepted conn: %v", reject)
541 go cl.incomingConnection(conn)
543 cl.logger.LazyLog(log.Debug, func() log.Msg {
544 return log.Fmsg("accepted %q connection at %q from %q",
550 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
551 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
552 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
557 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
558 func regularNetConnPeerConnConnString(nc net.Conn) string {
559 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
562 func (cl *Client) incomingConnection(nc net.Conn) {
564 if tc, ok := nc.(*net.TCPConn); ok {
567 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
568 c := cl.newConnection(
572 remoteAddr: nc.RemoteAddr(),
573 localPublicAddr: cl.publicAddr(remoteAddr.IP),
574 network: nc.RemoteAddr().Network(),
575 connString: regularNetConnPeerConnConnString(nc),
582 c.Discovery = PeerSourceIncoming
583 cl.runReceivedConn(c)
586 // Returns a handle to the given torrent, if it's present in the client.
587 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
590 t, ok = cl.torrents[ih]
594 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
595 return cl.torrents[ih]
598 type DialResult struct {
603 func countDialResult(err error) {
605 torrent.Add("successful dials", 1)
607 torrent.Add("unsuccessful dials", 1)
611 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
612 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
613 if ret < minDialTimeout {
619 // Returns whether an address is known to connect to a client with our own ID.
620 func (cl *Client) dopplegangerAddr(addr string) bool {
621 _, ok := cl.dopplegangerAddrs[addr]
625 // Returns a connection over UTP or TCP, whichever is first to connect.
626 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
627 return DialFirst(ctx, addr, cl.dialers)
630 // Returns a connection over UTP or TCP, whichever is first to connect.
631 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
635 defer pool.startDrainer()
636 for _, _s := range dialers {
639 return pool.getFirst()
642 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
643 c, err := s.Dial(ctx, addr)
645 log.Levelf(log.Debug, "error dialing %q: %v", addr, err)
647 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
648 // it now in case we close the connection forthwith. Note this is also done in the TCP dialer
649 // code to increase the chance it's done.
650 if tc, ok := c.(*net.TCPConn); ok {
657 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingConnAttemptKey) {
658 path := t.getHalfOpenPath(addr, attemptKey)
660 panic("should exist")
664 if cl.numHalfOpen < 0 {
665 panic("should not be possible")
667 for _, t := range cl.torrents {
672 func (cl *Client) countHalfOpenFromTorrents() (count int) {
673 for _, t := range cl.torrents {
674 count += t.numHalfOpenAttempts()
679 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
680 // for valid reasons.
681 func (cl *Client) initiateProtocolHandshakes(
686 newConnOpts newConnectionOpts,
688 c *PeerConn, err error,
690 c = cl.newConnection(nc, newConnOpts)
691 c.headerEncrypted = encryptHeader
692 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
694 dl, ok := ctx.Deadline()
698 err = nc.SetDeadline(dl)
702 err = cl.initiateHandshakes(c, t)
706 func doProtocolHandshakeOnDialResult(
708 obfuscatedHeader bool,
712 c *PeerConn, err error,
716 addrIpPort, _ := tryIpPortFromNetAddr(addr)
717 c, err = cl.initiateProtocolHandshakes(
718 context.Background(), nc, t, obfuscatedHeader,
722 // It would be possible to retrieve a public IP from the dialer used here?
723 localPublicAddr: cl.publicAddr(addrIpPort.IP),
724 network: dr.Dialer.DialerNetwork(),
725 connString: regularNetConnPeerConnConnString(nc),
733 // Returns nil connection and nil error if no connection could be established for valid reasons.
734 func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn, err error) {
735 // It would be better if dial rate limiting could be tested when considering to open connections
736 // instead. Doing it here means if the limit is low, and the half-open limit is high, we could
737 // end up with lots of outgoing connection attempts pending that were initiated on stale data.
739 dialReservation := cl.config.DialRateLimiter.Reserve()
740 if !opts.receivedHolepunchConnect {
741 if !dialReservation.OK() {
742 err = errors.New("can't make dial limit reservation")
745 time.Sleep(dialReservation.Delay())
748 torrent.Add("establish outgoing connection", 1)
749 addr := opts.peerInfo.Addr
750 dialPool := dialPool{
751 resCh: make(chan DialResult),
754 defer dialPool.startDrainer()
755 dialTimeout := opts.t.getDialTimeoutUnlocked()
757 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
759 for _, d := range cl.dialers {
763 holepunchAddr, holepunchAddrErr := addrPortFromPeerRemoteAddr(addr)
764 if holepunchAddrErr == nil && opts.receivedHolepunchConnect {
766 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
767 g.MakeMapIfNilAndSet(
768 &cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
775 headerObfuscationPolicy := opts.HeaderObfuscationPolicy
776 obfuscatedHeaderFirst := headerObfuscationPolicy.Preferred
777 firstDialResult := dialPool.getFirst()
778 if firstDialResult.Conn == nil {
779 // No dialers worked. Try to initiate a holepunching rendezvous.
780 if holepunchAddrErr == nil {
782 if !opts.receivedHolepunchConnect {
783 g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
785 if !opts.skipHolepunchRendezvous {
786 opts.t.trySendHolepunchRendezvous(holepunchAddr)
790 err = fmt.Errorf("all initial dials failed")
793 if opts.receivedHolepunchConnect && holepunchAddrErr == nil {
795 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
796 g.MakeMapIfNilAndSet(&cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
798 g.MakeMapIfNil(&cl.dialedSuccessfullyAfterHolepunchConnect)
799 g.MapInsert(cl.dialedSuccessfullyAfterHolepunchConnect, holepunchAddr, struct{}{})
802 c, err = doProtocolHandshakeOnDialResult(
804 obfuscatedHeaderFirst,
809 torrent.Add("initiated conn with preferred header obfuscation", 1)
814 "error doing protocol handshake with header obfuscation %v",
815 obfuscatedHeaderFirst,
817 firstDialResult.Conn.Close()
818 // We should have just tried with the preferred header obfuscation. If it was required, there's nothing else to try.
819 if headerObfuscationPolicy.RequirePreferred {
822 // Reuse the dialer that returned already but failed to handshake.
824 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
826 dialPool.add(ctx, firstDialResult.Dialer)
828 secondDialResult := dialPool.getFirst()
829 if secondDialResult.Conn == nil {
832 c, err = doProtocolHandshakeOnDialResult(
834 !obfuscatedHeaderFirst,
839 torrent.Add("initiated conn with fallback header obfuscation", 1)
844 "error doing protocol handshake with header obfuscation %v",
845 !obfuscatedHeaderFirst,
847 secondDialResult.Conn.Close()
851 type outgoingConnOpts struct {
854 // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
855 requireRendezvous bool
856 // Don't send rendezvous requests to eligible relays.
857 skipHolepunchRendezvous bool
858 // Outgoing connection attempt is in response to holepunch connect message.
859 receivedHolepunchConnect bool
860 HeaderObfuscationPolicy HeaderObfuscationPolicy
863 // Called to dial out and run a connection. The addr we're given is already
864 // considered half-open.
865 func (cl *Client) outgoingConnection(
866 opts outgoingConnOpts,
867 attemptKey outgoingConnAttemptKey,
869 c, err := cl.dialAndCompleteHandshake(opts)
871 c.conn.SetWriteDeadline(time.Time{})
875 // Don't release lock between here and addPeerConn, unless it's for failure.
876 cl.noLongerHalfOpen(opts.t, opts.peerInfo.Addr.String(), attemptKey)
881 "error establishing outgoing connection to %v: %v",
889 c.Discovery = opts.peerInfo.Source
890 c.trusted = opts.peerInfo.Trusted
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(
1008 hex.EncodeToString(res.PeerExtensionBits[:]), 1)
1010 c.PeerExtensionBytes = res.PeerExtensionBits
1011 c.PeerID = res.PeerID
1012 c.completedHandshake = time.Now()
1013 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
1019 func (cl *Client) runReceivedConn(c *PeerConn) {
1020 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1024 t, err := cl.receiveHandshakes(c)
1026 cl.logger.LazyLog(log.Debug, func() log.Msg {
1028 "error receiving handshakes on %v: %s", c, err,
1030 "network", c.Network,
1033 torrent.Add("error receiving handshake", 1)
1035 cl.onBadAccept(c.RemoteAddr)
1040 torrent.Add("received handshake for unloaded torrent", 1)
1041 cl.logger.LazyLog(log.Debug, func() log.Msg {
1042 return log.Fmsg("received handshake for unloaded torrent")
1045 cl.onBadAccept(c.RemoteAddr)
1049 torrent.Add("received handshake for loaded torrent", 1)
1050 c.conn.SetWriteDeadline(time.Time{})
1053 t.runHandshookConnLoggingErr(c)
1056 // Client lock must be held before entering this.
1057 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
1059 for i, b := range cl.config.MinPeerExtensions {
1060 if c.PeerExtensionBytes[i]&b != b {
1061 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
1064 if c.PeerID == cl.peerID {
1067 addr := c.RemoteAddr.String()
1068 cl.dopplegangerAddrs[addr] = struct{}{}
1070 // Because the remote address is not necessarily the same as its client's torrent listen
1071 // address, we won't record the remote address as a doppleganger. Instead, the initiator
1072 // can record *us* as the doppleganger.
1074 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1077 c.r = deadlineReader{c.conn, c.r}
1078 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1079 if connIsIpv6(c.conn) {
1080 torrent.Add("completed handshake over ipv6", 1)
1082 if err := t.addPeerConn(c); err != nil {
1083 return fmt.Errorf("adding connection: %w", err)
1085 defer t.dropConnection(c)
1086 c.startMessageWriter()
1087 cl.sendInitialMessages(c, t)
1088 c.initUpdateRequestsTimer()
1089 err := c.mainReadLoop()
1091 return fmt.Errorf("main read loop: %w", err)
1096 func (p *Peer) initUpdateRequestsTimer() {
1098 if p.updateRequestsTimer != nil {
1099 panic(p.updateRequestsTimer)
1102 if enableUpdateRequestsTimer {
1103 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1107 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1109 func (c *Peer) updateRequestsTimerFunc() {
1111 defer c.locker().Unlock()
1112 if c.closed.IsSet() {
1115 if c.isLowOnRequests() {
1116 // If there are no outstanding requests, then a request update should have already run.
1119 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1120 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1121 // already been fired.
1122 torrent.Add("spurious timer requests updates", 1)
1125 c.updateRequests(peerUpdateRequestsTimerReason)
1128 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1129 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1130 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1131 const localClientReqq = 1024
1133 // See the order given in Transmission's tr_peerMsgsNew.
1134 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1135 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1136 conn.write(pp.Message{
1138 ExtendedID: pp.HandshakeExtendedID,
1139 ExtendedPayload: func() []byte {
1140 msg := pp.ExtendedHandshakeMessage{
1141 M: map[pp.ExtensionName]pp.ExtensionNumber{
1142 pp.ExtensionNameMetadata: metadataExtendedId,
1143 utHolepunch.ExtensionName: utHolepunchExtendedId,
1145 V: cl.config.ExtendedHandshakeClientVersion,
1146 Reqq: localClientReqq,
1147 YourIp: pp.CompactIp(conn.remoteIp()),
1148 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1149 Port: cl.incomingPeerPort(),
1150 MetadataSize: torrent.metadataSize(),
1151 // TODO: We can figure these out specific to the socket used.
1152 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1153 Ipv6: cl.config.PublicIp6.To16(),
1155 if !cl.config.DisablePEX {
1156 msg.M[pp.ExtensionNamePex] = pexExtendedId
1158 return bencode.MustMarshal(msg)
1163 if conn.fastEnabled() {
1164 if torrent.haveAllPieces() {
1165 conn.write(pp.Message{Type: pp.HaveAll})
1166 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1168 } else if !torrent.haveAnyPieces() {
1169 conn.write(pp.Message{Type: pp.HaveNone})
1170 conn.sentHaves.Clear()
1176 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1177 conn.write(pp.Message{
1184 func (cl *Client) dhtPort() (ret uint16) {
1185 if len(cl.dhtServers) == 0 {
1188 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1191 func (cl *Client) haveDhtServer() bool {
1192 return len(cl.dhtServers) > 0
1195 // Process incoming ut_metadata message.
1196 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1197 var d pp.ExtendedMetadataRequestMsg
1198 err := bencode.Unmarshal(payload, &d)
1199 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1200 } else if err != nil {
1201 return fmt.Errorf("error unmarshalling bencode: %s", err)
1205 case pp.DataMetadataExtensionMsgType:
1206 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1207 if !c.requestedMetadataPiece(piece) {
1208 return fmt.Errorf("got unexpected piece %d", piece)
1210 c.metadataRequests[piece] = false
1211 begin := len(payload) - d.PieceSize()
1212 if begin < 0 || begin >= len(payload) {
1213 return fmt.Errorf("data has bad offset in payload: %d", begin)
1215 t.saveMetadataPiece(piece, payload[begin:])
1216 c.lastUsefulChunkReceived = time.Now()
1217 err = t.maybeCompleteMetadata()
1219 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1220 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1221 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1222 // log consumers can filter for this message.
1223 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1226 case pp.RequestMetadataExtensionMsgType:
1227 if !t.haveMetadataPiece(piece) {
1228 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1231 start := (1 << 14) * piece
1232 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1233 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1235 case pp.RejectMetadataExtensionMsgType:
1238 return errors.New("unknown msg_type value")
1242 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1243 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1244 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1249 // Returns whether the IP address and port are considered "bad".
1250 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1251 if port == 0 || ip == nil {
1254 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1257 if _, ok := cl.ipBlockRange(ip); ok {
1260 ipAddr, ok := netip.AddrFromSlice(ip)
1264 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1270 // Return a Torrent ready for insertion into a Client.
1271 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1272 return cl.newTorrentOpt(AddTorrentOpts{
1274 Storage: specStorage,
1278 // Return a Torrent ready for insertion into a Client.
1279 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1280 // use provided storage, if provided
1281 storageClient := cl.defaultStorage
1282 if opts.Storage != nil {
1283 storageClient = storage.NewClient(opts.Storage)
1288 infoHash: opts.InfoHash,
1289 peers: prioritizedPeers{
1291 getPrio: func(p PeerInfo) peerPriority {
1293 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1296 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1298 storageOpener: storageClient,
1299 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1301 metadataChanged: sync.Cond{
1304 webSeeds: make(map[string]*Peer),
1305 gotMetainfoC: make(chan struct{}),
1307 t.smartBanCache.Hash = sha1.Sum
1308 t.smartBanCache.Init()
1309 t.networkingEnabled.Set()
1310 t.logger = cl.logger.WithDefaultLevel(log.Debug)
1311 t.sourcesLogger = t.logger.WithNames("sources")
1312 if opts.ChunkSize == 0 {
1313 opts.ChunkSize = defaultChunkSize
1315 t.setChunkSize(opts.ChunkSize)
1319 // A file-like handle to some torrent data resource.
1320 type Handle interface {
1327 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1328 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1331 // Adds a torrent by InfoHash with a custom Storage implementation.
1332 // If the torrent already exists then this Storage is ignored and the
1333 // existing torrent returned with `new` set to `false`
1334 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1337 t, ok := cl.torrents[infoHash]
1343 t = cl.newTorrent(infoHash, specStorage)
1344 cl.eachDhtServer(func(s DhtServer) {
1345 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1346 go t.dhtAnnouncer(s)
1349 cl.torrents[infoHash] = t
1350 cl.clearAcceptLimits()
1351 t.updateWantPeersEvent()
1352 // Tickle Client.waitAccept, new torrent may want conns.
1353 cl.event.Broadcast()
1357 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1358 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1359 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1360 infoHash := opts.InfoHash
1363 t, ok := cl.torrents[infoHash]
1369 t = cl.newTorrentOpt(opts)
1370 cl.eachDhtServer(func(s DhtServer) {
1371 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1372 go t.dhtAnnouncer(s)
1375 cl.torrents[infoHash] = t
1376 t.setInfoBytesLocked(opts.InfoBytes)
1377 cl.clearAcceptLimits()
1378 t.updateWantPeersEvent()
1379 // Tickle Client.waitAccept, new torrent may want conns.
1380 cl.event.Broadcast()
1384 type AddTorrentOpts struct {
1386 Storage storage.ClientImpl
1387 ChunkSize pp.Integer
1391 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1392 // Torrent.MergeSpec.
1393 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1394 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1395 InfoHash: spec.InfoHash,
1396 Storage: spec.Storage,
1397 ChunkSize: spec.ChunkSize,
1401 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1403 modSpec.ChunkSize = 0
1405 err = t.MergeSpec(&modSpec)
1406 if err != nil && new {
1412 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1413 // spec.DisallowDataDownload/Upload will be read and applied
1414 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1415 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1416 if spec.DisplayName != "" {
1417 t.SetDisplayName(spec.DisplayName)
1419 if spec.InfoBytes != nil {
1420 err := t.SetInfoBytes(spec.InfoBytes)
1426 cl.AddDhtNodes(spec.DhtNodes)
1427 t.UseSources(spec.Sources)
1430 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1431 for _, url := range spec.Webseeds {
1434 for _, peerAddr := range spec.PeerAddrs {
1436 Addr: StringAddr(peerAddr),
1437 Source: PeerSourceDirect,
1441 if spec.ChunkSize != 0 {
1442 panic("chunk size cannot be changed for existing Torrent")
1444 t.addTrackers(spec.Trackers)
1446 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1447 t.dataUploadDisallowed = spec.DisallowDataUpload
1451 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1452 t, ok := cl.torrents[infoHash]
1454 err = fmt.Errorf("no such torrent")
1458 delete(cl.torrents, infoHash)
1462 func (cl *Client) allTorrentsCompleted() bool {
1463 for _, t := range cl.torrents {
1467 if !t.haveAllPieces() {
1474 // Returns true when all torrents are completely downloaded and false if the
1475 // client is stopped before that.
1476 func (cl *Client) WaitAll() bool {
1479 for !cl.allTorrentsCompleted() {
1480 if cl.closed.IsSet() {
1488 // Returns handles to all the torrents loaded in the Client.
1489 func (cl *Client) Torrents() []*Torrent {
1492 return cl.torrentsAsSlice()
1495 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1496 for _, t := range cl.torrents {
1497 ret = append(ret, t)
1502 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1503 spec, err := TorrentSpecFromMagnetUri(uri)
1507 T, _, err = cl.AddTorrentSpec(spec)
1511 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1512 ts, err := TorrentSpecFromMetaInfoErr(mi)
1516 T, _, err = cl.AddTorrentSpec(ts)
1520 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1521 mi, err := metainfo.LoadFromFile(filename)
1525 return cl.AddTorrent(mi)
1528 func (cl *Client) DhtServers() []DhtServer {
1529 return cl.dhtServers
1532 func (cl *Client) AddDhtNodes(nodes []string) {
1533 for _, n := range nodes {
1534 hmp := missinggo.SplitHostMaybePort(n)
1535 ip := net.ParseIP(hmp.Host)
1537 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1540 ni := krpc.NodeInfo{
1541 Addr: krpc.NodeAddr{
1546 cl.eachDhtServer(func(s DhtServer) {
1552 func (cl *Client) banPeerIP(ip net.IP) {
1553 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1554 // addresses directly to v4on6, which doesn't compare equal with v4.
1555 ipAddr, ok := netip.AddrFromSlice(ip)
1559 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1560 for _, t := range cl.torrents {
1561 t.iterPeers(func(p *Peer) {
1562 if p.remoteIp().Equal(ip) {
1563 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1564 // Should this be a close?
1571 type newConnectionOpts struct {
1573 remoteAddr PeerRemoteAddr
1574 localPublicAddr peerLocalPublicAddr
1579 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1580 if opts.network == "" {
1581 panic(opts.remoteAddr)
1585 outgoing: opts.outgoing,
1588 PeerMaxRequests: 250,
1590 RemoteAddr: opts.remoteAddr,
1591 localPublicAddr: opts.localPublicAddr,
1592 Network: opts.network,
1593 callbacks: &cl.config.Callbacks,
1595 connString: opts.connString,
1598 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1599 c.initRequestState()
1600 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1601 if opts.remoteAddr != nil {
1602 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1604 c.bannableAddr = Some(netipAddrPort.Addr())
1608 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1609 c.logger = c.logger.WithContextText(fmt.Sprintf("%T %p", c, c))
1610 c.setRW(connStatsReadWriter{nc, c})
1611 c.r = &rateLimitedReader{
1612 l: cl.config.DownloadRateLimiter,
1617 "inited with remoteAddr %v network %v outgoing %t",
1618 opts.remoteAddr, opts.network, opts.outgoing,
1620 for _, f := range cl.config.Callbacks.NewPeer {
1626 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1633 t.addPeers([]PeerInfo{{
1634 Addr: ipPortAddr{ip, port},
1635 Source: PeerSourceDhtAnnouncePeer,
1639 func firstNotNil(ips ...net.IP) net.IP {
1640 for _, ip := range ips {
1648 func (cl *Client) eachListener(f func(Listener) bool) {
1649 for _, s := range cl.listeners {
1656 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1657 for i := 0; i < len(cl.listeners); i += 1 {
1658 if ret = cl.listeners[i]; f(ret) {
1665 func (cl *Client) publicIp(peer net.IP) net.IP {
1666 // TODO: Use BEP 10 to determine how peers are seeing us.
1667 if peer.To4() != nil {
1669 cl.config.PublicIp4,
1670 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1675 cl.config.PublicIp6,
1676 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1680 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1681 l := cl.findListener(
1682 func(l Listener) bool {
1683 return f(addrIpOrNil(l.Addr()))
1689 return addrIpOrNil(l.Addr())
1692 // Our IP as a peer should see it.
1693 func (cl *Client) publicAddr(peer net.IP) IpPort {
1694 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1697 // ListenAddrs addresses currently being listened to.
1698 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1700 ret = make([]net.Addr, len(cl.listeners))
1701 for i := 0; i < len(cl.listeners); i += 1 {
1702 ret[i] = cl.listeners[i].Addr()
1708 func (cl *Client) PublicIPs() (ips []net.IP) {
1709 if ip := cl.config.PublicIp4; ip != nil {
1710 ips = append(ips, ip)
1712 if ip := cl.config.PublicIp6; ip != nil {
1713 ips = append(ips, ip)
1718 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1719 ipa, ok := tryIpPortFromNetAddr(addr)
1723 ip := maskIpForAcceptLimiting(ipa.IP)
1724 if cl.acceptLimiter == nil {
1725 cl.acceptLimiter = make(map[ipStr]int)
1727 cl.acceptLimiter[ipStr(ip.String())]++
1730 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1731 if ip4 := ip.To4(); ip4 != nil {
1732 return ip4.Mask(net.CIDRMask(24, 32))
1737 func (cl *Client) clearAcceptLimits() {
1738 cl.acceptLimiter = nil
1741 func (cl *Client) acceptLimitClearer() {
1744 case <-cl.closed.Done():
1746 case <-time.After(15 * time.Minute):
1748 cl.clearAcceptLimits()
1754 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1755 if cl.config.DisableAcceptRateLimiting {
1758 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1761 func (cl *Client) rLock() {
1765 func (cl *Client) rUnlock() {
1769 func (cl *Client) lock() {
1773 func (cl *Client) unlock() {
1777 func (cl *Client) locker() *lockWithDeferreds {
1781 func (cl *Client) String() string {
1782 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1785 // Returns connection-level aggregate connStats at the Client level. See the comment on
1786 // TorrentStats.ConnStats.
1787 func (cl *Client) ConnStats() ConnStats {
1788 return cl.connStats.Copy()
1791 func (cl *Client) Stats() ClientStats {
1794 return cl.statsLocked()