2 Package torrent implements a torrent client.
9 if err := c.AddTorrent(externalMetaInfoPackageSux); err != nil {
10 return fmt.Errors("error adding torrent: %s", err)
13 log.Print("erhmahgerd, torrent downloaded")
38 "github.com/h2so5/utp"
40 "github.com/anacrolix/libtorgo/metainfo"
41 "github.com/nsf/libtorgo/bencode"
43 "bitbucket.org/anacrolix/go.torrent/dht"
44 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
45 "bitbucket.org/anacrolix/go.torrent/tracker"
46 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
47 . "bitbucket.org/anacrolix/go.torrent/util"
48 "bitbucket.org/anacrolix/go.torrent/util/levelmu"
52 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
53 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
54 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
55 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
56 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
57 unexpectedCancels = expvar.NewInt("unexpectedCancels")
58 postedCancels = expvar.NewInt("postedCancels")
59 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
60 failedPieceHashes = expvar.NewInt("failedPieceHashes")
64 // Justification for set bits follows.
66 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html
67 // DHT: http://www.bittorrent.org/beps/bep_0005.html
68 extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
70 socketsPerTorrent = 40
73 // Currently doesn't really queue, but should in the future.
74 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
75 piece := t.Pieces[pieceIndex]
76 if piece.QueuedForHash {
79 piece.QueuedForHash = true
80 go cl.verifyPiece(t, pieceIndex)
83 func (cl *Client) queueFirstHash(t *torrent, piece int) {
85 if p.EverHashed || p.Hashing || p.QueuedForHash {
88 cl.queuePieceCheck(t, pp.Integer(piece))
91 // Queues the torrent data for the given region for download. The beginning of
92 // the region is given highest priority to allow a subsequent read at the same
93 // offset to return data ASAP.
94 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
99 return errors.New("no such active torrent")
102 return errors.New("missing metadata")
104 me.downloadStrategy.TorrentPrioritize(t, off, len_)
105 for _, cn := range t.Conns {
106 me.replenishConnRequests(t, cn)
111 type dataWait struct {
121 listeners []net.Listener
123 downloadStrategy DownloadStrategy
126 mu levelmu.LevelMutex
132 torrents map[InfoHash]*torrent
134 dataWaits map[*torrent][]dataWait
137 func (me *Client) PeerID() string {
138 return string(me.peerID[:])
141 func (me *Client) ListenAddr() (addr net.Addr) {
142 for _, l := range me.listeners {
143 if addr != nil && l.Addr().String() != addr.String() {
144 panic("listeners exist on different addresses")
151 func (cl *Client) WriteStatus(w io.Writer) {
154 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
155 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
156 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
158 fmt.Fprintf(w, "DHT nodes: %d\n", cl.dHT.NumNodes())
159 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
160 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
161 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
163 cl.downloadStrategy.WriteStatus(w)
165 for _, t := range cl.torrents {
166 fmt.Fprintf(w, "%s: %f%%\n", t.Name(), func() float32 {
170 return 100 * (1 - float32(t.BytesLeft())/float32(t.Length()))
173 fmt.Fprint(w, "Blocked reads:")
174 for _, dw := range cl.dataWaits[t] {
175 fmt.Fprintf(w, " %d", dw.offset)
183 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
185 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
190 err = errors.New("unknown torrent")
193 index := pp.Integer(off / int64(t.UsualPieceSize()))
194 // Reading outside the bounds of a file is an error.
199 if int(index) >= len(t.Pieces) {
203 piece := t.Pieces[index]
204 pieceOff := pp.Integer(off % int64(t.UsualPieceSize()))
205 pieceLeft := int(t.PieceLength(index) - pieceOff)
210 if len(p) > pieceLeft {
213 for cs, _ := range piece.PendingChunkSpecs {
214 chunkOff := int64(pieceOff) - int64(cs.Begin)
215 if chunkOff >= int64(t.PieceLength(index)) {
218 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
219 // read begins in a pending chunk
220 err = ErrDataNotReady
223 // pending chunk caps available data
224 if chunkOff < 0 && int64(len(p)) > -chunkOff {
231 return t.Data.ReadAt(p, off)
234 func dhtAddr(listen net.Addr) (s string, err error) {
235 host, port, err := net.SplitHostPort(listen.String())
239 i64, err := strconv.ParseInt(port, 0, 0)
243 s = net.JoinHostPort(host, strconv.FormatInt(i64+1, 10))
247 func NewClient(cfg *Config) (cl *Client, err error) {
253 noUpload: cfg.NoUpload,
254 disableTrackers: cfg.DisableTrackers,
255 downloadStrategy: cfg.DownloadStrategy,
257 dataDir: cfg.DataDir,
259 quit: make(chan struct{}),
260 torrents: make(map[InfoHash]*torrent),
262 dataWaits: make(map[*torrent][]dataWait),
267 if cfg.PeerID != "" {
268 CopyExact(&cl.peerID, cfg.PeerID)
270 o := copy(cl.peerID[:], BEP20)
271 _, err = rand.Read(cl.peerID[o:])
273 panic("error generating peer id")
277 if cl.downloadStrategy == nil {
278 cl.downloadStrategy = &DefaultDownloadStrategy{}
281 // Returns the laddr string to listen on for the next Listen call.
282 listenAddr := func() string {
283 if addr := cl.ListenAddr(); addr != nil {
286 return cfg.ListenAddr
290 l, err = net.Listen("tcp", listenAddr())
294 cl.listeners = append(cl.listeners, l)
295 go cl.acceptConnections(l, false)
298 l, err = utp.Listen("utp", listenAddr())
302 cl.listeners = append(cl.listeners, l)
303 go cl.acceptConnections(l, true)
307 dhtAddr_, err = dhtAddr(cl.ListenAddr())
311 cl.dHT, err = dht.NewServer(&dht.ServerConfig{
322 func (cl *Client) stopped() bool {
331 // Stops the client. All connections to peers are closed and all activity will
333 func (me *Client) Stop() {
337 for _, t := range me.torrents {
343 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
345 // We accept all connections immediately, because we don't what
346 // torrent they're for.
347 conn, err := l.Accept()
361 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
368 func (me *Client) torrent(ih InfoHash) *torrent {
369 for _, t := range me.torrents {
370 if t.InfoHash == ih {
377 // Start the process of connecting to the given peer for the given torrent if
379 func (me *Client) initiateConn(peer Peer, t *torrent) {
380 if peer.Id == me.peerID {
383 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
384 if t.addrActive(addr) {
385 duplicateConnsAvoided.Add(1)
388 t.HalfOpen[addr] = struct{}{}
390 // Binding to the listener address and dialing via net.Dialer gives
391 // "address in use" error. It seems it's not possible to dial out from
392 // this address so that peers associate our local address with our
399 conn, err = net.DialTimeout("tcp", addr, dialTimeout)
401 conn, err = (&utp.Dialer{Timeout: dialTimeout}).Dial("utp", addr)
404 // Whether or not the connection attempt succeeds, the half open
405 // counter should be decremented, and new connection attempts made.
409 if _, ok := t.HalfOpen[addr]; !ok {
410 panic("invariant broken")
412 delete(t.HalfOpen, addr)
416 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
419 if netOpErr, ok := err.(*net.OpError); ok {
420 switch netOpErr.Err {
421 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
426 log.Printf("error connecting to peer: %s %#v", err, err)
429 // log.Printf("connected to %s", conn.RemoteAddr())
430 err = me.runConnection(conn, t, peer.Source, true)
437 // The port number for incoming peer connections. 0 if the client isn't
439 func (cl *Client) incomingPeerPort() int {
440 listenAddr := cl.ListenAddr()
441 if listenAddr == nil {
444 return addrPort(listenAddr)
447 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
448 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
449 func addrCompactIP(addr net.Addr) (string, error) {
450 host, _, err := net.SplitHostPort(addr.String())
454 ip := net.ParseIP(host)
455 if v4 := ip.To4(); v4 != nil {
459 return string(v4), nil
461 return string(ip.To16()), nil
464 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
476 type peerExtensionBytes [8]byte
479 type handshakeResult struct {
485 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
486 // Bytes to be sent to the peer. Should never block the sender.
487 postCh := make(chan []byte, 4)
488 // A single error value sent when the writer completes.
489 writeDone := make(chan error, 1)
490 // Performs writes to the socket and ensures posts don't block.
491 go handshakeWriter(sock, postCh, writeDone)
494 close(postCh) // Done writing.
501 // Wait until writes complete before returning from handshake.
504 err = fmt.Errorf("error writing during handshake: %s", err)
508 post := func(bb []byte) {
512 panic("mustn't block while posting")
516 post([]byte(pp.Protocol))
517 post([]byte(extensionBytes))
518 if ih != nil { // We already know what we want.
523 _, err = io.ReadFull(sock, b[:68])
528 if string(b[:20]) != pp.Protocol {
531 CopyExact(&res.peerExtensionBytes, b[20:28])
532 CopyExact(&res.InfoHash, b[28:48])
533 CopyExact(&res.peerID, b[48:68])
535 if ih == nil { // We were waiting for the peer to tell us what they wanted.
536 post(res.InfoHash[:])
544 type peerConn struct {
548 func (pc peerConn) Read(b []byte) (n int, err error) {
549 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
553 n, err = pc.Conn.Read(b)
555 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
557 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
567 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource, uTP bool) (err error) {
568 if tcpConn, ok := sock.(*net.TCPConn); ok {
575 // One minute to complete handshake.
576 sock.SetDeadline(time.Now().Add(time.Minute))
577 hsRes, ok, err := handshake(sock, func() *InfoHash {
581 return &torrent.InfoHash
586 if me.handshaking == 0 {
587 panic("handshake count invariant is broken")
591 err = fmt.Errorf("error during handshake: %s", err)
597 if hsRes.peerID == me.peerID {
600 torrent = me.torrent(hsRes.InfoHash)
604 sock.SetWriteDeadline(time.Time{})
605 sock = peerConn{sock}
606 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
608 conn.Discovery = discovery
609 if !me.addConnection(torrent, conn) {
612 if conn.PeerExtensionBytes[5]&0x10 != 0 {
613 conn.Post(pp.Message{
615 ExtendedID: pp.HandshakeExtendedID,
616 ExtendedPayload: func() []byte {
617 d := map[string]interface{}{
622 "v": "go.torrent dev 20140825", // Just the date
623 // No upload queue is implemented yet.
626 // No need to look strange if it costs us nothing.
633 if torrent.metadataSizeKnown() {
634 d["metadata_size"] = torrent.metadataSize()
636 if p := me.incomingPeerPort(); p != 0 {
639 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
641 log.Printf("error calculating yourip field value in extension handshake: %s", err)
645 // log.Printf("sending %v", d)
646 b, err := bencode.Marshal(d)
654 if torrent.haveAnyPieces() {
655 conn.Post(pp.Message{
657 Bitfield: torrent.bitfield(),
660 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
661 addr, _ := me.dHT.LocalAddr().(*net.UDPAddr)
662 conn.Post(pp.Message{
664 Port: uint16(addr.Port),
667 err = me.connectionLoop(torrent, conn)
669 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
671 me.dropConnection(torrent, conn)
675 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
676 for piece >= len(c.PeerPieces) {
677 c.PeerPieces = append(c.PeerPieces, false)
679 c.PeerPieces[piece] = true
680 if !t.havePiece(piece) {
681 me.replenishConnRequests(t, c)
685 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
686 me.replenishConnRequests(torrent, conn)
689 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
693 cl.downloadStrategy.DeleteRequest(t, r)
698 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
699 if !cn.RequestPending(r) {
702 cl.downloadStrategy.DeleteRequest(t, r)
703 delete(cn.Requests, r)
706 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
711 for index := 0; index < t.MetadataPieceCount(); index++ {
712 if !t.HaveMetadataPiece(index) {
713 pending = append(pending, index)
716 for _, i := range mathRand.Perm(len(pending)) {
719 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
720 ExtendedPayload: func() []byte {
721 b, err := bencode.Marshal(map[string]int{
734 func (cl *Client) completedMetadata(t *torrent) {
738 CopyExact(&ih, h.Sum(nil))
739 if ih != t.InfoHash {
740 log.Print("bad metadata")
741 t.InvalidateMetadata()
744 var info metainfo.Info
745 err := bencode.Unmarshal(t.MetaData, &info)
747 log.Printf("error unmarshalling metadata: %s", err)
748 t.InvalidateMetadata()
751 // TODO(anacrolix): If this fails, I think something harsher should be
753 err = cl.setMetaData(t, info, t.MetaData)
755 log.Printf("error setting metadata: %s", err)
756 t.InvalidateMetadata()
759 log.Printf("%s: got metadata from peers", t)
762 // Process incoming ut_metadata message.
763 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
765 err = bencode.Unmarshal(payload, &d)
767 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
770 msgType, ok := d["msg_type"]
772 err = errors.New("missing msg_type field")
777 case pp.DataMetadataExtensionMsgType:
781 t.SaveMetadataPiece(piece, payload[len(payload)-metadataPieceSize(d["total_size"], piece):])
782 if !t.HaveAllMetadataPieces() {
785 cl.completedMetadata(t)
786 case pp.RequestMetadataExtensionMsgType:
787 if !t.HaveMetadataPiece(piece) {
788 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
791 start := (1 << 14) * piece
792 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
793 case pp.RejectMetadataExtensionMsgType:
795 err = errors.New("unknown msg_type value")
800 type peerExchangeMessage struct {
801 Added CompactPeers `bencode:"added"`
802 AddedFlags []byte `bencode:"added.f"`
803 Dropped []tracker.Peer `bencode:"dropped"`
806 // Extracts the port as an integer from an address string.
807 func addrPort(addr net.Addr) int {
808 return AddrPort(addr)
811 // Processes incoming bittorrent messages. The client lock is held upon entry
813 func (me *Client) connectionLoop(t *torrent, c *connection) error {
814 decoder := pp.Decoder{
815 R: bufio.NewReaderSize(c.Socket, 20*1024),
816 MaxLength: 256 * 1024,
821 err := decoder.Decode(&msg)
823 c.lastMessageReceived = time.Now()
830 if me.stopped() || err == io.EOF {
841 for r := range c.Requests {
842 me.connDeleteRequest(t, c, r)
846 me.peerUnchoked(t, c)
848 c.PeerInterested = true
849 // TODO: This should be done from a dedicated unchoking routine.
854 case pp.NotInterested:
855 c.PeerInterested = false
858 me.peerGotPiece(t, c, int(msg.Index))
863 if c.PeerRequests == nil {
864 c.PeerRequests = make(map[request]struct{}, maxRequests)
866 request := newRequest(msg.Index, msg.Begin, msg.Length)
867 // TODO: Requests should be satisfied from a dedicated upload routine.
868 // c.PeerRequests[request] = struct{}{}
869 p := make([]byte, msg.Length)
870 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
872 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
874 if n != int(msg.Length) {
875 return fmt.Errorf("bad request: %v", msg)
883 uploadChunksPosted.Add(1)
885 req := newRequest(msg.Index, msg.Begin, msg.Length)
886 if !c.PeerCancel(req) {
887 unexpectedCancels.Add(1)
890 if c.PeerPieces != nil {
891 err = errors.New("received unexpected bitfield")
895 if len(msg.Bitfield) < t.NumPieces() {
896 err = errors.New("received invalid bitfield")
899 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
901 c.PeerPieces = msg.Bitfield
902 for index, has := range c.PeerPieces {
904 me.peerGotPiece(t, c, index)
908 err = me.downloadedChunk(t, c, &msg)
910 switch msg.ExtendedID {
911 case pp.HandshakeExtendedID:
912 // TODO: Create a bencode struct for this.
913 var d map[string]interface{}
914 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
916 err = fmt.Errorf("error decoding extended message payload: %s", err)
919 // log.Printf("got handshake: %v", d)
920 if reqq, ok := d["reqq"]; ok {
921 if i, ok := reqq.(int64); ok {
922 c.PeerMaxRequests = int(i)
925 if v, ok := d["v"]; ok {
926 c.PeerClientName = v.(string)
930 err = errors.New("handshake missing m item")
933 mTyped, ok := m.(map[string]interface{})
935 err = errors.New("handshake m value is not dict")
938 if c.PeerExtensionIDs == nil {
939 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
941 for name, v := range mTyped {
944 log.Printf("bad handshake m item extension ID type: %T", v)
948 delete(c.PeerExtensionIDs, name)
950 c.PeerExtensionIDs[name] = id
953 metadata_sizeUntyped, ok := d["metadata_size"]
955 metadata_size, ok := metadata_sizeUntyped.(int64)
957 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
959 t.SetMetadataSize(metadata_size)
962 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
963 me.requestPendingMetadata(t, c)
966 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
968 err = fmt.Errorf("error handling metadata extension message: %s", err)
971 var pexMsg peerExchangeMessage
972 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
974 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
978 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
979 for _, cp := range pexMsg.Added {
983 Source: peerSourcePEX,
985 if n := copy(p.IP, cp.IP[:]); n != 4 {
993 log.Printf("error adding PEX peers: %s", err)
996 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
999 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1002 // That client uses its own extension IDs for outgoing message
1003 // types, which is incorrect.
1004 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1005 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1008 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1014 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1019 pingAddr.Port = int(msg.Port)
1021 _, err = me.dHT.Ping(pingAddr)
1023 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1031 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1032 for r := range conn.Requests {
1033 me.connDeleteRequest(torrent, conn, r)
1036 for i0, c := range torrent.Conns {
1040 i1 := len(torrent.Conns) - 1
1042 torrent.Conns[i0] = torrent.Conns[i1]
1044 torrent.Conns = torrent.Conns[:i1]
1047 panic("connection not found")
1050 func (me *Client) addConnection(t *torrent, c *connection) bool {
1055 case <-t.ceasingNetworking:
1059 for _, c0 := range t.Conns {
1060 if c.PeerID == c0.PeerID {
1061 // Already connected to a client with that ID.
1065 t.Conns = append(t.Conns, c)
1066 if len(t.Conns) > socketsPerTorrent {
1067 wcs := t.worstConnsHeap()
1068 heap.Pop(wcs).(*connection).Close()
1073 func (me *Client) openNewConns() {
1074 for _, t := range me.torrents {
1076 case <-t.ceasingNetworking:
1080 for len(t.Peers) != 0 {
1081 if len(t.HalfOpen) >= me.halfOpenLimit {
1084 if len(t.HalfOpen)+me.handshaking+len(t.Conns) >= socketsPerTorrent {
1091 for k, p = range t.Peers {
1095 me.initiateConn(p, t)
1100 // Adds peers to the swarm for the torrent corresponding to infoHash.
1101 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1103 defer me.mu.Unlock()
1104 t := me.torrent(infoHash)
1106 return errors.New("no such torrent")
1113 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1114 err = t.setMetadata(md, cl.dataDir, bytes)
1118 // If the client intends to upload, it needs to know what state pieces are
1121 // Queue all pieces for hashing. This is done sequentially to avoid
1122 // spamming goroutines.
1123 for _, p := range t.Pieces {
1124 p.QueuedForHash = true
1127 for i := range t.Pieces {
1128 cl.verifyPiece(t, pp.Integer(i))
1133 cl.downloadStrategy.TorrentStarted(t)
1135 case t.gotMetainfo <- &metainfo.MetaInfo{
1136 Info: metainfo.InfoEx{
1139 CreationDate: time.Now().Unix(),
1140 Comment: "metadata set in client",
1141 CreatedBy: "go.torrent",
1142 // TODO(anacrolix): Expose trackers given when torrent added.
1145 panic("shouldn't block")
1147 close(t.gotMetainfo)
1152 // Prepare a Torrent without any attachment to a Client. That means we can
1153 // initialize fields all fields that don't require the Client without locking
1155 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1158 Peers: make(map[peersKey]Peer, 2000),
1160 closing: make(chan struct{}),
1161 ceasingNetworking: make(chan struct{}),
1163 gotMetainfo: make(chan *metainfo.MetaInfo, 1),
1165 HalfOpen: make(map[string]struct{}, halfOpenLimit),
1167 t.GotMetainfo = t.gotMetainfo
1168 t.Trackers = make([][]tracker.Client, len(announceList))
1169 for tierIndex := range announceList {
1170 tier := t.Trackers[tierIndex]
1171 for _, url := range announceList[tierIndex] {
1172 tr, err := tracker.New(url)
1177 tier = append(tier, tr)
1179 // The trackers within each tier must be shuffled before use.
1180 // http://stackoverflow.com/a/12267471/149482
1181 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1182 for i := range tier {
1183 j := mathRand.Intn(i + 1)
1184 tier[i], tier[j] = tier[j], tier[i]
1186 t.Trackers[tierIndex] = tier
1191 func (cl *Client) AddMagnet(uri string) (t *torrent, err error) {
1192 m, err := ParseMagnetURI(uri)
1196 t, err = newTorrent(m.InfoHash, [][]string{m.Trackers}, cl.halfOpenLimit)
1200 t.DisplayName = m.DisplayName
1202 defer cl.mu.Unlock()
1203 err = cl.addTorrent(t)
1210 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1212 defer me.mu.Unlock()
1213 t, ok := me.torrents[infoHash]
1215 err = fmt.Errorf("no such torrent")
1222 delete(me.torrents, infoHash)
1223 me.downloadStrategy.TorrentStopped(t)
1224 for _, dw := range me.dataWaits[t] {
1227 delete(me.dataWaits, t)
1231 func (me *Client) addTorrent(t *torrent) (err error) {
1232 if _, ok := me.torrents[t.InfoHash]; ok {
1233 err = fmt.Errorf("torrent infohash collision")
1236 me.torrents[t.InfoHash] = t
1237 if !me.disableTrackers {
1238 go me.announceTorrent(t)
1241 go me.announceTorrentDHT(t)
1246 // Adds the torrent to the client.
1247 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (err error) {
1249 CopyExact(&ih, metaInfo.Info.Hash)
1250 t, err := newTorrent(ih, metaInfo.AnnounceList, me.halfOpenLimit)
1255 defer me.mu.Unlock()
1256 err = me.addTorrent(t)
1260 err = me.setMetaData(t, metaInfo.Info.Info, metaInfo.Info.Bytes)
1267 func (me *Client) AddTorrentFromFile(name string) (err error) {
1268 mi, err := metainfo.LoadFromFile(name)
1270 err = fmt.Errorf("error loading metainfo from file: %s", err)
1273 return me.AddTorrent(mi)
1276 func (cl *Client) announceTorrentDHT(t *torrent) {
1278 ps, err := cl.dHT.GetPeers(string(t.InfoHash[:]))
1280 log.Printf("error getting peers from dht: %s", err)
1283 nextScrape := time.After(1 * time.Minute)
1289 case cps, ok := <-ps.Values:
1293 peersFoundByDHT.Add(int64(len(cps)))
1294 err = cl.AddPeers(t.InfoHash, func() (ret []Peer) {
1295 for _, cp := range cps {
1296 ret = append(ret, Peer{
1299 Source: peerSourceDHT,
1305 log.Printf("error adding peers from dht for torrent %q: %s", t, err)
1308 case <-t.ceasingNetworking:
1315 // After a GetPeers, we can announce on the best nodes that gave us an
1318 port := cl.incomingPeerPort()
1319 // If port is zero, then we're not listening, and there's nothing to
1322 // We can't allow the port to be implied as long as the UTP and
1323 // DHT ports are different.
1324 cl.dHT.AnnouncePeer(port, false, t.InfoHash.AsString())
1329 func (cl *Client) announceTorrent(t *torrent) {
1330 req := tracker.AnnounceRequest{
1331 Event: tracker.Started,
1333 Port: int16(cl.incomingPeerPort()),
1335 InfoHash: t.InfoHash,
1340 case <-t.ceasingNetworking:
1345 req.Left = t.BytesLeft()
1347 for _, tier := range t.Trackers {
1348 for trIndex, tr := range tier {
1349 if err := tr.Connect(); err != nil {
1353 resp, err := tr.Announce(&req)
1359 for _, peer := range resp.Peers {
1360 peers = append(peers, Peer{
1365 err = cl.AddPeers(t.InfoHash, peers)
1367 log.Printf("error adding peers to torrent %s: %s", t, err)
1369 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1371 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1372 time.Sleep(time.Second * time.Duration(resp.Interval))
1373 req.Event = tracker.None
1374 continue newAnnounce
1377 time.Sleep(5 * time.Second)
1381 func (cl *Client) allTorrentsCompleted() bool {
1382 for _, t := range cl.torrents {
1386 for e := t.IncompletePiecesByBytesLeft.Front(); e != nil; e = e.Next() {
1388 if t.Pieces[i].Complete() {
1391 // If the piece isn't complete, make sure it's not because it's
1392 // never been hashed.
1393 cl.queueFirstHash(t, i)
1400 // Returns true when all torrents are completely downloaded and false if the
1401 // client is stopped before that.
1402 func (me *Client) WaitAll() bool {
1404 defer me.mu.Unlock()
1405 for !me.allTorrentsCompleted() {
1414 func (cl *Client) assertRequestHeat() {
1415 dds, ok := cl.downloadStrategy.(*DefaultDownloadStrategy)
1419 for _, t := range cl.torrents {
1420 m := make(map[request]int, 3000)
1421 for _, cn := range t.Conns {
1422 for r := range cn.Requests {
1426 for r, h := range dds.heat[t] {
1428 panic(fmt.Sprintln(m[r], h))
1434 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
1438 for _, p := range me.downloadStrategy.FillRequests(t, c) {
1439 // Make sure the state of pieces that would have been requested is
1441 me.queueFirstHash(t, p)
1443 //me.assertRequestHeat()
1444 if len(c.Requests) == 0 && !c.PeerChoked {
1445 c.SetInterested(false)
1449 // Handle a received chunk from a peer.
1450 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
1451 chunksDownloadedCount.Add(1)
1453 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1455 // Request has been satisfied.
1456 me.connDeleteRequest(t, c, req)
1458 defer me.replenishConnRequests(t, c)
1460 // Do we actually want this chunk?
1461 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
1462 unusedDownloadedChunksCount.Add(1)
1463 c.UnwantedChunksReceived++
1467 c.UsefulChunksReceived++
1468 c.lastUsefulChunkReceived = time.Now()
1470 // Write the chunk out.
1471 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1473 return fmt.Errorf("error writing chunk: %s", err)
1476 // Record that we have the chunk.
1477 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
1478 me.dataReady(t, req)
1479 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
1480 me.queuePieceCheck(t, req.Index)
1482 t.PieceBytesLeftChanged(int(req.Index))
1484 // Unprioritize the chunk.
1485 me.downloadStrategy.TorrentGotChunk(t, req)
1487 // Cancel pending requests for this chunk.
1488 for _, c := range t.Conns {
1489 if me.connCancel(t, c, req) {
1490 me.replenishConnRequests(t, c)
1494 me.downloadStrategy.AssertNotRequested(t, req)
1499 func (cl *Client) dataReady(t *torrent, r request) {
1500 dws := cl.dataWaits[t]
1501 begin := t.requestOffset(r)
1502 end := begin + int64(r.Length)
1503 for i := 0; i < len(dws); {
1505 if begin <= dw.offset && dw.offset < end {
1507 dws[i] = dws[len(dws)-1]
1508 dws = dws[:len(dws)-1]
1513 cl.dataWaits[t] = dws
1516 // Returns a channel that is closed when new data has become available in the
1518 func (me *Client) DataWaiter(ih InfoHash, off int64) (ret <-chan struct{}) {
1520 defer me.mu.Unlock()
1521 ch := make(chan struct{})
1523 t := me.torrents[ih]
1528 if r, ok := t.offsetRequest(off); !ok || t.haveChunk(r) {
1532 me.dataWaits[t] = append(me.dataWaits[t], dataWait{
1539 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
1540 p := t.Pieces[piece]
1541 if p.EverHashed && !correct {
1542 log.Printf("%s: piece %d failed hash", t, piece)
1543 failedPieceHashes.Add(1)
1547 p.PendingChunkSpecs = nil
1548 me.downloadStrategy.TorrentGotPiece(t, int(piece))
1549 me.dataReady(t, request{
1551 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
1554 if len(p.PendingChunkSpecs) == 0 {
1555 t.pendAllChunkSpecs(piece)
1558 t.PieceBytesLeftChanged(int(piece))
1559 for _, conn := range t.Conns {
1561 conn.Post(pp.Message{
1563 Index: pp.Integer(piece),
1565 // TODO: Cancel requests for this piece.
1566 for r := range conn.Requests {
1567 if r.Index == piece {
1572 // Do this even if the piece is correct because new first-hashings may
1573 // need to be scheduled.
1574 if conn.PeerHasPiece(piece) {
1575 me.replenishConnRequests(t, conn)
1578 if t.haveAllPieces() && me.noUpload {
1581 me.event.Broadcast()
1584 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
1586 defer cl.mu.Unlock()
1587 p := t.Pieces[index]
1595 p.QueuedForHash = false
1597 sum := t.HashPiece(index)
1605 cl.pieceHashed(t, index, sum == p.Hash)
1608 func (me *Client) Torrents() (ret []*torrent) {
1610 for _, t := range me.torrents {
1611 ret = append(ret, t)