21 "github.com/anacrolix/torrent/internal/panicif"
23 "github.com/anacrolix/chansync"
24 "github.com/anacrolix/chansync/events"
25 "github.com/anacrolix/dht/v2"
26 "github.com/anacrolix/dht/v2/krpc"
27 . "github.com/anacrolix/generics"
28 g "github.com/anacrolix/generics"
29 "github.com/anacrolix/log"
30 "github.com/anacrolix/missinggo/perf"
31 "github.com/anacrolix/missinggo/v2"
32 "github.com/anacrolix/missinggo/v2/bitmap"
33 "github.com/anacrolix/missinggo/v2/pproffd"
34 "github.com/anacrolix/sync"
35 "github.com/davecgh/go-spew/spew"
36 "github.com/dustin/go-humanize"
37 gbtree "github.com/google/btree"
38 "github.com/pion/datachannel"
39 "golang.org/x/time/rate"
41 "github.com/anacrolix/torrent/bencode"
42 "github.com/anacrolix/torrent/internal/check"
43 "github.com/anacrolix/torrent/internal/limiter"
44 "github.com/anacrolix/torrent/iplist"
45 "github.com/anacrolix/torrent/metainfo"
46 "github.com/anacrolix/torrent/mse"
47 pp "github.com/anacrolix/torrent/peer_protocol"
48 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
49 request_strategy "github.com/anacrolix/torrent/request-strategy"
50 "github.com/anacrolix/torrent/storage"
51 "github.com/anacrolix/torrent/tracker"
52 "github.com/anacrolix/torrent/types/infohash"
53 "github.com/anacrolix/torrent/webtorrent"
56 // Clients contain zero or more Torrents. A Client manages a blocklist, the
57 // TCP/UDP protocol ports, and DHT as desired.
59 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
65 closed chansync.SetOnce
71 defaultStorage *storage.Client
75 dhtServers []DhtServer
76 ipBlockList iplist.Ranger
78 // Set of addresses that have our client ID. This intentionally will
79 // include ourselves if we end up trying to connect to our own address
80 // through legitimate channels.
81 dopplegangerAddrs map[string]struct{}
82 badPeerIPs map[netip.Addr]struct{}
83 torrents map[InfoHash]*Torrent
84 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
86 acceptLimiter map[ipStr]int
87 dialRateLimiter *rate.Limiter
90 websocketTrackers websocketTrackers
92 activeAnnounceLimiter limiter.Instance
93 httpClient *http.Client
95 undialableWithoutHolepunch map[netip.AddrPort]struct{}
96 undialableWithoutHolepunchDialAttemptedAfterHolepunchConnect map[netip.AddrPort]struct{}
97 dialableOnlyAfterHolepunch map[netip.AddrPort]struct{}
102 func (cl *Client) BadPeerIPs() (ips []string) {
104 ips = cl.badPeerIPsLocked()
109 func (cl *Client) badPeerIPsLocked() (ips []string) {
110 ips = make([]string, len(cl.badPeerIPs))
112 for k := range cl.badPeerIPs {
119 func (cl *Client) PeerID() PeerID {
123 // Returns the port number for the first listener that has one. No longer assumes that all port
124 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
126 func (cl *Client) LocalPort() (port int) {
127 for i := 0; i < len(cl.listeners); i += 1 {
128 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
135 func writeDhtServerStatus(w io.Writer, s DhtServer) {
136 dhtStats := s.Stats()
137 fmt.Fprintf(w, " ID: %x\n", s.ID())
138 spew.Fdump(w, dhtStats)
141 // Writes out a human readable status of the client, such as for writing to a
143 func (cl *Client) WriteStatus(_w io.Writer) {
146 w := bufio.NewWriter(_w)
148 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
149 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
150 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
151 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
152 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
153 cl.eachDhtServer(func(s DhtServer) {
154 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
155 writeDhtServerStatus(w, s)
157 dumpStats(w, cl.statsLocked())
158 torrentsSlice := cl.torrentsAsSlice()
159 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
161 sort.Slice(torrentsSlice, func(l, r int) bool {
162 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
164 for _, t := range torrentsSlice {
166 fmt.Fprint(w, "<unknown name>")
168 fmt.Fprint(w, t.name())
174 "%f%% of %d bytes (%s)",
175 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
177 humanize.Bytes(uint64(t.length())))
179 w.WriteString("<missing metainfo>")
187 func (cl *Client) initLogger() {
188 logger := cl.config.Logger
193 logger = logger.FilterLevel(log.Debug)
195 cl.logger = logger.WithValues(cl)
198 func (cl *Client) announceKey() int32 {
199 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
202 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
203 func (cl *Client) init(cfg *ClientConfig) {
205 g.MakeMap(&cl.dopplegangerAddrs)
206 cl.torrents = make(map[metainfo.Hash]*Torrent)
207 cl.dialRateLimiter = rate.NewLimiter(10, 10)
208 cl.activeAnnounceLimiter.SlotsPerKey = 2
209 cl.event.L = cl.locker()
210 cl.ipBlockList = cfg.IPBlocklist
211 cl.httpClient = &http.Client{
212 Transport: &http.Transport{
213 Proxy: cfg.HTTPProxy,
214 DialContext: cfg.HTTPDialContext,
215 // I think this value was observed from some webseeds. It seems reasonable to extend it
216 // to other uses of HTTP from the client.
222 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
224 cfg = NewDefaultClientConfig()
230 go cl.acceptLimitClearer()
239 storageImpl := cfg.DefaultStorage
240 if storageImpl == nil {
241 // We'd use mmap by default but HFS+ doesn't support sparse files.
242 storageImplCloser := storage.NewFile(cfg.DataDir)
243 cl.onClose = append(cl.onClose, func() {
244 if err := storageImplCloser.Close(); err != nil {
245 cl.logger.Printf("error closing default storage: %s", err)
248 storageImpl = storageImplCloser
250 cl.defaultStorage = storage.NewClient(storageImpl)
252 if cfg.PeerID != "" {
253 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
255 o := copy(cl.peerID[:], cfg.Bep20)
256 _, err = rand.Read(cl.peerID[o:])
258 panic("error generating peer id")
262 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
270 for _, _s := range sockets {
271 s := _s // Go is fucking retarded.
272 cl.onClose = append(cl.onClose, func() { go s.Close() })
273 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
274 cl.dialers = append(cl.dialers, s)
275 cl.listeners = append(cl.listeners, s)
276 if cl.config.AcceptPeerConnections {
277 go cl.acceptConnections(s)
284 for _, s := range sockets {
285 if pc, ok := s.(net.PacketConn); ok {
286 ds, err := cl.NewAnacrolixDhtServer(pc)
290 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
291 cl.onClose = append(cl.onClose, func() { ds.Close() })
296 cl.websocketTrackers = websocketTrackers{
299 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
302 t, ok := cl.torrents[infoHash]
304 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
306 return t.announceRequest(event), nil
308 Proxy: cl.config.HTTPProxy,
309 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
310 DialContext: cl.config.TrackerDialContext,
311 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
314 t, ok := cl.torrents[dcc.InfoHash]
316 cl.logger.WithDefaultLevel(log.Warning).Printf(
317 "got webrtc conn for unloaded torrent with infohash %x",
323 go t.onWebRtcConn(dc, dcc)
330 func (cl *Client) AddDhtServer(d DhtServer) {
331 cl.dhtServers = append(cl.dhtServers, d)
334 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
335 // given address for any Torrent.
336 func (cl *Client) AddDialer(d Dialer) {
339 cl.dialers = append(cl.dialers, d)
340 for _, t := range cl.torrents {
345 func (cl *Client) Listeners() []Listener {
349 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
351 func (cl *Client) AddListener(l Listener) {
352 cl.listeners = append(cl.listeners, l)
353 if cl.config.AcceptPeerConnections {
354 go cl.acceptConnections(l)
358 func (cl *Client) firewallCallback(net.Addr) bool {
360 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
363 torrent.Add("connections firewalled", 1)
365 torrent.Add("connections not firewalled", 1)
370 func (cl *Client) listenOnNetwork(n network) bool {
371 if n.Ipv4 && cl.config.DisableIPv4 {
374 if n.Ipv6 && cl.config.DisableIPv6 {
377 if n.Tcp && cl.config.DisableTCP {
380 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
386 func (cl *Client) listenNetworks() (ns []network) {
387 for _, n := range allPeerNetworks {
388 if cl.listenOnNetwork(n) {
395 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
396 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
397 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
398 cfg := dht.ServerConfig{
399 IPBlocklist: cl.ipBlockList,
401 OnAnnouncePeer: cl.onDHTAnnouncePeer,
402 PublicIP: func() net.IP {
403 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
404 return cl.config.PublicIp6
406 return cl.config.PublicIp4
408 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
409 OnQuery: cl.config.DHTOnQuery,
412 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
415 s, err = dht.NewServer(&cfg)
417 go s.TableMaintainer()
422 func (cl *Client) Closed() events.Done {
423 return cl.closed.Done()
426 func (cl *Client) eachDhtServer(f func(DhtServer)) {
427 for _, ds := range cl.dhtServers {
432 // Stops the client. All connections to peers are closed and all activity will come to a halt.
433 func (cl *Client) Close() (errs []error) {
434 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
436 for _, t := range cl.torrents {
437 err := t.close(&closeGroup)
439 errs = append(errs, err)
442 for i := range cl.onClose {
443 cl.onClose[len(cl.onClose)-1-i]()
448 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
452 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
453 if cl.ipBlockList == nil {
456 return cl.ipBlockList.Lookup(ip)
459 func (cl *Client) ipIsBlocked(ip net.IP) bool {
460 _, blocked := cl.ipBlockRange(ip)
464 func (cl *Client) wantConns() bool {
465 if cl.config.AlwaysWantConns {
468 for _, t := range cl.torrents {
469 if t.wantIncomingConns() {
476 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
477 func (cl *Client) rejectAccepted(conn net.Conn) error {
479 return errors.New("don't want conns right now")
481 ra := conn.RemoteAddr()
482 if rip := addrIpOrNil(ra); rip != nil {
483 if cl.config.DisableIPv4Peers && rip.To4() != nil {
484 return errors.New("ipv4 peers disabled")
486 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
487 return errors.New("ipv4 disabled")
489 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
490 return errors.New("ipv6 disabled")
492 if cl.rateLimitAccept(rip) {
493 return errors.New("source IP accepted rate limited")
495 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
496 return errors.New("bad source addr")
502 func (cl *Client) acceptConnections(l Listener) {
504 conn, err := l.Accept()
505 torrent.Add("client listener accepts", 1)
506 conn = pproffd.WrapNetConn(conn)
508 closed := cl.closed.IsSet()
510 if !closed && conn != nil {
511 reject = cl.rejectAccepted(conn)
521 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
526 torrent.Add("rejected accepted connections", 1)
527 cl.logger.LazyLog(log.Debug, func() log.Msg {
528 return log.Fmsg("rejecting accepted conn: %v", reject)
532 go cl.incomingConnection(conn)
534 cl.logger.LazyLog(log.Debug, func() log.Msg {
535 return log.Fmsg("accepted %q connection at %q from %q",
541 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
542 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
543 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
548 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
549 func regularNetConnPeerConnConnString(nc net.Conn) string {
550 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
553 func (cl *Client) incomingConnection(nc net.Conn) {
555 if tc, ok := nc.(*net.TCPConn); ok {
558 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
559 c := cl.newConnection(
563 remoteAddr: nc.RemoteAddr(),
564 localPublicAddr: cl.publicAddr(remoteAddr.IP),
565 network: nc.RemoteAddr().Network(),
566 connString: regularNetConnPeerConnConnString(nc),
573 c.Discovery = PeerSourceIncoming
574 cl.runReceivedConn(c)
577 // Returns a handle to the given torrent, if it's present in the client.
578 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
581 t, ok = cl.torrents[ih]
585 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
586 return cl.torrents[ih]
589 type DialResult struct {
594 func countDialResult(err error) {
596 torrent.Add("successful dials", 1)
598 torrent.Add("unsuccessful dials", 1)
602 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
603 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
604 if ret < minDialTimeout {
610 // Returns whether an address is known to connect to a client with our own ID.
611 func (cl *Client) dopplegangerAddr(addr string) bool {
612 _, ok := cl.dopplegangerAddrs[addr]
616 // Returns a connection over UTP or TCP, whichever is first to connect.
617 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
618 return DialFirst(ctx, addr, cl.dialers)
621 // Returns a connection over UTP or TCP, whichever is first to connect.
622 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
624 t := perf.NewTimer(perf.CallerName(0))
627 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
629 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
633 ctx, cancel := context.WithCancel(ctx)
634 // As soon as we return one connection, cancel the others.
637 resCh := make(chan DialResult, left)
638 for _, _s := range dialers {
643 dialFromSocket(ctx, s, addr),
648 // Wait for a successful connection.
650 defer perf.ScopeTimer()()
651 for ; left > 0 && res.Conn == nil; left-- {
655 // There are still uncompleted dials.
657 for ; left > 0; left-- {
658 conn := (<-resCh).Conn
665 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
670 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
671 c, err := s.Dial(ctx, addr)
673 log.Levelf(log.Debug, "error dialing %q: %v", addr, err)
675 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
676 // it now in case we close the connection forthwith. Note this is also done in the TCP dialer
677 // code to increase the chance it's done.
678 if tc, ok := c.(*net.TCPConn); ok {
685 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingConnAttemptKey) {
686 path := t.getHalfOpenPath(addr, attemptKey)
688 panic("should exist")
692 if cl.numHalfOpen < 0 {
693 panic("should not be possible")
695 for _, t := range cl.torrents {
700 func (cl *Client) countHalfOpenFromTorrents() (count int) {
701 for _, t := range cl.torrents {
702 count += t.numHalfOpenAttempts()
707 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
708 // for valid reasons.
709 func (cl *Client) initiateProtocolHandshakes(
714 newConnOpts newConnectionOpts,
716 c *PeerConn, err error,
718 c = cl.newConnection(nc, newConnOpts)
719 c.headerEncrypted = encryptHeader
720 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
722 dl, ok := ctx.Deadline()
726 err = nc.SetDeadline(dl)
730 err = cl.initiateHandshakes(c, t)
734 func (cl *Client) waitForRendezvousConnect(ctx context.Context, rz *utHolepunchRendezvous) error {
737 case rz.gotConnect.IsSet():
739 case len(rz.relays) == 0:
740 return errors.New("all relays failed")
741 case ctx.Err() != nil:
742 return context.Cause(ctx)
744 relayCond := rz.relayCond.Signaled()
747 case <-rz.gotConnect.Done():
755 // Returns nil connection and nil error if no connection could be established for valid reasons.
756 func (cl *Client) initiateRendezvousConnect(
757 t *Torrent, holepunchAddr netip.AddrPort,
758 ) (ok bool, err error) {
761 rz, err := t.startHolepunchRendezvous(holepunchAddr)
769 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
771 err = cl.waitForRendezvousConnect(ctx, rz)
772 delete(t.utHolepunchRendezvous, holepunchAddr)
774 err = fmt.Errorf("waiting for rendezvous connect signal: %w", err)
779 // Returns nil connection and nil error if no connection could be established for valid reasons.
780 func (cl *Client) establishOutgoingConnEx(
781 opts outgoingConnOpts,
782 obfuscatedHeader bool,
784 _ *PeerConn, err error,
788 holepunchAddr, err := addrPortFromPeerRemoteAddr(addr)
789 var sentRendezvous bool
791 if !opts.skipHolepunchRendezvous {
792 sentRendezvous, err = cl.initiateRendezvousConnect(t, holepunchAddr)
794 err = fmt.Errorf("initiating rendezvous connect: %w", err)
798 gotHolepunchConnect := (err == nil && sentRendezvous) || opts.receivedHolepunchConnect
799 if opts.requireRendezvous && !sentRendezvous {
805 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
808 return t.dialTimeout()
811 dr := cl.dialFirst(dialCtx, addr.String())
814 if gotHolepunchConnect && g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
815 g.MakeMapIfNilAndSet(
816 &cl.undialableWithoutHolepunchDialAttemptedAfterHolepunchConnect,
823 if !sentRendezvous && !gotHolepunchConnect {
825 g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
828 if dialCtx.Err() != nil {
829 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
831 return nil, errors.New("dial failed")
833 if gotHolepunchConnect {
834 panicif.False(holepunchAddr.IsValid())
836 if g.MapContains(cl.undialableWithoutHolepunchDialAttemptedAfterHolepunchConnect, holepunchAddr) {
837 g.MakeMapIfNilAndSet(
838 &cl.dialableOnlyAfterHolepunch,
845 addrIpPort, _ := tryIpPortFromNetAddr(addr)
846 c, err := cl.initiateProtocolHandshakes(
847 context.Background(), nc, t, obfuscatedHeader,
851 // It would be possible to retrieve a public IP from the dialer used here?
852 localPublicAddr: cl.publicAddr(addrIpPort.IP),
853 network: dr.Dialer.DialerNetwork(),
854 connString: regularNetConnPeerConnConnString(nc),
862 // Returns nil connection and nil error if no connection could be established
863 // for valid reasons.
864 func (cl *Client) establishOutgoingConn(opts outgoingConnOpts) (c *PeerConn, err error) {
865 torrent.Add("establish outgoing connection", 1)
866 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
867 c, err = cl.establishOutgoingConnEx(opts, obfuscatedHeaderFirst)
869 torrent.Add("initiated conn with preferred header obfuscation", 1)
872 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
873 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
874 // We should have just tried with the preferred header obfuscation. If it was required,
875 // there's nothing else to try.
878 // Try again with encryption if we didn't earlier, or without if we did.
879 c, err = cl.establishOutgoingConnEx(opts, !obfuscatedHeaderFirst)
881 torrent.Add("initiated conn with fallback header obfuscation", 1)
883 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
887 type outgoingConnOpts struct {
890 // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
891 requireRendezvous bool
892 // Don't send rendezvous requests to eligible relays.
893 skipHolepunchRendezvous bool
894 // Outgoing connection attempt is in response to holepunch connect message.
895 receivedHolepunchConnect bool
898 // Called to dial out and run a connection. The addr we're given is already
899 // considered half-open.
900 func (cl *Client) outgoingConnection(
901 opts outgoingConnOpts,
904 attemptKey outgoingConnAttemptKey,
906 cl.dialRateLimiter.Wait(context.Background())
907 c, err := cl.establishOutgoingConn(opts)
909 c.conn.SetWriteDeadline(time.Time{})
913 // Don't release lock between here and addPeerConn, unless it's for
915 cl.noLongerHalfOpen(opts.t, opts.addr.String(), attemptKey)
918 cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", opts.addr, err)
925 opts.t.runHandshookConnLoggingErr(c)
928 // The port number for incoming peer connections. 0 if the client isn't listening.
929 func (cl *Client) incomingPeerPort() int {
930 return cl.LocalPort()
933 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
934 if c.headerEncrypted {
937 rw, c.cryptoMethod, err = mse.InitiateHandshake(
944 cl.config.CryptoProvides,
948 return fmt.Errorf("header obfuscation handshake: %w", err)
951 ih, err := cl.connBtHandshake(c, &t.infoHash)
953 return fmt.Errorf("bittorrent protocol handshake: %w", err)
955 if ih != t.infoHash {
956 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
961 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
962 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
963 func (cl *Client) forSkeys(f func([]byte) bool) {
966 if false { // Emulate the bug from #114
968 for ih := range cl.torrents {
972 for range cl.torrents {
979 for ih := range cl.torrents {
986 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
987 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
993 // Do encryption and bittorrent handshakes as receiver.
994 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
995 defer perf.ScopeTimerErr(&err)()
997 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
999 if err == nil || err == mse.ErrNoSecretKeyMatch {
1000 if c.headerEncrypted {
1001 torrent.Add("handshakes received encrypted", 1)
1003 torrent.Add("handshakes received unencrypted", 1)
1006 torrent.Add("handshakes received with error while handling encryption", 1)
1009 if err == mse.ErrNoSecretKeyMatch {
1014 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
1015 err = errors.New("connection does not have required header obfuscation")
1018 ih, err := cl.connBtHandshake(c, nil)
1020 return nil, fmt.Errorf("during bt handshake: %w", err)
1028 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
1032 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
1033 &successfulPeerWireProtocolHandshakePeerReservedBytes)
1036 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
1037 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
1041 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
1043 c.PeerExtensionBytes = res.PeerExtensionBits
1044 c.PeerID = res.PeerID
1045 c.completedHandshake = time.Now()
1046 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
1052 func (cl *Client) runReceivedConn(c *PeerConn) {
1053 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1057 t, err := cl.receiveHandshakes(c)
1059 cl.logger.LazyLog(log.Debug, func() log.Msg {
1061 "error receiving handshakes on %v: %s", c, err,
1063 "network", c.Network,
1066 torrent.Add("error receiving handshake", 1)
1068 cl.onBadAccept(c.RemoteAddr)
1073 torrent.Add("received handshake for unloaded torrent", 1)
1074 cl.logger.LazyLog(log.Debug, func() log.Msg {
1075 return log.Fmsg("received handshake for unloaded torrent")
1078 cl.onBadAccept(c.RemoteAddr)
1082 torrent.Add("received handshake for loaded torrent", 1)
1083 c.conn.SetWriteDeadline(time.Time{})
1086 t.runHandshookConnLoggingErr(c)
1089 // Client lock must be held before entering this.
1090 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
1092 for i, b := range cl.config.MinPeerExtensions {
1093 if c.PeerExtensionBytes[i]&b != b {
1094 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
1097 if c.PeerID == cl.peerID {
1100 addr := c.RemoteAddr.String()
1101 cl.dopplegangerAddrs[addr] = struct{}{}
1103 // Because the remote address is not necessarily the same as its client's torrent listen
1104 // address, we won't record the remote address as a doppleganger. Instead, the initiator
1105 // can record *us* as the doppleganger.
1107 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1110 c.r = deadlineReader{c.conn, c.r}
1111 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1112 if connIsIpv6(c.conn) {
1113 torrent.Add("completed handshake over ipv6", 1)
1115 if err := t.addPeerConn(c); err != nil {
1116 return fmt.Errorf("adding connection: %w", err)
1118 defer t.dropConnection(c)
1119 c.startMessageWriter()
1120 cl.sendInitialMessages(c, t)
1121 c.initUpdateRequestsTimer()
1122 err := c.mainReadLoop()
1124 return fmt.Errorf("main read loop: %w", err)
1129 func (p *Peer) initUpdateRequestsTimer() {
1131 if p.updateRequestsTimer != nil {
1132 panic(p.updateRequestsTimer)
1135 if enableUpdateRequestsTimer {
1136 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1140 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1142 func (c *Peer) updateRequestsTimerFunc() {
1144 defer c.locker().Unlock()
1145 if c.closed.IsSet() {
1148 if c.isLowOnRequests() {
1149 // If there are no outstanding requests, then a request update should have already run.
1152 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1153 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1154 // already been fired.
1155 torrent.Add("spurious timer requests updates", 1)
1158 c.updateRequests(peerUpdateRequestsTimerReason)
1161 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1162 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1163 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1164 const localClientReqq = 1024
1166 // See the order given in Transmission's tr_peerMsgsNew.
1167 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1168 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1169 conn.write(pp.Message{
1171 ExtendedID: pp.HandshakeExtendedID,
1172 ExtendedPayload: func() []byte {
1173 msg := pp.ExtendedHandshakeMessage{
1174 M: map[pp.ExtensionName]pp.ExtensionNumber{
1175 pp.ExtensionNameMetadata: metadataExtendedId,
1176 utHolepunch.ExtensionName: utHolepunchExtendedId,
1178 V: cl.config.ExtendedHandshakeClientVersion,
1179 Reqq: localClientReqq,
1180 YourIp: pp.CompactIp(conn.remoteIp()),
1181 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1182 Port: cl.incomingPeerPort(),
1183 MetadataSize: torrent.metadataSize(),
1184 // TODO: We can figure these out specific to the socket used.
1185 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1186 Ipv6: cl.config.PublicIp6.To16(),
1188 if !cl.config.DisablePEX {
1189 msg.M[pp.ExtensionNamePex] = pexExtendedId
1191 return bencode.MustMarshal(msg)
1196 if conn.fastEnabled() {
1197 if torrent.haveAllPieces() {
1198 conn.write(pp.Message{Type: pp.HaveAll})
1199 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1201 } else if !torrent.haveAnyPieces() {
1202 conn.write(pp.Message{Type: pp.HaveNone})
1203 conn.sentHaves.Clear()
1209 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1210 conn.write(pp.Message{
1217 func (cl *Client) dhtPort() (ret uint16) {
1218 if len(cl.dhtServers) == 0 {
1221 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1224 func (cl *Client) haveDhtServer() bool {
1225 return len(cl.dhtServers) > 0
1228 // Process incoming ut_metadata message.
1229 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1230 var d pp.ExtendedMetadataRequestMsg
1231 err := bencode.Unmarshal(payload, &d)
1232 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1233 } else if err != nil {
1234 return fmt.Errorf("error unmarshalling bencode: %s", err)
1238 case pp.DataMetadataExtensionMsgType:
1239 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1240 if !c.requestedMetadataPiece(piece) {
1241 return fmt.Errorf("got unexpected piece %d", piece)
1243 c.metadataRequests[piece] = false
1244 begin := len(payload) - d.PieceSize()
1245 if begin < 0 || begin >= len(payload) {
1246 return fmt.Errorf("data has bad offset in payload: %d", begin)
1248 t.saveMetadataPiece(piece, payload[begin:])
1249 c.lastUsefulChunkReceived = time.Now()
1250 err = t.maybeCompleteMetadata()
1252 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1253 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1254 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1255 // log consumers can filter for this message.
1256 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1259 case pp.RequestMetadataExtensionMsgType:
1260 if !t.haveMetadataPiece(piece) {
1261 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1264 start := (1 << 14) * piece
1265 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1266 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1268 case pp.RejectMetadataExtensionMsgType:
1271 return errors.New("unknown msg_type value")
1275 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1276 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1277 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1282 // Returns whether the IP address and port are considered "bad".
1283 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1284 if port == 0 || ip == nil {
1287 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1290 if _, ok := cl.ipBlockRange(ip); ok {
1293 ipAddr, ok := netip.AddrFromSlice(ip)
1297 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1303 // Return a Torrent ready for insertion into a Client.
1304 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1305 return cl.newTorrentOpt(AddTorrentOpts{
1307 Storage: specStorage,
1311 // Return a Torrent ready for insertion into a Client.
1312 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1313 // use provided storage, if provided
1314 storageClient := cl.defaultStorage
1315 if opts.Storage != nil {
1316 storageClient = storage.NewClient(opts.Storage)
1321 infoHash: opts.InfoHash,
1322 peers: prioritizedPeers{
1324 getPrio: func(p PeerInfo) peerPriority {
1326 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1329 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1331 storageOpener: storageClient,
1332 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1334 metadataChanged: sync.Cond{
1337 webSeeds: make(map[string]*Peer),
1338 gotMetainfoC: make(chan struct{}),
1340 t.smartBanCache.Hash = sha1.Sum
1341 t.smartBanCache.Init()
1342 t.networkingEnabled.Set()
1343 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString()).WithDefaultLevel(log.Debug)
1344 t.sourcesLogger = t.logger.WithNames("sources")
1345 if opts.ChunkSize == 0 {
1346 opts.ChunkSize = defaultChunkSize
1348 t.setChunkSize(opts.ChunkSize)
1352 // A file-like handle to some torrent data resource.
1353 type Handle interface {
1360 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1361 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1364 // Adds a torrent by InfoHash with a custom Storage implementation.
1365 // If the torrent already exists then this Storage is ignored and the
1366 // existing torrent returned with `new` set to `false`
1367 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1370 t, ok := cl.torrents[infoHash]
1376 t = cl.newTorrent(infoHash, specStorage)
1377 cl.eachDhtServer(func(s DhtServer) {
1378 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1379 go t.dhtAnnouncer(s)
1382 cl.torrents[infoHash] = t
1383 cl.clearAcceptLimits()
1384 t.updateWantPeersEvent()
1385 // Tickle Client.waitAccept, new torrent may want conns.
1386 cl.event.Broadcast()
1390 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1391 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1392 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1393 infoHash := opts.InfoHash
1396 t, ok := cl.torrents[infoHash]
1402 t = cl.newTorrentOpt(opts)
1403 cl.eachDhtServer(func(s DhtServer) {
1404 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1405 go t.dhtAnnouncer(s)
1408 cl.torrents[infoHash] = t
1409 t.setInfoBytesLocked(opts.InfoBytes)
1410 cl.clearAcceptLimits()
1411 t.updateWantPeersEvent()
1412 // Tickle Client.waitAccept, new torrent may want conns.
1413 cl.event.Broadcast()
1417 type AddTorrentOpts struct {
1419 Storage storage.ClientImpl
1420 ChunkSize pp.Integer
1424 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1425 // Torrent.MergeSpec.
1426 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1427 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1428 InfoHash: spec.InfoHash,
1429 Storage: spec.Storage,
1430 ChunkSize: spec.ChunkSize,
1434 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1436 modSpec.ChunkSize = 0
1438 err = t.MergeSpec(&modSpec)
1439 if err != nil && new {
1445 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1446 // spec.DisallowDataDownload/Upload will be read and applied
1447 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1448 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1449 if spec.DisplayName != "" {
1450 t.SetDisplayName(spec.DisplayName)
1452 if spec.InfoBytes != nil {
1453 err := t.SetInfoBytes(spec.InfoBytes)
1459 cl.AddDhtNodes(spec.DhtNodes)
1460 t.UseSources(spec.Sources)
1463 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1464 for _, url := range spec.Webseeds {
1467 for _, peerAddr := range spec.PeerAddrs {
1469 Addr: StringAddr(peerAddr),
1470 Source: PeerSourceDirect,
1474 if spec.ChunkSize != 0 {
1475 panic("chunk size cannot be changed for existing Torrent")
1477 t.addTrackers(spec.Trackers)
1479 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1480 t.dataUploadDisallowed = spec.DisallowDataUpload
1484 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1485 t, ok := cl.torrents[infoHash]
1487 err = fmt.Errorf("no such torrent")
1491 delete(cl.torrents, infoHash)
1495 func (cl *Client) allTorrentsCompleted() bool {
1496 for _, t := range cl.torrents {
1500 if !t.haveAllPieces() {
1507 // Returns true when all torrents are completely downloaded and false if the
1508 // client is stopped before that.
1509 func (cl *Client) WaitAll() bool {
1512 for !cl.allTorrentsCompleted() {
1513 if cl.closed.IsSet() {
1521 // Returns handles to all the torrents loaded in the Client.
1522 func (cl *Client) Torrents() []*Torrent {
1525 return cl.torrentsAsSlice()
1528 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1529 for _, t := range cl.torrents {
1530 ret = append(ret, t)
1535 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1536 spec, err := TorrentSpecFromMagnetUri(uri)
1540 T, _, err = cl.AddTorrentSpec(spec)
1544 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1545 ts, err := TorrentSpecFromMetaInfoErr(mi)
1549 T, _, err = cl.AddTorrentSpec(ts)
1553 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1554 mi, err := metainfo.LoadFromFile(filename)
1558 return cl.AddTorrent(mi)
1561 func (cl *Client) DhtServers() []DhtServer {
1562 return cl.dhtServers
1565 func (cl *Client) AddDhtNodes(nodes []string) {
1566 for _, n := range nodes {
1567 hmp := missinggo.SplitHostMaybePort(n)
1568 ip := net.ParseIP(hmp.Host)
1570 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1573 ni := krpc.NodeInfo{
1574 Addr: krpc.NodeAddr{
1579 cl.eachDhtServer(func(s DhtServer) {
1585 func (cl *Client) banPeerIP(ip net.IP) {
1586 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1587 // addresses directly to v4on6, which doesn't compare equal with v4.
1588 ipAddr, ok := netip.AddrFromSlice(ip)
1592 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1593 for _, t := range cl.torrents {
1594 t.iterPeers(func(p *Peer) {
1595 if p.remoteIp().Equal(ip) {
1596 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1597 // Should this be a close?
1604 type newConnectionOpts struct {
1606 remoteAddr PeerRemoteAddr
1607 localPublicAddr peerLocalPublicAddr
1612 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1613 if opts.network == "" {
1614 panic(opts.remoteAddr)
1618 outgoing: opts.outgoing,
1621 PeerMaxRequests: 250,
1623 RemoteAddr: opts.remoteAddr,
1624 localPublicAddr: opts.localPublicAddr,
1625 Network: opts.network,
1626 callbacks: &cl.config.Callbacks,
1628 connString: opts.connString,
1631 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1632 c.initRequestState()
1633 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1634 if opts.remoteAddr != nil {
1635 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1637 c.bannableAddr = Some(netipAddrPort.Addr())
1641 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1642 c.setRW(connStatsReadWriter{nc, c})
1643 c.r = &rateLimitedReader{
1644 l: cl.config.DownloadRateLimiter,
1649 "new PeerConn %p [Client %p remoteAddr %v network %v outgoing %t]",
1650 c, cl, opts.remoteAddr, opts.network, opts.outgoing,
1652 for _, f := range cl.config.Callbacks.NewPeer {
1658 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1665 t.addPeers([]PeerInfo{{
1666 Addr: ipPortAddr{ip, port},
1667 Source: PeerSourceDhtAnnouncePeer,
1671 func firstNotNil(ips ...net.IP) net.IP {
1672 for _, ip := range ips {
1680 func (cl *Client) eachListener(f func(Listener) bool) {
1681 for _, s := range cl.listeners {
1688 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1689 for i := 0; i < len(cl.listeners); i += 1 {
1690 if ret = cl.listeners[i]; f(ret) {
1697 func (cl *Client) publicIp(peer net.IP) net.IP {
1698 // TODO: Use BEP 10 to determine how peers are seeing us.
1699 if peer.To4() != nil {
1701 cl.config.PublicIp4,
1702 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1707 cl.config.PublicIp6,
1708 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1712 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1713 l := cl.findListener(
1714 func(l Listener) bool {
1715 return f(addrIpOrNil(l.Addr()))
1721 return addrIpOrNil(l.Addr())
1724 // Our IP as a peer should see it.
1725 func (cl *Client) publicAddr(peer net.IP) IpPort {
1726 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1729 // ListenAddrs addresses currently being listened to.
1730 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1732 ret = make([]net.Addr, len(cl.listeners))
1733 for i := 0; i < len(cl.listeners); i += 1 {
1734 ret[i] = cl.listeners[i].Addr()
1740 func (cl *Client) PublicIPs() (ips []net.IP) {
1741 if ip := cl.config.PublicIp4; ip != nil {
1742 ips = append(ips, ip)
1744 if ip := cl.config.PublicIp6; ip != nil {
1745 ips = append(ips, ip)
1750 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1751 ipa, ok := tryIpPortFromNetAddr(addr)
1755 ip := maskIpForAcceptLimiting(ipa.IP)
1756 if cl.acceptLimiter == nil {
1757 cl.acceptLimiter = make(map[ipStr]int)
1759 cl.acceptLimiter[ipStr(ip.String())]++
1762 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1763 if ip4 := ip.To4(); ip4 != nil {
1764 return ip4.Mask(net.CIDRMask(24, 32))
1769 func (cl *Client) clearAcceptLimits() {
1770 cl.acceptLimiter = nil
1773 func (cl *Client) acceptLimitClearer() {
1776 case <-cl.closed.Done():
1778 case <-time.After(15 * time.Minute):
1780 cl.clearAcceptLimits()
1786 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1787 if cl.config.DisableAcceptRateLimiting {
1790 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1793 func (cl *Client) rLock() {
1797 func (cl *Client) rUnlock() {
1801 func (cl *Client) lock() {
1805 func (cl *Client) unlock() {
1809 func (cl *Client) locker() *lockWithDeferreds {
1813 func (cl *Client) String() string {
1814 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1817 // Returns connection-level aggregate connStats at the Client level. See the comment on
1818 // TorrentStats.ConnStats.
1819 func (cl *Client) ConnStats() ConnStats {
1820 return cl.connStats.Copy()
1823 func (cl *Client) Stats() ClientStats {
1826 return cl.statsLocked()
1829 func (cl *Client) statsLocked() (stats ClientStats) {
1830 stats.ConnStats = cl.connStats.Copy()
1831 stats.ActiveHalfOpenAttempts = cl.numHalfOpen
1832 stats.NumPeersUndialableWithoutHolepunchDialedAfterHolepunchConnect =
1833 len(cl.undialableWithoutHolepunchDialAttemptedAfterHolepunchConnect)
1834 stats.NumPeersDialableOnlyAfterHolepunch =
1835 len(cl.dialableOnlyAfterHolepunch)