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{}
82 torrents map[*Torrent]struct{}
83 // All Torrents by their short infohashes (v1 if valid, and truncated v2 if valid). Unless the
84 // info has been obtained, there's no knowing if an infohash belongs to v1 or v2.
85 torrentsByShortHash map[InfoHash]*Torrent
87 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
89 acceptLimiter map[ipStr]int
92 websocketTrackers websocketTrackers
94 activeAnnounceLimiter limiter.Instance
95 httpClient *http.Client
97 clientHolepunchAddrSets
99 defaultLocalLtepProtocolMap LocalLtepProtocolMap
104 func (cl *Client) BadPeerIPs() (ips []string) {
106 ips = cl.badPeerIPsLocked()
111 func (cl *Client) badPeerIPsLocked() (ips []string) {
112 ips = make([]string, len(cl.badPeerIPs))
114 for k := range cl.badPeerIPs {
121 func (cl *Client) PeerID() PeerID {
125 // Returns the port number for the first listener that has one. No longer assumes that all port
126 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
128 func (cl *Client) LocalPort() (port int) {
129 for i := 0; i < len(cl.listeners); i += 1 {
130 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
137 func writeDhtServerStatus(w io.Writer, s DhtServer) {
138 dhtStats := s.Stats()
139 fmt.Fprintf(w, " ID: %x\n", s.ID())
140 spew.Fdump(w, dhtStats)
143 // Writes out a human readable status of the client, such as for writing to a
145 func (cl *Client) WriteStatus(_w io.Writer) {
148 w := bufio.NewWriter(_w)
150 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
151 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
152 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
153 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
154 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
155 cl.eachDhtServer(func(s DhtServer) {
156 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
157 writeDhtServerStatus(w, s)
159 dumpStats(w, cl.statsLocked())
160 torrentsSlice := cl.torrentsAsSlice()
161 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
163 sort.Slice(torrentsSlice, func(l, r int) bool {
164 return torrentsSlice[l].canonicalShortInfohash().AsString() < torrentsSlice[r].canonicalShortInfohash().AsString()
166 for _, t := range torrentsSlice {
168 fmt.Fprint(w, "<unknown name>")
170 fmt.Fprint(w, t.name())
176 "%f%% of %d bytes (%s)",
177 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
179 humanize.Bytes(uint64(t.length())))
181 w.WriteString("<missing metainfo>")
189 func (cl *Client) initLogger() {
190 logger := cl.config.Logger
195 logger = logger.FilterLevel(log.Debug)
197 cl.logger = logger.WithValues(cl)
200 func (cl *Client) announceKey() int32 {
201 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
204 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
205 func (cl *Client) init(cfg *ClientConfig) {
207 g.MakeMap(&cl.dopplegangerAddrs)
208 g.MakeMap(&cl.torrentsByShortHash)
209 g.MakeMap(&cl.torrents)
210 cl.torrentsByShortHash = make(map[metainfo.Hash]*Torrent)
211 cl.activeAnnounceLimiter.SlotsPerKey = 2
212 cl.event.L = cl.locker()
213 cl.ipBlockList = cfg.IPBlocklist
214 cl.httpClient = &http.Client{
215 Transport: cfg.WebTransport,
217 if cl.httpClient.Transport == nil {
218 cl.httpClient.Transport = &http.Transport{
219 Proxy: cfg.HTTPProxy,
220 DialContext: cfg.HTTPDialContext,
221 // I think this value was observed from some webseeds. It seems reasonable to extend it
222 // to other uses of HTTP from the client.
226 cl.defaultLocalLtepProtocolMap = makeBuiltinLtepProtocols(!cfg.DisablePEX)
229 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
231 cfg = NewDefaultClientConfig()
236 go cl.acceptLimitClearer()
245 storageImpl := cfg.DefaultStorage
246 if storageImpl == nil {
247 // We'd use mmap by default but HFS+ doesn't support sparse files.
248 storageImplCloser := storage.NewFile(cfg.DataDir)
249 cl.onClose = append(cl.onClose, func() {
250 if err := storageImplCloser.Close(); err != nil {
251 cl.logger.Printf("error closing default storage: %s", err)
254 storageImpl = storageImplCloser
256 cl.defaultStorage = storage.NewClient(storageImpl)
258 if cfg.PeerID != "" {
259 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
261 o := copy(cl.peerID[:], cfg.Bep20)
262 _, err = rand.Read(cl.peerID[o:])
264 panic("error generating peer id")
268 builtinListenNetworks := cl.listenNetworks()
269 sockets, err := listenAll(
270 builtinListenNetworks,
271 cl.config.ListenHost,
272 cl.config.ListenPort,
279 if len(sockets) == 0 && len(builtinListenNetworks) != 0 {
280 err = fmt.Errorf("no sockets created for networks %v", builtinListenNetworks)
287 for _, _s := range sockets {
288 s := _s // Go is fucking retarded.
289 cl.onClose = append(cl.onClose, func() { go s.Close() })
290 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
291 cl.dialers = append(cl.dialers, s)
292 cl.listeners = append(cl.listeners, s)
293 if cl.config.AcceptPeerConnections {
294 go cl.acceptConnections(s)
301 for _, s := range sockets {
302 if pc, ok := s.(net.PacketConn); ok {
303 ds, err := cl.NewAnacrolixDhtServer(pc)
307 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
308 cl.onClose = append(cl.onClose, func() { ds.Close() })
313 cl.websocketTrackers = websocketTrackers{
316 GetAnnounceRequest: func(
317 event tracker.AnnounceEvent, infoHash [20]byte,
319 tracker.AnnounceRequest, error,
323 t, ok := cl.torrentsByShortHash[infoHash]
325 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
327 return t.announceRequest(event, infoHash), nil
329 Proxy: cl.config.HTTPProxy,
330 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
331 ICEServers: cl.config.ICEServers,
332 DialContext: cl.config.TrackerDialContext,
333 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
336 t, ok := cl.torrentsByShortHash[dcc.InfoHash]
338 cl.logger.WithDefaultLevel(log.Warning).Printf(
339 "got webrtc conn for unloaded torrent with infohash %x",
345 go t.onWebRtcConn(dc, dcc)
352 func (cl *Client) AddDhtServer(d DhtServer) {
353 cl.dhtServers = append(cl.dhtServers, d)
356 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
357 // given address for any Torrent.
358 func (cl *Client) AddDialer(d Dialer) {
361 cl.dialers = append(cl.dialers, d)
362 for t := range cl.torrents {
367 func (cl *Client) Listeners() []Listener {
371 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
373 func (cl *Client) AddListener(l Listener) {
374 cl.listeners = append(cl.listeners, l)
375 if cl.config.AcceptPeerConnections {
376 go cl.acceptConnections(l)
380 func (cl *Client) firewallCallback(net.Addr) bool {
382 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
385 torrent.Add("connections firewalled", 1)
387 torrent.Add("connections not firewalled", 1)
392 func (cl *Client) listenOnNetwork(n network) bool {
393 if n.Ipv4 && cl.config.DisableIPv4 {
396 if n.Ipv6 && cl.config.DisableIPv6 {
399 if n.Tcp && cl.config.DisableTCP {
402 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
408 func (cl *Client) listenNetworks() (ns []network) {
409 for _, n := range allPeerNetworks {
410 if cl.listenOnNetwork(n) {
417 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
418 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
419 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
420 cfg := dht.ServerConfig{
421 IPBlocklist: cl.ipBlockList,
423 OnAnnouncePeer: cl.onDHTAnnouncePeer,
424 PublicIP: func() net.IP {
425 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
426 return cl.config.PublicIp6
428 return cl.config.PublicIp4
430 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
431 OnQuery: cl.config.DHTOnQuery,
434 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
437 s, err = dht.NewServer(&cfg)
439 go s.TableMaintainer()
444 func (cl *Client) Closed() events.Done {
445 return cl.closed.Done()
448 func (cl *Client) eachDhtServer(f func(DhtServer)) {
449 for _, ds := range cl.dhtServers {
454 // Stops the client. All connections to peers are closed and all activity will come to a halt.
455 func (cl *Client) Close() (errs []error) {
456 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
458 for t := range cl.torrents {
459 err := t.close(&closeGroup)
461 errs = append(errs, err)
464 for i := range cl.onClose {
465 cl.onClose[len(cl.onClose)-1-i]()
470 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
474 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
475 if cl.ipBlockList == nil {
478 return cl.ipBlockList.Lookup(ip)
481 func (cl *Client) ipIsBlocked(ip net.IP) bool {
482 _, blocked := cl.ipBlockRange(ip)
486 func (cl *Client) wantConns() bool {
487 if cl.config.AlwaysWantConns {
490 for t := range cl.torrents {
491 if t.wantIncomingConns() {
498 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
499 func (cl *Client) rejectAccepted(conn net.Conn) error {
501 return errors.New("don't want conns right now")
503 ra := conn.RemoteAddr()
504 if rip := addrIpOrNil(ra); rip != nil {
505 if cl.config.DisableIPv4Peers && rip.To4() != nil {
506 return errors.New("ipv4 peers disabled")
508 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
509 return errors.New("ipv4 disabled")
511 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
512 return errors.New("ipv6 disabled")
514 if cl.rateLimitAccept(rip) {
515 return errors.New("source IP accepted rate limited")
517 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
518 return errors.New("bad source addr")
524 func (cl *Client) acceptConnections(l Listener) {
526 conn, err := l.Accept()
527 torrent.Add("client listener accepts", 1)
529 holepunchAddr, holepunchErr := addrPortFromPeerRemoteAddr(conn.RemoteAddr())
530 if holepunchErr == nil {
532 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
533 setAdd(&cl.accepted, holepunchAddr)
536 cl.undialableWithoutHolepunchDialedAfterHolepunchConnect,
539 setAdd(&cl.probablyOnlyConnectedDueToHolepunch, holepunchAddr)
544 conn = pproffd.WrapNetConn(conn)
546 closed := cl.closed.IsSet()
548 if !closed && conn != nil {
549 reject = cl.rejectAccepted(conn)
559 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
564 torrent.Add("rejected accepted connections", 1)
565 cl.logger.LazyLog(log.Debug, func() log.Msg {
566 return log.Fmsg("rejecting accepted conn: %v", reject)
570 go cl.incomingConnection(conn)
572 cl.logger.LazyLog(log.Debug, func() log.Msg {
573 return log.Fmsg("accepted %q connection at %q from %q",
579 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
580 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
581 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
586 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
587 func regularNetConnPeerConnConnString(nc net.Conn) string {
588 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
591 func (cl *Client) incomingConnection(nc net.Conn) {
593 if tc, ok := nc.(*net.TCPConn); ok {
596 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
597 c := cl.newConnection(
601 remoteAddr: nc.RemoteAddr(),
602 localPublicAddr: cl.publicAddr(remoteAddr.IP),
603 network: nc.RemoteAddr().Network(),
604 connString: regularNetConnPeerConnConnString(nc),
611 c.Discovery = PeerSourceIncoming
612 cl.runReceivedConn(c)
615 // Returns a handle to the given torrent, if it's present in the client.
616 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
619 t, ok = cl.torrentsByShortHash[ih]
623 type DialResult struct {
628 func countDialResult(err error) {
630 torrent.Add("successful dials", 1)
632 torrent.Add("unsuccessful dials", 1)
636 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
637 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
638 if ret < minDialTimeout {
644 // Returns whether an address is known to connect to a client with our own ID.
645 func (cl *Client) dopplegangerAddr(addr string) bool {
646 _, ok := cl.dopplegangerAddrs[addr]
650 // Returns a connection over UTP or TCP, whichever is first to connect.
651 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
652 return DialFirst(ctx, addr, cl.dialers)
655 // Returns a connection over UTP or TCP, whichever is first to connect.
656 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
660 defer pool.startDrainer()
661 for _, _s := range dialers {
664 return pool.getFirst()
667 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
668 c, err := s.Dial(ctx, addr)
670 log.Levelf(log.Debug, "error dialing %q: %v", addr, err)
672 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
673 // it now in case we close the connection forthwith. Note this is also done in the TCP dialer
674 // code to increase the chance it's done.
675 if tc, ok := c.(*net.TCPConn); ok {
682 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string, attemptKey outgoingConnAttemptKey) {
683 path := t.getHalfOpenPath(addr, attemptKey)
685 panic("should exist")
689 if cl.numHalfOpen < 0 {
690 panic("should not be possible")
692 for t := range cl.torrents {
697 func (cl *Client) countHalfOpenFromTorrents() (count int) {
698 for t := range cl.torrents {
699 count += t.numHalfOpenAttempts()
704 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
705 // for valid reasons.
706 func (cl *Client) initiateProtocolHandshakes(
711 newConnOpts newConnectionOpts,
713 c *PeerConn, err error,
715 c = cl.newConnection(nc, newConnOpts)
716 c.headerEncrypted = encryptHeader
717 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
719 dl, ok := ctx.Deadline()
723 err = nc.SetDeadline(dl)
727 err = cl.initiateHandshakes(c, t)
731 func doProtocolHandshakeOnDialResult(
733 obfuscatedHeader bool,
737 c *PeerConn, err error,
741 addrIpPort, _ := tryIpPortFromNetAddr(addr)
742 c, err = cl.initiateProtocolHandshakes(
743 context.Background(), nc, t, obfuscatedHeader,
747 // It would be possible to retrieve a public IP from the dialer used here?
748 localPublicAddr: cl.publicAddr(addrIpPort.IP),
749 network: dr.Dialer.DialerNetwork(),
750 connString: regularNetConnPeerConnConnString(nc),
758 // Returns nil connection and nil error if no connection could be established for valid reasons.
759 func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn, err error) {
760 // It would be better if dial rate limiting could be tested when considering to open connections
761 // instead. Doing it here means if the limit is low, and the half-open limit is high, we could
762 // end up with lots of outgoing connection attempts pending that were initiated on stale data.
764 dialReservation := cl.config.DialRateLimiter.Reserve()
765 if !opts.receivedHolepunchConnect {
766 if !dialReservation.OK() {
767 err = errors.New("can't make dial limit reservation")
770 time.Sleep(dialReservation.Delay())
773 torrent.Add("establish outgoing connection", 1)
774 addr := opts.peerInfo.Addr
775 dialPool := dialPool{
776 resCh: make(chan DialResult),
779 defer dialPool.startDrainer()
780 dialTimeout := opts.t.getDialTimeoutUnlocked()
782 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
784 for _, d := range cl.dialers {
788 holepunchAddr, holepunchAddrErr := addrPortFromPeerRemoteAddr(addr)
789 headerObfuscationPolicy := opts.HeaderObfuscationPolicy
790 obfuscatedHeaderFirst := headerObfuscationPolicy.Preferred
791 firstDialResult := dialPool.getFirst()
792 if firstDialResult.Conn == nil {
793 // No dialers worked. Try to initiate a holepunching rendezvous.
794 if holepunchAddrErr == nil {
796 if !opts.receivedHolepunchConnect {
797 g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
799 if !opts.skipHolepunchRendezvous {
800 opts.t.trySendHolepunchRendezvous(holepunchAddr)
804 err = fmt.Errorf("all initial dials failed")
807 if opts.receivedHolepunchConnect && holepunchAddrErr == nil {
809 if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
810 g.MakeMapIfNilAndSet(&cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
812 g.MakeMapIfNil(&cl.dialedSuccessfullyAfterHolepunchConnect)
813 g.MapInsert(cl.dialedSuccessfullyAfterHolepunchConnect, holepunchAddr, struct{}{})
816 c, err = doProtocolHandshakeOnDialResult(
818 obfuscatedHeaderFirst,
823 torrent.Add("initiated conn with preferred header obfuscation", 1)
828 "error doing protocol handshake with header obfuscation %v",
829 obfuscatedHeaderFirst,
831 firstDialResult.Conn.Close()
832 // We should have just tried with the preferred header obfuscation. If it was required, there's nothing else to try.
833 if headerObfuscationPolicy.RequirePreferred {
836 // Reuse the dialer that returned already but failed to handshake.
838 ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
840 dialPool.add(ctx, firstDialResult.Dialer)
842 secondDialResult := dialPool.getFirst()
843 if secondDialResult.Conn == nil {
846 c, err = doProtocolHandshakeOnDialResult(
848 !obfuscatedHeaderFirst,
853 torrent.Add("initiated conn with fallback header obfuscation", 1)
858 "error doing protocol handshake with header obfuscation %v",
859 !obfuscatedHeaderFirst,
861 secondDialResult.Conn.Close()
865 type outgoingConnOpts struct {
868 // Don't attempt to connect unless a connect message is received after initiating a rendezvous.
869 requireRendezvous bool
870 // Don't send rendezvous requests to eligible relays.
871 skipHolepunchRendezvous bool
872 // Outgoing connection attempt is in response to holepunch connect message.
873 receivedHolepunchConnect bool
874 HeaderObfuscationPolicy HeaderObfuscationPolicy
877 // Called to dial out and run a connection. The addr we're given is already
878 // considered half-open.
879 func (cl *Client) outgoingConnection(
880 opts outgoingConnOpts,
881 attemptKey outgoingConnAttemptKey,
883 c, err := cl.dialAndCompleteHandshake(opts)
885 c.conn.SetWriteDeadline(time.Time{})
889 // Don't release lock between here and addPeerConn, unless it's for failure.
890 cl.noLongerHalfOpen(opts.t, opts.peerInfo.Addr.String(), attemptKey)
895 "error establishing outgoing connection to %v: %v",
903 c.Discovery = opts.peerInfo.Source
904 c.trusted = opts.peerInfo.Trusted
905 opts.t.runHandshookConnLoggingErr(c)
908 // The port number for incoming peer connections. 0 if the client isn't listening.
909 func (cl *Client) incomingPeerPort() int {
910 return cl.LocalPort()
913 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) (err error) {
914 if c.headerEncrypted {
916 rw, c.cryptoMethod, err = mse.InitiateHandshake(
921 t.canonicalShortInfohash().Bytes(),
923 cl.config.CryptoProvides,
927 return fmt.Errorf("header obfuscation handshake: %w", err)
930 ih, err := cl.connBtHandshake(c, t.canonicalShortInfohash())
932 return fmt.Errorf("bittorrent protocol handshake: %w", err)
934 if g.Some(ih) == t.infoHash {
937 if t.infoHashV2.Ok && *t.infoHashV2.Value.ToShort() == ih {
941 err = errors.New("bittorrent protocol handshake: peer infohash didn't match")
945 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
946 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
947 func (cl *Client) forSkeys(f func([]byte) bool) {
950 if false { // Emulate the bug from #114
952 for ih := range cl.torrentsByShortHash {
956 for range cl.torrentsByShortHash {
963 for ih := range cl.torrentsByShortHash {
970 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
971 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
977 // Do encryption and bittorrent handshakes as receiver.
978 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
979 defer perf.ScopeTimerErr(&err)()
981 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(
983 cl.handshakeReceiverSecretKeys(),
984 cl.config.HeaderObfuscationPolicy,
985 cl.config.CryptoSelector,
988 if err == nil || err == mse.ErrNoSecretKeyMatch {
989 if c.headerEncrypted {
990 torrent.Add("handshakes received encrypted", 1)
992 torrent.Add("handshakes received unencrypted", 1)
995 torrent.Add("handshakes received with error while handling encryption", 1)
998 if err == mse.ErrNoSecretKeyMatch {
1003 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
1004 err = errors.New("connection does not have required header obfuscation")
1007 ih, err := cl.connBtHandshake(c, nil)
1009 return nil, fmt.Errorf("during bt handshake: %w", err)
1012 t = cl.torrentsByShortHash[ih]
1017 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
1021 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
1022 &successfulPeerWireProtocolHandshakePeerReservedBytes)
1025 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
1026 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
1030 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(
1031 hex.EncodeToString(res.PeerExtensionBits[:]), 1)
1033 c.PeerExtensionBytes = res.PeerExtensionBits
1034 c.PeerID = res.PeerID
1035 c.completedHandshake = time.Now()
1036 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
1042 func (cl *Client) runReceivedConn(c *PeerConn) {
1043 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
1047 t, err := cl.receiveHandshakes(c)
1049 cl.logger.LazyLog(log.Debug, func() log.Msg {
1051 "error receiving handshakes on %v: %s", c, err,
1053 "network", c.Network,
1056 torrent.Add("error receiving handshake", 1)
1058 cl.onBadAccept(c.RemoteAddr)
1063 torrent.Add("received handshake for unloaded torrent", 1)
1064 cl.logger.LazyLog(log.Debug, func() log.Msg {
1065 return log.Fmsg("received handshake for unloaded torrent")
1068 cl.onBadAccept(c.RemoteAddr)
1072 torrent.Add("received handshake for loaded torrent", 1)
1073 c.conn.SetWriteDeadline(time.Time{})
1076 t.runHandshookConnLoggingErr(c)
1079 // Client lock must be held before entering this.
1080 func (t *Torrent) runHandshookConn(pc *PeerConn) error {
1083 for i, b := range cl.config.MinPeerExtensions {
1084 if pc.PeerExtensionBytes[i]&b != b {
1085 return fmt.Errorf("peer did not meet minimum peer extensions: %x", pc.PeerExtensionBytes[:])
1088 if pc.PeerID == cl.peerID {
1091 addr := pc.RemoteAddr.String()
1092 cl.dopplegangerAddrs[addr] = struct{}{}
1094 // Because the remote address is not necessarily the same as its client's torrent listen
1095 // address, we won't record the remote address as a doppleganger. Instead, the initiator
1096 // can record *us* as the doppleganger.
1098 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
1101 pc.r = deadlineReader{pc.conn, pc.r}
1102 completedHandshakeConnectionFlags.Add(pc.connectionFlags(), 1)
1103 if connIsIpv6(pc.conn) {
1104 torrent.Add("completed handshake over ipv6", 1)
1106 if err := t.addPeerConn(pc); err != nil {
1107 return fmt.Errorf("adding connection: %w", err)
1109 defer t.dropConnection(pc)
1110 pc.addBuiltinLtepProtocols(!cl.config.DisablePEX)
1111 for _, cb := range pc.callbacks.PeerConnAdded {
1114 pc.startMessageWriter()
1115 pc.sendInitialMessages()
1116 pc.initUpdateRequestsTimer()
1117 err := pc.mainReadLoop()
1119 return fmt.Errorf("main read loop: %w", err)
1124 func (p *Peer) initUpdateRequestsTimer() {
1126 if p.updateRequestsTimer != nil {
1127 panic(p.updateRequestsTimer)
1130 if enableUpdateRequestsTimer {
1131 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1135 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1137 func (c *Peer) updateRequestsTimerFunc() {
1139 defer c.locker().Unlock()
1140 if c.closed.IsSet() {
1143 if c.isLowOnRequests() {
1144 // If there are no outstanding requests, then a request update should have already run.
1147 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1148 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1149 // already been fired.
1150 torrent.Add("spurious timer requests updates", 1)
1153 c.updateRequests(peerUpdateRequestsTimerReason)
1156 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1157 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1158 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1159 const localClientReqq = 1024
1161 // See the order given in Transmission's tr_peerMsgsNew.
1162 func (pc *PeerConn) sendInitialMessages() {
1165 if pc.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1166 pc.write(pp.Message{
1168 ExtendedID: pp.HandshakeExtendedID,
1169 ExtendedPayload: func() []byte {
1170 msg := pp.ExtendedHandshakeMessage{
1171 V: cl.config.ExtendedHandshakeClientVersion,
1172 Reqq: localClientReqq,
1173 YourIp: pp.CompactIp(pc.remoteIp()),
1174 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1175 Port: cl.incomingPeerPort(),
1176 MetadataSize: t.metadataSize(),
1177 // TODO: We can figure these out specific to the socket used.
1178 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1179 Ipv6: cl.config.PublicIp6.To16(),
1181 msg.M = pc.LocalLtepProtocolMap.toSupportedExtensionDict()
1182 return bencode.MustMarshal(msg)
1187 if pc.fastEnabled() {
1188 if t.haveAllPieces() {
1189 pc.write(pp.Message{Type: pp.HaveAll})
1190 pc.sentHaves.AddRange(0, bitmap.BitRange(pc.t.NumPieces()))
1192 } else if !t.haveAnyPieces() {
1193 pc.write(pp.Message{Type: pp.HaveNone})
1194 pc.sentHaves.Clear()
1200 if pc.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1201 pc.write(pp.Message{
1208 func (cl *Client) dhtPort() (ret uint16) {
1209 if len(cl.dhtServers) == 0 {
1212 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1215 func (cl *Client) haveDhtServer() bool {
1216 return len(cl.dhtServers) > 0
1219 // Process incoming ut_metadata message.
1220 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1221 var d pp.ExtendedMetadataRequestMsg
1222 err := bencode.Unmarshal(payload, &d)
1223 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1224 } else if err != nil {
1225 return fmt.Errorf("error unmarshalling bencode: %s", err)
1229 case pp.DataMetadataExtensionMsgType:
1230 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1231 if !c.requestedMetadataPiece(piece) {
1232 return fmt.Errorf("got unexpected piece %d", piece)
1234 c.metadataRequests[piece] = false
1235 begin := len(payload) - d.PieceSize()
1236 if begin < 0 || begin >= len(payload) {
1237 return fmt.Errorf("data has bad offset in payload: %d", begin)
1239 t.saveMetadataPiece(piece, payload[begin:])
1240 c.lastUsefulChunkReceived = time.Now()
1241 err = t.maybeCompleteMetadata()
1243 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1244 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1245 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1246 // log consumers can filter for this message.
1247 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1250 case pp.RequestMetadataExtensionMsgType:
1251 if !t.haveMetadataPiece(piece) {
1252 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1255 start := (1 << 14) * piece
1256 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1257 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1259 case pp.RejectMetadataExtensionMsgType:
1262 return errors.New("unknown msg_type value")
1266 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1267 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1268 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1273 // Returns whether the IP address and port are considered "bad".
1274 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1275 if port == 0 || ip == nil {
1278 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1281 if _, ok := cl.ipBlockRange(ip); ok {
1284 ipAddr, ok := netip.AddrFromSlice(ip)
1288 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1294 // Return a Torrent ready for insertion into a Client.
1295 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1296 return cl.newTorrentOpt(AddTorrentOpts{
1298 Storage: specStorage,
1302 // Return a Torrent ready for insertion into a Client.
1303 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1304 var v1InfoHash g.Option[infohash.T]
1305 if !opts.InfoHash.IsZero() {
1306 v1InfoHash.Set(opts.InfoHash)
1308 if !v1InfoHash.Ok && !opts.InfoHashV2.Ok {
1309 panic("v1 infohash must be nonzero or v2 infohash must be set")
1311 // use provided storage, if provided
1312 storageClient := cl.defaultStorage
1313 if opts.Storage != nil {
1314 storageClient = storage.NewClient(opts.Storage)
1319 infoHash: v1InfoHash,
1320 infoHashV2: opts.InfoHashV2,
1321 peers: prioritizedPeers{
1323 getPrio: func(p PeerInfo) peerPriority {
1325 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1328 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1330 storageOpener: storageClient,
1331 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1333 metadataChanged: sync.Cond{
1336 webSeeds: make(map[string]*Peer),
1337 gotMetainfoC: make(chan struct{}),
1341 t.smartBanCache.Hash = func(b []byte) uint64 {
1347 t.smartBanCache.Init()
1348 t.networkingEnabled.Set()
1349 t.logger = cl.logger.WithDefaultLevel(log.Debug)
1350 t.sourcesLogger = t.logger.WithNames("sources")
1351 if opts.ChunkSize == 0 {
1352 opts.ChunkSize = defaultChunkSize
1354 t.setChunkSize(opts.ChunkSize)
1358 // A file-like handle to some torrent data resource.
1359 type Handle interface {
1366 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1367 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1370 // Deprecated. Adds a torrent by InfoHash with a custom Storage implementation.
1371 // If the torrent already exists then this Storage is ignored and the
1372 // existing torrent returned with `new` set to `false`
1373 func (cl *Client) AddTorrentInfoHashWithStorage(
1374 infoHash metainfo.Hash,
1375 specStorage storage.ClientImpl,
1376 ) (t *Torrent, new bool) {
1379 t, ok := cl.torrentsByShortHash[infoHash]
1385 t = cl.newTorrent(infoHash, specStorage)
1386 cl.eachDhtServer(func(s DhtServer) {
1387 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1388 go t.dhtAnnouncer(s)
1391 cl.torrentsByShortHash[infoHash] = t
1392 cl.torrents[t] = struct{}{}
1393 cl.clearAcceptLimits()
1394 t.updateWantPeersEvent()
1395 // Tickle Client.waitAccept, new torrent may want conns.
1396 cl.event.Broadcast()
1400 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1401 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1402 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1403 infoHash := opts.InfoHash
1406 t, ok := cl.torrentsByShortHash[infoHash]
1410 if opts.InfoHashV2.Ok {
1411 t, ok = cl.torrentsByShortHash[*opts.InfoHashV2.Value.ToShort()]
1418 t = cl.newTorrentOpt(opts)
1419 cl.eachDhtServer(func(s DhtServer) {
1420 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1421 go t.dhtAnnouncer(s)
1424 cl.torrentsByShortHash[infoHash] = t
1425 cl.torrents[t] = struct{}{}
1426 t.setInfoBytesLocked(opts.InfoBytes)
1427 cl.clearAcceptLimits()
1428 t.updateWantPeersEvent()
1429 // Tickle Client.waitAccept, new torrent may want conns.
1430 cl.event.Broadcast()
1434 type AddTorrentOpts struct {
1436 InfoHashV2 g.Option[infohash_v2.T]
1437 Storage storage.ClientImpl
1438 ChunkSize pp.Integer
1442 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1443 // Torrent.MergeSpec.
1444 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1445 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1446 InfoHash: spec.InfoHash,
1447 InfoHashV2: spec.InfoHashV2,
1448 Storage: spec.Storage,
1449 ChunkSize: spec.ChunkSize,
1453 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1455 modSpec.ChunkSize = 0
1457 err = t.MergeSpec(&modSpec)
1458 if err != nil && new {
1464 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1465 // spec.DisallowDataDownload/Upload will be read and applied
1466 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1467 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1468 if spec.DisplayName != "" {
1469 t.SetDisplayName(spec.DisplayName)
1471 if spec.InfoBytes != nil {
1472 err := t.SetInfoBytes(spec.InfoBytes)
1478 cl.AddDhtNodes(spec.DhtNodes)
1479 t.UseSources(spec.Sources)
1482 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1483 for _, url := range spec.Webseeds {
1486 for _, peerAddr := range spec.PeerAddrs {
1488 Addr: StringAddr(peerAddr),
1489 Source: PeerSourceDirect,
1493 if spec.ChunkSize != 0 {
1494 panic("chunk size cannot be changed for existing Torrent")
1496 t.addTrackers(spec.Trackers)
1498 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1499 t.dataUploadDisallowed = spec.DisallowDataUpload
1500 return t.AddPieceLayers(spec.PieceLayers)
1503 func (cl *Client) dropTorrent(t *Torrent, wg *sync.WaitGroup) (err error) {
1504 t.eachShortInfohash(func(short [20]byte) {
1505 delete(cl.torrentsByShortHash, short)
1508 delete(cl.torrents, t)
1512 func (cl *Client) allTorrentsCompleted() bool {
1513 for t := range cl.torrents {
1517 if !t.haveAllPieces() {
1524 // Returns true when all torrents are completely downloaded and false if the
1525 // client is stopped before that.
1526 func (cl *Client) WaitAll() bool {
1529 for !cl.allTorrentsCompleted() {
1530 if cl.closed.IsSet() {
1538 // Returns handles to all the torrents loaded in the Client.
1539 func (cl *Client) Torrents() []*Torrent {
1542 return cl.torrentsAsSlice()
1545 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1546 for t := range cl.torrents {
1547 ret = append(ret, t)
1552 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1553 spec, err := TorrentSpecFromMagnetUri(uri)
1557 T, _, err = cl.AddTorrentSpec(spec)
1561 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1562 ts, err := TorrentSpecFromMetaInfoErr(mi)
1566 T, _, err = cl.AddTorrentSpec(ts)
1570 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1571 mi, err := metainfo.LoadFromFile(filename)
1575 return cl.AddTorrent(mi)
1578 func (cl *Client) DhtServers() []DhtServer {
1579 return cl.dhtServers
1582 func (cl *Client) AddDhtNodes(nodes []string) {
1583 for _, n := range nodes {
1584 hmp := missinggo.SplitHostMaybePort(n)
1585 ip := net.ParseIP(hmp.Host)
1587 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1590 ni := krpc.NodeInfo{
1591 Addr: krpc.NodeAddr{
1596 cl.eachDhtServer(func(s DhtServer) {
1602 func (cl *Client) banPeerIP(ip net.IP) {
1603 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1604 // addresses directly to v4on6, which doesn't compare equal with v4.
1605 ipAddr, ok := netip.AddrFromSlice(ip)
1609 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1610 for t := range cl.torrents {
1611 t.iterPeers(func(p *Peer) {
1612 if p.remoteIp().Equal(ip) {
1613 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1614 // Should this be a close?
1621 type newConnectionOpts struct {
1623 remoteAddr PeerRemoteAddr
1624 localPublicAddr peerLocalPublicAddr
1629 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1630 if opts.network == "" {
1631 panic(opts.remoteAddr)
1635 outgoing: opts.outgoing,
1638 PeerMaxRequests: 250,
1640 RemoteAddr: opts.remoteAddr,
1641 localPublicAddr: opts.localPublicAddr,
1642 Network: opts.network,
1643 callbacks: &cl.config.Callbacks,
1645 connString: opts.connString,
1648 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1649 c.initRequestState()
1650 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1651 if opts.remoteAddr != nil {
1652 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1654 c.bannableAddr = Some(netipAddrPort.Addr())
1658 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1659 c.logger = c.logger.WithContextText(fmt.Sprintf("%T %p", c, c))
1660 c.setRW(connStatsReadWriter{nc, c})
1661 c.r = &rateLimitedReader{
1662 l: cl.config.DownloadRateLimiter,
1667 "inited with remoteAddr %v network %v outgoing %t",
1668 opts.remoteAddr, opts.network, opts.outgoing,
1670 for _, f := range cl.config.Callbacks.NewPeer {
1676 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1679 t := cl.torrentsByShortHash[ih]
1683 t.addPeers([]PeerInfo{{
1684 Addr: ipPortAddr{ip, port},
1685 Source: PeerSourceDhtAnnouncePeer,
1689 func firstNotNil(ips ...net.IP) net.IP {
1690 for _, ip := range ips {
1698 func (cl *Client) eachListener(f func(Listener) bool) {
1699 for _, s := range cl.listeners {
1706 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1707 for i := 0; i < len(cl.listeners); i += 1 {
1708 if ret = cl.listeners[i]; f(ret) {
1715 func (cl *Client) publicIp(peer net.IP) net.IP {
1716 // TODO: Use BEP 10 to determine how peers are seeing us.
1717 if peer.To4() != nil {
1719 cl.config.PublicIp4,
1720 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1725 cl.config.PublicIp6,
1726 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1730 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1731 l := cl.findListener(
1732 func(l Listener) bool {
1733 return f(addrIpOrNil(l.Addr()))
1739 return addrIpOrNil(l.Addr())
1742 // Our IP as a peer should see it.
1743 func (cl *Client) publicAddr(peer net.IP) IpPort {
1744 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1747 // ListenAddrs addresses currently being listened to.
1748 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1750 ret = make([]net.Addr, len(cl.listeners))
1751 for i := 0; i < len(cl.listeners); i += 1 {
1752 ret[i] = cl.listeners[i].Addr()
1758 func (cl *Client) PublicIPs() (ips []net.IP) {
1759 if ip := cl.config.PublicIp4; ip != nil {
1760 ips = append(ips, ip)
1762 if ip := cl.config.PublicIp6; ip != nil {
1763 ips = append(ips, ip)
1768 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1769 ipa, ok := tryIpPortFromNetAddr(addr)
1773 ip := maskIpForAcceptLimiting(ipa.IP)
1774 if cl.acceptLimiter == nil {
1775 cl.acceptLimiter = make(map[ipStr]int)
1777 cl.acceptLimiter[ipStr(ip.String())]++
1780 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1781 if ip4 := ip.To4(); ip4 != nil {
1782 return ip4.Mask(net.CIDRMask(24, 32))
1787 func (cl *Client) clearAcceptLimits() {
1788 cl.acceptLimiter = nil
1791 func (cl *Client) acceptLimitClearer() {
1794 case <-cl.closed.Done():
1796 case <-time.After(15 * time.Minute):
1798 cl.clearAcceptLimits()
1804 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1805 if cl.config.DisableAcceptRateLimiting {
1808 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1811 func (cl *Client) rLock() {
1815 func (cl *Client) rUnlock() {
1819 func (cl *Client) lock() {
1823 func (cl *Client) unlock() {
1827 func (cl *Client) locker() *lockWithDeferreds {
1831 func (cl *Client) String() string {
1832 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1835 // Returns connection-level aggregate connStats at the Client level. See the comment on
1836 // TorrentStats.ConnStats.
1837 func (cl *Client) ConnStats() ConnStats {
1838 return cl.connStats.Copy()
1841 func (cl *Client) Stats() ClientStats {
1844 return cl.statsLocked()