22 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
24 "github.com/anacrolix/chansync"
25 "github.com/anacrolix/chansync/events"
26 "github.com/anacrolix/dht/v2"
27 "github.com/anacrolix/dht/v2/krpc"
28 . "github.com/anacrolix/generics"
29 g "github.com/anacrolix/generics"
30 "github.com/anacrolix/log"
31 "github.com/anacrolix/missinggo/perf"
32 "github.com/anacrolix/missinggo/v2"
33 "github.com/anacrolix/missinggo/v2/bitmap"
34 "github.com/anacrolix/missinggo/v2/pproffd"
35 "github.com/anacrolix/sync"
36 "github.com/davecgh/go-spew/spew"
37 "github.com/dustin/go-humanize"
38 gbtree "github.com/google/btree"
39 "github.com/pion/datachannel"
40 "golang.org/x/time/rate"
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 request_strategy "github.com/anacrolix/torrent/request-strategy"
49 "github.com/anacrolix/torrent/storage"
50 "github.com/anacrolix/torrent/tracker"
51 "github.com/anacrolix/torrent/types/infohash"
52 "github.com/anacrolix/torrent/webtorrent"
55 // Clients contain zero or more Torrents. A Client manages a blocklist, the
56 // TCP/UDP protocol ports, and DHT as desired.
58 // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
64 closed chansync.SetOnce
70 defaultStorage *storage.Client
74 dhtServers []DhtServer
75 ipBlockList iplist.Ranger
77 // Set of addresses that have our client ID. This intentionally will
78 // include ourselves if we end up trying to connect to our own address
79 // through legitimate channels.
80 dopplegangerAddrs map[string]struct{}
81 badPeerIPs map[netip.Addr]struct{}
82 torrents map[InfoHash]*Torrent
83 pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
85 acceptLimiter map[ipStr]int
86 dialRateLimiter *rate.Limiter
89 websocketTrackers websocketTrackers
91 activeAnnounceLimiter limiter.Instance
92 httpClient *http.Client
97 func (cl *Client) BadPeerIPs() (ips []string) {
99 ips = cl.badPeerIPsLocked()
104 func (cl *Client) badPeerIPsLocked() (ips []string) {
105 ips = make([]string, len(cl.badPeerIPs))
107 for k := range cl.badPeerIPs {
114 func (cl *Client) PeerID() PeerID {
118 // Returns the port number for the first listener that has one. No longer assumes that all port
119 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
121 func (cl *Client) LocalPort() (port int) {
122 for i := 0; i < len(cl.listeners); i += 1 {
123 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
130 func writeDhtServerStatus(w io.Writer, s DhtServer) {
131 dhtStats := s.Stats()
132 fmt.Fprintf(w, " ID: %x\n", s.ID())
133 spew.Fdump(w, dhtStats)
136 // Writes out a human readable status of the client, such as for writing to a
138 func (cl *Client) WriteStatus(_w io.Writer) {
141 w := bufio.NewWriter(_w)
143 fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
144 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
145 fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
146 fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
147 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
148 cl.eachDhtServer(func(s DhtServer) {
149 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
150 writeDhtServerStatus(w, s)
152 spew.Fdump(w, &cl.stats)
153 torrentsSlice := cl.torrentsAsSlice()
154 fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
156 sort.Slice(torrentsSlice, func(l, r int) bool {
157 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
159 for _, t := range torrentsSlice {
161 fmt.Fprint(w, "<unknown name>")
163 fmt.Fprint(w, t.name())
169 "%f%% of %d bytes (%s)",
170 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
172 humanize.Bytes(uint64(t.length())))
174 w.WriteString("<missing metainfo>")
182 func (cl *Client) initLogger() {
183 logger := cl.config.Logger
188 logger = logger.FilterLevel(log.Debug)
190 cl.logger = logger.WithValues(cl)
193 func (cl *Client) announceKey() int32 {
194 return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
197 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
198 func (cl *Client) init(cfg *ClientConfig) {
200 g.MakeMap(&cl.dopplegangerAddrs)
201 cl.torrents = make(map[metainfo.Hash]*Torrent)
202 cl.dialRateLimiter = rate.NewLimiter(10, 10)
203 cl.activeAnnounceLimiter.SlotsPerKey = 2
204 cl.event.L = cl.locker()
205 cl.ipBlockList = cfg.IPBlocklist
206 cl.httpClient = &http.Client{
207 Transport: &http.Transport{
208 Proxy: cfg.HTTPProxy,
209 DialContext: cfg.HTTPDialContext,
210 // I think this value was observed from some webseeds. It seems reasonable to extend it
211 // to other uses of HTTP from the client.
217 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
219 cfg = NewDefaultClientConfig()
225 go cl.acceptLimitClearer()
234 storageImpl := cfg.DefaultStorage
235 if storageImpl == nil {
236 // We'd use mmap by default but HFS+ doesn't support sparse files.
237 storageImplCloser := storage.NewFile(cfg.DataDir)
238 cl.onClose = append(cl.onClose, func() {
239 if err := storageImplCloser.Close(); err != nil {
240 cl.logger.Printf("error closing default storage: %s", err)
243 storageImpl = storageImplCloser
245 cl.defaultStorage = storage.NewClient(storageImpl)
247 if cfg.PeerID != "" {
248 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
250 o := copy(cl.peerID[:], cfg.Bep20)
251 _, err = rand.Read(cl.peerID[o:])
253 panic("error generating peer id")
257 sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
265 for _, _s := range sockets {
266 s := _s // Go is fucking retarded.
267 cl.onClose = append(cl.onClose, func() { go s.Close() })
268 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
269 cl.dialers = append(cl.dialers, s)
270 cl.listeners = append(cl.listeners, s)
271 if cl.config.AcceptPeerConnections {
272 go cl.acceptConnections(s)
279 for _, s := range sockets {
280 if pc, ok := s.(net.PacketConn); ok {
281 ds, err := cl.NewAnacrolixDhtServer(pc)
285 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
286 cl.onClose = append(cl.onClose, func() { ds.Close() })
291 cl.websocketTrackers = websocketTrackers{
294 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
297 t, ok := cl.torrents[infoHash]
299 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
301 return t.announceRequest(event), nil
303 Proxy: cl.config.HTTPProxy,
304 WebsocketTrackerHttpHeader: cl.config.WebsocketTrackerHttpHeader,
305 DialContext: cl.config.TrackerDialContext,
306 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
309 t, ok := cl.torrents[dcc.InfoHash]
311 cl.logger.WithDefaultLevel(log.Warning).Printf(
312 "got webrtc conn for unloaded torrent with infohash %x",
318 go t.onWebRtcConn(dc, dcc)
325 func (cl *Client) AddDhtServer(d DhtServer) {
326 cl.dhtServers = append(cl.dhtServers, d)
329 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
330 // given address for any Torrent.
331 func (cl *Client) AddDialer(d Dialer) {
334 cl.dialers = append(cl.dialers, d)
335 for _, t := range cl.torrents {
340 func (cl *Client) Listeners() []Listener {
344 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
346 func (cl *Client) AddListener(l Listener) {
347 cl.listeners = append(cl.listeners, l)
348 if cl.config.AcceptPeerConnections {
349 go cl.acceptConnections(l)
353 func (cl *Client) firewallCallback(net.Addr) bool {
355 block := !cl.wantConns() || !cl.config.AcceptPeerConnections
358 torrent.Add("connections firewalled", 1)
360 torrent.Add("connections not firewalled", 1)
365 func (cl *Client) listenOnNetwork(n network) bool {
366 if n.Ipv4 && cl.config.DisableIPv4 {
369 if n.Ipv6 && cl.config.DisableIPv6 {
372 if n.Tcp && cl.config.DisableTCP {
375 if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
381 func (cl *Client) listenNetworks() (ns []network) {
382 for _, n := range allPeerNetworks {
383 if cl.listenOnNetwork(n) {
390 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
391 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
392 logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
393 cfg := dht.ServerConfig{
394 IPBlocklist: cl.ipBlockList,
396 OnAnnouncePeer: cl.onDHTAnnouncePeer,
397 PublicIP: func() net.IP {
398 if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
399 return cl.config.PublicIp6
401 return cl.config.PublicIp4
403 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
404 OnQuery: cl.config.DHTOnQuery,
407 if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
410 s, err = dht.NewServer(&cfg)
412 go s.TableMaintainer()
417 func (cl *Client) Closed() events.Done {
418 return cl.closed.Done()
421 func (cl *Client) eachDhtServer(f func(DhtServer)) {
422 for _, ds := range cl.dhtServers {
427 // Stops the client. All connections to peers are closed and all activity will come to a halt.
428 func (cl *Client) Close() (errs []error) {
429 var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
431 for _, t := range cl.torrents {
432 err := t.close(&closeGroup)
434 errs = append(errs, err)
437 for i := range cl.onClose {
438 cl.onClose[len(cl.onClose)-1-i]()
443 closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
447 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
448 if cl.ipBlockList == nil {
451 return cl.ipBlockList.Lookup(ip)
454 func (cl *Client) ipIsBlocked(ip net.IP) bool {
455 _, blocked := cl.ipBlockRange(ip)
459 func (cl *Client) wantConns() bool {
460 if cl.config.AlwaysWantConns {
463 for _, t := range cl.torrents {
464 if t.wantIncomingConns() {
471 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
472 func (cl *Client) rejectAccepted(conn net.Conn) error {
474 return errors.New("don't want conns right now")
476 ra := conn.RemoteAddr()
477 if rip := addrIpOrNil(ra); rip != nil {
478 if cl.config.DisableIPv4Peers && rip.To4() != nil {
479 return errors.New("ipv4 peers disabled")
481 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
482 return errors.New("ipv4 disabled")
484 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
485 return errors.New("ipv6 disabled")
487 if cl.rateLimitAccept(rip) {
488 return errors.New("source IP accepted rate limited")
490 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
491 return errors.New("bad source addr")
497 func (cl *Client) acceptConnections(l Listener) {
499 conn, err := l.Accept()
500 torrent.Add("client listener accepts", 1)
501 conn = pproffd.WrapNetConn(conn)
503 closed := cl.closed.IsSet()
505 if !closed && conn != nil {
506 reject = cl.rejectAccepted(conn)
516 log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
521 torrent.Add("rejected accepted connections", 1)
522 cl.logger.LazyLog(log.Debug, func() log.Msg {
523 return log.Fmsg("rejecting accepted conn: %v", reject)
527 go cl.incomingConnection(conn)
529 cl.logger.LazyLog(log.Debug, func() log.Msg {
530 return log.Fmsg("accepted %q connection at %q from %q",
536 torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
537 torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
538 torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
543 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
544 func regularNetConnPeerConnConnString(nc net.Conn) string {
545 return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
548 func (cl *Client) incomingConnection(nc net.Conn) {
550 if tc, ok := nc.(*net.TCPConn); ok {
553 remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
554 c := cl.newConnection(
558 remoteAddr: nc.RemoteAddr(),
559 localPublicAddr: cl.publicAddr(remoteAddr.IP),
560 network: nc.RemoteAddr().Network(),
561 connString: regularNetConnPeerConnConnString(nc),
568 c.Discovery = PeerSourceIncoming
569 cl.runReceivedConn(c)
572 // Returns a handle to the given torrent, if it's present in the client.
573 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
576 t, ok = cl.torrents[ih]
580 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
581 return cl.torrents[ih]
584 type DialResult struct {
589 func countDialResult(err error) {
591 torrent.Add("successful dials", 1)
593 torrent.Add("unsuccessful dials", 1)
597 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
598 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
599 if ret < minDialTimeout {
605 // Returns whether an address is known to connect to a client with our own ID.
606 func (cl *Client) dopplegangerAddr(addr string) bool {
607 _, ok := cl.dopplegangerAddrs[addr]
611 // Returns a connection over UTP or TCP, whichever is first to connect.
612 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
613 return DialFirst(ctx, addr, cl.dialers)
616 // Returns a connection over UTP or TCP, whichever is first to connect.
617 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
619 t := perf.NewTimer(perf.CallerName(0))
622 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
624 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
628 ctx, cancel := context.WithCancel(ctx)
629 // As soon as we return one connection, cancel the others.
632 resCh := make(chan DialResult, left)
633 for _, _s := range dialers {
638 dialFromSocket(ctx, s, addr),
643 // Wait for a successful connection.
645 defer perf.ScopeTimer()()
646 for ; left > 0 && res.Conn == nil; left-- {
650 // There are still incompleted dials.
652 for ; left > 0; left-- {
653 conn := (<-resCh).Conn
660 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
665 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
666 c, err := s.Dial(ctx, addr)
667 // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
668 // it now in case we close the connection forthwith.
669 if tc, ok := c.(*net.TCPConn); ok {
676 func forgettableDialError(err error) bool {
677 return strings.Contains(err.Error(), "no suitable address found")
680 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
681 if _, ok := t.halfOpen[addr]; !ok {
682 panic("invariant broken")
684 delete(t.halfOpen, addr)
686 for _, t := range cl.torrents {
691 // Performs initiator handshakes and returns a connection. Returns nil *PeerConn if no connection
692 // for valid reasons.
693 func (cl *Client) initiateProtocolHandshakes(
698 newConnOpts newConnectionOpts,
700 c *PeerConn, err error,
702 c = cl.newConnection(nc, newConnOpts)
703 c.headerEncrypted = encryptHeader
704 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
706 dl, ok := ctx.Deadline()
710 err = nc.SetDeadline(dl)
714 err = cl.initiateHandshakes(c, t)
718 // Returns nil connection and nil error if no connection could be established for valid reasons.
719 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
720 dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
723 return t.dialTimeout()
726 dr := cl.dialFirst(dialCtx, addr.String())
729 if dialCtx.Err() != nil {
730 return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
732 return nil, errors.New("dial failed")
734 addrIpPort, _ := tryIpPortFromNetAddr(addr)
735 c, err := cl.initiateProtocolHandshakes(
736 context.Background(), nc, t, obfuscatedHeader,
740 // It would be possible to retrieve a public IP from the dialer used here?
741 localPublicAddr: cl.publicAddr(addrIpPort.IP),
742 network: dr.Dialer.DialerNetwork(),
743 connString: regularNetConnPeerConnConnString(nc),
751 // Returns nil connection and nil error if no connection could be established
752 // for valid reasons.
753 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
754 torrent.Add("establish outgoing connection", 1)
755 obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
756 c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
758 torrent.Add("initiated conn with preferred header obfuscation", 1)
761 // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
762 if cl.config.HeaderObfuscationPolicy.RequirePreferred {
763 // We should have just tried with the preferred header obfuscation. If it was required,
764 // there's nothing else to try.
767 // Try again with encryption if we didn't earlier, or without if we did.
768 c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
770 torrent.Add("initiated conn with fallback header obfuscation", 1)
772 // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
776 // Called to dial out and run a connection. The addr we're given is already
777 // considered half-open.
778 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
779 cl.dialRateLimiter.Wait(context.Background())
780 c, err := cl.establishOutgoingConn(t, addr)
782 c.conn.SetWriteDeadline(time.Time{})
786 // Don't release lock between here and addPeerConn, unless it's for
788 cl.noLongerHalfOpen(t, addr.String())
791 cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", addr, err)
798 t.runHandshookConnLoggingErr(c)
801 // The port number for incoming peer connections. 0 if the client isn't listening.
802 func (cl *Client) incomingPeerPort() int {
803 return cl.LocalPort()
806 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
807 if c.headerEncrypted {
810 rw, c.cryptoMethod, err = mse.InitiateHandshake(
817 cl.config.CryptoProvides,
821 return fmt.Errorf("header obfuscation handshake: %w", err)
824 ih, err := cl.connBtHandshake(c, &t.infoHash)
826 return fmt.Errorf("bittorrent protocol handshake: %w", err)
828 if ih != t.infoHash {
829 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
834 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
835 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
836 func (cl *Client) forSkeys(f func([]byte) bool) {
839 if false { // Emulate the bug from #114
841 for ih := range cl.torrents {
845 for range cl.torrents {
852 for ih := range cl.torrents {
859 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
860 if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
866 // Do encryption and bittorrent handshakes as receiver.
867 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
868 defer perf.ScopeTimerErr(&err)()
870 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
872 if err == nil || err == mse.ErrNoSecretKeyMatch {
873 if c.headerEncrypted {
874 torrent.Add("handshakes received encrypted", 1)
876 torrent.Add("handshakes received unencrypted", 1)
879 torrent.Add("handshakes received with error while handling encryption", 1)
882 if err == mse.ErrNoSecretKeyMatch {
887 if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
888 err = errors.New("connection does not have required header obfuscation")
891 ih, err := cl.connBtHandshake(c, nil)
893 return nil, fmt.Errorf("during bt handshake: %w", err)
901 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
905 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
906 &successfulPeerWireProtocolHandshakePeerReservedBytes)
909 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
910 res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
914 successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
916 c.PeerExtensionBytes = res.PeerExtensionBits
917 c.PeerID = res.PeerID
918 c.completedHandshake = time.Now()
919 if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
925 func (cl *Client) runReceivedConn(c *PeerConn) {
926 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
930 t, err := cl.receiveHandshakes(c)
932 cl.logger.LazyLog(log.Debug, func() log.Msg {
934 "error receiving handshakes on %v: %s", c, err,
936 "network", c.Network,
939 torrent.Add("error receiving handshake", 1)
941 cl.onBadAccept(c.RemoteAddr)
946 torrent.Add("received handshake for unloaded torrent", 1)
947 cl.logger.LazyLog(log.Debug, func() log.Msg {
948 return log.Fmsg("received handshake for unloaded torrent")
951 cl.onBadAccept(c.RemoteAddr)
955 torrent.Add("received handshake for loaded torrent", 1)
956 c.conn.SetWriteDeadline(time.Time{})
959 t.runHandshookConnLoggingErr(c)
962 // Client lock must be held before entering this.
963 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
965 for i, b := range cl.config.MinPeerExtensions {
966 if c.PeerExtensionBytes[i]&b != b {
967 return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
970 if c.PeerID == cl.peerID {
973 addr := c.RemoteAddr.String()
974 cl.dopplegangerAddrs[addr] = struct{}{}
976 // Because the remote address is not necessarily the same as its client's torrent listen
977 // address, we won't record the remote address as a doppleganger. Instead, the initiator
978 // can record *us* as the doppleganger.
980 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
983 c.r = deadlineReader{c.conn, c.r}
984 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
985 if connIsIpv6(c.conn) {
986 torrent.Add("completed handshake over ipv6", 1)
988 if err := t.addPeerConn(c); err != nil {
989 return fmt.Errorf("adding connection: %w", err)
991 defer t.dropConnection(c)
992 c.startMessageWriter()
993 cl.sendInitialMessages(c, t)
994 c.initUpdateRequestsTimer()
995 err := c.mainReadLoop()
997 return fmt.Errorf("main read loop: %w", err)
1004 func (p *Peer) initUpdateRequestsTimer() {
1006 if p.updateRequestsTimer != nil {
1007 panic(p.updateRequestsTimer)
1010 if enableUpdateRequestsTimer {
1011 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1015 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1017 func (c *Peer) updateRequestsTimerFunc() {
1019 defer c.locker().Unlock()
1020 if c.closed.IsSet() {
1023 if c.isLowOnRequests() {
1024 // If there are no outstanding requests, then a request update should have already run.
1027 if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1028 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1029 // already been fired.
1030 torrent.Add("spurious timer requests updates", 1)
1033 c.updateRequests(peerUpdateRequestsTimerReason)
1036 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1037 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1038 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1039 const localClientReqq = 1024
1041 // See the order given in Transmission's tr_peerMsgsNew.
1042 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1043 if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1044 conn.write(pp.Message{
1046 ExtendedID: pp.HandshakeExtendedID,
1047 ExtendedPayload: func() []byte {
1048 msg := pp.ExtendedHandshakeMessage{
1049 M: map[pp.ExtensionName]pp.ExtensionNumber{
1050 pp.ExtensionNameMetadata: metadataExtendedId,
1051 utHolepunch.ExtensionName: utHolepunchExtendedId,
1053 V: cl.config.ExtendedHandshakeClientVersion,
1054 Reqq: localClientReqq,
1055 YourIp: pp.CompactIp(conn.remoteIp()),
1056 Encryption: cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1057 Port: cl.incomingPeerPort(),
1058 MetadataSize: torrent.metadataSize(),
1059 // TODO: We can figure these out specific to the socket used.
1060 Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1061 Ipv6: cl.config.PublicIp6.To16(),
1063 if !cl.config.DisablePEX {
1064 msg.M[pp.ExtensionNamePex] = pexExtendedId
1066 return bencode.MustMarshal(msg)
1071 if conn.fastEnabled() {
1072 if torrent.haveAllPieces() {
1073 conn.write(pp.Message{Type: pp.HaveAll})
1074 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1076 } else if !torrent.haveAnyPieces() {
1077 conn.write(pp.Message{Type: pp.HaveNone})
1078 conn.sentHaves.Clear()
1084 if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1085 conn.write(pp.Message{
1092 func (cl *Client) dhtPort() (ret uint16) {
1093 if len(cl.dhtServers) == 0 {
1096 return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1099 func (cl *Client) haveDhtServer() bool {
1100 return len(cl.dhtServers) > 0
1103 // Process incoming ut_metadata message.
1104 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1105 var d pp.ExtendedMetadataRequestMsg
1106 err := bencode.Unmarshal(payload, &d)
1107 if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1108 } else if err != nil {
1109 return fmt.Errorf("error unmarshalling bencode: %s", err)
1113 case pp.DataMetadataExtensionMsgType:
1114 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1115 if !c.requestedMetadataPiece(piece) {
1116 return fmt.Errorf("got unexpected piece %d", piece)
1118 c.metadataRequests[piece] = false
1119 begin := len(payload) - d.PieceSize()
1120 if begin < 0 || begin >= len(payload) {
1121 return fmt.Errorf("data has bad offset in payload: %d", begin)
1123 t.saveMetadataPiece(piece, payload[begin:])
1124 c.lastUsefulChunkReceived = time.Now()
1125 err = t.maybeCompleteMetadata()
1127 // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1128 // don't know who to blame. TODO: Also errors can be returned here that aren't related
1129 // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1130 // log consumers can filter for this message.
1131 t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1134 case pp.RequestMetadataExtensionMsgType:
1135 if !t.haveMetadataPiece(piece) {
1136 c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1139 start := (1 << 14) * piece
1140 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1141 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1143 case pp.RejectMetadataExtensionMsgType:
1146 return errors.New("unknown msg_type value")
1150 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1151 if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1152 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1157 // Returns whether the IP address and port are considered "bad".
1158 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1159 if port == 0 || ip == nil {
1162 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1165 if _, ok := cl.ipBlockRange(ip); ok {
1168 ipAddr, ok := netip.AddrFromSlice(ip)
1172 if _, ok := cl.badPeerIPs[ipAddr]; ok {
1178 // Return a Torrent ready for insertion into a Client.
1179 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1180 return cl.newTorrentOpt(AddTorrentOpts{
1182 Storage: specStorage,
1186 // Return a Torrent ready for insertion into a Client.
1187 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1188 // use provided storage, if provided
1189 storageClient := cl.defaultStorage
1190 if opts.Storage != nil {
1191 storageClient = storage.NewClient(opts.Storage)
1196 infoHash: opts.InfoHash,
1197 peers: prioritizedPeers{
1199 getPrio: func(p PeerInfo) peerPriority {
1201 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1204 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1206 halfOpen: make(map[string]PeerInfo),
1208 storageOpener: storageClient,
1209 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1211 metadataChanged: sync.Cond{
1214 webSeeds: make(map[string]*Peer),
1215 gotMetainfoC: make(chan struct{}),
1217 t.smartBanCache.Hash = sha1.Sum
1218 t.smartBanCache.Init()
1219 t.networkingEnabled.Set()
1220 t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1221 t.sourcesLogger = t.logger.WithNames("sources")
1222 if opts.ChunkSize == 0 {
1223 opts.ChunkSize = defaultChunkSize
1225 t.setChunkSize(opts.ChunkSize)
1229 // A file-like handle to some torrent data resource.
1230 type Handle interface {
1237 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1238 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1241 // Adds a torrent by InfoHash with a custom Storage implementation.
1242 // If the torrent already exists then this Storage is ignored and the
1243 // existing torrent returned with `new` set to `false`
1244 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1247 t, ok := cl.torrents[infoHash]
1253 t = cl.newTorrent(infoHash, specStorage)
1254 cl.eachDhtServer(func(s DhtServer) {
1255 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1256 go t.dhtAnnouncer(s)
1259 cl.torrents[infoHash] = t
1260 cl.clearAcceptLimits()
1261 t.updateWantPeersEvent()
1262 // Tickle Client.waitAccept, new torrent may want conns.
1263 cl.event.Broadcast()
1267 // Adds a torrent by InfoHash with a custom Storage implementation. If the torrent already exists
1268 // then this Storage is ignored and the existing torrent returned with `new` set to `false`.
1269 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1270 infoHash := opts.InfoHash
1273 t, ok := cl.torrents[infoHash]
1279 t = cl.newTorrentOpt(opts)
1280 cl.eachDhtServer(func(s DhtServer) {
1281 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1282 go t.dhtAnnouncer(s)
1285 cl.torrents[infoHash] = t
1286 t.setInfoBytesLocked(opts.InfoBytes)
1287 cl.clearAcceptLimits()
1288 t.updateWantPeersEvent()
1289 // Tickle Client.waitAccept, new torrent may want conns.
1290 cl.event.Broadcast()
1294 type AddTorrentOpts struct {
1296 Storage storage.ClientImpl
1297 ChunkSize pp.Integer
1301 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1302 // Torrent.MergeSpec.
1303 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1304 t, new = cl.AddTorrentOpt(AddTorrentOpts{
1305 InfoHash: spec.InfoHash,
1306 Storage: spec.Storage,
1307 ChunkSize: spec.ChunkSize,
1311 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1313 modSpec.ChunkSize = 0
1315 err = t.MergeSpec(&modSpec)
1316 if err != nil && new {
1322 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1323 // spec.DisallowDataDownload/Upload will be read and applied
1324 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1325 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1326 if spec.DisplayName != "" {
1327 t.SetDisplayName(spec.DisplayName)
1329 if spec.InfoBytes != nil {
1330 err := t.SetInfoBytes(spec.InfoBytes)
1336 cl.AddDhtNodes(spec.DhtNodes)
1337 t.UseSources(spec.Sources)
1340 t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1341 for _, url := range spec.Webseeds {
1344 for _, peerAddr := range spec.PeerAddrs {
1346 Addr: StringAddr(peerAddr),
1347 Source: PeerSourceDirect,
1351 if spec.ChunkSize != 0 {
1352 panic("chunk size cannot be changed for existing Torrent")
1354 t.addTrackers(spec.Trackers)
1356 t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1357 t.dataUploadDisallowed = spec.DisallowDataUpload
1361 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1362 t, ok := cl.torrents[infoHash]
1364 err = fmt.Errorf("no such torrent")
1368 delete(cl.torrents, infoHash)
1372 func (cl *Client) allTorrentsCompleted() bool {
1373 for _, t := range cl.torrents {
1377 if !t.haveAllPieces() {
1384 // Returns true when all torrents are completely downloaded and false if the
1385 // client is stopped before that.
1386 func (cl *Client) WaitAll() bool {
1389 for !cl.allTorrentsCompleted() {
1390 if cl.closed.IsSet() {
1398 // Returns handles to all the torrents loaded in the Client.
1399 func (cl *Client) Torrents() []*Torrent {
1402 return cl.torrentsAsSlice()
1405 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1406 for _, t := range cl.torrents {
1407 ret = append(ret, t)
1412 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1413 spec, err := TorrentSpecFromMagnetUri(uri)
1417 T, _, err = cl.AddTorrentSpec(spec)
1421 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1422 ts, err := TorrentSpecFromMetaInfoErr(mi)
1426 T, _, err = cl.AddTorrentSpec(ts)
1430 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1431 mi, err := metainfo.LoadFromFile(filename)
1435 return cl.AddTorrent(mi)
1438 func (cl *Client) DhtServers() []DhtServer {
1439 return cl.dhtServers
1442 func (cl *Client) AddDhtNodes(nodes []string) {
1443 for _, n := range nodes {
1444 hmp := missinggo.SplitHostMaybePort(n)
1445 ip := net.ParseIP(hmp.Host)
1447 cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1450 ni := krpc.NodeInfo{
1451 Addr: krpc.NodeAddr{
1456 cl.eachDhtServer(func(s DhtServer) {
1462 func (cl *Client) banPeerIP(ip net.IP) {
1463 // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1464 // addresses directly to v4on6, which doesn't compare equal with v4.
1465 ipAddr, ok := netip.AddrFromSlice(ip)
1469 g.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1470 for _, t := range cl.torrents {
1471 t.iterPeers(func(p *Peer) {
1472 if p.remoteIp().Equal(ip) {
1473 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1474 // Should this be a close?
1481 type newConnectionOpts struct {
1483 remoteAddr PeerRemoteAddr
1484 localPublicAddr peerLocalPublicAddr
1489 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1490 if opts.network == "" {
1491 panic(opts.remoteAddr)
1495 outgoing: opts.outgoing,
1498 PeerMaxRequests: 250,
1500 RemoteAddr: opts.remoteAddr,
1501 localPublicAddr: opts.localPublicAddr,
1502 Network: opts.network,
1503 callbacks: &cl.config.Callbacks,
1505 connString: opts.connString,
1508 c.peerRequestDataAllocLimiter.Max = cl.config.MaxAllocPeerRequestDataPerConn
1509 c.initRequestState()
1510 // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1511 if opts.remoteAddr != nil {
1512 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1514 c.bannableAddr = Some(netipAddrPort.Addr())
1518 c.logger = cl.logger.WithDefaultLevel(log.Warning)
1519 c.setRW(connStatsReadWriter{nc, c})
1520 c.r = &rateLimitedReader{
1521 l: cl.config.DownloadRateLimiter,
1526 "new PeerConn %p [Client %p remoteAddr %v network %v outgoing %t]",
1527 c, cl, opts.remoteAddr, opts.network, opts.outgoing,
1529 for _, f := range cl.config.Callbacks.NewPeer {
1535 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1542 t.addPeers([]PeerInfo{{
1543 Addr: ipPortAddr{ip, port},
1544 Source: PeerSourceDhtAnnouncePeer,
1548 func firstNotNil(ips ...net.IP) net.IP {
1549 for _, ip := range ips {
1557 func (cl *Client) eachListener(f func(Listener) bool) {
1558 for _, s := range cl.listeners {
1565 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1566 for i := 0; i < len(cl.listeners); i += 1 {
1567 if ret = cl.listeners[i]; f(ret) {
1574 func (cl *Client) publicIp(peer net.IP) net.IP {
1575 // TODO: Use BEP 10 to determine how peers are seeing us.
1576 if peer.To4() != nil {
1578 cl.config.PublicIp4,
1579 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1584 cl.config.PublicIp6,
1585 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1589 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1590 l := cl.findListener(
1591 func(l Listener) bool {
1592 return f(addrIpOrNil(l.Addr()))
1598 return addrIpOrNil(l.Addr())
1601 // Our IP as a peer should see it.
1602 func (cl *Client) publicAddr(peer net.IP) IpPort {
1603 return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1606 // ListenAddrs addresses currently being listened to.
1607 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1609 ret = make([]net.Addr, len(cl.listeners))
1610 for i := 0; i < len(cl.listeners); i += 1 {
1611 ret[i] = cl.listeners[i].Addr()
1617 func (cl *Client) PublicIPs() (ips []net.IP) {
1618 if ip := cl.config.PublicIp4; ip != nil {
1619 ips = append(ips, ip)
1621 if ip := cl.config.PublicIp6; ip != nil {
1622 ips = append(ips, ip)
1627 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1628 ipa, ok := tryIpPortFromNetAddr(addr)
1632 ip := maskIpForAcceptLimiting(ipa.IP)
1633 if cl.acceptLimiter == nil {
1634 cl.acceptLimiter = make(map[ipStr]int)
1636 cl.acceptLimiter[ipStr(ip.String())]++
1639 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1640 if ip4 := ip.To4(); ip4 != nil {
1641 return ip4.Mask(net.CIDRMask(24, 32))
1646 func (cl *Client) clearAcceptLimits() {
1647 cl.acceptLimiter = nil
1650 func (cl *Client) acceptLimitClearer() {
1653 case <-cl.closed.Done():
1655 case <-time.After(15 * time.Minute):
1657 cl.clearAcceptLimits()
1663 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1664 if cl.config.DisableAcceptRateLimiting {
1667 return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1670 func (cl *Client) rLock() {
1674 func (cl *Client) rUnlock() {
1678 func (cl *Client) lock() {
1682 func (cl *Client) unlock() {
1686 func (cl *Client) locker() *lockWithDeferreds {
1690 func (cl *Client) String() string {
1691 return fmt.Sprintf("<%[1]T %[1]p>", cl)
1694 // Returns connection-level aggregate stats at the Client level. See the comment on
1695 // TorrentStats.ConnStats.
1696 func (cl *Client) ConnStats() ConnStats {
1697 return cl.stats.Copy()