20 "github.com/anacrolix/dht"
21 "github.com/anacrolix/dht/krpc"
22 "github.com/anacrolix/missinggo"
23 "github.com/anacrolix/missinggo/pproffd"
24 "github.com/anacrolix/missinggo/pubsub"
25 "github.com/anacrolix/missinggo/slices"
26 "github.com/anacrolix/sync"
27 "github.com/dustin/go-humanize"
28 "golang.org/x/time/rate"
30 "github.com/anacrolix/torrent/bencode"
31 "github.com/anacrolix/torrent/iplist"
32 "github.com/anacrolix/torrent/metainfo"
33 "github.com/anacrolix/torrent/mse"
34 pp "github.com/anacrolix/torrent/peer_protocol"
35 "github.com/anacrolix/torrent/storage"
38 // Clients contain zero or more Torrents. A Client manages a blocklist, the
39 // TCP/UDP protocol ports, and DHT as desired.
43 closed missinggo.Event
49 defaultStorage *storage.Client
51 tcpListener net.Listener
54 ipBlockList iplist.Ranger
55 // Our BitTorrent protocol extension bytes, sent in our BT handshakes.
56 extensionBytes peerExtensionBytes
57 // The net.Addr.String part that should be common to all active listeners.
59 uploadLimit *rate.Limiter
60 downloadLimit *rate.Limiter
62 // Set of addresses that have our client ID. This intentionally will
63 // include ourselves if we end up trying to connect to our own address
64 // through legitimate channels.
65 dopplegangerAddrs map[string]struct{}
66 badPeerIPs map[string]struct{}
67 torrents map[metainfo.Hash]*Torrent
70 func (cl *Client) BadPeerIPs() []string {
73 return cl.badPeerIPsLocked()
76 func (cl *Client) badPeerIPsLocked() []string {
77 return slices.FromMapKeys(cl.badPeerIPs).([]string)
80 func (cl *Client) IPBlockList() iplist.Ranger {
86 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
91 cl.dHT.SetIPBlockList(list)
95 func (cl *Client) PeerID() string {
96 return string(cl.peerID[:])
99 type torrentAddr string
101 func (torrentAddr) Network() string { return "" }
103 func (me torrentAddr) String() string { return string(me) }
105 func (cl *Client) ListenAddr() net.Addr {
106 if cl.listenAddr == "" {
109 return torrentAddr(cl.listenAddr)
112 // Writes out a human readable status of the client, such as for writing to a
114 func (cl *Client) WriteStatus(_w io.Writer) {
117 w := bufio.NewWriter(_w)
119 if addr := cl.ListenAddr(); addr != nil {
120 fmt.Fprintf(w, "Listening on %s\n", addr)
122 fmt.Fprintln(w, "Not listening!")
124 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
125 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
126 if dht := cl.DHT(); dht != nil {
127 dhtStats := dht.Stats()
128 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
129 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
130 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
131 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
132 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
134 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
136 for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
137 return l.InfoHash().AsString() < r.InfoHash().AsString()
140 fmt.Fprint(w, "<unknown name>")
142 fmt.Fprint(w, t.name())
146 fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength())))
148 w.WriteString("<missing metainfo>")
156 func listenUTP(networkSuffix, addr string) (utpSocket, error) {
157 return NewUtpSocket("udp"+networkSuffix, addr)
160 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
161 return net.Listen("tcp"+networkSuffix, addr)
164 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
166 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
170 listenedAddr = tcpL.Addr().String()
171 utpSock, err = listenUTP(networkSuffix, listenedAddr)
176 if !strings.Contains(err.Error(), "address already in use") {
182 // Listen to enabled protocols, ensuring ports match.
183 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
190 host, port, err = missinggo.ParseHostPort(addr)
195 // If both protocols are active, they need to have the same port.
196 return listenBothSameDynamicPort(networkSuffix, host)
205 tcpL, err = listenTCP(networkSuffix, addr)
214 listenedAddr = tcpL.Addr().String()
217 utpSock, err = listenUTP(networkSuffix, addr)
221 listenedAddr = utpSock.Addr().String()
226 // Creates a new client.
227 func NewClient(cfg *Config) (cl *Client, err error) {
230 DHTConfig: dht.ServerConfig{
231 StartingNodes: dht.GlobalBootstrapAddrs,
242 halfOpenLimit: defaultHalfOpenConnsPerTorrent,
244 dopplegangerAddrs: make(map[string]struct{}),
245 torrents: make(map[metainfo.Hash]*Torrent),
253 if cfg.UploadRateLimiter == nil {
254 cl.uploadLimit = rate.NewLimiter(rate.Inf, 0)
256 cl.uploadLimit = cfg.UploadRateLimiter
258 if cfg.DownloadRateLimiter == nil {
259 cl.downloadLimit = rate.NewLimiter(rate.Inf, 0)
261 cl.downloadLimit = cfg.DownloadRateLimiter
263 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
265 storageImpl := cfg.DefaultStorage
266 if storageImpl == nil {
267 // We'd use mmap but HFS+ doesn't support sparse files.
268 storageImpl = storage.NewFile(cfg.DataDir)
269 cl.onClose = append(cl.onClose, func() {
270 if err := storageImpl.Close(); err != nil {
271 log.Printf("error closing default storage: %s", err)
275 cl.defaultStorage = storage.NewClient(storageImpl)
276 if cfg.IPBlocklist != nil {
277 cl.ipBlockList = cfg.IPBlocklist
280 if cfg.PeerID != "" {
281 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
283 o := copy(cl.peerID[:], bep20)
284 _, err = rand.Read(cl.peerID[o:])
286 panic("error generating peer id")
290 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
291 !cl.config.DisableTCP,
292 !cl.config.DisableUTP,
294 if cl.config.DisableIPv6 {
300 cl.config.ListenAddr)
304 if cl.tcpListener != nil {
305 go cl.acceptConnections(cl.tcpListener, false)
307 if cl.utpSock != nil {
308 go cl.acceptConnections(cl.utpSock, true)
311 dhtCfg := cfg.DHTConfig
312 if dhtCfg.IPBlocklist == nil {
313 dhtCfg.IPBlocklist = cl.ipBlockList
315 if dhtCfg.Conn == nil {
316 if cl.utpSock != nil {
317 dhtCfg.Conn = cl.utpSock
319 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
325 if dhtCfg.OnAnnouncePeer == nil {
326 dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
328 cl.dHT, err = dht.NewServer(&dhtCfg)
333 if _, err := cl.dHT.Bootstrap(); err != nil {
334 log.Printf("error bootstrapping dht: %s", err)
342 func firstNonEmptyString(ss ...string) string {
343 for _, s := range ss {
351 // Stops the client. All connections to peers are closed and all activity will
353 func (cl *Client) Close() {
360 if cl.utpSock != nil {
363 if cl.tcpListener != nil {
364 cl.tcpListener.Close()
366 for _, t := range cl.torrents {
369 for _, f := range cl.onClose {
375 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
377 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
378 if cl.ipBlockList == nil {
382 // If blocklists are enabled, then block non-IPv4 addresses, because
383 // blocklists do not yet support IPv6.
385 if missinggo.CryHeard() {
386 log.Printf("blocking non-IPv4 address: %s", ip)
392 return cl.ipBlockList.Lookup(ip4)
395 func (cl *Client) waitAccept() {
397 for _, t := range cl.torrents {
402 if cl.closed.IsSet() {
409 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
415 conn, err := l.Accept()
416 conn = pproffd.WrapNetConn(conn)
418 if cl.closed.IsSet() {
426 // I think something harsher should happen here? Our accept
427 // routine just fucked off.
436 log.Printf("accepted connection from %s", conn.RemoteAddr())
438 reject := cl.badPeerIPPort(
439 missinggo.AddrIP(conn.RemoteAddr()),
440 missinggo.AddrPort(conn.RemoteAddr()))
443 log.Printf("rejecting connection from %s", conn.RemoteAddr())
449 go cl.incomingConnection(conn, utp)
453 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
455 if tc, ok := nc.(*net.TCPConn); ok {
458 c := cl.newConnection(nc)
459 c.Discovery = peerSourceIncoming
461 cl.runReceivedConn(c)
464 // Returns a handle to the given torrent, if it's present in the client.
465 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
468 t, ok = cl.torrents[ih]
472 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
473 return cl.torrents[ih]
476 type dialResult struct {
481 func countDialResult(err error) {
483 successfulDials.Add(1)
485 unsuccessfulDials.Add(1)
489 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
490 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
491 if ret < minDialTimeout {
497 // Returns whether an address is known to connect to a client with our own ID.
498 func (cl *Client) dopplegangerAddr(addr string) bool {
499 _, ok := cl.dopplegangerAddrs[addr]
503 // Start the process of connecting to the given peer for the given torrent if
505 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
506 if peer.Id == cl.peerID {
509 if cl.badPeerIPPort(peer.IP, peer.Port) {
512 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
513 if t.addrActive(addr) {
516 t.halfOpen[addr] = peer
517 go cl.outgoingConnection(t, addr, peer.Source)
520 func (cl *Client) dialTCP(ctx context.Context, addr string) (c net.Conn, err error) {
522 // LocalAddr: cl.tcpListener.Addr(),
524 c, err = d.DialContext(ctx, "tcp", addr)
527 c.(*net.TCPConn).SetLinger(0)
529 c = pproffd.WrapNetConn(c)
533 func (cl *Client) dialUTP(ctx context.Context, addr string) (c net.Conn, err error) {
534 c, err = cl.utpSock.DialContext(ctx, addr)
540 dialledFirstUtp = expvar.NewInt("dialledFirstUtp")
541 dialledFirstNotUtp = expvar.NewInt("dialledFirstNotUtp")
544 // Returns a connection over UTP or TCP, whichever is first to connect.
545 func (cl *Client) dialFirst(ctx context.Context, addr string) (conn net.Conn, utp bool) {
546 ctx, cancel := context.WithCancel(ctx)
547 // As soon as we return one connection, cancel the others.
550 resCh := make(chan dialResult, left)
551 if !cl.config.DisableUTP {
554 c, _ := cl.dialUTP(ctx, addr)
555 resCh <- dialResult{c, true}
558 if !cl.config.DisableTCP {
561 c, _ := cl.dialTCP(ctx, addr)
562 resCh <- dialResult{c, false}
566 // Wait for a successful connection.
567 for ; left > 0 && res.Conn == nil; left-- {
571 // There are still incompleted dials.
573 for ; left > 0; left-- {
574 conn := (<-resCh).Conn
585 dialledFirstUtp.Add(1)
587 dialledFirstNotUtp.Add(1)
593 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
594 if _, ok := t.halfOpen[addr]; !ok {
595 panic("invariant broken")
597 delete(t.halfOpen, addr)
601 // Performs initiator handshakes and returns a connection. Returns nil
602 // *connection if no connection for valid reasons.
603 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader, utp bool) (c *connection, err error) {
604 c = cl.newConnection(nc)
605 c.headerEncrypted = encryptHeader
607 ctx, cancel := context.WithTimeout(ctx, handshakesTimeout)
609 dl, ok := ctx.Deadline()
613 err = nc.SetDeadline(dl)
617 ok, err = cl.initiateHandshakes(c, t)
625 initiatedConnWithPreferredHeaderEncryption = expvar.NewInt("initiatedConnWithPreferredHeaderEncryption")
626 initiatedConnWithFallbackHeaderEncryption = expvar.NewInt("initiatedConnWithFallbackHeaderEncryption")
629 // Returns nil connection and nil error if no connection could be established
630 // for valid reasons.
631 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
632 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
634 nc, utp := cl.dialFirst(ctx, addr)
638 obfuscatedHeaderFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
639 c, err = cl.handshakesConnection(ctx, nc, t, obfuscatedHeaderFirst, utp)
641 // log.Printf("error initiating connection handshakes: %s", err)
645 initiatedConnWithPreferredHeaderEncryption.Add(1)
649 if cl.config.ForceEncryption {
650 // We should have just tried with an obfuscated header. A plaintext
651 // header can't result in an encrypted connection, so we're done.
652 if !obfuscatedHeaderFirst {
653 panic(cl.config.EncryptionPolicy)
657 // Try again with encryption if we didn't earlier, or without if we did,
658 // using whichever protocol type worked last time.
660 nc, err = cl.dialUTP(ctx, addr)
662 nc, err = cl.dialTCP(ctx, addr)
665 err = fmt.Errorf("error dialing for header encryption fallback: %s", err)
668 c, err = cl.handshakesConnection(ctx, nc, t, !obfuscatedHeaderFirst, utp)
669 if err != nil || c == nil {
672 if err == nil && c != nil {
673 initiatedConnWithFallbackHeaderEncryption.Add(1)
678 // Called to dial out and run a connection. The addr we're given is already
679 // considered half-open.
680 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
681 c, err := cl.establishOutgoingConn(t, addr)
684 // Don't release lock between here and addConnection, unless it's for
686 cl.noLongerHalfOpen(t, addr)
689 log.Printf("error establishing outgoing connection: %s", err)
698 cl.runInitiatedHandshookConn(c, t)
701 // The port number for incoming peer connections. 0 if the client isn't
703 func (cl *Client) incomingPeerPort() int {
704 if cl.listenAddr == "" {
707 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
714 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
715 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
716 func addrCompactIP(addr net.Addr) (string, error) {
717 host, _, err := net.SplitHostPort(addr.String())
721 ip := net.ParseIP(host)
722 if v4 := ip.To4(); v4 != nil {
726 return string(v4), nil
728 return string(ip.To16()), nil
731 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
743 peerExtensionBytes [8]byte
747 func (pex *peerExtensionBytes) SupportsExtended() bool {
748 return pex[5]&0x10 != 0
751 func (pex *peerExtensionBytes) SupportsDHT() bool {
752 return pex[7]&0x01 != 0
755 func (pex *peerExtensionBytes) SupportsFast() bool {
756 return pex[7]&0x04 != 0
759 type handshakeResult struct {
765 // ih is nil if we expect the peer to declare the InfoHash, such as when the
766 // peer initiated the connection. Returns ok if the handshake was successful,
767 // and err if there was an unexpected condition other than the peer simply
768 // abandoning the handshake.
769 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
770 // Bytes to be sent to the peer. Should never block the sender.
771 postCh := make(chan []byte, 4)
772 // A single error value sent when the writer completes.
773 writeDone := make(chan error, 1)
774 // Performs writes to the socket and ensures posts don't block.
775 go handshakeWriter(sock, postCh, writeDone)
778 close(postCh) // Done writing.
785 // Wait until writes complete before returning from handshake.
788 err = fmt.Errorf("error writing: %s", err)
792 post := func(bb []byte) {
796 panic("mustn't block while posting")
800 post([]byte(pp.Protocol))
802 if ih != nil { // We already know what we want.
807 _, err = io.ReadFull(sock, b[:68])
812 if string(b[:20]) != pp.Protocol {
815 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
816 missinggo.CopyExact(&res.Hash, b[28:48])
817 missinggo.CopyExact(&res.peerID, b[48:68])
818 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
820 // TODO: Maybe we can just drop peers here if we're not interested. This
821 // could prevent them trying to reconnect, falsely believing there was
823 if ih == nil { // We were waiting for the peer to tell us what they wanted.
832 // Wraps a raw connection and provides the interface we want for using the
833 // connection in the message loop.
834 type deadlineReader struct {
839 func (r deadlineReader) Read(b []byte) (int, error) {
840 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
841 err := r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
843 return 0, fmt.Errorf("error setting read deadline: %s", err)
848 func handleEncryption(
850 skeys mse.SecretKeyIter,
851 policy EncryptionPolicy,
854 headerEncrypted bool,
858 if !policy.ForceEncryption {
859 var protocol [len(pp.Protocol)]byte
860 _, err = io.ReadFull(rw, protocol[:])
868 io.MultiReader(bytes.NewReader(protocol[:]), rw),
871 if string(protocol[:]) == pp.Protocol {
876 headerEncrypted = true
877 ret, err = mse.ReceiveHandshake(rw, skeys, func(provides uint32) uint32 {
878 cryptoMethod = func() uint32 {
880 case policy.ForceEncryption:
881 return mse.CryptoMethodRC4
882 case policy.DisableEncryption:
883 return mse.CryptoMethodPlaintext
884 case policy.PreferNoEncryption && provides&mse.CryptoMethodPlaintext != 0:
885 return mse.CryptoMethodPlaintext
887 return mse.DefaultCryptoSelector(provides)
895 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
896 if c.headerEncrypted {
898 rw, err = mse.InitiateHandshake(
907 case cl.config.ForceEncryption:
908 return mse.CryptoMethodRC4
909 case cl.config.DisableEncryption:
910 return mse.CryptoMethodPlaintext
912 return mse.AllSupportedCrypto
921 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
922 if ih != t.infoHash {
928 // Calls f with any secret keys.
929 func (cl *Client) forSkeys(f func([]byte) bool) {
932 for ih := range cl.torrents {
939 // Do encryption and bittorrent handshakes as receiver.
940 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
942 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
945 if err == mse.ErrNoSecretKeyMatch {
950 if cl.config.ForceEncryption && !c.headerEncrypted {
951 err = errors.New("connection not encrypted")
954 ih, ok, err := cl.connBTHandshake(c, nil)
956 err = fmt.Errorf("error during bt handshake: %s", err)
968 // Returns !ok if handshake failed for valid reasons.
969 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
970 res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
971 if err != nil || !ok {
975 c.PeerExtensionBytes = res.peerExtensionBytes
976 c.PeerID = res.peerID
977 c.completedHandshake = time.Now()
981 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
982 if c.PeerID == cl.peerID {
984 addr := c.conn.RemoteAddr().String()
985 cl.dopplegangerAddrs[addr] = struct{}{}
988 cl.runHandshookConn(c, t, true)
991 func (cl *Client) runReceivedConn(c *connection) {
992 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
996 t, err := cl.receiveHandshakes(c)
999 log.Printf("error receiving handshakes: %s", err)
1007 defer cl.mu.Unlock()
1008 if c.PeerID == cl.peerID {
1009 // Because the remote address is not necessarily the same as its
1010 // client's torrent listen address, we won't record the remote address
1011 // as a doppleganger. Instead, the initiator can record *us* as the
1015 cl.runHandshookConn(c, t, false)
1018 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
1019 c.conn.SetWriteDeadline(time.Time{})
1020 c.r = deadlineReader{c.conn, c.r}
1021 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1022 if !t.addConnection(c, outgoing) {
1025 defer t.dropConnection(c)
1026 go c.writer(time.Minute)
1027 cl.sendInitialMessages(c, t)
1028 err := c.mainReadLoop()
1029 if err != nil && cl.config.Debug {
1030 log.Printf("error during connection loop: %s", err)
1034 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
1035 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
1036 conn.Post(pp.Message{
1038 ExtendedID: pp.HandshakeExtendedID,
1039 ExtendedPayload: func() []byte {
1040 d := map[string]interface{}{
1041 "m": func() (ret map[string]int) {
1042 ret = make(map[string]int, 2)
1043 ret["ut_metadata"] = metadataExtendedId
1044 if !cl.config.DisablePEX {
1045 ret["ut_pex"] = pexExtendedId
1049 "v": extendedHandshakeClientVersion,
1050 // No upload queue is implemented yet.
1053 if !cl.config.DisableEncryption {
1056 if torrent.metadataSizeKnown() {
1057 d["metadata_size"] = torrent.metadataSize()
1059 if p := cl.incomingPeerPort(); p != 0 {
1062 yourip, err := addrCompactIP(conn.remoteAddr())
1064 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1066 d["yourip"] = yourip
1068 // log.Printf("sending %v", d)
1069 b, err := bencode.Marshal(d)
1077 if torrent.haveAnyPieces() {
1078 conn.Bitfield(torrent.bitfield())
1079 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1080 conn.Post(pp.Message{
1084 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
1085 conn.Post(pp.Message{
1087 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
1092 // Process incoming ut_metadata message.
1093 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1094 var d map[string]int
1095 err := bencode.Unmarshal(payload, &d)
1097 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1099 msgType, ok := d["msg_type"]
1101 return errors.New("missing msg_type field")
1105 case pp.DataMetadataExtensionMsgType:
1106 if !c.requestedMetadataPiece(piece) {
1107 return fmt.Errorf("got unexpected piece %d", piece)
1109 c.metadataRequests[piece] = false
1110 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1111 if begin < 0 || begin >= len(payload) {
1112 return fmt.Errorf("data has bad offset in payload: %d", begin)
1114 t.saveMetadataPiece(piece, payload[begin:])
1115 c.UsefulChunksReceived++
1116 c.lastUsefulChunkReceived = time.Now()
1117 return t.maybeCompleteMetadata()
1118 case pp.RequestMetadataExtensionMsgType:
1119 if !t.haveMetadataPiece(piece) {
1120 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1123 start := (1 << 14) * piece
1124 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1126 case pp.RejectMetadataExtensionMsgType:
1129 return errors.New("unknown msg_type value")
1133 func (cl *Client) sendChunk(t *Torrent, c *connection, r request, msg func(pp.Message) bool) (more bool, err error) {
1134 // Count the chunk being sent, even if it isn't.
1135 b := make([]byte, r.Length)
1136 p := t.info.Piece(int(r.Index))
1137 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1140 panic("expected error")
1143 } else if err == io.EOF {
1146 more = msg(pp.Message{
1153 uploadChunksPosted.Add(1)
1154 c.lastChunkSent = time.Now()
1158 func (cl *Client) openNewConns(t *Torrent) {
1159 defer t.updateWantPeersEvent()
1160 for len(t.peers) != 0 {
1164 if len(t.halfOpen) >= cl.halfOpenLimit {
1171 for k, p = range t.peers {
1175 cl.initiateConn(p, t)
1179 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1183 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1186 if _, ok := cl.ipBlockRange(ip); ok {
1189 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1195 // Return a Torrent ready for insertion into a Client.
1196 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1197 // use provided storage, if provided
1198 storageClient := cl.defaultStorage
1199 if specStorage != nil {
1200 storageClient = storage.NewClient(specStorage)
1206 peers: make(map[peersKey]Peer),
1207 conns: make(map[*connection]struct{}, 2*defaultEstablishedConnsPerTorrent),
1209 halfOpen: make(map[string]Peer),
1210 pieceStateChanges: pubsub.NewPubSub(),
1212 storageOpener: storageClient,
1213 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1215 networkingEnabled: true,
1218 t.setChunkSize(defaultChunkSize)
1222 // A file-like handle to some torrent data resource.
1223 type Handle interface {
1230 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1231 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1234 // Adds a torrent by InfoHash with a custom Storage implementation.
1235 // If the torrent already exists then this Storage is ignored and the
1236 // existing torrent returned with `new` set to `false`
1237 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1239 defer cl.mu.Unlock()
1240 t, ok := cl.torrents[infoHash]
1245 t = cl.newTorrent(infoHash, specStorage)
1249 cl.torrents[infoHash] = t
1250 t.updateWantPeersEvent()
1251 // Tickle Client.waitAccept, new torrent may want conns.
1252 cl.event.Broadcast()
1256 // Add or merge a torrent spec. If the torrent is already present, the
1257 // trackers will be merged with the existing ones. If the Info isn't yet
1258 // known, it will be set. The display name is replaced if the new spec
1259 // provides one. Returns new if the torrent wasn't already in the client.
1260 // Note that any `Storage` defined on the spec will be ignored if the
1261 // torrent is already present (i.e. `new` return value is `true`)
1262 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1263 t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1264 if spec.DisplayName != "" {
1265 t.SetDisplayName(spec.DisplayName)
1267 if spec.InfoBytes != nil {
1268 err = t.SetInfoBytes(spec.InfoBytes)
1274 defer cl.mu.Unlock()
1275 if spec.ChunkSize != 0 {
1276 t.setChunkSize(pp.Integer(spec.ChunkSize))
1278 t.addTrackers(spec.Trackers)
1283 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1284 t, ok := cl.torrents[infoHash]
1286 err = fmt.Errorf("no such torrent")
1293 delete(cl.torrents, infoHash)
1297 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1298 _url, err := url.Parse(announceURL)
1302 hmp := missinggo.SplitHostMaybePort(_url.Host)
1307 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1312 _, blocked = cl.ipBlockRange(addr.IP)
1315 hmp.Host = addr.String()
1316 _url.Host = hmp.String()
1317 urlToUse = _url.String()
1321 func (cl *Client) allTorrentsCompleted() bool {
1322 for _, t := range cl.torrents {
1326 if t.numPiecesCompleted() != t.numPieces() {
1333 // Returns true when all torrents are completely downloaded and false if the
1334 // client is stopped before that.
1335 func (cl *Client) WaitAll() bool {
1337 defer cl.mu.Unlock()
1338 for !cl.allTorrentsCompleted() {
1339 if cl.closed.IsSet() {
1347 // Returns handles to all the torrents loaded in the Client.
1348 func (cl *Client) Torrents() []*Torrent {
1350 defer cl.mu.Unlock()
1351 return cl.torrentsAsSlice()
1354 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1355 for _, t := range cl.torrents {
1356 ret = append(ret, t)
1361 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1362 spec, err := TorrentSpecFromMagnetURI(uri)
1366 T, _, err = cl.AddTorrentSpec(spec)
1370 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1371 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1373 slices.MakeInto(&ss, mi.Nodes)
1378 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1379 mi, err := metainfo.LoadFromFile(filename)
1383 return cl.AddTorrent(mi)
1386 func (cl *Client) DHT() *dht.Server {
1390 func (cl *Client) AddDHTNodes(nodes []string) {
1391 if cl.DHT() == nil {
1394 for _, n := range nodes {
1395 hmp := missinggo.SplitHostMaybePort(n)
1396 ip := net.ParseIP(hmp.Host)
1398 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1401 ni := krpc.NodeInfo{
1407 cl.DHT().AddNode(ni)
1411 func (cl *Client) banPeerIP(ip net.IP) {
1412 if cl.badPeerIPs == nil {
1413 cl.badPeerIPs = make(map[string]struct{})
1415 cl.badPeerIPs[ip.String()] = struct{}{}
1418 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1424 PeerMaxRequests: 250,
1426 c.writerCond.L = &cl.mu
1427 c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1428 c.r = rateLimitedReader{cl.downloadLimit, c.r}
1432 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1434 defer cl.mu.Unlock()
1442 Source: peerSourceDHTAnnouncePeer,