19 "github.com/anacrolix/dht"
20 "github.com/anacrolix/dht/krpc"
21 "github.com/anacrolix/missinggo"
22 "github.com/anacrolix/missinggo/pproffd"
23 "github.com/anacrolix/missinggo/pubsub"
24 "github.com/anacrolix/missinggo/slices"
25 "github.com/anacrolix/sync"
26 "github.com/dustin/go-humanize"
27 "golang.org/x/time/rate"
29 "github.com/anacrolix/torrent/bencode"
30 "github.com/anacrolix/torrent/iplist"
31 "github.com/anacrolix/torrent/metainfo"
32 "github.com/anacrolix/torrent/mse"
33 pp "github.com/anacrolix/torrent/peer_protocol"
34 "github.com/anacrolix/torrent/storage"
37 // Clients contain zero or more Torrents. A Client manages a blocklist, the
38 // TCP/UDP protocol ports, and DHT as desired.
42 closed missinggo.Event
48 defaultStorage *storage.Client
50 tcpListener net.Listener
53 ipBlockList iplist.Ranger
54 // Our BitTorrent protocol extension bytes, sent in our BT handshakes.
55 extensionBytes peerExtensionBytes
56 // The net.Addr.String part that should be common to all active listeners.
58 uploadLimit *rate.Limiter
59 downloadLimit *rate.Limiter
61 // Set of addresses that have our client ID. This intentionally will
62 // include ourselves if we end up trying to connect to our own address
63 // through legitimate channels.
64 dopplegangerAddrs map[string]struct{}
65 badPeerIPs map[string]struct{}
66 torrents map[metainfo.Hash]*Torrent
69 func (cl *Client) BadPeerIPs() []string {
72 return cl.badPeerIPsLocked()
75 func (cl *Client) badPeerIPsLocked() []string {
76 return slices.FromMapKeys(cl.badPeerIPs).([]string)
79 func (cl *Client) IPBlockList() iplist.Ranger {
85 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
90 cl.dHT.SetIPBlockList(list)
94 func (cl *Client) PeerID() string {
95 return string(cl.peerID[:])
98 type torrentAddr string
100 func (torrentAddr) Network() string { return "" }
102 func (me torrentAddr) String() string { return string(me) }
104 func (cl *Client) ListenAddr() net.Addr {
105 if cl.listenAddr == "" {
108 return torrentAddr(cl.listenAddr)
111 // Writes out a human readable status of the client, such as for writing to a
113 func (cl *Client) WriteStatus(_w io.Writer) {
116 w := bufio.NewWriter(_w)
118 if addr := cl.ListenAddr(); addr != nil {
119 fmt.Fprintf(w, "Listening on %s\n", addr)
121 fmt.Fprintln(w, "Not listening!")
123 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
124 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
125 if dht := cl.DHT(); dht != nil {
126 dhtStats := dht.Stats()
127 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
128 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
129 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
130 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
131 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
133 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
135 for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
136 return l.InfoHash().AsString() < r.InfoHash().AsString()
139 fmt.Fprint(w, "<unknown name>")
141 fmt.Fprint(w, t.name())
145 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())))
147 w.WriteString("<missing metainfo>")
155 func listenUTP(networkSuffix, addr string) (utpSocket, error) {
156 return NewUtpSocket("udp"+networkSuffix, addr)
159 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
160 return net.Listen("tcp"+networkSuffix, addr)
163 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
165 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
169 listenedAddr = tcpL.Addr().String()
170 utpSock, err = listenUTP(networkSuffix, listenedAddr)
175 if !strings.Contains(err.Error(), "address already in use") {
181 // Listen to enabled protocols, ensuring ports match.
182 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
189 host, port, err = missinggo.ParseHostPort(addr)
194 // If both protocols are active, they need to have the same port.
195 return listenBothSameDynamicPort(networkSuffix, host)
204 tcpL, err = listenTCP(networkSuffix, addr)
213 listenedAddr = tcpL.Addr().String()
216 utpSock, err = listenUTP(networkSuffix, addr)
220 listenedAddr = utpSock.Addr().String()
225 // Creates a new client.
226 func NewClient(cfg *Config) (cl *Client, err error) {
229 DHTConfig: dht.ServerConfig{
230 StartingNodes: dht.GlobalBootstrapAddrs,
241 halfOpenLimit: defaultHalfOpenConnsPerTorrent,
243 dopplegangerAddrs: make(map[string]struct{}),
244 torrents: make(map[metainfo.Hash]*Torrent),
252 if cfg.UploadRateLimiter == nil {
253 cl.uploadLimit = rate.NewLimiter(rate.Inf, 0)
255 cl.uploadLimit = cfg.UploadRateLimiter
257 if cfg.DownloadRateLimiter == nil {
258 cl.downloadLimit = rate.NewLimiter(rate.Inf, 0)
260 cl.downloadLimit = cfg.DownloadRateLimiter
262 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
264 storageImpl := cfg.DefaultStorage
265 if storageImpl == nil {
266 storageImpl = storage.NewFile(cfg.DataDir)
267 cl.onClose = append(cl.onClose, func() {
268 if err := storageImpl.Close(); err != nil {
269 log.Printf("error closing default storage: %s", err)
273 cl.defaultStorage = storage.NewClient(storageImpl)
274 if cfg.IPBlocklist != nil {
275 cl.ipBlockList = cfg.IPBlocklist
278 if cfg.PeerID != "" {
279 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
281 o := copy(cl.peerID[:], bep20)
282 _, err = rand.Read(cl.peerID[o:])
284 panic("error generating peer id")
288 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
289 !cl.config.DisableTCP,
290 !cl.config.DisableUTP,
292 if cl.config.DisableIPv6 {
298 cl.config.ListenAddr)
302 if cl.tcpListener != nil {
303 go cl.acceptConnections(cl.tcpListener, false)
305 if cl.utpSock != nil {
306 go cl.acceptConnections(cl.utpSock, true)
309 dhtCfg := cfg.DHTConfig
310 if dhtCfg.IPBlocklist == nil {
311 dhtCfg.IPBlocklist = cl.ipBlockList
313 if dhtCfg.Conn == nil {
314 if cl.utpSock != nil {
315 dhtCfg.Conn = cl.utpSock
317 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
323 if dhtCfg.OnAnnouncePeer == nil {
324 dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
326 cl.dHT, err = dht.NewServer(&dhtCfg)
331 if _, err := cl.dHT.Bootstrap(); err != nil {
332 log.Printf("error bootstrapping dht: %s", err)
340 func firstNonEmptyString(ss ...string) string {
341 for _, s := range ss {
349 // Stops the client. All connections to peers are closed and all activity will
351 func (cl *Client) Close() {
358 if cl.utpSock != nil {
361 if cl.tcpListener != nil {
362 cl.tcpListener.Close()
364 for _, t := range cl.torrents {
367 for _, f := range cl.onClose {
373 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
375 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
376 if cl.ipBlockList == nil {
380 // If blocklists are enabled, then block non-IPv4 addresses, because
381 // blocklists do not yet support IPv6.
383 if missinggo.CryHeard() {
384 log.Printf("blocking non-IPv4 address: %s", ip)
390 return cl.ipBlockList.Lookup(ip4)
393 func (cl *Client) waitAccept() {
395 for _, t := range cl.torrents {
400 if cl.closed.IsSet() {
407 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
413 conn, err := l.Accept()
414 conn = pproffd.WrapNetConn(conn)
416 if cl.closed.IsSet() {
424 // I think something harsher should happen here? Our accept
425 // routine just fucked off.
434 log.Printf("accepted connection from %s", conn.RemoteAddr())
436 reject := cl.badPeerIPPort(
437 missinggo.AddrIP(conn.RemoteAddr()),
438 missinggo.AddrPort(conn.RemoteAddr()))
441 log.Printf("rejecting connection from %s", conn.RemoteAddr())
447 go cl.incomingConnection(conn, utp)
451 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
453 if tc, ok := nc.(*net.TCPConn); ok {
456 c := cl.newConnection(nc)
457 c.Discovery = peerSourceIncoming
459 cl.runReceivedConn(c)
462 // Returns a handle to the given torrent, if it's present in the client.
463 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
466 t, ok = cl.torrents[ih]
470 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
471 return cl.torrents[ih]
474 type dialResult struct {
479 func countDialResult(err error) {
481 successfulDials.Add(1)
483 unsuccessfulDials.Add(1)
487 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
488 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
489 if ret < minDialTimeout {
495 // Returns whether an address is known to connect to a client with our own ID.
496 func (cl *Client) dopplegangerAddr(addr string) bool {
497 _, ok := cl.dopplegangerAddrs[addr]
501 // Start the process of connecting to the given peer for the given torrent if
503 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
504 if peer.Id == cl.peerID {
507 if cl.badPeerIPPort(peer.IP, peer.Port) {
510 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
511 if t.addrActive(addr) {
514 t.halfOpen[addr] = struct{}{}
515 go cl.outgoingConnection(t, addr, peer.Source)
518 func (cl *Client) dialTCP(ctx context.Context, addr string) (c net.Conn, err error) {
520 // LocalAddr: cl.tcpListener.Addr(),
522 c, err = d.DialContext(ctx, "tcp", addr)
525 c.(*net.TCPConn).SetLinger(0)
527 c = pproffd.WrapNetConn(c)
531 func (cl *Client) dialUTP(ctx context.Context, addr string) (c net.Conn, err error) {
532 c, err = cl.utpSock.DialContext(ctx, addr)
537 // Returns a connection over UTP or TCP, whichever is first to connect.
538 func (cl *Client) dialFirst(ctx context.Context, addr string) (conn net.Conn, utp bool) {
539 ctx, cancel := context.WithCancel(ctx)
540 // As soon as we return one connection, cancel the others.
543 resCh := make(chan dialResult, left)
544 if !cl.config.DisableUTP {
547 c, _ := cl.dialUTP(ctx, addr)
548 resCh <- dialResult{c, true}
551 if !cl.config.DisableTCP {
554 c, _ := cl.dialTCP(ctx, addr)
555 resCh <- dialResult{c, false}
559 // Wait for a successful connection.
560 for ; left > 0 && res.Conn == nil; left-- {
564 // There are still incompleted dials.
566 for ; left > 0; left-- {
567 conn := (<-resCh).Conn
579 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
580 if _, ok := t.halfOpen[addr]; !ok {
581 panic("invariant broken")
583 delete(t.halfOpen, addr)
587 // Performs initiator handshakes and returns a connection. Returns nil
588 // *connection if no connection for valid reasons.
589 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
590 c = cl.newConnection(nc)
591 c.encrypted = encrypted
593 ctx, cancel := context.WithTimeout(ctx, handshakesTimeout)
595 dl, ok := ctx.Deadline()
599 err = nc.SetDeadline(dl)
603 ok, err = cl.initiateHandshakes(c, t)
610 // Returns nil connection and nil error if no connection could be established
611 // for valid reasons.
612 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
613 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
615 nc, utp := cl.dialFirst(ctx, addr)
619 encryptFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
620 c, err = cl.handshakesConnection(ctx, nc, t, encryptFirst, utp)
628 if cl.config.DisableEncryption || cl.config.ForceEncryption {
629 // There's no alternate encryption case to try.
632 // Try again with encryption if we didn't earlier, or without if we did,
633 // using whichever protocol type worked last time.
635 nc, err = cl.dialUTP(ctx, addr)
637 nc, err = cl.dialTCP(ctx, addr)
640 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
643 c, err = cl.handshakesConnection(ctx, nc, t, !encryptFirst, utp)
644 if err != nil || c == nil {
650 // Called to dial out and run a connection. The addr we're given is already
651 // considered half-open.
652 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
653 c, err := cl.establishOutgoingConn(t, addr)
656 // Don't release lock between here and addConnection, unless it's for
658 cl.noLongerHalfOpen(t, addr)
661 log.Printf("error establishing outgoing connection: %s", err)
670 cl.runInitiatedHandshookConn(c, t)
673 // The port number for incoming peer connections. 0 if the client isn't
675 func (cl *Client) incomingPeerPort() int {
676 if cl.listenAddr == "" {
679 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
686 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
687 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
688 func addrCompactIP(addr net.Addr) (string, error) {
689 host, _, err := net.SplitHostPort(addr.String())
693 ip := net.ParseIP(host)
694 if v4 := ip.To4(); v4 != nil {
698 return string(v4), nil
700 return string(ip.To16()), nil
703 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
715 peerExtensionBytes [8]byte
719 func (pex *peerExtensionBytes) SupportsExtended() bool {
720 return pex[5]&0x10 != 0
723 func (pex *peerExtensionBytes) SupportsDHT() bool {
724 return pex[7]&0x01 != 0
727 func (pex *peerExtensionBytes) SupportsFast() bool {
728 return pex[7]&0x04 != 0
731 type handshakeResult struct {
737 // ih is nil if we expect the peer to declare the InfoHash, such as when the
738 // peer initiated the connection. Returns ok if the handshake was successful,
739 // and err if there was an unexpected condition other than the peer simply
740 // abandoning the handshake.
741 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
742 // Bytes to be sent to the peer. Should never block the sender.
743 postCh := make(chan []byte, 4)
744 // A single error value sent when the writer completes.
745 writeDone := make(chan error, 1)
746 // Performs writes to the socket and ensures posts don't block.
747 go handshakeWriter(sock, postCh, writeDone)
750 close(postCh) // Done writing.
757 // Wait until writes complete before returning from handshake.
760 err = fmt.Errorf("error writing: %s", err)
764 post := func(bb []byte) {
768 panic("mustn't block while posting")
772 post([]byte(pp.Protocol))
774 if ih != nil { // We already know what we want.
779 _, err = io.ReadFull(sock, b[:68])
784 if string(b[:20]) != pp.Protocol {
787 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
788 missinggo.CopyExact(&res.Hash, b[28:48])
789 missinggo.CopyExact(&res.peerID, b[48:68])
790 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
792 // TODO: Maybe we can just drop peers here if we're not interested. This
793 // could prevent them trying to reconnect, falsely believing there was
795 if ih == nil { // We were waiting for the peer to tell us what they wanted.
804 // Wraps a raw connection and provides the interface we want for using the
805 // connection in the message loop.
806 type deadlineReader struct {
811 func (r deadlineReader) Read(b []byte) (n int, err error) {
812 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
813 err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
815 err = fmt.Errorf("error setting read deadline: %s", err)
818 // Convert common errors into io.EOF.
820 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
822 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
832 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys mse.SecretKeyIter) (ret io.ReadWriter, encrypted bool, err error) {
833 var protocol [len(pp.Protocol)]byte
834 _, err = io.ReadFull(rw, protocol[:])
842 io.MultiReader(bytes.NewReader(protocol[:]), rw),
845 if string(protocol[:]) == pp.Protocol {
849 ret, err = mse.ReceiveHandshakeLazy(ret, skeys)
853 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
856 rw, err = mse.InitiateHandshake(struct {
859 }{c.r, c.w}, t.infoHash[:], nil)
865 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
866 if ih != t.infoHash {
872 // Calls f with any secret keys.
873 func (cl *Client) forSkeys(f func([]byte) bool) {
876 for ih := range cl.torrents {
883 // Do encryption and bittorrent handshakes as receiver.
884 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
885 if !cl.config.DisableEncryption {
887 rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw(), cl.forSkeys)
890 if err == mse.ErrNoSecretKeyMatch {
896 if cl.config.ForceEncryption && !c.encrypted {
897 err = errors.New("connection not encrypted")
900 ih, ok, err := cl.connBTHandshake(c, nil)
902 err = fmt.Errorf("error during bt handshake: %s", err)
914 // Returns !ok if handshake failed for valid reasons.
915 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
916 res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
917 if err != nil || !ok {
921 c.PeerExtensionBytes = res.peerExtensionBytes
922 c.PeerID = res.peerID
923 c.completedHandshake = time.Now()
927 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
928 if c.PeerID == cl.peerID {
930 addr := c.conn.RemoteAddr().String()
931 cl.dopplegangerAddrs[addr] = struct{}{}
934 cl.runHandshookConn(c, t, true)
937 func (cl *Client) runReceivedConn(c *connection) {
938 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
942 t, err := cl.receiveHandshakes(c)
945 log.Printf("error receiving handshakes: %s", err)
954 if c.PeerID == cl.peerID {
955 // Because the remote address is not necessarily the same as its
956 // client's torrent listen address, we won't record the remote address
957 // as a doppleganger. Instead, the initiator can record *us* as the
961 cl.runHandshookConn(c, t, false)
964 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
965 c.conn.SetWriteDeadline(time.Time{})
966 c.r = deadlineReader{c.conn, c.r}
967 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
968 if !t.addConnection(c, outgoing) {
971 defer t.dropConnection(c)
972 go c.writer(time.Minute)
973 cl.sendInitialMessages(c, t)
974 err := c.mainReadLoop()
975 if err != nil && cl.config.Debug {
976 log.Printf("error during connection loop: %s", err)
980 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
981 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
982 conn.Post(pp.Message{
984 ExtendedID: pp.HandshakeExtendedID,
985 ExtendedPayload: func() []byte {
986 d := map[string]interface{}{
987 "m": func() (ret map[string]int) {
988 ret = make(map[string]int, 2)
989 ret["ut_metadata"] = metadataExtendedId
990 if !cl.config.DisablePEX {
991 ret["ut_pex"] = pexExtendedId
995 "v": extendedHandshakeClientVersion,
996 // No upload queue is implemented yet.
999 if !cl.config.DisableEncryption {
1002 if torrent.metadataSizeKnown() {
1003 d["metadata_size"] = torrent.metadataSize()
1005 if p := cl.incomingPeerPort(); p != 0 {
1008 yourip, err := addrCompactIP(conn.remoteAddr())
1010 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1012 d["yourip"] = yourip
1014 // log.Printf("sending %v", d)
1015 b, err := bencode.Marshal(d)
1023 if torrent.haveAnyPieces() {
1024 conn.Bitfield(torrent.bitfield())
1025 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1026 conn.Post(pp.Message{
1030 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
1031 conn.Post(pp.Message{
1033 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
1038 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
1039 conn.updateRequests()
1042 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1045 postedCancels.Add(1)
1050 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1051 if !cn.RequestPending(r) {
1054 delete(cn.Requests, r)
1058 // Process incoming ut_metadata message.
1059 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1060 var d map[string]int
1061 err := bencode.Unmarshal(payload, &d)
1063 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1065 msgType, ok := d["msg_type"]
1067 return errors.New("missing msg_type field")
1071 case pp.DataMetadataExtensionMsgType:
1072 if !c.requestedMetadataPiece(piece) {
1073 return fmt.Errorf("got unexpected piece %d", piece)
1075 c.metadataRequests[piece] = false
1076 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1077 if begin < 0 || begin >= len(payload) {
1078 return fmt.Errorf("data has bad offset in payload: %d", begin)
1080 t.saveMetadataPiece(piece, payload[begin:])
1081 c.UsefulChunksReceived++
1082 c.lastUsefulChunkReceived = time.Now()
1083 return t.maybeCompleteMetadata()
1084 case pp.RequestMetadataExtensionMsgType:
1085 if !t.haveMetadataPiece(piece) {
1086 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1089 start := (1 << 14) * piece
1090 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1092 case pp.RejectMetadataExtensionMsgType:
1095 return errors.New("unknown msg_type value")
1099 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1100 // Count the chunk being sent, even if it isn't.
1101 b := make([]byte, r.Length)
1102 p := t.info.Piece(int(r.Index))
1103 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1106 panic("expected error")
1117 uploadChunksPosted.Add(1)
1118 c.lastChunkSent = time.Now()
1122 func (cl *Client) openNewConns(t *Torrent) {
1123 defer t.updateWantPeersEvent()
1124 for len(t.peers) != 0 {
1128 if len(t.halfOpen) >= cl.halfOpenLimit {
1135 for k, p = range t.peers {
1139 cl.initiateConn(p, t)
1143 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1147 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1150 if _, ok := cl.ipBlockRange(ip); ok {
1153 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1159 // Return a Torrent ready for insertion into a Client.
1160 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1161 // use provided storage, if provided
1162 storageClient := cl.defaultStorage
1163 if specStorage != nil {
1164 storageClient = storage.NewClient(specStorage)
1170 peers: make(map[peersKey]Peer),
1171 conns: make(map[*connection]struct{}, 2*defaultEstablishedConnsPerTorrent),
1173 halfOpen: make(map[string]struct{}),
1174 pieceStateChanges: pubsub.NewPubSub(),
1176 storageOpener: storageClient,
1177 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1179 networkingEnabled: true,
1181 t.setChunkSize(defaultChunkSize)
1185 // A file-like handle to some torrent data resource.
1186 type Handle interface {
1193 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1194 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1197 // Adds a torrent by InfoHash with a custom Storage implementation.
1198 // If the torrent already exists then this Storage is ignored and the
1199 // existing torrent returned with `new` set to `false`
1200 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1202 defer cl.mu.Unlock()
1203 t, ok := cl.torrents[infoHash]
1208 t = cl.newTorrent(infoHash, specStorage)
1212 cl.torrents[infoHash] = t
1213 t.updateWantPeersEvent()
1214 // Tickle Client.waitAccept, new torrent may want conns.
1215 cl.event.Broadcast()
1219 // Add or merge a torrent spec. If the torrent is already present, the
1220 // trackers will be merged with the existing ones. If the Info isn't yet
1221 // known, it will be set. The display name is replaced if the new spec
1222 // provides one. Returns new if the torrent wasn't already in the client.
1223 // Note that any `Storage` defined on the spec will be ignored if the
1224 // torrent is already present (i.e. `new` return value is `true`)
1225 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1226 t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1227 if spec.DisplayName != "" {
1228 t.SetDisplayName(spec.DisplayName)
1230 if spec.InfoBytes != nil {
1231 err = t.SetInfoBytes(spec.InfoBytes)
1237 defer cl.mu.Unlock()
1238 if spec.ChunkSize != 0 {
1239 t.setChunkSize(pp.Integer(spec.ChunkSize))
1241 t.addTrackers(spec.Trackers)
1246 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1247 t, ok := cl.torrents[infoHash]
1249 err = fmt.Errorf("no such torrent")
1256 delete(cl.torrents, infoHash)
1260 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1261 _url, err := url.Parse(announceURL)
1265 hmp := missinggo.SplitHostMaybePort(_url.Host)
1270 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1275 _, blocked = cl.ipBlockRange(addr.IP)
1278 hmp.Host = addr.String()
1279 _url.Host = hmp.String()
1280 urlToUse = _url.String()
1284 func (cl *Client) allTorrentsCompleted() bool {
1285 for _, t := range cl.torrents {
1289 if t.numPiecesCompleted() != t.numPieces() {
1296 // Returns true when all torrents are completely downloaded and false if the
1297 // client is stopped before that.
1298 func (cl *Client) WaitAll() bool {
1300 defer cl.mu.Unlock()
1301 for !cl.allTorrentsCompleted() {
1302 if cl.closed.IsSet() {
1310 // Returns handles to all the torrents loaded in the Client.
1311 func (cl *Client) Torrents() []*Torrent {
1313 defer cl.mu.Unlock()
1314 return cl.torrentsAsSlice()
1317 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1318 for _, t := range cl.torrents {
1319 ret = append(ret, t)
1324 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1325 spec, err := TorrentSpecFromMagnetURI(uri)
1329 T, _, err = cl.AddTorrentSpec(spec)
1333 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1334 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1336 slices.MakeInto(&ss, mi.Nodes)
1341 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1342 mi, err := metainfo.LoadFromFile(filename)
1346 return cl.AddTorrent(mi)
1349 func (cl *Client) DHT() *dht.Server {
1353 func (cl *Client) AddDHTNodes(nodes []string) {
1354 if cl.DHT() == nil {
1357 for _, n := range nodes {
1358 hmp := missinggo.SplitHostMaybePort(n)
1359 ip := net.ParseIP(hmp.Host)
1361 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1364 ni := krpc.NodeInfo{
1370 cl.DHT().AddNode(ni)
1374 func (cl *Client) banPeerIP(ip net.IP) {
1375 if cl.badPeerIPs == nil {
1376 cl.badPeerIPs = make(map[string]struct{})
1378 cl.badPeerIPs[ip.String()] = struct{}{}
1381 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1387 PeerMaxRequests: 250,
1389 c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1390 c.r = rateLimitedReader{cl.downloadLimit, c.r}
1394 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1396 defer cl.mu.Unlock()
1404 Source: peerSourceDHTAnnouncePeer,