22 "github.com/anacrolix/chansync"
23 "github.com/anacrolix/chansync/events"
24 "github.com/anacrolix/dht/v2"
25 "github.com/anacrolix/dht/v2/krpc"
26 . "github.com/anacrolix/generics"
27 g "github.com/anacrolix/generics"
28 "github.com/anacrolix/log"
29 "github.com/anacrolix/missinggo/perf"
30 "github.com/anacrolix/missinggo/v2"
31 "github.com/anacrolix/missinggo/v2/bitmap"
32 "github.com/anacrolix/missinggo/v2/pproffd"
33 "github.com/anacrolix/sync"
34 "github.com/davecgh/go-spew/spew"
35 "github.com/dustin/go-humanize"
36 gbtree "github.com/google/btree"
37 "golang.org/x/time/rate"
39 "github.com/anacrolix/torrent/bencode"
40 "github.com/anacrolix/torrent/internal/limiter"
41 "github.com/anacrolix/torrent/iplist"
42 "github.com/anacrolix/torrent/metainfo"
43 "github.com/anacrolix/torrent/mse"
44 pp "github.com/anacrolix/torrent/peer_protocol"
45 request_strategy "github.com/anacrolix/torrent/request-strategy"
46 "github.com/anacrolix/torrent/storage"
47 "github.com/anacrolix/torrent/types/infohash"
50 // Clients contain zero or more Torrents. A Client manages a blocklist, the
51 // TCP/UDP protocol ports, and DHT as desired.
53 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
59 closed chansync.SetOnce
65 defaultStorage *storage.Client
69 dhtServers []DhtServer
70 ipBlockList iplist.Ranger
72 // Set of addresses that have our client ID. This intentionally will
73 // include ourselves if we end up trying to connect to our own address
74 // through legitimate channels.
75 dopplegangerAddrs map[string]struct{}
76 badPeerIPs map[netip.Addr]struct{}
77 torrents map[InfoHash]*Torrent
78 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
80 acceptLimiter map[ipStr]int
81 dialRateLimiter *rate.Limiter
84 activeAnnounceLimiter limiter.Instance
85 httpClient *http.Client
90 func (cl *Client) BadPeerIPs() (ips []string) {
92 ips = cl.badPeerIPsLocked()
97 func (cl *Client) badPeerIPsLocked() (ips []string) {
98 ips = make([]string, len(cl.badPeerIPs))
100 for k := range cl.badPeerIPs {
107 func (cl *Client) PeerID() PeerID {
111 // Returns the port number for the first listener that has one. No longer assumes that all port
112 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
114 func (cl *Client) LocalPort() (port int) {
115 for i := 0; i < len(cl.listeners); i += 1 {
116 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
123 func writeDhtServerStatus(w io.Writer, s DhtServer) {
124 dhtStats := s.Stats()
125 fmt.Fprintf(w, " ID: %x\n", s.ID())
126 spew.Fdump(w, dhtStats)
129 // Writes out a human readable status of the client, such as for writing to a
131 func (cl *Client) WriteStatus(_w io.Writer) {
134 w := bufio.NewWriter(_w)
136 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
137 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
138 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
139 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
140 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
141 cl.eachDhtServer(func(s DhtServer) {
142 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
143 writeDhtServerStatus(w, s)
145 spew.Fdump(w, &cl.stats)
146 torrentsSlice := cl.torrentsAsSlice()
147 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
149 sort.Slice(torrentsSlice, func(l, r int) bool {
150 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
152 for _, t := range torrentsSlice {
154 fmt.Fprint(w, "<unknown name>")
156 fmt.Fprint(w, t.name())
162 "%f%% of %d bytes (%s)",
163 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
165 humanize.Bytes(uint64(t.length())))
167 w.WriteString("<missing metainfo>")
175 func (cl *Client) initLogger() {
176 logger := cl.config.Logger
181 logger = logger.FilterLevel(log.Debug)
183 cl.logger = logger.WithValues(cl)
186 func (cl *Client) announceKey() int32 {
187 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
190 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
191 func (cl *Client) init(cfg *ClientConfig) {
193 g.MakeMap(&cl.dopplegangerAddrs)
194 cl.torrents = make(map[metainfo.Hash]*Torrent)
195 cl.dialRateLimiter = rate.NewLimiter(10, 10)
196 cl.activeAnnounceLimiter.SlotsPerKey = 2
197 cl.event.L = cl.locker()
198 cl.ipBlockList = cfg.IPBlocklist
199 cl.httpClient = &http.Client{
200 Transport: &http.Transport{
201 Proxy: cfg.HTTPProxy,
202 DialContext: cfg.HTTPDialContext,
203 // I think this value was observed from some webseeds. It seems reasonable to extend it
204 // to other uses of HTTP from the client.
210 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
212 cfg = NewDefaultClientConfig()
218 go cl.acceptLimitClearer()
227 storageImpl := cfg.DefaultStorage
228 if storageImpl == nil {
229 // We'd use mmap by default but HFS+ doesn't support sparse files.
230 storageImplCloser := storage.NewFile(cfg.DataDir)
231 cl.onClose = append(cl.onClose, func() {
232 if err := storageImplCloser.Close(); err != nil {
233 cl.logger.Printf("error closing default storage: %s", err)
236 storageImpl = storageImplCloser
238 cl.defaultStorage = storage.NewClient(storageImpl)
240 if cfg.PeerID != "" {
241 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
243 o := copy(cl.peerID[:], cfg.Bep20)
244 _, err = rand.Read(cl.peerID[o:])
246 panic("error generating peer id")
250 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
258 for _, _s := range sockets {
259 s := _s // Go is fucking retarded.
260 cl.onClose = append(cl.onClose, func() { go s.Close() })
261 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
262 cl.dialers = append(cl.dialers, s)
263 cl.listeners = append(cl.listeners, s)
264 if cl.config.AcceptPeerConnections {
265 go cl.acceptConnections(s)
272 for _, s := range sockets {
273 if pc, ok := s.(net.PacketConn); ok {
274 ds, err := cl.NewAnacrolixDhtServer(pc)
278 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
279 cl.onClose = append(cl.onClose, func() { ds.Close() })
287 func (cl *Client) AddDhtServer(d DhtServer) {
288 cl.dhtServers = append(cl.dhtServers, d)
291 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
292 // given address for any Torrent.
293 func (cl *Client) AddDialer(d Dialer) {
296 cl.dialers = append(cl.dialers, d)
297 for _, t := range cl.torrents {
302 func (cl *Client) Listeners() []Listener {
306 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
308 func (cl *Client) AddListener(l Listener) {
309 cl.listeners = append(cl.listeners, l)
310 if cl.config.AcceptPeerConnections {
311 go cl.acceptConnections(l)
315 func (cl *Client) firewallCallback(net.Addr) bool {
317 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
320 torrent.Add("connections firewalled", 1)
322 torrent.Add("connections not firewalled", 1)
327 func (cl *Client) listenOnNetwork(n network) bool {
328 if n.Ipv4 && cl.config.DisableIPv4 {
331 if n.Ipv6 && cl.config.DisableIPv6 {
334 if n.Tcp && cl.config.DisableTCP {
337 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
343 func (cl *Client) listenNetworks() (ns []network) {
344 for _, n := range allPeerNetworks {
345 if cl.listenOnNetwork(n) {
352 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
353 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
354 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
355 cfg := dht.ServerConfig{
356 IPBlocklist: cl.ipBlockList,
358 OnAnnouncePeer: cl.onDHTAnnouncePeer,
359 PublicIP: func() net.IP {
360 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
361 return cl.config.PublicIp6
363 return cl.config.PublicIp4
365 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
366 OnQuery: cl.config.DHTOnQuery,
369 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
372 s, err = dht.NewServer(&cfg)
374 go s.TableMaintainer()
379 func (cl *Client) Closed() events.Done {
380 return cl.closed.Done()
383 func (cl *Client) eachDhtServer(f func(DhtServer)) {
384 for _, ds := range cl.dhtServers {
389 // Stops the client. All connections to peers are closed and all activity will come to a halt.
390 func (cl *Client) Close() (errs []error) {
391 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
393 for _, t := range cl.torrents {
394 err := t.close(&closeGroup)
396 errs = append(errs, err)
399 for i := range cl.onClose {
400 cl.onClose[len(cl.onClose)-1-i]()
405 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
409 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
410 if cl.ipBlockList == nil {
413 return cl.ipBlockList.Lookup(ip)
416 func (cl *Client) ipIsBlocked(ip net.IP) bool {
417 _, blocked := cl.ipBlockRange(ip)
421 func (cl *Client) wantConns() bool {
422 if cl.config.AlwaysWantConns {
425 for _, t := range cl.torrents {
433 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
434 func (cl *Client) rejectAccepted(conn net.Conn) error {
436 return errors.New("don't want conns right now")
438 ra := conn.RemoteAddr()
439 if rip := addrIpOrNil(ra); rip != nil {
440 if cl.config.DisableIPv4Peers && rip.To4() != nil {
441 return errors.New("ipv4 peers disabled")
443 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
444 return errors.New("ipv4 disabled")
446 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
447 return errors.New("ipv6 disabled")
449 if cl.rateLimitAccept(rip) {
450 return errors.New("source IP accepted rate limited")
452 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
453 return errors.New("bad source addr")
459 func (cl *Client) acceptConnections(l Listener) {
461 conn, err := l.Accept()
462 torrent.Add("client listener accepts", 1)
463 conn = pproffd.WrapNetConn(conn)
465 closed := cl.closed.IsSet()
467 if !closed && conn != nil {
468 reject = cl.rejectAccepted(conn)
478 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
483 torrent.Add("rejected accepted connections", 1)
484 cl.logger.LazyLog(log.Debug, func() log.Msg {
485 return log.Fmsg("rejecting accepted conn: %v", reject)
489 go cl.incomingConnection(conn)
491 cl.logger.LazyLog(log.Debug, func() log.Msg {
492 return log.Fmsg("accepted %q connection at %q from %q",
498 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
499 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
500 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
505 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
506 func regularNetConnPeerConnConnString(nc net.Conn) string {
507 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
510 func (cl *Client) incomingConnection(nc net.Conn) {
512 if tc, ok := nc.(*net.TCPConn); ok {
515 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
516 c := cl.newConnection(
520 remoteAddr: nc.RemoteAddr(),
521 localPublicAddr: cl.publicAddr(remoteAddr.IP),
522 network: nc.RemoteAddr().Network(),
523 connString: regularNetConnPeerConnConnString(nc),
530 c.Discovery = PeerSourceIncoming
531 cl.runReceivedConn(c)
534 // Returns a handle to the given torrent, if it's present in the client.
535 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
538 t, ok = cl.torrents[ih]
542 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
543 return cl.torrents[ih]
546 type DialResult struct {
551 func countDialResult(err error) {
553 torrent.Add("successful dials", 1)
555 torrent.Add("unsuccessful dials", 1)
559 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
560 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
561 if ret < minDialTimeout {
567 // Returns whether an address is known to connect to a client with our own ID.
568 func (cl *Client) dopplegangerAddr(addr string) bool {
569 _, ok := cl.dopplegangerAddrs[addr]
573 // Returns a connection over UTP or TCP, whichever is first to connect.
574 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
575 return DialFirst(ctx, addr, cl.dialers)
578 // Returns a connection over UTP or TCP, whichever is first to connect.
579 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
581 t := perf.NewTimer(perf.CallerName(0))
584 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
586 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
590 ctx, cancel := context.WithCancel(ctx)
591 // As soon as we return one connection, cancel the others.
594 resCh := make(chan DialResult, left)
595 for _, _s := range dialers {
600 dialFromSocket(ctx, s, addr),
605 // Wait for a successful connection.
607 defer perf.ScopeTimer()()
608 for ; left > 0 && res.Conn == nil; left-- {
612 // There are still incompleted dials.
614 for ; left > 0; left-- {
615 conn := (<-resCh).Conn
622 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
627 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
628 c, err := s.Dial(ctx, addr)
629 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
630 // it now in case we close the connection forthwith.
631 if tc, ok := c.(*net.TCPConn); ok {
638 func forgettableDialError(err error) bool {
639 return strings.Contains(err.Error(), "no suitable address found")
642 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
643 if _, ok := t.halfOpen[addr]; !ok {
644 panic("invariant broken")
646 delete(t.halfOpen, addr)
648 for _, t := range cl.torrents {
653 // Performs initiator handshakes and returns a connection. Returns nil *connection if no connection
654 // for valid reasons.
655 func (cl *Client) initiateProtocolHandshakes(
660 newConnOpts newConnectionOpts,
662 c *PeerConn, err error,
664 c = cl.newConnection(nc, newConnOpts)
665 c.headerEncrypted = encryptHeader
666 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
668 dl, ok := ctx.Deadline()
672 err = nc.SetDeadline(dl)
676 err = cl.initiateHandshakes(c, t)
680 // Returns nil connection and nil error if no connection could be established for valid reasons.
681 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
682 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
685 return t.dialTimeout()
688 dr := cl.dialFirst(dialCtx, addr.String())
691 if dialCtx.Err() != nil {
692 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
694 return nil, errors.New("dial failed")
696 addrIpPort, _ := tryIpPortFromNetAddr(addr)
697 c, err := cl.initiateProtocolHandshakes(context.Background(), nc, t, obfuscatedHeader, newConnectionOpts{
700 // It would be possible to retrieve a public IP from the dialer used here?
701 localPublicAddr: cl.publicAddr(addrIpPort.IP),
702 network: dr.Dialer.DialerNetwork(),
703 connString: regularNetConnPeerConnConnString(nc),
711 // Returns nil connection and nil error if no connection could be established
712 // for valid reasons.
713 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
714 torrent.Add("establish outgoing connection", 1)
715 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
716 c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
718 torrent.Add("initiated conn with preferred header obfuscation", 1)
721 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
722 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
723 // We should have just tried with the preferred header obfuscation. If it was required,
724 // there's nothing else to try.
727 // Try again with encryption if we didn't earlier, or without if we did.
728 c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
730 torrent.Add("initiated conn with fallback header obfuscation", 1)
732 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
736 // Called to dial out and run a connection. The addr we're given is already
737 // considered half-open.
738 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
739 cl.dialRateLimiter.Wait(context.Background())
740 c, err := cl.establishOutgoingConn(t, addr)
742 c.conn.SetWriteDeadline(time.Time{})
746 // Don't release lock between here and addPeerConn, unless it's for
748 cl.noLongerHalfOpen(t, addr.String())
751 cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", addr, err)
758 t.runHandshookConnLoggingErr(c)
761 // The port number for incoming peer connections. 0 if the client isn't listening.
762 func (cl *Client) incomingPeerPort() int {
763 return cl.LocalPort()
766 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
767 if c.headerEncrypted {
770 rw, c.cryptoMethod, err = mse.InitiateHandshake(
777 cl.config.CryptoProvides,
781 return fmt.Errorf("header obfuscation handshake: %w", err)
784 ih, err := cl.connBtHandshake(c, &t.infoHash)
786 return fmt.Errorf("bittorrent protocol handshake: %w", err)
788 if ih != t.infoHash {
789 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
794 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
795 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
796 func (cl *Client) forSkeys(f func([]byte) bool) {
799 if false { // Emulate the bug from #114
801 for ih := range cl.torrents {
805 for range cl.torrents {
812 for ih := range cl.torrents {
819 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
820 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
826 // Do encryption and bittorrent handshakes as receiver.
827 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
828 defer perf.ScopeTimerErr(&err)()
830 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
832 if err == nil || err == mse.ErrNoSecretKeyMatch {
833 if c.headerEncrypted {
834 torrent.Add("handshakes received encrypted", 1)
836 torrent.Add("handshakes received unencrypted", 1)
839 torrent.Add("handshakes received with error while handling encryption", 1)
842 if err == mse.ErrNoSecretKeyMatch {
847 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
848 err = errors.New("connection does not have required header obfuscation")
851 ih, err := cl.connBtHandshake(c, nil)
853 return nil, fmt.Errorf("during bt handshake: %w", err)
861 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
865 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
866 &successfulPeerWireProtocolHandshakePeerReservedBytes)
869 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
870 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
874 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
876 c.PeerExtensionBytes = res.PeerExtensionBits
877 c.PeerID = res.PeerID
878 c.completedHandshake = time.Now()
879 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
885 func (cl *Client) runReceivedConn(c *PeerConn) {
886 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
890 t, err := cl.receiveHandshakes(c)
892 cl.logger.LazyLog(log.Debug, func() log.Msg {
894 "error receiving handshakes on %v: %s", c, err,
896 "network", c.Network,
899 torrent.Add("error receiving handshake", 1)
901 cl.onBadAccept(c.RemoteAddr)
906 torrent.Add("received handshake for unloaded torrent", 1)
907 cl.logger.LazyLog(log.Debug, func() log.Msg {
908 return log.Fmsg("received handshake for unloaded torrent")
911 cl.onBadAccept(c.RemoteAddr)
915 torrent.Add("received handshake for loaded torrent", 1)
916 c.conn.SetWriteDeadline(time.Time{})
919 t.runHandshookConnLoggingErr(c)
922 // Client lock must be held before entering this.
923 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
925 for i, b := range cl.config.MinPeerExtensions {
926 if c.PeerExtensionBytes[i]&b != b {
927 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
930 if c.PeerID == cl.peerID {
933 addr := c.RemoteAddr.String()
934 cl.dopplegangerAddrs[addr] = struct{}{}
936 // Because the remote address is not necessarily the same as its client's torrent listen
937 // address, we won't record the remote address as a doppleganger. Instead, the initiator
938 // can record *us* as the doppleganger.
940 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
943 c.r = deadlineReader{c.conn, c.r}
944 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
945 if connIsIpv6(c.conn) {
946 torrent.Add("completed handshake over ipv6", 1)
948 if err := t.addPeerConn(c); err != nil {
949 return fmt.Errorf("adding connection: %w", err)
951 defer t.dropConnection(c)
952 c.startMessageWriter()
953 cl.sendInitialMessages(c, t)
954 c.initUpdateRequestsTimer()
955 err := c.mainReadLoop()
957 return fmt.Errorf("main read loop: %w", err)
964 func (p *Peer) initUpdateRequestsTimer() {
966 if p.updateRequestsTimer != nil {
967 panic(p.updateRequestsTimer)
970 if enableUpdateRequestsTimer {
971 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
975 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
977 func (c *Peer) updateRequestsTimerFunc() {
979 defer c.locker().Unlock()
980 if c.closed.IsSet() {
983 if c.isLowOnRequests() {
984 // If there are no outstanding requests, then a request update should have already run.
987 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
988 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
989 // already been fired.
990 torrent.Add("spurious timer requests updates", 1)
993 c.updateRequests(peerUpdateRequestsTimerReason)
996 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
997 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
998 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
999 const localClientReqq = 1024
1001 // See the order given in Transmission's tr_peerMsgsNew.
1002 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1003 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1004 conn.write(pp.Message{
1006 ExtendedID: pp.HandshakeExtendedID,
1007 ExtendedPayload: func() []byte {
1008 msg := pp.ExtendedHandshakeMessage{
1009 M: map[pp.ExtensionName]pp.ExtensionNumber{
1010 pp.ExtensionNameMetadata: metadataExtendedId,
1012 V: cl.config.ExtendedHandshakeClientVersion,
1013 Reqq: localClientReqq,
1014 YourIp: pp.CompactIp(conn.remoteIp()),
1015 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1016 Port: cl.incomingPeerPort(),
1017 MetadataSize: torrent.metadataSize(),
1018 // TODO: We can figure these out specific to the socket used.
1019 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1020 Ipv6: cl.config.PublicIp6.To16(),
1022 if !cl.config.DisablePEX {
1023 msg.M[pp.ExtensionNamePex] = pexExtendedId
1025 return bencode.MustMarshal(msg)
1030 if conn.fastEnabled() {
1031 if torrent.haveAllPieces() {
1032 conn.write(pp.Message{Type: pp.HaveAll})
1033 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1035 } else if !torrent.haveAnyPieces() {
1036 conn.write(pp.Message{Type: pp.HaveNone})
1037 conn.sentHaves.Clear()
1043 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1044 conn.write(pp.Message{
1051 func (cl *Client) dhtPort() (ret uint16) {
1052 if len(cl.dhtServers) == 0 {
1055 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1058 func (cl *Client) haveDhtServer() bool {
1059 return len(cl.dhtServers) > 0
1062 // Process incoming ut_metadata message.
1063 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1064 var d pp.ExtendedMetadataRequestMsg
1065 err := bencode.Unmarshal(payload, &d)
1066 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1067 } else if err != nil {
1068 return fmt.Errorf("error unmarshalling bencode: %s", err)
1072 case pp.DataMetadataExtensionMsgType:
1073 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1074 if !c.requestedMetadataPiece(piece) {
1075 return fmt.Errorf("got unexpected piece %d", piece)
1077 c.metadataRequests[piece] = false
1078 begin := len(payload) - d.PieceSize()
1079 if begin < 0 || begin >= len(payload) {
1080 return fmt.Errorf("data has bad offset in payload: %d", begin)
1082 t.saveMetadataPiece(piece, payload[begin:])
1083 c.lastUsefulChunkReceived = time.Now()
1084 err = t.maybeCompleteMetadata()
1086 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1087 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1088 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1089 // log consumers can filter for this message.
1090 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1093 case pp.RequestMetadataExtensionMsgType:
1094 if !t.haveMetadataPiece(piece) {
1095 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1098 start := (1 << 14) * piece
1099 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1100 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1102 case pp.RejectMetadataExtensionMsgType:
1105 return errors.New("unknown msg_type value")
1109 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1110 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1111 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1116 // Returns whether the IP address and port are considered "bad".
1117 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1118 if port == 0 || ip == nil {
1121 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1124 if _, ok := cl.ipBlockRange(ip); ok {
1127 ipAddr, ok := netip.AddrFromSlice(ip)
1131 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1137 // Return a Torrent ready for insertion into a Client.
1138 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1139 return cl.newTorrentOpt(AddTorrentOpts{
1141 Storage: specStorage,
1145 // Return a Torrent ready for insertion into a Client.
1146 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1147 // use provided storage, if provided
1148 storageClient := cl.defaultStorage
1149 if opts.Storage != nil {
1150 storageClient = storage.NewClient(opts.Storage)
1155 infoHash: opts.InfoHash,
1156 peers: prioritizedPeers{
1158 getPrio: func(p PeerInfo) peerPriority {
1160 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1163 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1165 halfOpen: make(map[string]PeerInfo),
1167 storageOpener: storageClient,
1168 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1170 metadataChanged: sync.Cond{
1173 webSeeds: make(map[string]*Peer),
1174 gotMetainfoC: make(chan struct{}),
1176 t.smartBanCache.Hash = sha1.Sum
1177 t.smartBanCache.Init()
1178 t.networkingEnabled.Set()
1179 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1180 t.sourcesLogger = t.logger.WithNames("sources")
1181 if opts.ChunkSize == 0 {
1182 opts.ChunkSize = defaultChunkSize
1184 t.setChunkSize(opts.ChunkSize)
1188 // A file-like handle to some torrent data resource.
1189 type Handle interface {
1196 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1197 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1200 // Adds a torrent by InfoHash with a custom Storage implementation.
1201 // If the torrent already exists then this Storage is ignored and the
1202 // existing torrent returned with `new` set to `false`
1203 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1206 t, ok := cl.torrents[infoHash]
1212 t = cl.newTorrent(infoHash, specStorage)
1213 cl.eachDhtServer(func(s DhtServer) {
1214 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1215 go t.dhtAnnouncer(s)
1218 cl.torrents[infoHash] = t
1219 cl.clearAcceptLimits()
1220 t.updateWantPeersEvent()
1221 // Tickle Client.waitAccept, new torrent may want conns.
1222 cl.event.Broadcast()
1226 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1227 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1228 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1229 infoHash := opts.InfoHash
1232 t, ok := cl.torrents[infoHash]
1238 t = cl.newTorrentOpt(opts)
1239 cl.eachDhtServer(func(s DhtServer) {
1240 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1241 go t.dhtAnnouncer(s)
1244 cl.torrents[infoHash] = t
1245 t.setInfoBytesLocked(opts.InfoBytes)
1246 cl.clearAcceptLimits()
1247 t.updateWantPeersEvent()
1248 // Tickle Client.waitAccept, new torrent may want conns.
1249 cl.event.Broadcast()
1253 type AddTorrentOpts struct {
1255 Storage storage.ClientImpl
1256 ChunkSize pp.Integer
1260 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1261 // Torrent.MergeSpec.
1262 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1263 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1264 InfoHash: spec.InfoHash,
1265 Storage: spec.Storage,
1266 ChunkSize: spec.ChunkSize,
1270 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1272 modSpec.ChunkSize = 0
1274 err = t.MergeSpec(&modSpec)
1275 if err != nil && new {
1281 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1282 // spec.DisallowDataDownload/Upload will be read and applied
1283 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1284 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1285 if spec.DisplayName != "" {
1286 t.SetDisplayName(spec.DisplayName)
1288 if spec.InfoBytes != nil {
1289 err := t.SetInfoBytes(spec.InfoBytes)
1295 cl.AddDhtNodes(spec.DhtNodes)
1296 t.UseSources(spec.Sources)
1299 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1300 for _, url := range spec.Webseeds {
1303 for _, peerAddr := range spec.PeerAddrs {
1305 Addr: StringAddr(peerAddr),
1306 Source: PeerSourceDirect,
1310 if spec.ChunkSize != 0 {
1311 panic("chunk size cannot be changed for existing Torrent")
1313 t.addTrackers(spec.Trackers)
1315 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1316 t.dataUploadDisallowed = spec.DisallowDataUpload
1320 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1321 t, ok := cl.torrents[infoHash]
1323 err = fmt.Errorf("no such torrent")
1327 delete(cl.torrents, infoHash)
1331 func (cl *Client) allTorrentsCompleted() bool {
1332 for _, t := range cl.torrents {
1336 if !t.haveAllPieces() {
1343 // Returns true when all torrents are completely downloaded and false if the
1344 // client is stopped before that.
1345 func (cl *Client) WaitAll() bool {
1348 for !cl.allTorrentsCompleted() {
1349 if cl.closed.IsSet() {
1357 // Returns handles to all the torrents loaded in the Client.
1358 func (cl *Client) Torrents() []*Torrent {
1361 return cl.torrentsAsSlice()
1364 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1365 for _, t := range cl.torrents {
1366 ret = append(ret, t)
1371 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1372 spec, err := TorrentSpecFromMagnetUri(uri)
1376 T, _, err = cl.AddTorrentSpec(spec)
1380 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1381 ts, err := TorrentSpecFromMetaInfoErr(mi)
1385 T, _, err = cl.AddTorrentSpec(ts)
1389 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1390 mi, err := metainfo.LoadFromFile(filename)
1394 return cl.AddTorrent(mi)
1397 func (cl *Client) DhtServers() []DhtServer {
1398 return cl.dhtServers
1401 func (cl *Client) AddDhtNodes(nodes []string) {
1402 for _, n := range nodes {
1403 hmp := missinggo.SplitHostMaybePort(n)
1404 ip := net.ParseIP(hmp.Host)
1406 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1409 ni := krpc.NodeInfo{
1410 Addr: krpc.NodeAddr{
1415 cl.eachDhtServer(func(s DhtServer) {
1421 func (cl *Client) banPeerIP(ip net.IP) {
1422 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1423 // addresses directly to v4on6, which doesn't compare equal with v4.
1424 ipAddr, ok := netip.AddrFromSlice(ip)
1428 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1429 for _, t := range cl.torrents {
1430 t.iterPeers(func(p *Peer) {
1431 if p.remoteIp().Equal(ip) {
1432 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1433 // Should this be a close?
1440 type newConnectionOpts struct {
1442 remoteAddr PeerRemoteAddr
1443 localPublicAddr peerLocalPublicAddr
1448 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1449 if opts.network == "" {
1450 panic(opts.remoteAddr)
1454 outgoing: opts.outgoing,
1457 PeerMaxRequests: 250,
1459 RemoteAddr: opts.remoteAddr,
1460 localPublicAddr: opts.localPublicAddr,
1461 Network: opts.network,
1462 callbacks: &cl.config.Callbacks,
1464 connString: opts.connString,
1467 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1468 c.initRequestState()
1469 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1470 if opts.remoteAddr != nil {
1471 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1473 c.bannableAddr = Some(netipAddrPort.Addr())
1477 c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1478 c.setRW(connStatsReadWriter{nc, c})
1479 c.r = &rateLimitedReader{
1480 l: cl.config.DownloadRateLimiter,
1483 c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", opts.remoteAddr, opts.network, opts.outgoing)
1484 for _, f := range cl.config.Callbacks.NewPeer {
1490 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1497 t.addPeers([]PeerInfo{{
1498 Addr: ipPortAddr{ip, port},
1499 Source: PeerSourceDhtAnnouncePeer,
1503 func firstNotNil(ips ...net.IP) net.IP {
1504 for _, ip := range ips {
1512 func (cl *Client) eachListener(f func(Listener) bool) {
1513 for _, s := range cl.listeners {
1520 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1521 for i := 0; i < len(cl.listeners); i += 1 {
1522 if ret = cl.listeners[i]; f(ret) {
1529 func (cl *Client) publicIp(peer net.IP) net.IP {
1530 // TODO: Use BEP 10 to determine how peers are seeing us.
1531 if peer.To4() != nil {
1533 cl.config.PublicIp4,
1534 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1539 cl.config.PublicIp6,
1540 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1544 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1545 l := cl.findListener(
1546 func(l Listener) bool {
1547 return f(addrIpOrNil(l.Addr()))
1553 return addrIpOrNil(l.Addr())
1556 // Our IP as a peer should see it.
1557 func (cl *Client) publicAddr(peer net.IP) IpPort {
1558 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1561 // ListenAddrs addresses currently being listened to.
1562 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1564 ret = make([]net.Addr, len(cl.listeners))
1565 for i := 0; i < len(cl.listeners); i += 1 {
1566 ret[i] = cl.listeners[i].Addr()
1572 func (cl *Client) PublicIPs() (ips []net.IP) {
1573 if ip := cl.config.PublicIp4; ip != nil {
1574 ips = append(ips, ip)
1576 if ip := cl.config.PublicIp6; ip != nil {
1577 ips = append(ips, ip)
1582 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1583 ipa, ok := tryIpPortFromNetAddr(addr)
1587 ip := maskIpForAcceptLimiting(ipa.IP)
1588 if cl.acceptLimiter == nil {
1589 cl.acceptLimiter = make(map[ipStr]int)
1591 cl.acceptLimiter[ipStr(ip.String())]++
1594 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1595 if ip4 := ip.To4(); ip4 != nil {
1596 return ip4.Mask(net.CIDRMask(24, 32))
1601 func (cl *Client) clearAcceptLimits() {
1602 cl.acceptLimiter = nil
1605 func (cl *Client) acceptLimitClearer() {
1608 case <-cl.closed.Done():
1610 case <-time.After(15 * time.Minute):
1612 cl.clearAcceptLimits()
1618 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1619 if cl.config.DisableAcceptRateLimiting {
1622 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1625 func (cl *Client) rLock() {
1629 func (cl *Client) rUnlock() {
1633 func (cl *Client) lock() {
1637 func (cl *Client) unlock() {
1641 func (cl *Client) locker() *lockWithDeferreds {
1645 func (cl *Client) String() string {
1646 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1649 // Returns connection-level aggregate stats at the Client level. See the comment on
1650 // TorrentStats.ConnStats.
1651 func (cl *Client) ConnStats() ConnStats {
1652 return cl.stats.Copy()