18 "github.com/anacrolix/dht"
19 "github.com/anacrolix/dht/krpc"
20 "github.com/anacrolix/missinggo"
21 "github.com/anacrolix/missinggo/pproffd"
22 "github.com/anacrolix/missinggo/pubsub"
23 "github.com/anacrolix/missinggo/slices"
24 "github.com/anacrolix/sync"
25 "github.com/dustin/go-humanize"
26 "golang.org/x/time/rate"
28 "github.com/anacrolix/torrent/bencode"
29 "github.com/anacrolix/torrent/iplist"
30 "github.com/anacrolix/torrent/metainfo"
31 "github.com/anacrolix/torrent/mse"
32 pp "github.com/anacrolix/torrent/peer_protocol"
33 "github.com/anacrolix/torrent/storage"
36 // Clients contain zero or more Torrents. A Client manages a blocklist, the
37 // TCP/UDP protocol ports, and DHT as desired.
41 closed missinggo.Event
47 defaultStorage *storage.Client
49 tcpListener net.Listener
52 ipBlockList iplist.Ranger
53 // Our BitTorrent protocol extension bytes, sent in our BT handshakes.
54 extensionBytes peerExtensionBytes
55 // The net.Addr.String part that should be common to all active listeners.
57 uploadLimit *rate.Limiter
58 downloadLimit *rate.Limiter
60 // Set of addresses that have our client ID. This intentionally will
61 // include ourselves if we end up trying to connect to our own address
62 // through legitimate channels.
63 dopplegangerAddrs map[string]struct{}
64 badPeerIPs map[string]struct{}
65 torrents map[metainfo.Hash]*Torrent
68 func (cl *Client) BadPeerIPs() []string {
71 return cl.badPeerIPsLocked()
74 func (cl *Client) badPeerIPsLocked() []string {
75 return slices.FromMapKeys(cl.badPeerIPs).([]string)
78 func (cl *Client) IPBlockList() iplist.Ranger {
84 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
89 cl.dHT.SetIPBlockList(list)
93 func (cl *Client) PeerID() string {
94 return string(cl.peerID[:])
97 type torrentAddr string
99 func (torrentAddr) Network() string { return "" }
101 func (me torrentAddr) String() string { return string(me) }
103 func (cl *Client) ListenAddr() net.Addr {
104 if cl.listenAddr == "" {
107 return torrentAddr(cl.listenAddr)
110 // Writes out a human readable status of the client, such as for writing to a
112 func (cl *Client) WriteStatus(_w io.Writer) {
115 w := bufio.NewWriter(_w)
117 if addr := cl.ListenAddr(); addr != nil {
118 fmt.Fprintf(w, "Listening on %s\n", addr)
120 fmt.Fprintln(w, "Not listening!")
122 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
123 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
124 if dht := cl.DHT(); dht != nil {
125 dhtStats := dht.Stats()
126 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
127 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
128 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
129 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
130 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
132 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
134 for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
135 return l.InfoHash().AsString() < r.InfoHash().AsString()
138 fmt.Fprint(w, "<unknown name>")
140 fmt.Fprint(w, t.name())
144 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())))
146 w.WriteString("<missing metainfo>")
154 func listenUTP(networkSuffix, addr string) (utpSocket, error) {
155 return NewUtpSocket("udp"+networkSuffix, addr)
158 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
159 return net.Listen("tcp"+networkSuffix, addr)
162 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
164 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
168 listenedAddr = tcpL.Addr().String()
169 utpSock, err = listenUTP(networkSuffix, listenedAddr)
174 if !strings.Contains(err.Error(), "address already in use") {
180 // Listen to enabled protocols, ensuring ports match.
181 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
188 host, port, err = missinggo.ParseHostPort(addr)
193 // If both protocols are active, they need to have the same port.
194 return listenBothSameDynamicPort(networkSuffix, host)
203 tcpL, err = listenTCP(networkSuffix, addr)
212 listenedAddr = tcpL.Addr().String()
215 utpSock, err = listenUTP(networkSuffix, addr)
219 listenedAddr = utpSock.Addr().String()
224 // Creates a new client.
225 func NewClient(cfg *Config) (cl *Client, err error) {
236 halfOpenLimit: defaultHalfOpenConnsPerTorrent,
238 dopplegangerAddrs: make(map[string]struct{}),
239 torrents: make(map[metainfo.Hash]*Torrent),
247 if cfg.UploadRateLimiter == nil {
248 cl.uploadLimit = rate.NewLimiter(rate.Inf, 0)
250 cl.uploadLimit = cfg.UploadRateLimiter
252 if cfg.DownloadRateLimiter == nil {
253 cl.downloadLimit = rate.NewLimiter(rate.Inf, 0)
255 cl.downloadLimit = cfg.DownloadRateLimiter
257 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
259 storageImpl := cfg.DefaultStorage
260 if storageImpl == nil {
261 storageImpl = storage.NewFile(cfg.DataDir)
262 cl.onClose = append(cl.onClose, func() {
263 if err := storageImpl.Close(); err != nil {
264 log.Printf("error closing default storage: %s", err)
268 cl.defaultStorage = storage.NewClient(storageImpl)
269 if cfg.IPBlocklist != nil {
270 cl.ipBlockList = cfg.IPBlocklist
273 if cfg.PeerID != "" {
274 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
276 o := copy(cl.peerID[:], bep20)
277 _, err = rand.Read(cl.peerID[o:])
279 panic("error generating peer id")
283 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
284 !cl.config.DisableTCP,
285 !cl.config.DisableUTP,
287 if cl.config.DisableIPv6 {
293 cl.config.ListenAddr)
297 if cl.tcpListener != nil {
298 go cl.acceptConnections(cl.tcpListener, false)
300 if cl.utpSock != nil {
301 go cl.acceptConnections(cl.utpSock, true)
304 dhtCfg := cfg.DHTConfig
305 if dhtCfg.IPBlocklist == nil {
306 dhtCfg.IPBlocklist = cl.ipBlockList
308 if dhtCfg.Conn == nil {
309 if cl.utpSock != nil {
310 dhtCfg.Conn = cl.utpSock
312 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
318 if dhtCfg.OnAnnouncePeer == nil {
319 dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
321 cl.dHT, err = dht.NewServer(&dhtCfg)
326 if _, err := cl.dHT.Bootstrap(); err != nil {
327 log.Printf("error bootstrapping dht: %s", err)
335 func firstNonEmptyString(ss ...string) string {
336 for _, s := range ss {
344 // Stops the client. All connections to peers are closed and all activity will
346 func (cl *Client) Close() {
353 if cl.utpSock != nil {
356 if cl.tcpListener != nil {
357 cl.tcpListener.Close()
359 for _, t := range cl.torrents {
362 for _, f := range cl.onClose {
368 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
370 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
371 if cl.ipBlockList == nil {
375 // If blocklists are enabled, then block non-IPv4 addresses, because
376 // blocklists do not yet support IPv6.
378 if missinggo.CryHeard() {
379 log.Printf("blocking non-IPv4 address: %s", ip)
385 return cl.ipBlockList.Lookup(ip4)
388 func (cl *Client) waitAccept() {
390 for _, t := range cl.torrents {
395 if cl.closed.IsSet() {
402 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
408 conn, err := l.Accept()
409 conn = pproffd.WrapNetConn(conn)
411 if cl.closed.IsSet() {
419 // I think something harsher should happen here? Our accept
420 // routine just fucked off.
429 log.Printf("accepted connection from %s", conn.RemoteAddr())
431 reject := cl.badPeerIPPort(
432 missinggo.AddrIP(conn.RemoteAddr()),
433 missinggo.AddrPort(conn.RemoteAddr()))
436 log.Printf("rejecting connection from %s", conn.RemoteAddr())
442 go cl.incomingConnection(conn, utp)
446 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
448 if tc, ok := nc.(*net.TCPConn); ok {
451 c := cl.newConnection(nc)
452 c.Discovery = peerSourceIncoming
454 cl.runReceivedConn(c)
457 // Returns a handle to the given torrent, if it's present in the client.
458 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
461 t, ok = cl.torrents[ih]
465 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
466 return cl.torrents[ih]
469 type dialResult struct {
474 func doDial(dial func(string, *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
475 conn, err := dial(addr, t)
480 conn = nil // Pedantic
482 ch <- dialResult{conn, utp}
484 successfulDials.Add(1)
487 unsuccessfulDials.Add(1)
490 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
491 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
492 if ret < minDialTimeout {
498 // Returns whether an address is known to connect to a client with our own ID.
499 func (cl *Client) dopplegangerAddr(addr string) bool {
500 _, ok := cl.dopplegangerAddrs[addr]
504 // Start the process of connecting to the given peer for the given torrent if
506 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
507 if peer.Id == cl.peerID {
510 if cl.badPeerIPPort(peer.IP, peer.Port) {
513 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
514 if t.addrActive(addr) {
517 t.halfOpen[addr] = struct{}{}
518 go cl.outgoingConnection(t, addr, peer.Source)
521 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
523 pendingPeers := len(t.peers)
525 return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
528 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
529 c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
531 c.(*net.TCPConn).SetLinger(0)
533 c = pproffd.WrapNetConn(c)
537 func (cl *Client) dialUTP(addr string, t *Torrent) (net.Conn, error) {
538 return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
541 // Returns a connection over UTP or TCP, whichever is first to connect.
542 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
543 // Initiate connections via TCP and UTP simultaneously. Use the first one
546 resCh := make(chan dialResult, left)
547 if !cl.config.DisableUTP {
549 go doDial(cl.dialUTP, resCh, true, addr, t)
551 if !cl.config.DisableTCP {
553 go doDial(cl.dialTCP, resCh, false, addr, t)
556 // Wait for a successful connection.
557 for ; left > 0 && res.Conn == nil; left-- {
561 // There are still incompleted dials.
563 for ; left > 0; left-- {
564 conn := (<-resCh).Conn
576 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
577 if _, ok := t.halfOpen[addr]; !ok {
578 panic("invariant broken")
580 delete(t.halfOpen, addr)
584 // Performs initiator handshakes and returns a connection. Returns nil
585 // *connection if no connection for valid reasons.
586 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
587 c = cl.newConnection(nc)
588 c.encrypted = encrypted
590 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
594 ok, err := cl.initiateHandshakes(c, t)
601 // Returns nil connection and nil error if no connection could be established
602 // for valid reasons.
603 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
604 nc, utp := cl.dialFirst(addr, t)
608 encryptFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
609 c, err = cl.handshakesConnection(nc, t, encryptFirst, utp)
617 if cl.config.DisableEncryption || cl.config.ForceEncryption {
618 // There's no alternate encryption case to try.
621 // Try again with encryption if we didn't earlier, or without if we did,
622 // using whichever protocol type worked last time.
624 nc, err = cl.dialUTP(addr, t)
626 nc, err = cl.dialTCP(addr, t)
629 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
632 c, err = cl.handshakesConnection(nc, t, !encryptFirst, utp)
633 if err != nil || c == nil {
639 // Called to dial out and run a connection. The addr we're given is already
640 // considered half-open.
641 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
642 c, err := cl.establishOutgoingConn(t, addr)
645 // Don't release lock between here and addConnection, unless it's for
647 cl.noLongerHalfOpen(t, addr)
650 log.Printf("error establishing outgoing connection: %s", err)
659 cl.runInitiatedHandshookConn(c, t)
662 // The port number for incoming peer connections. 0 if the client isn't
664 func (cl *Client) incomingPeerPort() int {
665 if cl.listenAddr == "" {
668 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
675 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
676 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
677 func addrCompactIP(addr net.Addr) (string, error) {
678 host, _, err := net.SplitHostPort(addr.String())
682 ip := net.ParseIP(host)
683 if v4 := ip.To4(); v4 != nil {
687 return string(v4), nil
689 return string(ip.To16()), nil
692 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
704 peerExtensionBytes [8]byte
708 func (pex *peerExtensionBytes) SupportsExtended() bool {
709 return pex[5]&0x10 != 0
712 func (pex *peerExtensionBytes) SupportsDHT() bool {
713 return pex[7]&0x01 != 0
716 func (pex *peerExtensionBytes) SupportsFast() bool {
717 return pex[7]&0x04 != 0
720 type handshakeResult struct {
726 // ih is nil if we expect the peer to declare the InfoHash, such as when the
727 // peer initiated the connection. Returns ok if the handshake was successful,
728 // and err if there was an unexpected condition other than the peer simply
729 // abandoning the handshake.
730 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
731 // Bytes to be sent to the peer. Should never block the sender.
732 postCh := make(chan []byte, 4)
733 // A single error value sent when the writer completes.
734 writeDone := make(chan error, 1)
735 // Performs writes to the socket and ensures posts don't block.
736 go handshakeWriter(sock, postCh, writeDone)
739 close(postCh) // Done writing.
746 // Wait until writes complete before returning from handshake.
749 err = fmt.Errorf("error writing: %s", err)
753 post := func(bb []byte) {
757 panic("mustn't block while posting")
761 post([]byte(pp.Protocol))
763 if ih != nil { // We already know what we want.
768 _, err = io.ReadFull(sock, b[:68])
773 if string(b[:20]) != pp.Protocol {
776 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
777 missinggo.CopyExact(&res.Hash, b[28:48])
778 missinggo.CopyExact(&res.peerID, b[48:68])
779 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
781 // TODO: Maybe we can just drop peers here if we're not interested. This
782 // could prevent them trying to reconnect, falsely believing there was
784 if ih == nil { // We were waiting for the peer to tell us what they wanted.
793 // Wraps a raw connection and provides the interface we want for using the
794 // connection in the message loop.
795 type deadlineReader struct {
800 func (r deadlineReader) Read(b []byte) (n int, err error) {
801 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
802 err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
804 err = fmt.Errorf("error setting read deadline: %s", err)
807 // Convert common errors into io.EOF.
809 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
811 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
821 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys mse.SecretKeyIter) (ret io.ReadWriter, encrypted bool, err error) {
822 var protocol [len(pp.Protocol)]byte
823 _, err = io.ReadFull(rw, protocol[:])
831 io.MultiReader(bytes.NewReader(protocol[:]), rw),
834 if string(protocol[:]) == pp.Protocol {
838 ret, err = mse.ReceiveHandshakeLazy(ret, skeys)
842 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
845 rw, err = mse.InitiateHandshake(struct {
848 }{c.r, c.w}, t.infoHash[:], nil)
854 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
855 if ih != t.infoHash {
861 // Calls f with any secret keys.
862 func (cl *Client) forSkeys(f func([]byte) bool) {
865 for ih := range cl.torrents {
872 // Do encryption and bittorrent handshakes as receiver.
873 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
874 if !cl.config.DisableEncryption {
876 rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw(), cl.forSkeys)
879 if err == mse.ErrNoSecretKeyMatch {
885 if cl.config.ForceEncryption && !c.encrypted {
886 err = errors.New("connection not encrypted")
889 ih, ok, err := cl.connBTHandshake(c, nil)
891 err = fmt.Errorf("error during bt handshake: %s", err)
903 // Returns !ok if handshake failed for valid reasons.
904 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
905 res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
906 if err != nil || !ok {
910 c.PeerExtensionBytes = res.peerExtensionBytes
911 c.PeerID = res.peerID
912 c.completedHandshake = time.Now()
916 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
917 if c.PeerID == cl.peerID {
919 addr := c.conn.RemoteAddr().String()
920 cl.dopplegangerAddrs[addr] = struct{}{}
923 cl.runHandshookConn(c, t, true)
926 func (cl *Client) runReceivedConn(c *connection) {
927 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
931 t, err := cl.receiveHandshakes(c)
934 log.Printf("error receiving handshakes: %s", err)
943 if c.PeerID == cl.peerID {
944 // Because the remote address is not necessarily the same as its
945 // client's torrent listen address, we won't record the remote address
946 // as a doppleganger. Instead, the initiator can record *us* as the
950 cl.runHandshookConn(c, t, false)
953 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
954 c.conn.SetWriteDeadline(time.Time{})
955 c.r = deadlineReader{c.conn, c.r}
956 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
957 if !t.addConnection(c, outgoing) {
960 defer t.dropConnection(c)
961 go c.writer(time.Minute)
962 cl.sendInitialMessages(c, t)
963 err := c.mainReadLoop()
964 if err != nil && cl.config.Debug {
965 log.Printf("error during connection loop: %s", err)
969 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
970 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
971 conn.Post(pp.Message{
973 ExtendedID: pp.HandshakeExtendedID,
974 ExtendedPayload: func() []byte {
975 d := map[string]interface{}{
976 "m": func() (ret map[string]int) {
977 ret = make(map[string]int, 2)
978 ret["ut_metadata"] = metadataExtendedId
979 if !cl.config.DisablePEX {
980 ret["ut_pex"] = pexExtendedId
984 "v": extendedHandshakeClientVersion,
985 // No upload queue is implemented yet.
988 if !cl.config.DisableEncryption {
991 if torrent.metadataSizeKnown() {
992 d["metadata_size"] = torrent.metadataSize()
994 if p := cl.incomingPeerPort(); p != 0 {
997 yourip, err := addrCompactIP(conn.remoteAddr())
999 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1001 d["yourip"] = yourip
1003 // log.Printf("sending %v", d)
1004 b, err := bencode.Marshal(d)
1012 if torrent.haveAnyPieces() {
1013 conn.Bitfield(torrent.bitfield())
1014 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1015 conn.Post(pp.Message{
1019 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
1020 conn.Post(pp.Message{
1022 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
1027 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
1028 conn.updateRequests()
1031 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1034 postedCancels.Add(1)
1039 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1040 if !cn.RequestPending(r) {
1043 delete(cn.Requests, r)
1047 // Process incoming ut_metadata message.
1048 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1049 var d map[string]int
1050 err := bencode.Unmarshal(payload, &d)
1052 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1054 msgType, ok := d["msg_type"]
1056 return errors.New("missing msg_type field")
1060 case pp.DataMetadataExtensionMsgType:
1061 if !c.requestedMetadataPiece(piece) {
1062 return fmt.Errorf("got unexpected piece %d", piece)
1064 c.metadataRequests[piece] = false
1065 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1066 if begin < 0 || begin >= len(payload) {
1067 return fmt.Errorf("data has bad offset in payload: %d", begin)
1069 t.saveMetadataPiece(piece, payload[begin:])
1070 c.UsefulChunksReceived++
1071 c.lastUsefulChunkReceived = time.Now()
1072 return t.maybeCompleteMetadata()
1073 case pp.RequestMetadataExtensionMsgType:
1074 if !t.haveMetadataPiece(piece) {
1075 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1078 start := (1 << 14) * piece
1079 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1081 case pp.RejectMetadataExtensionMsgType:
1084 return errors.New("unknown msg_type value")
1088 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1089 // Count the chunk being sent, even if it isn't.
1090 b := make([]byte, r.Length)
1091 p := t.info.Piece(int(r.Index))
1092 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1095 panic("expected error")
1106 uploadChunksPosted.Add(1)
1107 c.lastChunkSent = time.Now()
1111 func (cl *Client) openNewConns(t *Torrent) {
1112 defer t.updateWantPeersEvent()
1113 for len(t.peers) != 0 {
1117 if len(t.halfOpen) >= cl.halfOpenLimit {
1124 for k, p = range t.peers {
1128 cl.initiateConn(p, t)
1132 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1136 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1139 if _, ok := cl.ipBlockRange(ip); ok {
1142 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1148 // Return a Torrent ready for insertion into a Client.
1149 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1150 // use provided storage, if provided
1151 storageClient := cl.defaultStorage
1152 if specStorage != nil {
1153 storageClient = storage.NewClient(specStorage)
1159 peers: make(map[peersKey]Peer),
1160 conns: make(map[*connection]struct{}, 2*defaultEstablishedConnsPerTorrent),
1162 halfOpen: make(map[string]struct{}),
1163 pieceStateChanges: pubsub.NewPubSub(),
1165 storageOpener: storageClient,
1166 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1168 t.setChunkSize(defaultChunkSize)
1172 // A file-like handle to some torrent data resource.
1173 type Handle interface {
1180 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1181 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1184 // Adds a torrent by InfoHash with a custom Storage implementation.
1185 // If the torrent already exists then this Storage is ignored and the
1186 // existing torrent returned with `new` set to `false`
1187 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1189 defer cl.mu.Unlock()
1190 t, ok := cl.torrents[infoHash]
1195 t = cl.newTorrent(infoHash, specStorage)
1199 cl.torrents[infoHash] = t
1200 t.updateWantPeersEvent()
1201 // Tickle Client.waitAccept, new torrent may want conns.
1202 cl.event.Broadcast()
1206 // Add or merge a torrent spec. If the torrent is already present, the
1207 // trackers will be merged with the existing ones. If the Info isn't yet
1208 // known, it will be set. The display name is replaced if the new spec
1209 // provides one. Returns new if the torrent wasn't already in the client.
1210 // Note that any `Storage` defined on the spec will be ignored if the
1211 // torrent is already present (i.e. `new` return value is `true`)
1212 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1213 t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1214 if spec.DisplayName != "" {
1215 t.SetDisplayName(spec.DisplayName)
1217 if spec.InfoBytes != nil {
1218 err = t.SetInfoBytes(spec.InfoBytes)
1224 defer cl.mu.Unlock()
1225 if spec.ChunkSize != 0 {
1226 t.setChunkSize(pp.Integer(spec.ChunkSize))
1228 t.addTrackers(spec.Trackers)
1233 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1234 t, ok := cl.torrents[infoHash]
1236 err = fmt.Errorf("no such torrent")
1243 delete(cl.torrents, infoHash)
1247 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1248 _url, err := url.Parse(announceURL)
1252 hmp := missinggo.SplitHostMaybePort(_url.Host)
1257 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1262 _, blocked = cl.ipBlockRange(addr.IP)
1265 hmp.Host = addr.String()
1266 _url.Host = hmp.String()
1267 urlToUse = _url.String()
1271 func (cl *Client) allTorrentsCompleted() bool {
1272 for _, t := range cl.torrents {
1276 if t.numPiecesCompleted() != t.numPieces() {
1283 // Returns true when all torrents are completely downloaded and false if the
1284 // client is stopped before that.
1285 func (cl *Client) WaitAll() bool {
1287 defer cl.mu.Unlock()
1288 for !cl.allTorrentsCompleted() {
1289 if cl.closed.IsSet() {
1297 // Returns handles to all the torrents loaded in the Client.
1298 func (cl *Client) Torrents() []*Torrent {
1300 defer cl.mu.Unlock()
1301 return cl.torrentsAsSlice()
1304 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1305 for _, t := range cl.torrents {
1306 ret = append(ret, t)
1311 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1312 spec, err := TorrentSpecFromMagnetURI(uri)
1316 T, _, err = cl.AddTorrentSpec(spec)
1320 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1321 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1323 slices.MakeInto(&ss, mi.Nodes)
1328 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1329 mi, err := metainfo.LoadFromFile(filename)
1333 return cl.AddTorrent(mi)
1336 func (cl *Client) DHT() *dht.Server {
1340 func (cl *Client) AddDHTNodes(nodes []string) {
1341 if cl.DHT() == nil {
1344 for _, n := range nodes {
1345 hmp := missinggo.SplitHostMaybePort(n)
1346 ip := net.ParseIP(hmp.Host)
1348 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1351 ni := krpc.NodeInfo{
1357 cl.DHT().AddNode(ni)
1361 func (cl *Client) banPeerIP(ip net.IP) {
1362 if cl.badPeerIPs == nil {
1363 cl.badPeerIPs = make(map[string]struct{})
1365 cl.badPeerIPs[ip.String()] = struct{}{}
1368 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1374 PeerMaxRequests: 250,
1376 c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1377 c.r = rateLimitedReader{cl.downloadLimit, c.r}
1381 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1383 defer cl.mu.Unlock()
1391 Source: peerSourceDHTAnnouncePeer,