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 . "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"
49 // Clients contain zero or more Torrents. A Client manages a blocklist, the
50 // TCP/UDP protocol ports, and DHT as desired.
52 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
58 closed chansync.SetOnce
64 defaultStorage *storage.Client
68 dhtServers []DhtServer
69 ipBlockList iplist.Ranger
71 // Set of addresses that have our client ID. This intentionally will
72 // include ourselves if we end up trying to connect to our own address
73 // through legitimate channels.
74 dopplegangerAddrs map[string]struct{}
75 badPeerIPs map[netip.Addr]struct{}
76 torrents map[InfoHash]*Torrent
77 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
79 acceptLimiter map[ipStr]int
80 dialRateLimiter *rate.Limiter
83 activeAnnounceLimiter limiter.Instance
84 httpClient *http.Client
89 func (cl *Client) BadPeerIPs() (ips []string) {
91 ips = cl.badPeerIPsLocked()
96 func (cl *Client) badPeerIPsLocked() (ips []string) {
97 ips = make([]string, len(cl.badPeerIPs))
99 for k := range cl.badPeerIPs {
106 func (cl *Client) PeerID() PeerID {
110 // Returns the port number for the first listener that has one. No longer assumes that all port
111 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
113 func (cl *Client) LocalPort() (port int) {
114 for i := 0; i < len(cl.listeners); i += 1 {
115 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
122 func writeDhtServerStatus(w io.Writer, s DhtServer) {
123 dhtStats := s.Stats()
124 fmt.Fprintf(w, " ID: %x\n", s.ID())
125 spew.Fdump(w, dhtStats)
128 // Writes out a human readable status of the client, such as for writing to a
130 func (cl *Client) WriteStatus(_w io.Writer) {
133 w := bufio.NewWriter(_w)
135 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
136 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
137 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
138 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
139 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
140 cl.eachDhtServer(func(s DhtServer) {
141 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
142 writeDhtServerStatus(w, s)
144 spew.Fdump(w, &cl.stats)
145 torrentsSlice := cl.torrentsAsSlice()
146 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
148 sort.Slice(torrentsSlice, func(l, r int) bool {
149 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
151 for _, t := range torrentsSlice {
153 fmt.Fprint(w, "<unknown name>")
155 fmt.Fprint(w, t.name())
161 "%f%% of %d bytes (%s)",
162 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
164 humanize.Bytes(uint64(t.length())))
166 w.WriteString("<missing metainfo>")
174 func (cl *Client) initLogger() {
175 logger := cl.config.Logger
180 logger = logger.FilterLevel(log.Debug)
182 cl.logger = logger.WithValues(cl)
185 func (cl *Client) announceKey() int32 {
186 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
189 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
190 func (cl *Client) init(cfg *ClientConfig) {
192 generics.MakeMap(&cl.dopplegangerAddrs)
193 cl.torrents = make(map[metainfo.Hash]*Torrent)
194 cl.dialRateLimiter = rate.NewLimiter(10, 10)
195 cl.activeAnnounceLimiter.SlotsPerKey = 2
196 cl.event.L = cl.locker()
197 cl.ipBlockList = cfg.IPBlocklist
198 cl.httpClient = &http.Client{
199 Transport: &http.Transport{
200 Proxy: cfg.HTTPProxy,
201 DialContext: cfg.HTTPDialContext,
202 // I think this value was observed from some webseeds. It seems reasonable to extend it
203 // to other uses of HTTP from the client.
209 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
211 cfg = NewDefaultClientConfig()
217 go cl.acceptLimitClearer()
226 storageImpl := cfg.DefaultStorage
227 if storageImpl == nil {
228 // We'd use mmap by default but HFS+ doesn't support sparse files.
229 storageImplCloser := storage.NewFile(cfg.DataDir)
230 cl.onClose = append(cl.onClose, func() {
231 if err := storageImplCloser.Close(); err != nil {
232 cl.logger.Printf("error closing default storage: %s", err)
235 storageImpl = storageImplCloser
237 cl.defaultStorage = storage.NewClient(storageImpl)
239 if cfg.PeerID != "" {
240 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
242 o := copy(cl.peerID[:], cfg.Bep20)
243 _, err = rand.Read(cl.peerID[o:])
245 panic("error generating peer id")
249 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
257 for _, _s := range sockets {
258 s := _s // Go is fucking retarded.
259 cl.onClose = append(cl.onClose, func() { go s.Close() })
260 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
261 cl.dialers = append(cl.dialers, s)
262 cl.listeners = append(cl.listeners, s)
263 if cl.config.AcceptPeerConnections {
264 go cl.acceptConnections(s)
271 for _, s := range sockets {
272 if pc, ok := s.(net.PacketConn); ok {
273 ds, err := cl.NewAnacrolixDhtServer(pc)
277 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
278 cl.onClose = append(cl.onClose, func() { ds.Close() })
286 func (cl *Client) AddDhtServer(d DhtServer) {
287 cl.dhtServers = append(cl.dhtServers, d)
290 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
291 // given address for any Torrent.
292 func (cl *Client) AddDialer(d Dialer) {
295 cl.dialers = append(cl.dialers, d)
296 for _, t := range cl.torrents {
301 func (cl *Client) Listeners() []Listener {
305 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
307 func (cl *Client) AddListener(l Listener) {
308 cl.listeners = append(cl.listeners, l)
309 if cl.config.AcceptPeerConnections {
310 go cl.acceptConnections(l)
314 func (cl *Client) firewallCallback(net.Addr) bool {
316 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
319 torrent.Add("connections firewalled", 1)
321 torrent.Add("connections not firewalled", 1)
326 func (cl *Client) listenOnNetwork(n network) bool {
327 if n.Ipv4 && cl.config.DisableIPv4 {
330 if n.Ipv6 && cl.config.DisableIPv6 {
333 if n.Tcp && cl.config.DisableTCP {
336 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
342 func (cl *Client) listenNetworks() (ns []network) {
343 for _, n := range allPeerNetworks {
344 if cl.listenOnNetwork(n) {
351 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
352 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
353 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
354 cfg := dht.ServerConfig{
355 IPBlocklist: cl.ipBlockList,
357 OnAnnouncePeer: cl.onDHTAnnouncePeer,
358 PublicIP: func() net.IP {
359 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
360 return cl.config.PublicIp6
362 return cl.config.PublicIp4
364 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
365 OnQuery: cl.config.DHTOnQuery,
368 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
371 s, err = dht.NewServer(&cfg)
373 go s.TableMaintainer()
378 func (cl *Client) Closed() events.Done {
379 return cl.closed.Done()
382 func (cl *Client) eachDhtServer(f func(DhtServer)) {
383 for _, ds := range cl.dhtServers {
388 // Stops the client. All connections to peers are closed and all activity will come to a halt.
389 func (cl *Client) Close() (errs []error) {
390 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
392 for _, t := range cl.torrents {
393 err := t.close(&closeGroup)
395 errs = append(errs, err)
398 for i := range cl.onClose {
399 cl.onClose[len(cl.onClose)-1-i]()
404 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
408 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
409 if cl.ipBlockList == nil {
412 return cl.ipBlockList.Lookup(ip)
415 func (cl *Client) ipIsBlocked(ip net.IP) bool {
416 _, blocked := cl.ipBlockRange(ip)
420 func (cl *Client) wantConns() bool {
421 if cl.config.AlwaysWantConns {
424 for _, t := range cl.torrents {
432 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
433 func (cl *Client) rejectAccepted(conn net.Conn) error {
435 return errors.New("don't want conns right now")
437 ra := conn.RemoteAddr()
438 if rip := addrIpOrNil(ra); rip != nil {
439 if cl.config.DisableIPv4Peers && rip.To4() != nil {
440 return errors.New("ipv4 peers disabled")
442 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
443 return errors.New("ipv4 disabled")
445 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
446 return errors.New("ipv6 disabled")
448 if cl.rateLimitAccept(rip) {
449 return errors.New("source IP accepted rate limited")
451 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
452 return errors.New("bad source addr")
458 func (cl *Client) acceptConnections(l Listener) {
460 conn, err := l.Accept()
461 torrent.Add("client listener accepts", 1)
462 conn = pproffd.WrapNetConn(conn)
464 closed := cl.closed.IsSet()
466 if !closed && conn != nil {
467 reject = cl.rejectAccepted(conn)
477 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
482 torrent.Add("rejected accepted connections", 1)
483 cl.logger.LazyLog(log.Debug, func() log.Msg {
484 return log.Fmsg("rejecting accepted conn: %v", reject)
488 go cl.incomingConnection(conn)
490 cl.logger.LazyLog(log.Debug, func() log.Msg {
491 return log.Fmsg("accepted %q connection at %q from %q",
497 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
498 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
499 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
504 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
505 func regularNetConnPeerConnConnString(nc net.Conn) string {
506 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
509 func (cl *Client) incomingConnection(nc net.Conn) {
511 if tc, ok := nc.(*net.TCPConn); ok {
514 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
515 c := cl.newConnection(
519 remoteAddr: nc.RemoteAddr(),
520 localPublicAddr: cl.publicAddr(remoteAddr.IP),
521 network: nc.RemoteAddr().Network(),
522 connString: regularNetConnPeerConnConnString(nc),
529 c.Discovery = PeerSourceIncoming
530 cl.runReceivedConn(c)
533 // Returns a handle to the given torrent, if it's present in the client.
534 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
537 t, ok = cl.torrents[ih]
541 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
542 return cl.torrents[ih]
545 type DialResult struct {
550 func countDialResult(err error) {
552 torrent.Add("successful dials", 1)
554 torrent.Add("unsuccessful dials", 1)
558 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
559 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
560 if ret < minDialTimeout {
566 // Returns whether an address is known to connect to a client with our own ID.
567 func (cl *Client) dopplegangerAddr(addr string) bool {
568 _, ok := cl.dopplegangerAddrs[addr]
572 // Returns a connection over UTP or TCP, whichever is first to connect.
573 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
574 return DialFirst(ctx, addr, cl.dialers)
577 // Returns a connection over UTP or TCP, whichever is first to connect.
578 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
580 t := perf.NewTimer(perf.CallerName(0))
583 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
585 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
589 ctx, cancel := context.WithCancel(ctx)
590 // As soon as we return one connection, cancel the others.
593 resCh := make(chan DialResult, left)
594 for _, _s := range dialers {
599 dialFromSocket(ctx, s, addr),
604 // Wait for a successful connection.
606 defer perf.ScopeTimer()()
607 for ; left > 0 && res.Conn == nil; left-- {
611 // There are still incompleted dials.
613 for ; left > 0; left-- {
614 conn := (<-resCh).Conn
621 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
626 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
627 c, err := s.Dial(ctx, addr)
628 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
629 // it now in case we close the connection forthwith.
630 if tc, ok := c.(*net.TCPConn); ok {
637 func forgettableDialError(err error) bool {
638 return strings.Contains(err.Error(), "no suitable address found")
641 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
642 if _, ok := t.halfOpen[addr]; !ok {
643 panic("invariant broken")
645 delete(t.halfOpen, addr)
647 for _, t := range cl.torrents {
652 // Performs initiator handshakes and returns a connection. Returns nil *connection if no connection
653 // for valid reasons.
654 func (cl *Client) initiateProtocolHandshakes(
659 newConnOpts newConnectionOpts,
661 c *PeerConn, err error,
663 c = cl.newConnection(nc, newConnOpts)
664 c.headerEncrypted = encryptHeader
665 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
667 dl, ok := ctx.Deadline()
671 err = nc.SetDeadline(dl)
675 err = cl.initiateHandshakes(c, t)
679 // Returns nil connection and nil error if no connection could be established for valid reasons.
680 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
681 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
684 return t.dialTimeout()
687 dr := cl.dialFirst(dialCtx, addr.String())
690 if dialCtx.Err() != nil {
691 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
693 return nil, errors.New("dial failed")
695 addrIpPort, _ := tryIpPortFromNetAddr(addr)
696 c, err := cl.initiateProtocolHandshakes(context.Background(), nc, t, obfuscatedHeader, newConnectionOpts{
699 // It would be possible to retrieve a public IP from the dialer used here?
700 localPublicAddr: cl.publicAddr(addrIpPort.IP),
701 network: dr.Dialer.DialerNetwork(),
702 connString: regularNetConnPeerConnConnString(nc),
710 // Returns nil connection and nil error if no connection could be established
711 // for valid reasons.
712 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
713 torrent.Add("establish outgoing connection", 1)
714 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
715 c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
717 torrent.Add("initiated conn with preferred header obfuscation", 1)
720 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
721 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
722 // We should have just tried with the preferred header obfuscation. If it was required,
723 // there's nothing else to try.
726 // Try again with encryption if we didn't earlier, or without if we did.
727 c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
729 torrent.Add("initiated conn with fallback header obfuscation", 1)
731 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
735 // Called to dial out and run a connection. The addr we're given is already
736 // considered half-open.
737 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
738 cl.dialRateLimiter.Wait(context.Background())
739 c, err := cl.establishOutgoingConn(t, addr)
741 c.conn.SetWriteDeadline(time.Time{})
745 // Don't release lock between here and addPeerConn, unless it's for
747 cl.noLongerHalfOpen(t, addr.String())
750 cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", addr, err)
757 t.runHandshookConnLoggingErr(c)
760 // The port number for incoming peer connections. 0 if the client isn't listening.
761 func (cl *Client) incomingPeerPort() int {
762 return cl.LocalPort()
765 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
766 if c.headerEncrypted {
769 rw, c.cryptoMethod, err = mse.InitiateHandshake(
776 cl.config.CryptoProvides,
780 return fmt.Errorf("header obfuscation handshake: %w", err)
783 ih, err := cl.connBtHandshake(c, &t.infoHash)
785 return fmt.Errorf("bittorrent protocol handshake: %w", err)
787 if ih != t.infoHash {
788 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
793 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
794 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
795 func (cl *Client) forSkeys(f func([]byte) bool) {
798 if false { // Emulate the bug from #114
800 for ih := range cl.torrents {
804 for range cl.torrents {
811 for ih := range cl.torrents {
818 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
819 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
825 // Do encryption and bittorrent handshakes as receiver.
826 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
827 defer perf.ScopeTimerErr(&err)()
829 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
831 if err == nil || err == mse.ErrNoSecretKeyMatch {
832 if c.headerEncrypted {
833 torrent.Add("handshakes received encrypted", 1)
835 torrent.Add("handshakes received unencrypted", 1)
838 torrent.Add("handshakes received with error while handling encryption", 1)
841 if err == mse.ErrNoSecretKeyMatch {
846 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
847 err = errors.New("connection does not have required header obfuscation")
850 ih, err := cl.connBtHandshake(c, nil)
852 return nil, fmt.Errorf("during bt handshake: %w", err)
860 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
864 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
865 &successfulPeerWireProtocolHandshakePeerReservedBytes)
868 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
869 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
873 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
875 c.PeerExtensionBytes = res.PeerExtensionBits
876 c.PeerID = res.PeerID
877 c.completedHandshake = time.Now()
878 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
884 func (cl *Client) runReceivedConn(c *PeerConn) {
885 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
889 t, err := cl.receiveHandshakes(c)
891 cl.logger.LazyLog(log.Debug, func() log.Msg {
893 "error receiving handshakes on %v: %s", c, err,
895 "network", c.Network,
898 torrent.Add("error receiving handshake", 1)
900 cl.onBadAccept(c.RemoteAddr)
905 torrent.Add("received handshake for unloaded torrent", 1)
906 cl.logger.LazyLog(log.Debug, func() log.Msg {
907 return log.Fmsg("received handshake for unloaded torrent")
910 cl.onBadAccept(c.RemoteAddr)
914 torrent.Add("received handshake for loaded torrent", 1)
915 c.conn.SetWriteDeadline(time.Time{})
918 t.runHandshookConnLoggingErr(c)
921 // Client lock must be held before entering this.
922 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
924 for i, b := range cl.config.MinPeerExtensions {
925 if c.PeerExtensionBytes[i]&b != b {
926 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
929 if c.PeerID == cl.peerID {
932 addr := c.RemoteAddr.String()
933 cl.dopplegangerAddrs[addr] = struct{}{}
935 // Because the remote address is not necessarily the same as its client's torrent listen
936 // address, we won't record the remote address as a doppleganger. Instead, the initiator
937 // can record *us* as the doppleganger.
939 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
942 c.r = deadlineReader{c.conn, c.r}
943 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
944 if connIsIpv6(c.conn) {
945 torrent.Add("completed handshake over ipv6", 1)
947 if err := t.addPeerConn(c); err != nil {
948 return fmt.Errorf("adding connection: %w", err)
950 defer t.dropConnection(c)
951 c.startMessageWriter()
952 cl.sendInitialMessages(c, t)
953 c.initUpdateRequestsTimer()
954 err := c.mainReadLoop()
956 return fmt.Errorf("main read loop: %w", err)
963 func (p *Peer) initUpdateRequestsTimer() {
965 if p.updateRequestsTimer != nil {
966 panic(p.updateRequestsTimer)
969 if enableUpdateRequestsTimer {
970 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
974 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
976 func (c *Peer) updateRequestsTimerFunc() {
978 defer c.locker().Unlock()
979 if c.closed.IsSet() {
982 if c.isLowOnRequests() {
983 // If there are no outstanding requests, then a request update should have already run.
986 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
987 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
988 // already been fired.
989 torrent.Add("spurious timer requests updates", 1)
992 c.updateRequests(peerUpdateRequestsTimerReason)
995 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
996 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
997 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
998 const localClientReqq = 1024
1000 // See the order given in Transmission's tr_peerMsgsNew.
1001 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1002 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1003 conn.write(pp.Message{
1005 ExtendedID: pp.HandshakeExtendedID,
1006 ExtendedPayload: func() []byte {
1007 msg := pp.ExtendedHandshakeMessage{
1008 M: map[pp.ExtensionName]pp.ExtensionNumber{
1009 pp.ExtensionNameMetadata: metadataExtendedId,
1011 V: cl.config.ExtendedHandshakeClientVersion,
1012 Reqq: localClientReqq,
1013 YourIp: pp.CompactIp(conn.remoteIp()),
1014 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1015 Port: cl.incomingPeerPort(),
1016 MetadataSize: torrent.metadataSize(),
1017 // TODO: We can figure these out specific to the socket used.
1018 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1019 Ipv6: cl.config.PublicIp6.To16(),
1021 if !cl.config.DisablePEX {
1022 msg.M[pp.ExtensionNamePex] = pexExtendedId
1024 return bencode.MustMarshal(msg)
1029 if conn.fastEnabled() {
1030 if torrent.haveAllPieces() {
1031 conn.write(pp.Message{Type: pp.HaveAll})
1032 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1034 } else if !torrent.haveAnyPieces() {
1035 conn.write(pp.Message{Type: pp.HaveNone})
1036 conn.sentHaves.Clear()
1042 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1043 conn.write(pp.Message{
1050 func (cl *Client) dhtPort() (ret uint16) {
1051 if len(cl.dhtServers) == 0 {
1054 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1057 func (cl *Client) haveDhtServer() bool {
1058 return len(cl.dhtServers) > 0
1061 // Process incoming ut_metadata message.
1062 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1063 var d pp.ExtendedMetadataRequestMsg
1064 err := bencode.Unmarshal(payload, &d)
1065 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1066 } else if err != nil {
1067 return fmt.Errorf("error unmarshalling bencode: %s", err)
1071 case pp.DataMetadataExtensionMsgType:
1072 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1073 if !c.requestedMetadataPiece(piece) {
1074 return fmt.Errorf("got unexpected piece %d", piece)
1076 c.metadataRequests[piece] = false
1077 begin := len(payload) - d.PieceSize()
1078 if begin < 0 || begin >= len(payload) {
1079 return fmt.Errorf("data has bad offset in payload: %d", begin)
1081 t.saveMetadataPiece(piece, payload[begin:])
1082 c.lastUsefulChunkReceived = time.Now()
1083 err = t.maybeCompleteMetadata()
1085 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1086 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1087 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1088 // log consumers can filter for this message.
1089 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1092 case pp.RequestMetadataExtensionMsgType:
1093 if !t.haveMetadataPiece(piece) {
1094 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1097 start := (1 << 14) * piece
1098 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1099 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1101 case pp.RejectMetadataExtensionMsgType:
1104 return errors.New("unknown msg_type value")
1108 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1109 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1110 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1115 // Returns whether the IP address and port are considered "bad".
1116 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1117 if port == 0 || ip == nil {
1120 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1123 if _, ok := cl.ipBlockRange(ip); ok {
1126 ipAddr, ok := netip.AddrFromSlice(ip)
1130 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1136 // Return a Torrent ready for insertion into a Client.
1137 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1138 return cl.newTorrentOpt(AddTorrentOpts{
1140 Storage: specStorage,
1144 // Return a Torrent ready for insertion into a Client.
1145 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1146 // use provided storage, if provided
1147 storageClient := cl.defaultStorage
1148 if opts.Storage != nil {
1149 storageClient = storage.NewClient(opts.Storage)
1154 infoHash: opts.InfoHash,
1155 peers: prioritizedPeers{
1157 getPrio: func(p PeerInfo) peerPriority {
1159 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1162 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1164 halfOpen: make(map[string]PeerInfo),
1166 storageOpener: storageClient,
1167 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1169 metadataChanged: sync.Cond{
1172 webSeeds: make(map[string]*Peer),
1173 gotMetainfoC: make(chan struct{}),
1175 t.smartBanCache.Hash = sha1.Sum
1176 t.smartBanCache.Init()
1177 t.networkingEnabled.Set()
1178 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1179 t.sourcesLogger = t.logger.WithNames("sources")
1180 if opts.ChunkSize == 0 {
1181 opts.ChunkSize = defaultChunkSize
1183 t.setChunkSize(opts.ChunkSize)
1187 // A file-like handle to some torrent data resource.
1188 type Handle interface {
1195 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1196 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1199 // Adds a torrent by InfoHash with a custom Storage implementation.
1200 // If the torrent already exists then this Storage is ignored and the
1201 // existing torrent returned with `new` set to `false`
1202 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1205 t, ok := cl.torrents[infoHash]
1211 t = cl.newTorrent(infoHash, specStorage)
1212 cl.eachDhtServer(func(s DhtServer) {
1213 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1214 go t.dhtAnnouncer(s)
1217 cl.torrents[infoHash] = t
1218 cl.clearAcceptLimits()
1219 t.updateWantPeersEvent()
1220 // Tickle Client.waitAccept, new torrent may want conns.
1221 cl.event.Broadcast()
1225 // Adds a torrent by InfoHash with a custom Storage implementation.
1226 // If the torrent already exists then this Storage is ignored and the
1227 // 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 cl.clearAcceptLimits()
1246 t.updateWantPeersEvent()
1247 // Tickle Client.waitAccept, new torrent may want conns.
1248 cl.event.Broadcast()
1252 type AddTorrentOpts struct {
1254 Storage storage.ClientImpl
1255 ChunkSize pp.Integer
1258 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1259 // Torrent.MergeSpec.
1260 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1261 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1262 InfoHash: spec.InfoHash,
1263 Storage: spec.Storage,
1264 ChunkSize: spec.ChunkSize,
1268 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1270 modSpec.ChunkSize = 0
1272 err = t.MergeSpec(&modSpec)
1273 if err != nil && new {
1279 type stringAddr string
1281 var _ net.Addr = stringAddr("")
1283 func (stringAddr) Network() string { return "" }
1284 func (me stringAddr) String() string { return string(me) }
1286 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1287 // spec.DisallowDataDownload/Upload will be read and applied
1288 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1289 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1290 if spec.DisplayName != "" {
1291 t.SetDisplayName(spec.DisplayName)
1293 if spec.InfoBytes != nil {
1294 err := t.SetInfoBytes(spec.InfoBytes)
1300 cl.AddDhtNodes(spec.DhtNodes)
1301 t.UseSources(spec.Sources)
1304 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1305 for _, url := range spec.Webseeds {
1308 for _, peerAddr := range spec.PeerAddrs {
1310 Addr: stringAddr(peerAddr),
1311 Source: PeerSourceDirect,
1315 if spec.ChunkSize != 0 {
1316 panic("chunk size cannot be changed for existing Torrent")
1318 t.addTrackers(spec.Trackers)
1320 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1321 t.dataUploadDisallowed = spec.DisallowDataUpload
1325 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1326 t, ok := cl.torrents[infoHash]
1328 err = fmt.Errorf("no such torrent")
1332 delete(cl.torrents, infoHash)
1336 func (cl *Client) allTorrentsCompleted() bool {
1337 for _, t := range cl.torrents {
1341 if !t.haveAllPieces() {
1348 // Returns true when all torrents are completely downloaded and false if the
1349 // client is stopped before that.
1350 func (cl *Client) WaitAll() bool {
1353 for !cl.allTorrentsCompleted() {
1354 if cl.closed.IsSet() {
1362 // Returns handles to all the torrents loaded in the Client.
1363 func (cl *Client) Torrents() []*Torrent {
1366 return cl.torrentsAsSlice()
1369 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1370 for _, t := range cl.torrents {
1371 ret = append(ret, t)
1376 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1377 spec, err := TorrentSpecFromMagnetUri(uri)
1381 T, _, err = cl.AddTorrentSpec(spec)
1385 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1386 ts, err := TorrentSpecFromMetaInfoErr(mi)
1390 T, _, err = cl.AddTorrentSpec(ts)
1394 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1395 mi, err := metainfo.LoadFromFile(filename)
1399 return cl.AddTorrent(mi)
1402 func (cl *Client) DhtServers() []DhtServer {
1403 return cl.dhtServers
1406 func (cl *Client) AddDhtNodes(nodes []string) {
1407 for _, n := range nodes {
1408 hmp := missinggo.SplitHostMaybePort(n)
1409 ip := net.ParseIP(hmp.Host)
1411 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1414 ni := krpc.NodeInfo{
1415 Addr: krpc.NodeAddr{
1420 cl.eachDhtServer(func(s DhtServer) {
1426 func (cl *Client) banPeerIP(ip net.IP) {
1427 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1428 // addresses directly to v4on6, which doesn't compare equal with v4.
1429 ipAddr, ok := netip.AddrFromSlice(ip)
1433 generics.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1434 for _, t := range cl.torrents {
1435 t.iterPeers(func(p *Peer) {
1436 if p.remoteIp().Equal(ip) {
1437 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1438 // Should this be a close?
1445 type newConnectionOpts struct {
1447 remoteAddr PeerRemoteAddr
1448 localPublicAddr peerLocalPublicAddr
1453 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1454 if opts.network == "" {
1455 panic(opts.remoteAddr)
1459 outgoing: opts.outgoing,
1462 PeerMaxRequests: 250,
1464 RemoteAddr: opts.remoteAddr,
1465 localPublicAddr: opts.localPublicAddr,
1466 Network: opts.network,
1467 callbacks: &cl.config.Callbacks,
1469 connString: opts.connString,
1472 c.initRequestState()
1473 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1474 if opts.remoteAddr != nil {
1475 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1477 c.bannableAddr = Some(netipAddrPort.Addr())
1481 c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1482 c.setRW(connStatsReadWriter{nc, c})
1483 c.r = &rateLimitedReader{
1484 l: cl.config.DownloadRateLimiter,
1487 c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", opts.remoteAddr, opts.network, opts.outgoing)
1488 for _, f := range cl.config.Callbacks.NewPeer {
1494 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1501 t.addPeers([]PeerInfo{{
1502 Addr: ipPortAddr{ip, port},
1503 Source: PeerSourceDhtAnnouncePeer,
1507 func firstNotNil(ips ...net.IP) net.IP {
1508 for _, ip := range ips {
1516 func (cl *Client) eachListener(f func(Listener) bool) {
1517 for _, s := range cl.listeners {
1524 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1525 for i := 0; i < len(cl.listeners); i += 1 {
1526 if ret = cl.listeners[i]; f(ret) {
1533 func (cl *Client) publicIp(peer net.IP) net.IP {
1534 // TODO: Use BEP 10 to determine how peers are seeing us.
1535 if peer.To4() != nil {
1537 cl.config.PublicIp4,
1538 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1543 cl.config.PublicIp6,
1544 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1548 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1549 l := cl.findListener(
1550 func(l Listener) bool {
1551 return f(addrIpOrNil(l.Addr()))
1557 return addrIpOrNil(l.Addr())
1560 // Our IP as a peer should see it.
1561 func (cl *Client) publicAddr(peer net.IP) IpPort {
1562 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1565 // ListenAddrs addresses currently being listened to.
1566 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1568 ret = make([]net.Addr, len(cl.listeners))
1569 for i := 0; i < len(cl.listeners); i += 1 {
1570 ret[i] = cl.listeners[i].Addr()
1576 func (cl *Client) PublicIPs() (ips []net.IP) {
1577 if ip := cl.config.PublicIp4; ip != nil {
1578 ips = append(ips, ip)
1580 if ip := cl.config.PublicIp6; ip != nil {
1581 ips = append(ips, ip)
1586 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1587 ipa, ok := tryIpPortFromNetAddr(addr)
1591 ip := maskIpForAcceptLimiting(ipa.IP)
1592 if cl.acceptLimiter == nil {
1593 cl.acceptLimiter = make(map[ipStr]int)
1595 cl.acceptLimiter[ipStr(ip.String())]++
1598 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1599 if ip4 := ip.To4(); ip4 != nil {
1600 return ip4.Mask(net.CIDRMask(24, 32))
1605 func (cl *Client) clearAcceptLimits() {
1606 cl.acceptLimiter = nil
1609 func (cl *Client) acceptLimitClearer() {
1612 case <-cl.closed.Done():
1614 case <-time.After(15 * time.Minute):
1616 cl.clearAcceptLimits()
1622 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1623 if cl.config.DisableAcceptRateLimiting {
1626 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1629 func (cl *Client) rLock() {
1633 func (cl *Client) rUnlock() {
1637 func (cl *Client) lock() {
1641 func (cl *Client) unlock() {
1645 func (cl *Client) locker() *lockWithDeferreds {
1649 func (cl *Client) String() string {
1650 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1653 // Returns connection-level aggregate stats at the Client level. See the comment on
1654 // TorrentStats.ConnStats.
1655 func (cl *Client) ConnStats() ConnStats {
1656 return cl.stats.Copy()