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 "github.com/anacrolix/log"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/v2"
29 "github.com/anacrolix/missinggo/v2/bitmap"
30 "github.com/anacrolix/missinggo/v2/pproffd"
31 "github.com/anacrolix/sync"
32 request_strategy "github.com/anacrolix/torrent/request-strategy"
33 "github.com/davecgh/go-spew/spew"
34 "github.com/dustin/go-humanize"
35 "github.com/google/btree"
36 "github.com/pion/datachannel"
37 "golang.org/x/time/rate"
39 "github.com/anacrolix/chansync"
40 . "github.com/anacrolix/generics"
42 "github.com/anacrolix/torrent/bencode"
43 "github.com/anacrolix/torrent/internal/limiter"
44 "github.com/anacrolix/torrent/iplist"
45 "github.com/anacrolix/torrent/metainfo"
46 "github.com/anacrolix/torrent/mse"
47 pp "github.com/anacrolix/torrent/peer_protocol"
48 "github.com/anacrolix/torrent/storage"
49 "github.com/anacrolix/torrent/tracker"
50 "github.com/anacrolix/torrent/webtorrent"
53 // Clients contain zero or more Torrents. A Client manages a blocklist, the
54 // TCP/UDP protocol ports, and DHT as desired.
56 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
62 closed chansync.SetOnce
68 defaultStorage *storage.Client
72 dhtServers []DhtServer
73 ipBlockList iplist.Ranger
75 // Set of addresses that have our client ID. This intentionally will
76 // include ourselves if we end up trying to connect to our own address
77 // through legitimate channels.
78 dopplegangerAddrs map[string]struct{}
79 badPeerIPs map[netip.Addr]struct{}
80 torrents map[InfoHash]*Torrent
81 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
83 acceptLimiter map[ipStr]int
84 dialRateLimiter *rate.Limiter
87 websocketTrackers websocketTrackers
89 activeAnnounceLimiter limiter.Instance
90 httpClient *http.Client
95 func (cl *Client) BadPeerIPs() (ips []string) {
97 ips = cl.badPeerIPsLocked()
102 func (cl *Client) badPeerIPsLocked() (ips []string) {
103 ips = make([]string, len(cl.badPeerIPs))
105 for k := range cl.badPeerIPs {
112 func (cl *Client) PeerID() PeerID {
116 // Returns the port number for the first listener that has one. No longer assumes that all port
117 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
119 func (cl *Client) LocalPort() (port int) {
120 for i := 0; i < len(cl.listeners); i += 1 {
121 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
128 func writeDhtServerStatus(w io.Writer, s DhtServer) {
129 dhtStats := s.Stats()
130 fmt.Fprintf(w, " ID: %x\n", s.ID())
131 spew.Fdump(w, dhtStats)
134 // Writes out a human readable status of the client, such as for writing to a
136 func (cl *Client) WriteStatus(_w io.Writer) {
139 w := bufio.NewWriter(_w)
141 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
142 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
143 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
144 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
145 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
146 cl.eachDhtServer(func(s DhtServer) {
147 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
148 writeDhtServerStatus(w, s)
150 spew.Fdump(w, &cl.stats)
151 torrentsSlice := cl.torrentsAsSlice()
152 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
154 sort.Slice(torrentsSlice, func(l, r int) bool {
155 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
157 for _, t := range torrentsSlice {
159 fmt.Fprint(w, "<unknown name>")
161 fmt.Fprint(w, t.name())
167 "%f%% of %d bytes (%s)",
168 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
170 humanize.Bytes(uint64(*t.length)))
172 w.WriteString("<missing metainfo>")
180 func (cl *Client) initLogger() {
181 logger := cl.config.Logger
186 logger = logger.FilterLevel(log.Debug)
188 cl.logger = logger.WithValues(cl)
191 func (cl *Client) announceKey() int32 {
192 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
195 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
196 func (cl *Client) init(cfg *ClientConfig) {
198 generics.MakeMap(&cl.dopplegangerAddrs)
199 cl.torrents = make(map[metainfo.Hash]*Torrent)
200 cl.dialRateLimiter = rate.NewLimiter(10, 10)
201 cl.activeAnnounceLimiter.SlotsPerKey = 2
202 cl.event.L = cl.locker()
203 cl.ipBlockList = cfg.IPBlocklist
204 cl.httpClient = &http.Client{
205 Transport: &http.Transport{
206 Proxy: cfg.HTTPProxy,
207 // I think this value was observed from some webseeds. It seems reasonable to extend it
208 // to other uses of HTTP from the client.
214 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
216 cfg = NewDefaultClientConfig()
222 go cl.acceptLimitClearer()
231 storageImpl := cfg.DefaultStorage
232 if storageImpl == nil {
233 // We'd use mmap by default but HFS+ doesn't support sparse files.
234 storageImplCloser := storage.NewFile(cfg.DataDir)
235 cl.onClose = append(cl.onClose, func() {
236 if err := storageImplCloser.Close(); err != nil {
237 cl.logger.Printf("error closing default storage: %s", err)
240 storageImpl = storageImplCloser
242 cl.defaultStorage = storage.NewClient(storageImpl)
244 if cfg.PeerID != "" {
245 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
247 o := copy(cl.peerID[:], cfg.Bep20)
248 _, err = rand.Read(cl.peerID[o:])
250 panic("error generating peer id")
254 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
262 for _, _s := range sockets {
263 s := _s // Go is fucking retarded.
264 cl.onClose = append(cl.onClose, func() { go s.Close() })
265 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
266 cl.dialers = append(cl.dialers, s)
267 cl.listeners = append(cl.listeners, s)
268 if cl.config.AcceptPeerConnections {
269 go cl.acceptConnections(s)
276 for _, s := range sockets {
277 if pc, ok := s.(net.PacketConn); ok {
278 ds, err := cl.NewAnacrolixDhtServer(pc)
282 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
283 cl.onClose = append(cl.onClose, func() { ds.Close() })
288 cl.websocketTrackers = websocketTrackers{
291 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
294 t, ok := cl.torrents[infoHash]
296 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
298 return t.announceRequest(event), nil
300 Proxy: cl.config.HTTPProxy,
301 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
304 t, ok := cl.torrents[dcc.InfoHash]
306 cl.logger.WithDefaultLevel(log.Warning).Printf(
307 "got webrtc conn for unloaded torrent with infohash %x",
313 go t.onWebRtcConn(dc, dcc)
320 func (cl *Client) AddDhtServer(d DhtServer) {
321 cl.dhtServers = append(cl.dhtServers, d)
324 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
325 // given address for any Torrent.
326 func (cl *Client) AddDialer(d Dialer) {
329 cl.dialers = append(cl.dialers, d)
330 for _, t := range cl.torrents {
335 func (cl *Client) Listeners() []Listener {
339 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
341 func (cl *Client) AddListener(l Listener) {
342 cl.listeners = append(cl.listeners, l)
343 if cl.config.AcceptPeerConnections {
344 go cl.acceptConnections(l)
348 func (cl *Client) firewallCallback(net.Addr) bool {
350 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
353 torrent.Add("connections firewalled", 1)
355 torrent.Add("connections not firewalled", 1)
360 func (cl *Client) listenOnNetwork(n network) bool {
361 if n.Ipv4 && cl.config.DisableIPv4 {
364 if n.Ipv6 && cl.config.DisableIPv6 {
367 if n.Tcp && cl.config.DisableTCP {
370 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
376 func (cl *Client) listenNetworks() (ns []network) {
377 for _, n := range allPeerNetworks {
378 if cl.listenOnNetwork(n) {
385 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
386 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
387 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
388 cfg := dht.ServerConfig{
389 IPBlocklist: cl.ipBlockList,
391 OnAnnouncePeer: cl.onDHTAnnouncePeer,
392 PublicIP: func() net.IP {
393 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
394 return cl.config.PublicIp6
396 return cl.config.PublicIp4
398 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
399 OnQuery: cl.config.DHTOnQuery,
402 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
405 s, err = dht.NewServer(&cfg)
408 ts, err := s.Bootstrap()
410 logger.Levelf(log.Warning, "error bootstrapping dht: %s", err)
412 logger.Levelf(log.Debug, "completed bootstrap: %+v", ts)
418 func (cl *Client) Closed() events.Done {
419 return cl.closed.Done()
422 func (cl *Client) eachDhtServer(f func(DhtServer)) {
423 for _, ds := range cl.dhtServers {
428 // Stops the client. All connections to peers are closed and all activity will come to a halt.
429 func (cl *Client) Close() (errs []error) {
430 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
432 for _, t := range cl.torrents {
433 err := t.close(&closeGroup)
435 errs = append(errs, err)
438 for i := range cl.onClose {
439 cl.onClose[len(cl.onClose)-1-i]()
444 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
448 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
449 if cl.ipBlockList == nil {
452 return cl.ipBlockList.Lookup(ip)
455 func (cl *Client) ipIsBlocked(ip net.IP) bool {
456 _, blocked := cl.ipBlockRange(ip)
460 func (cl *Client) wantConns() bool {
461 if cl.config.AlwaysWantConns {
464 for _, t := range cl.torrents {
472 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
473 func (cl *Client) rejectAccepted(conn net.Conn) error {
475 return errors.New("don't want conns right now")
477 ra := conn.RemoteAddr()
478 if rip := addrIpOrNil(ra); rip != nil {
479 if cl.config.DisableIPv4Peers && rip.To4() != nil {
480 return errors.New("ipv4 peers disabled")
482 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
483 return errors.New("ipv4 disabled")
485 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
486 return errors.New("ipv6 disabled")
488 if cl.rateLimitAccept(rip) {
489 return errors.New("source IP accepted rate limited")
491 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
492 return errors.New("bad source addr")
498 func (cl *Client) acceptConnections(l Listener) {
500 conn, err := l.Accept()
501 torrent.Add("client listener accepts", 1)
502 conn = pproffd.WrapNetConn(conn)
504 closed := cl.closed.IsSet()
506 if !closed && conn != nil {
507 reject = cl.rejectAccepted(conn)
517 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
522 torrent.Add("rejected accepted connections", 1)
523 cl.logger.LazyLog(log.Debug, func() log.Msg {
524 return log.Fmsg("rejecting accepted conn: %v", reject)
528 go cl.incomingConnection(conn)
530 cl.logger.LazyLog(log.Debug, func() log.Msg {
531 return log.Fmsg("accepted %q connection at %q from %q",
537 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
538 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
539 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
544 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
545 func regularNetConnPeerConnConnString(nc net.Conn) string {
546 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
549 func (cl *Client) incomingConnection(nc net.Conn) {
551 if tc, ok := nc.(*net.TCPConn); ok {
554 c := cl.newConnection(nc, false, nc.RemoteAddr(), nc.RemoteAddr().Network(),
555 regularNetConnPeerConnConnString(nc))
561 c.Discovery = PeerSourceIncoming
562 cl.runReceivedConn(c)
565 // Returns a handle to the given torrent, if it's present in the client.
566 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
569 t, ok = cl.torrents[ih]
573 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
574 return cl.torrents[ih]
577 type DialResult struct {
582 func countDialResult(err error) {
584 torrent.Add("successful dials", 1)
586 torrent.Add("unsuccessful dials", 1)
590 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
591 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
592 if ret < minDialTimeout {
598 // Returns whether an address is known to connect to a client with our own ID.
599 func (cl *Client) dopplegangerAddr(addr string) bool {
600 _, ok := cl.dopplegangerAddrs[addr]
604 // Returns a connection over UTP or TCP, whichever is first to connect.
605 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
606 return DialFirst(ctx, addr, cl.dialers)
609 // Returns a connection over UTP or TCP, whichever is first to connect.
610 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
612 t := perf.NewTimer(perf.CallerName(0))
615 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
617 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
621 ctx, cancel := context.WithCancel(ctx)
622 // As soon as we return one connection, cancel the others.
625 resCh := make(chan DialResult, left)
626 for _, _s := range dialers {
631 dialFromSocket(ctx, s, addr),
636 // Wait for a successful connection.
638 defer perf.ScopeTimer()()
639 for ; left > 0 && res.Conn == nil; left-- {
643 // There are still incompleted dials.
645 for ; left > 0; left-- {
646 conn := (<-resCh).Conn
653 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
658 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
659 c, err := s.Dial(ctx, addr)
660 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
661 // it now in case we close the connection forthwith.
662 if tc, ok := c.(*net.TCPConn); ok {
669 func forgettableDialError(err error) bool {
670 return strings.Contains(err.Error(), "no suitable address found")
673 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
674 if _, ok := t.halfOpen[addr]; !ok {
675 panic("invariant broken")
677 delete(t.halfOpen, addr)
679 for _, t := range cl.torrents {
684 // Performs initiator handshakes and returns a connection. Returns nil *connection if no connection
685 // for valid reasons.
686 func (cl *Client) initiateProtocolHandshakes(
690 outgoing, encryptHeader bool,
691 remoteAddr PeerRemoteAddr,
692 network, connString string,
694 c *PeerConn, err error,
696 c = cl.newConnection(nc, outgoing, remoteAddr, network, connString)
697 c.headerEncrypted = encryptHeader
698 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
700 dl, ok := ctx.Deadline()
704 err = nc.SetDeadline(dl)
708 err = cl.initiateHandshakes(c, t)
712 // Returns nil connection and nil error if no connection could be established for valid reasons.
713 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
714 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
717 return t.dialTimeout()
720 dr := cl.dialFirst(dialCtx, addr.String())
723 if dialCtx.Err() != nil {
724 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
726 return nil, errors.New("dial failed")
728 c, err := cl.initiateProtocolHandshakes(context.Background(), nc, t, true, obfuscatedHeader, addr, dr.Dialer.DialerNetwork(), regularNetConnPeerConnConnString(nc))
735 // Returns nil connection and nil error if no connection could be established
736 // for valid reasons.
737 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
738 torrent.Add("establish outgoing connection", 1)
739 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
740 c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
742 torrent.Add("initiated conn with preferred header obfuscation", 1)
745 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
746 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
747 // We should have just tried with the preferred header obfuscation. If it was required,
748 // there's nothing else to try.
751 // Try again with encryption if we didn't earlier, or without if we did.
752 c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
754 torrent.Add("initiated conn with fallback header obfuscation", 1)
756 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
760 // Called to dial out and run a connection. The addr we're given is already
761 // considered half-open.
762 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
763 cl.dialRateLimiter.Wait(context.Background())
764 c, err := cl.establishOutgoingConn(t, addr)
766 c.conn.SetWriteDeadline(time.Time{})
770 // Don't release lock between here and addPeerConn, unless it's for
772 cl.noLongerHalfOpen(t, addr.String())
775 cl.logger.Printf("error establishing outgoing connection to %v: %v", addr, err)
782 t.runHandshookConnLoggingErr(c)
785 // The port number for incoming peer connections. 0 if the client isn't listening.
786 func (cl *Client) incomingPeerPort() int {
787 return cl.LocalPort()
790 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
791 if c.headerEncrypted {
794 rw, c.cryptoMethod, err = mse.InitiateHandshake(
801 cl.config.CryptoProvides,
805 return fmt.Errorf("header obfuscation handshake: %w", err)
808 ih, err := cl.connBtHandshake(c, &t.infoHash)
810 return fmt.Errorf("bittorrent protocol handshake: %w", err)
812 if ih != t.infoHash {
813 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
818 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
819 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
820 func (cl *Client) forSkeys(f func([]byte) bool) {
823 if false { // Emulate the bug from #114
825 for ih := range cl.torrents {
829 for range cl.torrents {
836 for ih := range cl.torrents {
843 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
844 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
850 // Do encryption and bittorrent handshakes as receiver.
851 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
852 defer perf.ScopeTimerErr(&err)()
854 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
856 if err == nil || err == mse.ErrNoSecretKeyMatch {
857 if c.headerEncrypted {
858 torrent.Add("handshakes received encrypted", 1)
860 torrent.Add("handshakes received unencrypted", 1)
863 torrent.Add("handshakes received with error while handling encryption", 1)
866 if err == mse.ErrNoSecretKeyMatch {
871 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
872 err = errors.New("connection does not have required header obfuscation")
875 ih, err := cl.connBtHandshake(c, nil)
877 return nil, fmt.Errorf("during bt handshake: %w", err)
885 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
889 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
890 &successfulPeerWireProtocolHandshakePeerReservedBytes)
893 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
894 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
898 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
900 c.PeerExtensionBytes = res.PeerExtensionBits
901 c.PeerID = res.PeerID
902 c.completedHandshake = time.Now()
903 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
909 func (cl *Client) runReceivedConn(c *PeerConn) {
910 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
914 t, err := cl.receiveHandshakes(c)
916 cl.logger.LazyLog(log.Debug, func() log.Msg {
918 "error receiving handshakes on %v: %s", c, err,
920 "network", c.Network,
923 torrent.Add("error receiving handshake", 1)
925 cl.onBadAccept(c.RemoteAddr)
930 torrent.Add("received handshake for unloaded torrent", 1)
931 cl.logger.LazyLog(log.Debug, func() log.Msg {
932 return log.Fmsg("received handshake for unloaded torrent")
935 cl.onBadAccept(c.RemoteAddr)
939 torrent.Add("received handshake for loaded torrent", 1)
940 c.conn.SetWriteDeadline(time.Time{})
943 t.runHandshookConnLoggingErr(c)
946 // Client lock must be held before entering this.
947 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
949 for i, b := range cl.config.MinPeerExtensions {
950 if c.PeerExtensionBytes[i]&b != b {
951 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
954 if c.PeerID == cl.peerID {
957 addr := c.RemoteAddr.String()
958 cl.dopplegangerAddrs[addr] = struct{}{}
960 // Because the remote address is not necessarily the same as its client's torrent listen
961 // address, we won't record the remote address as a doppleganger. Instead, the initiator
962 // can record *us* as the doppleganger.
964 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
967 c.r = deadlineReader{c.conn, c.r}
968 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
969 if connIsIpv6(c.conn) {
970 torrent.Add("completed handshake over ipv6", 1)
972 if err := t.addPeerConn(c); err != nil {
973 return fmt.Errorf("adding connection: %w", err)
975 defer t.dropConnection(c)
977 cl.sendInitialMessages(c, t)
978 c.initUpdateRequestsTimer()
979 err := c.mainReadLoop()
981 return fmt.Errorf("main read loop: %w", err)
988 func (p *Peer) initUpdateRequestsTimer() {
990 if p.updateRequestsTimer != nil {
991 panic(p.updateRequestsTimer)
994 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
997 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
999 func (c *Peer) updateRequestsTimerFunc() {
1001 defer c.locker().Unlock()
1002 if c.closed.IsSet() {
1005 if c.isLowOnRequests() {
1006 // If there are no outstanding requests, then a request update should have already run.
1009 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1010 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1011 // already been fired.
1012 torrent.Add("spurious timer requests updates", 1)
1015 c.updateRequests(peerUpdateRequestsTimerReason)
1018 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1019 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1020 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1021 const localClientReqq = 1 << 5
1023 // See the order given in Transmission's tr_peerMsgsNew.
1024 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1025 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1026 conn.write(pp.Message{
1028 ExtendedID: pp.HandshakeExtendedID,
1029 ExtendedPayload: func() []byte {
1030 msg := pp.ExtendedHandshakeMessage{
1031 M: map[pp.ExtensionName]pp.ExtensionNumber{
1032 pp.ExtensionNameMetadata: metadataExtendedId,
1034 V: cl.config.ExtendedHandshakeClientVersion,
1035 Reqq: localClientReqq,
1036 YourIp: pp.CompactIp(conn.remoteIp()),
1037 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1038 Port: cl.incomingPeerPort(),
1039 MetadataSize: torrent.metadataSize(),
1040 // TODO: We can figured these out specific to the socket
1042 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1043 Ipv6: cl.config.PublicIp6.To16(),
1045 if !cl.config.DisablePEX {
1046 msg.M[pp.ExtensionNamePex] = pexExtendedId
1048 return bencode.MustMarshal(msg)
1053 if conn.fastEnabled() {
1054 if torrent.haveAllPieces() {
1055 conn.write(pp.Message{Type: pp.HaveAll})
1056 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1058 } else if !torrent.haveAnyPieces() {
1059 conn.write(pp.Message{Type: pp.HaveNone})
1060 conn.sentHaves.Clear()
1066 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1067 conn.write(pp.Message{
1074 func (cl *Client) dhtPort() (ret uint16) {
1075 if len(cl.dhtServers) == 0 {
1078 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1081 func (cl *Client) haveDhtServer() bool {
1082 return len(cl.dhtServers) > 0
1085 // Process incoming ut_metadata message.
1086 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1087 var d pp.ExtendedMetadataRequestMsg
1088 err := bencode.Unmarshal(payload, &d)
1089 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1090 } else if err != nil {
1091 return fmt.Errorf("error unmarshalling bencode: %s", err)
1095 case pp.DataMetadataExtensionMsgType:
1096 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1097 if !c.requestedMetadataPiece(piece) {
1098 return fmt.Errorf("got unexpected piece %d", piece)
1100 c.metadataRequests[piece] = false
1101 begin := len(payload) - d.PieceSize()
1102 if begin < 0 || begin >= len(payload) {
1103 return fmt.Errorf("data has bad offset in payload: %d", begin)
1105 t.saveMetadataPiece(piece, payload[begin:])
1106 c.lastUsefulChunkReceived = time.Now()
1107 err = t.maybeCompleteMetadata()
1109 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1110 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1111 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1112 // log consumers can filter for this message.
1113 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1116 case pp.RequestMetadataExtensionMsgType:
1117 if !t.haveMetadataPiece(piece) {
1118 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1121 start := (1 << 14) * piece
1122 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1123 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1125 case pp.RejectMetadataExtensionMsgType:
1128 return errors.New("unknown msg_type value")
1132 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1133 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1134 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1139 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1143 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1146 if _, ok := cl.ipBlockRange(ip); ok {
1149 ipAddr, ok := netip.AddrFromSlice(ip)
1153 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1159 // Return a Torrent ready for insertion into a Client.
1160 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1161 return cl.newTorrentOpt(AddTorrentOpts{
1163 Storage: specStorage,
1167 // Return a Torrent ready for insertion into a Client.
1168 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1169 // use provided storage, if provided
1170 storageClient := cl.defaultStorage
1171 if opts.Storage != nil {
1172 storageClient = storage.NewClient(opts.Storage)
1177 infoHash: opts.InfoHash,
1178 peers: prioritizedPeers{
1180 getPrio: func(p PeerInfo) peerPriority {
1182 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1185 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1187 halfOpen: make(map[string]PeerInfo),
1189 storageOpener: storageClient,
1190 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1192 metadataChanged: sync.Cond{
1195 webSeeds: make(map[string]*Peer),
1196 gotMetainfoC: make(chan struct{}),
1198 t.smartBanCache.Hash = sha1.Sum
1199 t.smartBanCache.Init()
1200 t.networkingEnabled.Set()
1201 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1202 t.sourcesLogger = t.logger.WithNames("sources")
1203 if opts.ChunkSize == 0 {
1204 opts.ChunkSize = defaultChunkSize
1206 t.setChunkSize(opts.ChunkSize)
1210 // A file-like handle to some torrent data resource.
1211 type Handle interface {
1218 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1219 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1222 // Adds a torrent by InfoHash with a custom Storage implementation.
1223 // If the torrent already exists then this Storage is ignored and the
1224 // existing torrent returned with `new` set to `false`
1225 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1228 t, ok := cl.torrents[infoHash]
1234 t = cl.newTorrent(infoHash, specStorage)
1235 cl.eachDhtServer(func(s DhtServer) {
1236 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1237 go t.dhtAnnouncer(s)
1240 cl.torrents[infoHash] = t
1241 cl.clearAcceptLimits()
1242 t.updateWantPeersEvent()
1243 // Tickle Client.waitAccept, new torrent may want conns.
1244 cl.event.Broadcast()
1248 // Adds a torrent by InfoHash with a custom Storage implementation.
1249 // If the torrent already exists then this Storage is ignored and the
1250 // existing torrent returned with `new` set to `false`
1251 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1252 infoHash := opts.InfoHash
1255 t, ok := cl.torrents[infoHash]
1261 t = cl.newTorrentOpt(opts)
1262 cl.eachDhtServer(func(s DhtServer) {
1263 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1264 go t.dhtAnnouncer(s)
1267 cl.torrents[infoHash] = t
1268 cl.clearAcceptLimits()
1269 t.updateWantPeersEvent()
1270 // Tickle Client.waitAccept, new torrent may want conns.
1271 cl.event.Broadcast()
1275 type AddTorrentOpts struct {
1277 Storage storage.ClientImpl
1278 ChunkSize pp.Integer
1281 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1282 // Torrent.MergeSpec.
1283 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1284 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1285 InfoHash: spec.InfoHash,
1286 Storage: spec.Storage,
1287 ChunkSize: spec.ChunkSize,
1291 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1293 modSpec.ChunkSize = 0
1295 err = t.MergeSpec(&modSpec)
1296 if err != nil && new {
1302 type stringAddr string
1304 var _ net.Addr = stringAddr("")
1306 func (stringAddr) Network() string { return "" }
1307 func (me stringAddr) String() string { return string(me) }
1309 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1310 // spec.DisallowDataDownload/Upload will be read and applied
1311 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1312 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1313 if spec.DisplayName != "" {
1314 t.SetDisplayName(spec.DisplayName)
1316 if spec.InfoBytes != nil {
1317 err := t.SetInfoBytes(spec.InfoBytes)
1323 cl.AddDhtNodes(spec.DhtNodes)
1324 t.UseSources(spec.Sources)
1327 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1328 for _, url := range spec.Webseeds {
1329 t.addWebSeed(url, spec.EncodeWebSeedUrl)
1331 for _, peerAddr := range spec.PeerAddrs {
1333 Addr: stringAddr(peerAddr),
1334 Source: PeerSourceDirect,
1338 if spec.ChunkSize != 0 {
1339 panic("chunk size cannot be changed for existing Torrent")
1341 t.addTrackers(spec.Trackers)
1343 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1344 t.dataUploadDisallowed = spec.DisallowDataUpload
1348 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1349 t, ok := cl.torrents[infoHash]
1351 err = fmt.Errorf("no such torrent")
1355 delete(cl.torrents, infoHash)
1359 func (cl *Client) allTorrentsCompleted() bool {
1360 for _, t := range cl.torrents {
1364 if !t.haveAllPieces() {
1371 // Returns true when all torrents are completely downloaded and false if the
1372 // client is stopped before that.
1373 func (cl *Client) WaitAll() bool {
1376 for !cl.allTorrentsCompleted() {
1377 if cl.closed.IsSet() {
1385 // Returns handles to all the torrents loaded in the Client.
1386 func (cl *Client) Torrents() []*Torrent {
1389 return cl.torrentsAsSlice()
1392 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1393 for _, t := range cl.torrents {
1394 ret = append(ret, t)
1399 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1400 spec, err := TorrentSpecFromMagnetUri(uri)
1404 T, _, err = cl.AddTorrentSpec(spec)
1408 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1409 ts, err := TorrentSpecFromMetaInfoErr(mi)
1413 T, _, err = cl.AddTorrentSpec(ts)
1417 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1418 mi, err := metainfo.LoadFromFile(filename)
1422 return cl.AddTorrent(mi)
1425 func (cl *Client) DhtServers() []DhtServer {
1426 return cl.dhtServers
1429 func (cl *Client) AddDhtNodes(nodes []string) {
1430 for _, n := range nodes {
1431 hmp := missinggo.SplitHostMaybePort(n)
1432 ip := net.ParseIP(hmp.Host)
1434 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1437 ni := krpc.NodeInfo{
1438 Addr: krpc.NodeAddr{
1443 cl.eachDhtServer(func(s DhtServer) {
1449 func (cl *Client) banPeerIP(ip net.IP) {
1450 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1451 // addresses directly to v4on6, which doesn't compare equal with v4.
1452 ipAddr, ok := netip.AddrFromSlice(ip)
1456 generics.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1457 for _, t := range cl.torrents {
1458 t.iterPeers(func(p *Peer) {
1459 if p.remoteIp().Equal(ip) {
1460 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1461 // Should this be a close?
1468 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr PeerRemoteAddr, network, connString string) (c *PeerConn) {
1477 PeerMaxRequests: 250,
1479 RemoteAddr: remoteAddr,
1481 callbacks: &cl.config.Callbacks,
1483 connString: connString,
1486 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1487 if remoteAddr != nil {
1488 netipAddrPort, err := netip.ParseAddrPort(remoteAddr.String())
1490 c.bannableAddr = Some(netipAddrPort.Addr())
1494 c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1495 c.setRW(connStatsReadWriter{nc, c})
1496 c.r = &rateLimitedReader{
1497 l: cl.config.DownloadRateLimiter,
1500 c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", remoteAddr, network, outgoing)
1501 for _, f := range cl.config.Callbacks.NewPeer {
1507 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1514 t.addPeers([]PeerInfo{{
1515 Addr: ipPortAddr{ip, port},
1516 Source: PeerSourceDhtAnnouncePeer,
1520 func firstNotNil(ips ...net.IP) net.IP {
1521 for _, ip := range ips {
1529 func (cl *Client) eachListener(f func(Listener) bool) {
1530 for _, s := range cl.listeners {
1537 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1538 for i := 0; i < len(cl.listeners); i += 1 {
1539 if ret = cl.listeners[i]; f(ret) {
1546 func (cl *Client) publicIp(peer net.IP) net.IP {
1547 // TODO: Use BEP 10 to determine how peers are seeing us.
1548 if peer.To4() != nil {
1550 cl.config.PublicIp4,
1551 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1556 cl.config.PublicIp6,
1557 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1561 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1562 l := cl.findListener(
1563 func(l Listener) bool {
1564 return f(addrIpOrNil(l.Addr()))
1570 return addrIpOrNil(l.Addr())
1573 // Our IP as a peer should see it.
1574 func (cl *Client) publicAddr(peer net.IP) IpPort {
1575 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1578 // ListenAddrs addresses currently being listened to.
1579 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1581 ret = make([]net.Addr, len(cl.listeners))
1582 for i := 0; i < len(cl.listeners); i += 1 {
1583 ret[i] = cl.listeners[i].Addr()
1589 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1590 ipa, ok := tryIpPortFromNetAddr(addr)
1594 ip := maskIpForAcceptLimiting(ipa.IP)
1595 if cl.acceptLimiter == nil {
1596 cl.acceptLimiter = make(map[ipStr]int)
1598 cl.acceptLimiter[ipStr(ip.String())]++
1601 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1602 if ip4 := ip.To4(); ip4 != nil {
1603 return ip4.Mask(net.CIDRMask(24, 32))
1608 func (cl *Client) clearAcceptLimits() {
1609 cl.acceptLimiter = nil
1612 func (cl *Client) acceptLimitClearer() {
1615 case <-cl.closed.Done():
1617 case <-time.After(15 * time.Minute):
1619 cl.clearAcceptLimits()
1625 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1626 if cl.config.DisableAcceptRateLimiting {
1629 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1632 func (cl *Client) rLock() {
1636 func (cl *Client) rUnlock() {
1640 func (cl *Client) lock() {
1644 func (cl *Client) unlock() {
1648 func (cl *Client) locker() *lockWithDeferreds {
1652 func (cl *Client) String() string {
1653 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1656 // Returns connection-level aggregate stats at the Client level. See the comment on
1657 // TorrentStats.ConnStats.
1658 func (cl *Client) ConnStats() ConnStats {
1659 return cl.stats.Copy()