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 g "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 "github.com/pion/datachannel"
38 "golang.org/x/time/rate"
40 "github.com/anacrolix/torrent/bencode"
41 "github.com/anacrolix/torrent/internal/limiter"
42 "github.com/anacrolix/torrent/iplist"
43 "github.com/anacrolix/torrent/metainfo"
44 "github.com/anacrolix/torrent/mse"
45 pp "github.com/anacrolix/torrent/peer_protocol"
46 request_strategy "github.com/anacrolix/torrent/request-strategy"
47 "github.com/anacrolix/torrent/storage"
48 "github.com/anacrolix/torrent/tracker"
49 "github.com/anacrolix/torrent/types/infohash"
50 "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 g.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 DialContext: cfg.HTTPDialContext,
208 // I think this value was observed from some webseeds. It seems reasonable to extend it
209 // to other uses of HTTP from the client.
215 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
217 cfg = NewDefaultClientConfig()
223 go cl.acceptLimitClearer()
232 storageImpl := cfg.DefaultStorage
233 if storageImpl == nil {
234 // We'd use mmap by default but HFS+ doesn't support sparse files.
235 storageImplCloser := storage.NewFile(cfg.DataDir)
236 cl.onClose = append(cl.onClose, func() {
237 if err := storageImplCloser.Close(); err != nil {
238 cl.logger.Printf("error closing default storage: %s", err)
241 storageImpl = storageImplCloser
243 cl.defaultStorage = storage.NewClient(storageImpl)
245 if cfg.PeerID != "" {
246 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
248 o := copy(cl.peerID[:], cfg.Bep20)
249 _, err = rand.Read(cl.peerID[o:])
251 panic("error generating peer id")
255 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
263 for _, _s := range sockets {
264 s := _s // Go is fucking retarded.
265 cl.onClose = append(cl.onClose, func() { go s.Close() })
266 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
267 cl.dialers = append(cl.dialers, s)
268 cl.listeners = append(cl.listeners, s)
269 if cl.config.AcceptPeerConnections {
270 go cl.acceptConnections(s)
277 for _, s := range sockets {
278 if pc, ok := s.(net.PacketConn); ok {
279 ds, err := cl.NewAnacrolixDhtServer(pc)
283 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
284 cl.onClose = append(cl.onClose, func() { ds.Close() })
289 cl.websocketTrackers = websocketTrackers{
292 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
295 t, ok := cl.torrents[infoHash]
297 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
299 return t.announceRequest(event), nil
301 Proxy: cl.config.HTTPProxy,
302 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
303 DialContext: cl.config.TrackerDialContext,
304 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
307 t, ok := cl.torrents[dcc.InfoHash]
309 cl.logger.WithDefaultLevel(log.Warning).Printf(
310 "got webrtc conn for unloaded torrent with infohash %x",
316 go t.onWebRtcConn(dc, dcc)
323 func (cl *Client) AddDhtServer(d DhtServer) {
324 cl.dhtServers = append(cl.dhtServers, d)
327 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
328 // given address for any Torrent.
329 func (cl *Client) AddDialer(d Dialer) {
332 cl.dialers = append(cl.dialers, d)
333 for _, t := range cl.torrents {
338 func (cl *Client) Listeners() []Listener {
342 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
344 func (cl *Client) AddListener(l Listener) {
345 cl.listeners = append(cl.listeners, l)
346 if cl.config.AcceptPeerConnections {
347 go cl.acceptConnections(l)
351 func (cl *Client) firewallCallback(net.Addr) bool {
353 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
356 torrent.Add("connections firewalled", 1)
358 torrent.Add("connections not firewalled", 1)
363 func (cl *Client) listenOnNetwork(n network) bool {
364 if n.Ipv4 && cl.config.DisableIPv4 {
367 if n.Ipv6 && cl.config.DisableIPv6 {
370 if n.Tcp && cl.config.DisableTCP {
373 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
379 func (cl *Client) listenNetworks() (ns []network) {
380 for _, n := range allPeerNetworks {
381 if cl.listenOnNetwork(n) {
388 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
389 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
390 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
391 cfg := dht.ServerConfig{
392 IPBlocklist: cl.ipBlockList,
394 OnAnnouncePeer: cl.onDHTAnnouncePeer,
395 PublicIP: func() net.IP {
396 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
397 return cl.config.PublicIp6
399 return cl.config.PublicIp4
401 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
402 OnQuery: cl.config.DHTOnQuery,
405 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
408 s, err = dht.NewServer(&cfg)
410 go s.TableMaintainer()
415 func (cl *Client) Closed() events.Done {
416 return cl.closed.Done()
419 func (cl *Client) eachDhtServer(f func(DhtServer)) {
420 for _, ds := range cl.dhtServers {
425 // Stops the client. All connections to peers are closed and all activity will come to a halt.
426 func (cl *Client) Close() (errs []error) {
427 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
429 for _, t := range cl.torrents {
430 err := t.close(&closeGroup)
432 errs = append(errs, err)
435 for i := range cl.onClose {
436 cl.onClose[len(cl.onClose)-1-i]()
441 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
445 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
446 if cl.ipBlockList == nil {
449 return cl.ipBlockList.Lookup(ip)
452 func (cl *Client) ipIsBlocked(ip net.IP) bool {
453 _, blocked := cl.ipBlockRange(ip)
457 func (cl *Client) wantConns() bool {
458 if cl.config.AlwaysWantConns {
461 for _, t := range cl.torrents {
462 if t.wantIncomingConns() {
469 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
470 func (cl *Client) rejectAccepted(conn net.Conn) error {
472 return errors.New("don't want conns right now")
474 ra := conn.RemoteAddr()
475 if rip := addrIpOrNil(ra); rip != nil {
476 if cl.config.DisableIPv4Peers && rip.To4() != nil {
477 return errors.New("ipv4 peers disabled")
479 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
480 return errors.New("ipv4 disabled")
482 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
483 return errors.New("ipv6 disabled")
485 if cl.rateLimitAccept(rip) {
486 return errors.New("source IP accepted rate limited")
488 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
489 return errors.New("bad source addr")
495 func (cl *Client) acceptConnections(l Listener) {
497 conn, err := l.Accept()
498 torrent.Add("client listener accepts", 1)
499 conn = pproffd.WrapNetConn(conn)
501 closed := cl.closed.IsSet()
503 if !closed && conn != nil {
504 reject = cl.rejectAccepted(conn)
514 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
519 torrent.Add("rejected accepted connections", 1)
520 cl.logger.LazyLog(log.Debug, func() log.Msg {
521 return log.Fmsg("rejecting accepted conn: %v", reject)
525 go cl.incomingConnection(conn)
527 cl.logger.LazyLog(log.Debug, func() log.Msg {
528 return log.Fmsg("accepted %q connection at %q from %q",
534 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
535 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
536 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
541 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
542 func regularNetConnPeerConnConnString(nc net.Conn) string {
543 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
546 func (cl *Client) incomingConnection(nc net.Conn) {
548 if tc, ok := nc.(*net.TCPConn); ok {
551 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
552 c := cl.newConnection(
556 remoteAddr: nc.RemoteAddr(),
557 localPublicAddr: cl.publicAddr(remoteAddr.IP),
558 network: nc.RemoteAddr().Network(),
559 connString: regularNetConnPeerConnConnString(nc),
566 c.Discovery = PeerSourceIncoming
567 cl.runReceivedConn(c)
570 // Returns a handle to the given torrent, if it's present in the client.
571 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
574 t, ok = cl.torrents[ih]
578 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
579 return cl.torrents[ih]
582 type DialResult struct {
587 func countDialResult(err error) {
589 torrent.Add("successful dials", 1)
591 torrent.Add("unsuccessful dials", 1)
595 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
596 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
597 if ret < minDialTimeout {
603 // Returns whether an address is known to connect to a client with our own ID.
604 func (cl *Client) dopplegangerAddr(addr string) bool {
605 _, ok := cl.dopplegangerAddrs[addr]
609 // Returns a connection over UTP or TCP, whichever is first to connect.
610 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
611 return DialFirst(ctx, addr, cl.dialers)
614 // Returns a connection over UTP or TCP, whichever is first to connect.
615 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
617 t := perf.NewTimer(perf.CallerName(0))
620 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
622 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
626 ctx, cancel := context.WithCancel(ctx)
627 // As soon as we return one connection, cancel the others.
630 resCh := make(chan DialResult, left)
631 for _, _s := range dialers {
636 dialFromSocket(ctx, s, addr),
641 // Wait for a successful connection.
643 defer perf.ScopeTimer()()
644 for ; left > 0 && res.Conn == nil; left-- {
648 // There are still incompleted dials.
650 for ; left > 0; left-- {
651 conn := (<-resCh).Conn
658 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
663 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
664 c, err := s.Dial(ctx, addr)
665 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
666 // it now in case we close the connection forthwith.
667 if tc, ok := c.(*net.TCPConn); ok {
674 func forgettableDialError(err error) bool {
675 return strings.Contains(err.Error(), "no suitable address found")
678 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
679 if _, ok := t.halfOpen[addr]; !ok {
680 panic("invariant broken")
682 delete(t.halfOpen, addr)
684 for _, t := range cl.torrents {
689 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
690 // for valid reasons.
691 func (cl *Client) initiateProtocolHandshakes(
696 newConnOpts newConnectionOpts,
698 c *PeerConn, err error,
700 c = cl.newConnection(nc, newConnOpts)
701 c.headerEncrypted = encryptHeader
702 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
704 dl, ok := ctx.Deadline()
708 err = nc.SetDeadline(dl)
712 err = cl.initiateHandshakes(c, t)
716 // Returns nil connection and nil error if no connection could be established for valid reasons.
717 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
718 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
721 return t.dialTimeout()
724 dr := cl.dialFirst(dialCtx, addr.String())
727 if dialCtx.Err() != nil {
728 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
730 return nil, errors.New("dial failed")
732 addrIpPort, _ := tryIpPortFromNetAddr(addr)
733 c, err := cl.initiateProtocolHandshakes(
734 context.Background(), nc, t, obfuscatedHeader,
738 // It would be possible to retrieve a public IP from the dialer used here?
739 localPublicAddr: cl.publicAddr(addrIpPort.IP),
740 network: dr.Dialer.DialerNetwork(),
741 connString: regularNetConnPeerConnConnString(nc),
749 // Returns nil connection and nil error if no connection could be established
750 // for valid reasons.
751 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
752 torrent.Add("establish outgoing connection", 1)
753 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
754 c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
756 torrent.Add("initiated conn with preferred header obfuscation", 1)
759 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
760 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
761 // We should have just tried with the preferred header obfuscation. If it was required,
762 // there's nothing else to try.
765 // Try again with encryption if we didn't earlier, or without if we did.
766 c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
768 torrent.Add("initiated conn with fallback header obfuscation", 1)
770 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
774 // Called to dial out and run a connection. The addr we're given is already
775 // considered half-open.
776 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
777 cl.dialRateLimiter.Wait(context.Background())
778 c, err := cl.establishOutgoingConn(t, addr)
780 c.conn.SetWriteDeadline(time.Time{})
784 // Don't release lock between here and addPeerConn, unless it's for
786 cl.noLongerHalfOpen(t, addr.String())
789 cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", addr, err)
796 t.runHandshookConnLoggingErr(c)
799 // The port number for incoming peer connections. 0 if the client isn't listening.
800 func (cl *Client) incomingPeerPort() int {
801 return cl.LocalPort()
804 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
805 if c.headerEncrypted {
808 rw, c.cryptoMethod, err = mse.InitiateHandshake(
815 cl.config.CryptoProvides,
819 return fmt.Errorf("header obfuscation handshake: %w", err)
822 ih, err := cl.connBtHandshake(c, &t.infoHash)
824 return fmt.Errorf("bittorrent protocol handshake: %w", err)
826 if ih != t.infoHash {
827 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
832 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
833 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
834 func (cl *Client) forSkeys(f func([]byte) bool) {
837 if false { // Emulate the bug from #114
839 for ih := range cl.torrents {
843 for range cl.torrents {
850 for ih := range cl.torrents {
857 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
858 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
864 // Do encryption and bittorrent handshakes as receiver.
865 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
866 defer perf.ScopeTimerErr(&err)()
868 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
870 if err == nil || err == mse.ErrNoSecretKeyMatch {
871 if c.headerEncrypted {
872 torrent.Add("handshakes received encrypted", 1)
874 torrent.Add("handshakes received unencrypted", 1)
877 torrent.Add("handshakes received with error while handling encryption", 1)
880 if err == mse.ErrNoSecretKeyMatch {
885 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
886 err = errors.New("connection does not have required header obfuscation")
889 ih, err := cl.connBtHandshake(c, nil)
891 return nil, fmt.Errorf("during bt handshake: %w", err)
899 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
903 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
904 &successfulPeerWireProtocolHandshakePeerReservedBytes)
907 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
908 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
912 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
914 c.PeerExtensionBytes = res.PeerExtensionBits
915 c.PeerID = res.PeerID
916 c.completedHandshake = time.Now()
917 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
923 func (cl *Client) runReceivedConn(c *PeerConn) {
924 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
928 t, err := cl.receiveHandshakes(c)
930 cl.logger.LazyLog(log.Debug, func() log.Msg {
932 "error receiving handshakes on %v: %s", c, err,
934 "network", c.Network,
937 torrent.Add("error receiving handshake", 1)
939 cl.onBadAccept(c.RemoteAddr)
944 torrent.Add("received handshake for unloaded torrent", 1)
945 cl.logger.LazyLog(log.Debug, func() log.Msg {
946 return log.Fmsg("received handshake for unloaded torrent")
949 cl.onBadAccept(c.RemoteAddr)
953 torrent.Add("received handshake for loaded torrent", 1)
954 c.conn.SetWriteDeadline(time.Time{})
957 t.runHandshookConnLoggingErr(c)
960 // Client lock must be held before entering this.
961 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
963 for i, b := range cl.config.MinPeerExtensions {
964 if c.PeerExtensionBytes[i]&b != b {
965 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
968 if c.PeerID == cl.peerID {
971 addr := c.RemoteAddr.String()
972 cl.dopplegangerAddrs[addr] = struct{}{}
974 // Because the remote address is not necessarily the same as its client's torrent listen
975 // address, we won't record the remote address as a doppleganger. Instead, the initiator
976 // can record *us* as the doppleganger.
978 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
981 c.r = deadlineReader{c.conn, c.r}
982 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
983 if connIsIpv6(c.conn) {
984 torrent.Add("completed handshake over ipv6", 1)
986 if err := t.addPeerConn(c); err != nil {
987 return fmt.Errorf("adding connection: %w", err)
989 defer t.dropConnection(c)
990 c.startMessageWriter()
991 cl.sendInitialMessages(c, t)
992 c.initUpdateRequestsTimer()
993 err := c.mainReadLoop()
995 return fmt.Errorf("main read loop: %w", err)
1002 func (p *Peer) initUpdateRequestsTimer() {
1004 if p.updateRequestsTimer != nil {
1005 panic(p.updateRequestsTimer)
1008 if enableUpdateRequestsTimer {
1009 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1013 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1015 func (c *Peer) updateRequestsTimerFunc() {
1017 defer c.locker().Unlock()
1018 if c.closed.IsSet() {
1021 if c.isLowOnRequests() {
1022 // If there are no outstanding requests, then a request update should have already run.
1025 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1026 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1027 // already been fired.
1028 torrent.Add("spurious timer requests updates", 1)
1031 c.updateRequests(peerUpdateRequestsTimerReason)
1034 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1035 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1036 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1037 const localClientReqq = 1024
1039 // See the order given in Transmission's tr_peerMsgsNew.
1040 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1041 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1042 conn.write(pp.Message{
1044 ExtendedID: pp.HandshakeExtendedID,
1045 ExtendedPayload: func() []byte {
1046 msg := pp.ExtendedHandshakeMessage{
1047 M: map[pp.ExtensionName]pp.ExtensionNumber{
1048 pp.ExtensionNameMetadata: metadataExtendedId,
1050 V: cl.config.ExtendedHandshakeClientVersion,
1051 Reqq: localClientReqq,
1052 YourIp: pp.CompactIp(conn.remoteIp()),
1053 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1054 Port: cl.incomingPeerPort(),
1055 MetadataSize: torrent.metadataSize(),
1056 // TODO: We can figure these out specific to the socket used.
1057 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1058 Ipv6: cl.config.PublicIp6.To16(),
1060 if !cl.config.DisablePEX {
1061 msg.M[pp.ExtensionNamePex] = pexExtendedId
1063 return bencode.MustMarshal(msg)
1068 if conn.fastEnabled() {
1069 if torrent.haveAllPieces() {
1070 conn.write(pp.Message{Type: pp.HaveAll})
1071 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1073 } else if !torrent.haveAnyPieces() {
1074 conn.write(pp.Message{Type: pp.HaveNone})
1075 conn.sentHaves.Clear()
1081 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1082 conn.write(pp.Message{
1089 func (cl *Client) dhtPort() (ret uint16) {
1090 if len(cl.dhtServers) == 0 {
1093 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1096 func (cl *Client) haveDhtServer() bool {
1097 return len(cl.dhtServers) > 0
1100 // Process incoming ut_metadata message.
1101 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1102 var d pp.ExtendedMetadataRequestMsg
1103 err := bencode.Unmarshal(payload, &d)
1104 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1105 } else if err != nil {
1106 return fmt.Errorf("error unmarshalling bencode: %s", err)
1110 case pp.DataMetadataExtensionMsgType:
1111 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1112 if !c.requestedMetadataPiece(piece) {
1113 return fmt.Errorf("got unexpected piece %d", piece)
1115 c.metadataRequests[piece] = false
1116 begin := len(payload) - d.PieceSize()
1117 if begin < 0 || begin >= len(payload) {
1118 return fmt.Errorf("data has bad offset in payload: %d", begin)
1120 t.saveMetadataPiece(piece, payload[begin:])
1121 c.lastUsefulChunkReceived = time.Now()
1122 err = t.maybeCompleteMetadata()
1124 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1125 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1126 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1127 // log consumers can filter for this message.
1128 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1131 case pp.RequestMetadataExtensionMsgType:
1132 if !t.haveMetadataPiece(piece) {
1133 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1136 start := (1 << 14) * piece
1137 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1138 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1140 case pp.RejectMetadataExtensionMsgType:
1143 return errors.New("unknown msg_type value")
1147 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1148 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1149 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1154 // Returns whether the IP address and port are considered "bad".
1155 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1156 if port == 0 || ip == nil {
1159 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1162 if _, ok := cl.ipBlockRange(ip); ok {
1165 ipAddr, ok := netip.AddrFromSlice(ip)
1169 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1175 // Return a Torrent ready for insertion into a Client.
1176 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1177 return cl.newTorrentOpt(AddTorrentOpts{
1179 Storage: specStorage,
1183 // Return a Torrent ready for insertion into a Client.
1184 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1185 // use provided storage, if provided
1186 storageClient := cl.defaultStorage
1187 if opts.Storage != nil {
1188 storageClient = storage.NewClient(opts.Storage)
1193 infoHash: opts.InfoHash,
1194 peers: prioritizedPeers{
1196 getPrio: func(p PeerInfo) peerPriority {
1198 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1201 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1203 halfOpen: make(map[string]PeerInfo),
1205 storageOpener: storageClient,
1206 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1208 metadataChanged: sync.Cond{
1211 webSeeds: make(map[string]*Peer),
1212 gotMetainfoC: make(chan struct{}),
1214 t.smartBanCache.Hash = sha1.Sum
1215 t.smartBanCache.Init()
1216 t.networkingEnabled.Set()
1217 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1218 t.sourcesLogger = t.logger.WithNames("sources")
1219 if opts.ChunkSize == 0 {
1220 opts.ChunkSize = defaultChunkSize
1222 t.setChunkSize(opts.ChunkSize)
1226 // A file-like handle to some torrent data resource.
1227 type Handle interface {
1234 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1235 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1238 // Adds a torrent by InfoHash with a custom Storage implementation.
1239 // If the torrent already exists then this Storage is ignored and the
1240 // existing torrent returned with `new` set to `false`
1241 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1244 t, ok := cl.torrents[infoHash]
1250 t = cl.newTorrent(infoHash, specStorage)
1251 cl.eachDhtServer(func(s DhtServer) {
1252 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1253 go t.dhtAnnouncer(s)
1256 cl.torrents[infoHash] = t
1257 cl.clearAcceptLimits()
1258 t.updateWantPeersEvent()
1259 // Tickle Client.waitAccept, new torrent may want conns.
1260 cl.event.Broadcast()
1264 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1265 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1266 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1267 infoHash := opts.InfoHash
1270 t, ok := cl.torrents[infoHash]
1276 t = cl.newTorrentOpt(opts)
1277 cl.eachDhtServer(func(s DhtServer) {
1278 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1279 go t.dhtAnnouncer(s)
1282 cl.torrents[infoHash] = t
1283 t.setInfoBytesLocked(opts.InfoBytes)
1284 cl.clearAcceptLimits()
1285 t.updateWantPeersEvent()
1286 // Tickle Client.waitAccept, new torrent may want conns.
1287 cl.event.Broadcast()
1291 type AddTorrentOpts struct {
1293 Storage storage.ClientImpl
1294 ChunkSize pp.Integer
1298 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1299 // Torrent.MergeSpec.
1300 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1301 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1302 InfoHash: spec.InfoHash,
1303 Storage: spec.Storage,
1304 ChunkSize: spec.ChunkSize,
1308 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1310 modSpec.ChunkSize = 0
1312 err = t.MergeSpec(&modSpec)
1313 if err != nil && new {
1319 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1320 // spec.DisallowDataDownload/Upload will be read and applied
1321 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1322 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1323 if spec.DisplayName != "" {
1324 t.SetDisplayName(spec.DisplayName)
1326 if spec.InfoBytes != nil {
1327 err := t.SetInfoBytes(spec.InfoBytes)
1333 cl.AddDhtNodes(spec.DhtNodes)
1334 t.UseSources(spec.Sources)
1337 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1338 for _, url := range spec.Webseeds {
1341 for _, peerAddr := range spec.PeerAddrs {
1343 Addr: StringAddr(peerAddr),
1344 Source: PeerSourceDirect,
1348 if spec.ChunkSize != 0 {
1349 panic("chunk size cannot be changed for existing Torrent")
1351 t.addTrackers(spec.Trackers)
1353 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1354 t.dataUploadDisallowed = spec.DisallowDataUpload
1358 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1359 t, ok := cl.torrents[infoHash]
1361 err = fmt.Errorf("no such torrent")
1365 delete(cl.torrents, infoHash)
1369 func (cl *Client) allTorrentsCompleted() bool {
1370 for _, t := range cl.torrents {
1374 if !t.haveAllPieces() {
1381 // Returns true when all torrents are completely downloaded and false if the
1382 // client is stopped before that.
1383 func (cl *Client) WaitAll() bool {
1386 for !cl.allTorrentsCompleted() {
1387 if cl.closed.IsSet() {
1395 // Returns handles to all the torrents loaded in the Client.
1396 func (cl *Client) Torrents() []*Torrent {
1399 return cl.torrentsAsSlice()
1402 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1403 for _, t := range cl.torrents {
1404 ret = append(ret, t)
1409 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1410 spec, err := TorrentSpecFromMagnetUri(uri)
1414 T, _, err = cl.AddTorrentSpec(spec)
1418 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1419 ts, err := TorrentSpecFromMetaInfoErr(mi)
1423 T, _, err = cl.AddTorrentSpec(ts)
1427 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1428 mi, err := metainfo.LoadFromFile(filename)
1432 return cl.AddTorrent(mi)
1435 func (cl *Client) DhtServers() []DhtServer {
1436 return cl.dhtServers
1439 func (cl *Client) AddDhtNodes(nodes []string) {
1440 for _, n := range nodes {
1441 hmp := missinggo.SplitHostMaybePort(n)
1442 ip := net.ParseIP(hmp.Host)
1444 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1447 ni := krpc.NodeInfo{
1448 Addr: krpc.NodeAddr{
1453 cl.eachDhtServer(func(s DhtServer) {
1459 func (cl *Client) banPeerIP(ip net.IP) {
1460 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1461 // addresses directly to v4on6, which doesn't compare equal with v4.
1462 ipAddr, ok := netip.AddrFromSlice(ip)
1466 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1467 for _, t := range cl.torrents {
1468 t.iterPeers(func(p *Peer) {
1469 if p.remoteIp().Equal(ip) {
1470 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1471 // Should this be a close?
1478 type newConnectionOpts struct {
1480 remoteAddr PeerRemoteAddr
1481 localPublicAddr peerLocalPublicAddr
1486 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1487 if opts.network == "" {
1488 panic(opts.remoteAddr)
1492 outgoing: opts.outgoing,
1495 PeerMaxRequests: 250,
1497 RemoteAddr: opts.remoteAddr,
1498 localPublicAddr: opts.localPublicAddr,
1499 Network: opts.network,
1500 callbacks: &cl.config.Callbacks,
1502 connString: opts.connString,
1505 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1506 c.initRequestState()
1507 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1508 if opts.remoteAddr != nil {
1509 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1511 c.bannableAddr = Some(netipAddrPort.Addr())
1515 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1516 c.setRW(connStatsReadWriter{nc, c})
1517 c.r = &rateLimitedReader{
1518 l: cl.config.DownloadRateLimiter,
1523 "new PeerConn %p [Client %p remoteAddr %v network %v outgoing %t]",
1524 c, cl, opts.remoteAddr, opts.network, opts.outgoing,
1526 for _, f := range cl.config.Callbacks.NewPeer {
1532 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1539 t.addPeers([]PeerInfo{{
1540 Addr: ipPortAddr{ip, port},
1541 Source: PeerSourceDhtAnnouncePeer,
1545 func firstNotNil(ips ...net.IP) net.IP {
1546 for _, ip := range ips {
1554 func (cl *Client) eachListener(f func(Listener) bool) {
1555 for _, s := range cl.listeners {
1562 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1563 for i := 0; i < len(cl.listeners); i += 1 {
1564 if ret = cl.listeners[i]; f(ret) {
1571 func (cl *Client) publicIp(peer net.IP) net.IP {
1572 // TODO: Use BEP 10 to determine how peers are seeing us.
1573 if peer.To4() != nil {
1575 cl.config.PublicIp4,
1576 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1581 cl.config.PublicIp6,
1582 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1586 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1587 l := cl.findListener(
1588 func(l Listener) bool {
1589 return f(addrIpOrNil(l.Addr()))
1595 return addrIpOrNil(l.Addr())
1598 // Our IP as a peer should see it.
1599 func (cl *Client) publicAddr(peer net.IP) IpPort {
1600 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1603 // ListenAddrs addresses currently being listened to.
1604 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1606 ret = make([]net.Addr, len(cl.listeners))
1607 for i := 0; i < len(cl.listeners); i += 1 {
1608 ret[i] = cl.listeners[i].Addr()
1614 func (cl *Client) PublicIPs() (ips []net.IP) {
1615 if ip := cl.config.PublicIp4; ip != nil {
1616 ips = append(ips, ip)
1618 if ip := cl.config.PublicIp6; ip != nil {
1619 ips = append(ips, ip)
1624 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1625 ipa, ok := tryIpPortFromNetAddr(addr)
1629 ip := maskIpForAcceptLimiting(ipa.IP)
1630 if cl.acceptLimiter == nil {
1631 cl.acceptLimiter = make(map[ipStr]int)
1633 cl.acceptLimiter[ipStr(ip.String())]++
1636 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1637 if ip4 := ip.To4(); ip4 != nil {
1638 return ip4.Mask(net.CIDRMask(24, 32))
1643 func (cl *Client) clearAcceptLimits() {
1644 cl.acceptLimiter = nil
1647 func (cl *Client) acceptLimitClearer() {
1650 case <-cl.closed.Done():
1652 case <-time.After(15 * time.Minute):
1654 cl.clearAcceptLimits()
1660 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1661 if cl.config.DisableAcceptRateLimiting {
1664 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1667 func (cl *Client) rLock() {
1671 func (cl *Client) rUnlock() {
1675 func (cl *Client) lock() {
1679 func (cl *Client) unlock() {
1683 func (cl *Client) locker() *lockWithDeferreds {
1687 func (cl *Client) String() string {
1688 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1691 // Returns connection-level aggregate stats at the Client level. See the comment on
1692 // TorrentStats.ConnStats.
1693 func (cl *Client) ConnStats() ConnStats {
1694 return cl.stats.Copy()