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/cespare/xxhash"
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 request_strategy "github.com/anacrolix/torrent/request-strategy"
47 "github.com/anacrolix/torrent/storage"
48 "github.com/anacrolix/torrent/tracker"
49 "github.com/anacrolix/torrent/types/infohash"
50 infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2"
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
94 defaultLocalLtepProtocolMap LocalLtepProtocolMap
99 func (cl *Client) BadPeerIPs() (ips []string) {
101 ips = cl.badPeerIPsLocked()
106 func (cl *Client) badPeerIPsLocked() (ips []string) {
107 ips = make([]string, len(cl.badPeerIPs))
109 for k := range cl.badPeerIPs {
116 func (cl *Client) PeerID() PeerID {
120 // Returns the port number for the first listener that has one. No longer assumes that all port
121 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
123 func (cl *Client) LocalPort() (port int) {
124 for i := 0; i < len(cl.listeners); i += 1 {
125 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
132 func writeDhtServerStatus(w io.Writer, s DhtServer) {
133 dhtStats := s.Stats()
134 fmt.Fprintf(w, " ID: %x\n", s.ID())
135 spew.Fdump(w, dhtStats)
138 // Writes out a human readable status of the client, such as for writing to a
140 func (cl *Client) WriteStatus(_w io.Writer) {
143 w := bufio.NewWriter(_w)
145 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
146 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
147 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
148 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
149 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
150 cl.eachDhtServer(func(s DhtServer) {
151 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
152 writeDhtServerStatus(w, s)
154 dumpStats(w, cl.statsLocked())
155 torrentsSlice := cl.torrentsAsSlice()
156 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
158 sort.Slice(torrentsSlice, func(l, r int) bool {
159 return torrentsSlice[l].canonicalShortInfohash().AsString() < torrentsSlice[r].canonicalShortInfohash().AsString()
161 for _, t := range torrentsSlice {
163 fmt.Fprint(w, "<unknown name>")
165 fmt.Fprint(w, t.name())
171 "%f%% of %d bytes (%s)",
172 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
174 humanize.Bytes(uint64(t.length())))
176 w.WriteString("<missing metainfo>")
184 func (cl *Client) initLogger() {
185 logger := cl.config.Logger
190 logger = logger.FilterLevel(log.Debug)
192 cl.logger = logger.WithValues(cl)
195 func (cl *Client) announceKey() int32 {
196 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
199 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
200 func (cl *Client) init(cfg *ClientConfig) {
202 g.MakeMap(&cl.dopplegangerAddrs)
203 cl.torrents = make(map[metainfo.Hash]*Torrent)
204 cl.activeAnnounceLimiter.SlotsPerKey = 2
205 cl.event.L = cl.locker()
206 cl.ipBlockList = cfg.IPBlocklist
207 cl.httpClient = &http.Client{
208 Transport: cfg.WebTransport,
210 if cl.httpClient.Transport == nil {
211 cl.httpClient.Transport = &http.Transport{
212 Proxy: cfg.HTTPProxy,
213 DialContext: cfg.HTTPDialContext,
214 // I think this value was observed from some webseeds. It seems reasonable to extend it
215 // to other uses of HTTP from the client.
219 cl.defaultLocalLtepProtocolMap = makeBuiltinLtepProtocols(!cfg.DisablePEX)
222 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
224 cfg = NewDefaultClientConfig()
229 go cl.acceptLimitClearer()
238 storageImpl := cfg.DefaultStorage
239 if storageImpl == nil {
240 // We'd use mmap by default but HFS+ doesn't support sparse files.
241 storageImplCloser := storage.NewFile(cfg.DataDir)
242 cl.onClose = append(cl.onClose, func() {
243 if err := storageImplCloser.Close(); err != nil {
244 cl.logger.Printf("error closing default storage: %s", err)
247 storageImpl = storageImplCloser
249 cl.defaultStorage = storage.NewClient(storageImpl)
251 if cfg.PeerID != "" {
252 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
254 o := copy(cl.peerID[:], cfg.Bep20)
255 _, err = rand.Read(cl.peerID[o:])
257 panic("error generating peer id")
261 builtinListenNetworks := cl.listenNetworks()
262 sockets, err := listenAll(
263 builtinListenNetworks,
264 cl.config.ListenHost,
265 cl.config.ListenPort,
272 if len(sockets) == 0 && len(builtinListenNetworks) != 0 {
273 err = fmt.Errorf("no sockets created for networks %v", builtinListenNetworks)
280 for _, _s := range sockets {
281 s := _s // Go is fucking retarded.
282 cl.onClose = append(cl.onClose, func() { go s.Close() })
283 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
284 cl.dialers = append(cl.dialers, s)
285 cl.listeners = append(cl.listeners, s)
286 if cl.config.AcceptPeerConnections {
287 go cl.acceptConnections(s)
294 for _, s := range sockets {
295 if pc, ok := s.(net.PacketConn); ok {
296 ds, err := cl.NewAnacrolixDhtServer(pc)
300 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
301 cl.onClose = append(cl.onClose, func() { ds.Close() })
306 cl.websocketTrackers = websocketTrackers{
309 GetAnnounceRequest: func(
310 event tracker.AnnounceEvent, infoHash [20]byte,
312 tracker.AnnounceRequest, error,
316 t, ok := cl.torrents[infoHash]
318 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
320 return t.announceRequest(event, infoHash), nil
322 Proxy: cl.config.HTTPProxy,
323 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
324 ICEServers: cl.config.ICEServers,
325 DialContext: cl.config.TrackerDialContext,
326 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
329 t, ok := cl.torrents[dcc.InfoHash]
331 cl.logger.WithDefaultLevel(log.Warning).Printf(
332 "got webrtc conn for unloaded torrent with infohash %x",
338 go t.onWebRtcConn(dc, dcc)
345 func (cl *Client) AddDhtServer(d DhtServer) {
346 cl.dhtServers = append(cl.dhtServers, d)
349 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
350 // given address for any Torrent.
351 func (cl *Client) AddDialer(d Dialer) {
354 cl.dialers = append(cl.dialers, d)
355 for _, t := range cl.torrents {
360 func (cl *Client) Listeners() []Listener {
364 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
366 func (cl *Client) AddListener(l Listener) {
367 cl.listeners = append(cl.listeners, l)
368 if cl.config.AcceptPeerConnections {
369 go cl.acceptConnections(l)
373 func (cl *Client) firewallCallback(net.Addr) bool {
375 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
378 torrent.Add("connections firewalled", 1)
380 torrent.Add("connections not firewalled", 1)
385 func (cl *Client) listenOnNetwork(n network) bool {
386 if n.Ipv4 && cl.config.DisableIPv4 {
389 if n.Ipv6 && cl.config.DisableIPv6 {
392 if n.Tcp && cl.config.DisableTCP {
395 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
401 func (cl *Client) listenNetworks() (ns []network) {
402 for _, n := range allPeerNetworks {
403 if cl.listenOnNetwork(n) {
410 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
411 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
412 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
413 cfg := dht.ServerConfig{
414 IPBlocklist: cl.ipBlockList,
416 OnAnnouncePeer: cl.onDHTAnnouncePeer,
417 PublicIP: func() net.IP {
418 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
419 return cl.config.PublicIp6
421 return cl.config.PublicIp4
423 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
424 OnQuery: cl.config.DHTOnQuery,
427 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
430 s, err = dht.NewServer(&cfg)
432 go s.TableMaintainer()
437 func (cl *Client) Closed() events.Done {
438 return cl.closed.Done()
441 func (cl *Client) eachDhtServer(f func(DhtServer)) {
442 for _, ds := range cl.dhtServers {
447 // Stops the client. All connections to peers are closed and all activity will come to a halt.
448 func (cl *Client) Close() (errs []error) {
449 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
451 for _, t := range cl.torrents {
452 err := t.close(&closeGroup)
454 errs = append(errs, err)
457 for i := range cl.onClose {
458 cl.onClose[len(cl.onClose)-1-i]()
463 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
467 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
468 if cl.ipBlockList == nil {
471 return cl.ipBlockList.Lookup(ip)
474 func (cl *Client) ipIsBlocked(ip net.IP) bool {
475 _, blocked := cl.ipBlockRange(ip)
479 func (cl *Client) wantConns() bool {
480 if cl.config.AlwaysWantConns {
483 for _, t := range cl.torrents {
484 if t.wantIncomingConns() {
491 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
492 func (cl *Client) rejectAccepted(conn net.Conn) error {
494 return errors.New("don't want conns right now")
496 ra := conn.RemoteAddr()
497 if rip := addrIpOrNil(ra); rip != nil {
498 if cl.config.DisableIPv4Peers && rip.To4() != nil {
499 return errors.New("ipv4 peers disabled")
501 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
502 return errors.New("ipv4 disabled")
504 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
505 return errors.New("ipv6 disabled")
507 if cl.rateLimitAccept(rip) {
508 return errors.New("source IP accepted rate limited")
510 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
511 return errors.New("bad source addr")
517 func (cl *Client) acceptConnections(l Listener) {
519 conn, err := l.Accept()
520 torrent.Add("client listener accepts", 1)
522 holepunchAddr, holepunchErr := addrPortFromPeerRemoteAddr(conn.RemoteAddr())
523 if holepunchErr == nil {
525 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
526 setAdd(&cl.accepted, holepunchAddr)
529 cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
532 setAdd(&cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
537 conn = pproffd.WrapNetConn(conn)
539 closed := cl.closed.IsSet()
541 if !closed && conn != nil {
542 reject = cl.rejectAccepted(conn)
552 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
557 torrent.Add("rejected accepted connections", 1)
558 cl.logger.LazyLog(log.Debug, func() log.Msg {
559 return log.Fmsg("rejecting accepted conn: %v", reject)
563 go cl.incomingConnection(conn)
565 cl.logger.LazyLog(log.Debug, func() log.Msg {
566 return log.Fmsg("accepted %q connection at %q from %q",
572 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
573 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
574 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
579 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
580 func regularNetConnPeerConnConnString(nc net.Conn) string {
581 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
584 func (cl *Client) incomingConnection(nc net.Conn) {
586 if tc, ok := nc.(*net.TCPConn); ok {
589 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
590 c := cl.newConnection(
594 remoteAddr: nc.RemoteAddr(),
595 localPublicAddr: cl.publicAddr(remoteAddr.IP),
596 network: nc.RemoteAddr().Network(),
597 connString: regularNetConnPeerConnConnString(nc),
604 c.Discovery = PeerSourceIncoming
605 cl.runReceivedConn(c)
608 // Returns a handle to the given torrent, if it's present in the client.
609 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
612 t, ok = cl.torrents[ih]
616 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
617 return cl.torrents[ih]
620 type DialResult struct {
625 func countDialResult(err error) {
627 torrent.Add("successful dials", 1)
629 torrent.Add("unsuccessful dials", 1)
633 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
634 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
635 if ret < minDialTimeout {
641 // Returns whether an address is known to connect to a client with our own ID.
642 func (cl *Client) dopplegangerAddr(addr string) bool {
643 _, ok := cl.dopplegangerAddrs[addr]
647 // Returns a connection over UTP or TCP, whichever is first to connect.
648 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
649 return DialFirst(ctx, addr, cl.dialers)
652 // Returns a connection over UTP or TCP, whichever is first to connect.
653 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
657 defer pool.startDrainer()
658 for _, _s := range dialers {
661 return pool.getFirst()
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 doProtocolHandshakeOnDialResult(
730 obfuscatedHeader bool,
734 c *PeerConn, err error,
738 addrIpPort, _ := tryIpPortFromNetAddr(addr)
739 c, err = cl.initiateProtocolHandshakes(
740 context.Background(), nc, t, obfuscatedHeader,
744 // It would be possible to retrieve a public IP from the dialer used here?
745 localPublicAddr: cl.publicAddr(addrIpPort.IP),
746 network: dr.Dialer.DialerNetwork(),
747 connString: regularNetConnPeerConnConnString(nc),
755 // Returns nil connection and nil error if no connection could be established for valid reasons.
756 func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn, err error) {
757 // It would be better if dial rate limiting could be tested when considering to open connections
758 // instead. Doing it here means if the limit is low, and the half-open limit is high, we could
759 // end up with lots of outgoing connection attempts pending that were initiated on stale data.
761 dialReservation := cl.config.DialRateLimiter.Reserve()
762 if !opts.receivedHolepunchConnect {
763 if !dialReservation.OK() {
764 err = errors.New("can't make dial limit reservation")
767 time.Sleep(dialReservation.Delay())
770 torrent.Add("establish outgoing connection", 1)
771 addr := opts.peerInfo.Addr
772 dialPool := dialPool{
773 resCh: make(chan DialResult),
776 defer dialPool.startDrainer()
777 dialTimeout := opts.t.getDialTimeoutUnlocked()
779 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
781 for _, d := range cl.dialers {
785 holepunchAddr, holepunchAddrErr := addrPortFromPeerRemoteAddr(addr)
786 headerObfuscationPolicy := opts.HeaderObfuscationPolicy
787 obfuscatedHeaderFirst := headerObfuscationPolicy.Preferred
788 firstDialResult := dialPool.getFirst()
789 if firstDialResult.Conn == nil {
790 // No dialers worked. Try to initiate a holepunching rendezvous.
791 if holepunchAddrErr == nil {
793 if !opts.receivedHolepunchConnect {
794 g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
796 if !opts.skipHolepunchRendezvous {
797 opts.t.trySendHolepunchRendezvous(holepunchAddr)
801 err = fmt.Errorf("all initial dials failed")
804 if opts.receivedHolepunchConnect && holepunchAddrErr == nil {
806 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
807 g.MakeMapIfNilAndSet(&cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
809 g.MakeMapIfNil(&cl.dialedSuccessfullyAfterHolepunchConnect)
810 g.MapInsert(cl.dialedSuccessfullyAfterHolepunchConnect, holepunchAddr, struct{}{})
813 c, err = doProtocolHandshakeOnDialResult(
815 obfuscatedHeaderFirst,
820 torrent.Add("initiated conn with preferred header obfuscation", 1)
825 "error doing protocol handshake with header obfuscation %v",
826 obfuscatedHeaderFirst,
828 firstDialResult.Conn.Close()
829 // We should have just tried with the preferred header obfuscation. If it was required, there's nothing else to try.
830 if headerObfuscationPolicy.RequirePreferred {
833 // Reuse the dialer that returned already but failed to handshake.
835 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
837 dialPool.add(ctx, firstDialResult.Dialer)
839 secondDialResult := dialPool.getFirst()
840 if secondDialResult.Conn == nil {
843 c, err = doProtocolHandshakeOnDialResult(
845 !obfuscatedHeaderFirst,
850 torrent.Add("initiated conn with fallback header obfuscation", 1)
855 "error doing protocol handshake with header obfuscation %v",
856 !obfuscatedHeaderFirst,
858 secondDialResult.Conn.Close()
862 type outgoingConnOpts struct {
865 // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
866 requireRendezvous bool
867 // Don't send rendezvous requests to eligible relays.
868 skipHolepunchRendezvous bool
869 // Outgoing connection attempt is in response to holepunch connect message.
870 receivedHolepunchConnect bool
871 HeaderObfuscationPolicy HeaderObfuscationPolicy
874 // Called to dial out and run a connection. The addr we're given is already
875 // considered half-open.
876 func (cl *Client) outgoingConnection(
877 opts outgoingConnOpts,
878 attemptKey outgoingConnAttemptKey,
880 c, err := cl.dialAndCompleteHandshake(opts)
882 c.conn.SetWriteDeadline(time.Time{})
886 // Don't release lock between here and addPeerConn, unless it's for failure.
887 cl.noLongerHalfOpen(opts.t, opts.peerInfo.Addr.String(), attemptKey)
892 "error establishing outgoing connection to %v: %v",
900 c.Discovery = opts.peerInfo.Source
901 c.trusted = opts.peerInfo.Trusted
902 opts.t.runHandshookConnLoggingErr(c)
905 // The port number for incoming peer connections. 0 if the client isn't listening.
906 func (cl *Client) incomingPeerPort() int {
907 return cl.LocalPort()
910 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) (err error) {
911 if c.headerEncrypted {
913 rw, c.cryptoMethod, err = mse.InitiateHandshake(
918 t.canonicalShortInfohash().Bytes(),
920 cl.config.CryptoProvides,
924 return fmt.Errorf("header obfuscation handshake: %w", err)
927 ih, err := cl.connBtHandshake(c, t.canonicalShortInfohash())
929 return fmt.Errorf("bittorrent protocol handshake: %w", err)
931 if g.Some(ih) == t.infoHash {
934 if t.infoHashV2.Ok && *t.infoHashV2.Value.ToShort() == ih {
938 err = errors.New("bittorrent protocol handshake: peer infohash didn't match")
942 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
943 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
944 func (cl *Client) forSkeys(f func([]byte) bool) {
947 if false { // Emulate the bug from #114
949 for ih := range cl.torrents {
953 for range cl.torrents {
960 for ih := range cl.torrents {
967 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
968 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
974 // Do encryption and bittorrent handshakes as receiver.
975 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
976 defer perf.ScopeTimerErr(&err)()
978 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
980 if err == nil || err == mse.ErrNoSecretKeyMatch {
981 if c.headerEncrypted {
982 torrent.Add("handshakes received encrypted", 1)
984 torrent.Add("handshakes received unencrypted", 1)
987 torrent.Add("handshakes received with error while handling encryption", 1)
990 if err == mse.ErrNoSecretKeyMatch {
995 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
996 err = errors.New("connection does not have required header obfuscation")
999 ih, err := cl.connBtHandshake(c, nil)
1001 return nil, fmt.Errorf("during bt handshake: %w", err)
1009 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
1013 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
1014 &successfulPeerWireProtocolHandshakePeerReservedBytes)
1017 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
1018 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
1022 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(
1023 hex.EncodeToString(res.PeerExtensionBits[:]), 1)
1025 c.PeerExtensionBytes = res.PeerExtensionBits
1026 c.PeerID = res.PeerID
1027 c.completedHandshake = time.Now()
1028 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
1034 func (cl *Client) runReceivedConn(c *PeerConn) {
1035 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1039 t, err := cl.receiveHandshakes(c)
1041 cl.logger.LazyLog(log.Debug, func() log.Msg {
1043 "error receiving handshakes on %v: %s", c, err,
1045 "network", c.Network,
1048 torrent.Add("error receiving handshake", 1)
1050 cl.onBadAccept(c.RemoteAddr)
1055 torrent.Add("received handshake for unloaded torrent", 1)
1056 cl.logger.LazyLog(log.Debug, func() log.Msg {
1057 return log.Fmsg("received handshake for unloaded torrent")
1060 cl.onBadAccept(c.RemoteAddr)
1064 torrent.Add("received handshake for loaded torrent", 1)
1065 c.conn.SetWriteDeadline(time.Time{})
1068 t.runHandshookConnLoggingErr(c)
1071 // Client lock must be held before entering this.
1072 func (t *Torrent) runHandshookConn(pc *PeerConn) error {
1075 for i, b := range cl.config.MinPeerExtensions {
1076 if pc.PeerExtensionBytes[i]&b != b {
1077 return fmt.Errorf("peer did not meet minimum peer extensions: %x", pc.PeerExtensionBytes[:])
1080 if pc.PeerID == cl.peerID {
1083 addr := pc.RemoteAddr.String()
1084 cl.dopplegangerAddrs[addr] = struct{}{}
1086 // Because the remote address is not necessarily the same as its client's torrent listen
1087 // address, we won't record the remote address as a doppleganger. Instead, the initiator
1088 // can record *us* as the doppleganger.
1090 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1093 pc.r = deadlineReader{pc.conn, pc.r}
1094 completedHandshakeConnectionFlags.Add(pc.connectionFlags(), 1)
1095 if connIsIpv6(pc.conn) {
1096 torrent.Add("completed handshake over ipv6", 1)
1098 if err := t.addPeerConn(pc); err != nil {
1099 return fmt.Errorf("adding connection: %w", err)
1101 defer t.dropConnection(pc)
1102 pc.addBuiltinLtepProtocols(!cl.config.DisablePEX)
1103 for _, cb := range pc.callbacks.PeerConnAdded {
1106 pc.startMessageWriter()
1107 pc.sendInitialMessages()
1108 pc.initUpdateRequestsTimer()
1109 err := pc.mainReadLoop()
1111 return fmt.Errorf("main read loop: %w", err)
1116 func (p *Peer) initUpdateRequestsTimer() {
1118 if p.updateRequestsTimer != nil {
1119 panic(p.updateRequestsTimer)
1122 if enableUpdateRequestsTimer {
1123 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1127 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1129 func (c *Peer) updateRequestsTimerFunc() {
1131 defer c.locker().Unlock()
1132 if c.closed.IsSet() {
1135 if c.isLowOnRequests() {
1136 // If there are no outstanding requests, then a request update should have already run.
1139 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1140 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1141 // already been fired.
1142 torrent.Add("spurious timer requests updates", 1)
1145 c.updateRequests(peerUpdateRequestsTimerReason)
1148 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1149 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1150 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1151 const localClientReqq = 1024
1153 // See the order given in Transmission's tr_peerMsgsNew.
1154 func (pc *PeerConn) sendInitialMessages() {
1157 if pc.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1158 pc.write(pp.Message{
1160 ExtendedID: pp.HandshakeExtendedID,
1161 ExtendedPayload: func() []byte {
1162 msg := pp.ExtendedHandshakeMessage{
1163 V: cl.config.ExtendedHandshakeClientVersion,
1164 Reqq: localClientReqq,
1165 YourIp: pp.CompactIp(pc.remoteIp()),
1166 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1167 Port: cl.incomingPeerPort(),
1168 MetadataSize: t.metadataSize(),
1169 // TODO: We can figure these out specific to the socket used.
1170 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1171 Ipv6: cl.config.PublicIp6.To16(),
1173 msg.M = pc.LocalLtepProtocolMap.toSupportedExtensionDict()
1174 return bencode.MustMarshal(msg)
1179 if pc.fastEnabled() {
1180 if t.haveAllPieces() {
1181 pc.write(pp.Message{Type: pp.HaveAll})
1182 pc.sentHaves.AddRange(0, bitmap.BitRange(pc.t.NumPieces()))
1184 } else if !t.haveAnyPieces() {
1185 pc.write(pp.Message{Type: pp.HaveNone})
1186 pc.sentHaves.Clear()
1192 if pc.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1193 pc.write(pp.Message{
1200 func (cl *Client) dhtPort() (ret uint16) {
1201 if len(cl.dhtServers) == 0 {
1204 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1207 func (cl *Client) haveDhtServer() bool {
1208 return len(cl.dhtServers) > 0
1211 // Process incoming ut_metadata message.
1212 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1213 var d pp.ExtendedMetadataRequestMsg
1214 err := bencode.Unmarshal(payload, &d)
1215 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1216 } else if err != nil {
1217 return fmt.Errorf("error unmarshalling bencode: %s", err)
1221 case pp.DataMetadataExtensionMsgType:
1222 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1223 if !c.requestedMetadataPiece(piece) {
1224 return fmt.Errorf("got unexpected piece %d", piece)
1226 c.metadataRequests[piece] = false
1227 begin := len(payload) - d.PieceSize()
1228 if begin < 0 || begin >= len(payload) {
1229 return fmt.Errorf("data has bad offset in payload: %d", begin)
1231 t.saveMetadataPiece(piece, payload[begin:])
1232 c.lastUsefulChunkReceived = time.Now()
1233 err = t.maybeCompleteMetadata()
1235 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1236 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1237 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1238 // log consumers can filter for this message.
1239 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1242 case pp.RequestMetadataExtensionMsgType:
1243 if !t.haveMetadataPiece(piece) {
1244 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1247 start := (1 << 14) * piece
1248 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1249 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1251 case pp.RejectMetadataExtensionMsgType:
1254 return errors.New("unknown msg_type value")
1258 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1259 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1260 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1265 // Returns whether the IP address and port are considered "bad".
1266 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1267 if port == 0 || ip == nil {
1270 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1273 if _, ok := cl.ipBlockRange(ip); ok {
1276 ipAddr, ok := netip.AddrFromSlice(ip)
1280 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1286 // Return a Torrent ready for insertion into a Client.
1287 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1288 return cl.newTorrentOpt(AddTorrentOpts{
1290 Storage: specStorage,
1294 // Return a Torrent ready for insertion into a Client.
1295 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1296 var v1InfoHash g.Option[infohash.T]
1297 if !opts.InfoHash.IsZero() {
1298 v1InfoHash.Set(opts.InfoHash)
1300 if !v1InfoHash.Ok && !opts.InfoHashV2.Ok {
1301 panic("v1 infohash must be nonzero or v2 infohash must be set")
1303 // use provided storage, if provided
1304 storageClient := cl.defaultStorage
1305 if opts.Storage != nil {
1306 storageClient = storage.NewClient(opts.Storage)
1311 infoHash: v1InfoHash,
1312 infoHashV2: opts.InfoHashV2,
1313 peers: prioritizedPeers{
1315 getPrio: func(p PeerInfo) peerPriority {
1317 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1320 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1322 storageOpener: storageClient,
1323 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1325 metadataChanged: sync.Cond{
1328 webSeeds: make(map[string]*Peer),
1329 gotMetainfoC: make(chan struct{}),
1333 t.smartBanCache.Hash = func(b []byte) uint64 {
1339 t.smartBanCache.Init()
1340 t.networkingEnabled.Set()
1341 t.logger = cl.logger.WithDefaultLevel(log.Debug)
1342 t.sourcesLogger = t.logger.WithNames("sources")
1343 if opts.ChunkSize == 0 {
1344 opts.ChunkSize = defaultChunkSize
1346 t.setChunkSize(opts.ChunkSize)
1350 // A file-like handle to some torrent data resource.
1351 type Handle interface {
1358 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1359 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1362 // Deprecated. Adds a torrent by InfoHash with a custom Storage implementation.
1363 // If the torrent already exists then this Storage is ignored and the
1364 // existing torrent returned with `new` set to `false`
1365 func (cl *Client) AddTorrentInfoHashWithStorage(
1366 infoHash metainfo.Hash,
1367 specStorage storage.ClientImpl,
1368 ) (t *Torrent, new bool) {
1371 t, ok := cl.torrents[infoHash]
1377 t = cl.newTorrent(infoHash, specStorage)
1378 cl.eachDhtServer(func(s DhtServer) {
1379 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1380 go t.dhtAnnouncer(s)
1383 cl.torrents[infoHash] = t
1384 cl.clearAcceptLimits()
1385 t.updateWantPeersEvent()
1386 // Tickle Client.waitAccept, new torrent may want conns.
1387 cl.event.Broadcast()
1391 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1392 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1393 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1394 infoHash := opts.InfoHash
1397 t, ok := cl.torrents[infoHash]
1403 t = cl.newTorrentOpt(opts)
1404 cl.eachDhtServer(func(s DhtServer) {
1405 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1406 go t.dhtAnnouncer(s)
1409 cl.torrents[infoHash] = t
1410 t.setInfoBytesLocked(opts.InfoBytes)
1411 cl.clearAcceptLimits()
1412 t.updateWantPeersEvent()
1413 // Tickle Client.waitAccept, new torrent may want conns.
1414 cl.event.Broadcast()
1418 type AddTorrentOpts struct {
1420 InfoHashV2 g.Option[infohash_v2.T]
1421 Storage storage.ClientImpl
1422 ChunkSize pp.Integer
1426 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1427 // Torrent.MergeSpec.
1428 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1429 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1430 InfoHash: spec.InfoHash,
1431 InfoHashV2: spec.InfoHashV2,
1432 Storage: spec.Storage,
1433 ChunkSize: spec.ChunkSize,
1437 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1439 modSpec.ChunkSize = 0
1441 err = t.MergeSpec(&modSpec)
1442 if err != nil && new {
1448 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1449 // spec.DisallowDataDownload/Upload will be read and applied
1450 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1451 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1452 if spec.DisplayName != "" {
1453 t.SetDisplayName(spec.DisplayName)
1455 if spec.InfoBytes != nil {
1456 err := t.SetInfoBytes(spec.InfoBytes)
1462 cl.AddDhtNodes(spec.DhtNodes)
1463 t.UseSources(spec.Sources)
1466 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1467 for _, url := range spec.Webseeds {
1470 for _, peerAddr := range spec.PeerAddrs {
1472 Addr: StringAddr(peerAddr),
1473 Source: PeerSourceDirect,
1477 if spec.ChunkSize != 0 {
1478 panic("chunk size cannot be changed for existing Torrent")
1480 t.addTrackers(spec.Trackers)
1482 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1483 t.dataUploadDisallowed = spec.DisallowDataUpload
1484 return t.AddPieceLayers(spec.PieceLayers)
1487 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1488 t, ok := cl.torrents[infoHash]
1490 err = fmt.Errorf("no such torrent")
1494 delete(cl.torrents, infoHash)
1498 func (cl *Client) allTorrentsCompleted() bool {
1499 for _, t := range cl.torrents {
1503 if !t.haveAllPieces() {
1510 // Returns true when all torrents are completely downloaded and false if the
1511 // client is stopped before that.
1512 func (cl *Client) WaitAll() bool {
1515 for !cl.allTorrentsCompleted() {
1516 if cl.closed.IsSet() {
1524 // Returns handles to all the torrents loaded in the Client.
1525 func (cl *Client) Torrents() []*Torrent {
1528 return cl.torrentsAsSlice()
1531 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1532 for _, t := range cl.torrents {
1533 ret = append(ret, t)
1538 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1539 spec, err := TorrentSpecFromMagnetUri(uri)
1543 T, _, err = cl.AddTorrentSpec(spec)
1547 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1548 ts, err := TorrentSpecFromMetaInfoErr(mi)
1552 T, _, err = cl.AddTorrentSpec(ts)
1556 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1557 mi, err := metainfo.LoadFromFile(filename)
1561 return cl.AddTorrent(mi)
1564 func (cl *Client) DhtServers() []DhtServer {
1565 return cl.dhtServers
1568 func (cl *Client) AddDhtNodes(nodes []string) {
1569 for _, n := range nodes {
1570 hmp := missinggo.SplitHostMaybePort(n)
1571 ip := net.ParseIP(hmp.Host)
1573 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1576 ni := krpc.NodeInfo{
1577 Addr: krpc.NodeAddr{
1582 cl.eachDhtServer(func(s DhtServer) {
1588 func (cl *Client) banPeerIP(ip net.IP) {
1589 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1590 // addresses directly to v4on6, which doesn't compare equal with v4.
1591 ipAddr, ok := netip.AddrFromSlice(ip)
1595 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1596 for _, t := range cl.torrents {
1597 t.iterPeers(func(p *Peer) {
1598 if p.remoteIp().Equal(ip) {
1599 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1600 // Should this be a close?
1607 type newConnectionOpts struct {
1609 remoteAddr PeerRemoteAddr
1610 localPublicAddr peerLocalPublicAddr
1615 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1616 if opts.network == "" {
1617 panic(opts.remoteAddr)
1621 outgoing: opts.outgoing,
1624 PeerMaxRequests: 250,
1626 RemoteAddr: opts.remoteAddr,
1627 localPublicAddr: opts.localPublicAddr,
1628 Network: opts.network,
1629 callbacks: &cl.config.Callbacks,
1631 connString: opts.connString,
1634 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1635 c.initRequestState()
1636 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1637 if opts.remoteAddr != nil {
1638 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1640 c.bannableAddr = Some(netipAddrPort.Addr())
1644 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1645 c.logger = c.logger.WithContextText(fmt.Sprintf("%T %p", c, c))
1646 c.setRW(connStatsReadWriter{nc, c})
1647 c.r = &rateLimitedReader{
1648 l: cl.config.DownloadRateLimiter,
1653 "inited with remoteAddr %v network %v outgoing %t",
1654 opts.remoteAddr, opts.network, opts.outgoing,
1656 for _, f := range cl.config.Callbacks.NewPeer {
1662 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1669 t.addPeers([]PeerInfo{{
1670 Addr: ipPortAddr{ip, port},
1671 Source: PeerSourceDhtAnnouncePeer,
1675 func firstNotNil(ips ...net.IP) net.IP {
1676 for _, ip := range ips {
1684 func (cl *Client) eachListener(f func(Listener) bool) {
1685 for _, s := range cl.listeners {
1692 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1693 for i := 0; i < len(cl.listeners); i += 1 {
1694 if ret = cl.listeners[i]; f(ret) {
1701 func (cl *Client) publicIp(peer net.IP) net.IP {
1702 // TODO: Use BEP 10 to determine how peers are seeing us.
1703 if peer.To4() != nil {
1705 cl.config.PublicIp4,
1706 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1711 cl.config.PublicIp6,
1712 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1716 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1717 l := cl.findListener(
1718 func(l Listener) bool {
1719 return f(addrIpOrNil(l.Addr()))
1725 return addrIpOrNil(l.Addr())
1728 // Our IP as a peer should see it.
1729 func (cl *Client) publicAddr(peer net.IP) IpPort {
1730 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1733 // ListenAddrs addresses currently being listened to.
1734 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1736 ret = make([]net.Addr, len(cl.listeners))
1737 for i := 0; i < len(cl.listeners); i += 1 {
1738 ret[i] = cl.listeners[i].Addr()
1744 func (cl *Client) PublicIPs() (ips []net.IP) {
1745 if ip := cl.config.PublicIp4; ip != nil {
1746 ips = append(ips, ip)
1748 if ip := cl.config.PublicIp6; ip != nil {
1749 ips = append(ips, ip)
1754 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1755 ipa, ok := tryIpPortFromNetAddr(addr)
1759 ip := maskIpForAcceptLimiting(ipa.IP)
1760 if cl.acceptLimiter == nil {
1761 cl.acceptLimiter = make(map[ipStr]int)
1763 cl.acceptLimiter[ipStr(ip.String())]++
1766 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1767 if ip4 := ip.To4(); ip4 != nil {
1768 return ip4.Mask(net.CIDRMask(24, 32))
1773 func (cl *Client) clearAcceptLimits() {
1774 cl.acceptLimiter = nil
1777 func (cl *Client) acceptLimitClearer() {
1780 case <-cl.closed.Done():
1782 case <-time.After(15 * time.Minute):
1784 cl.clearAcceptLimits()
1790 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1791 if cl.config.DisableAcceptRateLimiting {
1794 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1797 func (cl *Client) rLock() {
1801 func (cl *Client) rUnlock() {
1805 func (cl *Client) lock() {
1809 func (cl *Client) unlock() {
1813 func (cl *Client) locker() *lockWithDeferreds {
1817 func (cl *Client) String() string {
1818 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1821 // Returns connection-level aggregate connStats at the Client level. See the comment on
1822 // TorrentStats.ConnStats.
1823 func (cl *Client) ConnStats() ConnStats {
1824 return cl.connStats.Copy()
1827 func (cl *Client) Stats() ClientStats {
1830 return cl.statsLocked()