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) ListenAddr() (addr net.Addr) {
138 for _, l := range me.listeners {
139 if addr != nil && l.Addr().String() != addr.String() {
140 panic("listeners exist on different addresses")
147 func (cl *Client) WriteStatus(w io.Writer) {
150 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
151 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
152 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
154 fmt.Fprintf(w, "DHT nodes: %d\n", cl.dHT.NumNodes())
155 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
156 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
157 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
159 cl.downloadStrategy.WriteStatus(w)
161 for _, t := range cl.torrents {
162 fmt.Fprintf(w, "%s: %f%%\n", t.Name(), func() float32 {
166 return 100 * (1 - float32(t.BytesLeft())/float32(t.Length()))
169 fmt.Fprint(w, "Blocked reads:")
170 for _, dw := range cl.dataWaits[t] {
171 fmt.Fprintf(w, " %d", dw.offset)
179 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
181 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
186 err = errors.New("unknown torrent")
189 index := pp.Integer(off / int64(t.UsualPieceSize()))
190 // Reading outside the bounds of a file is an error.
195 if int(index) >= len(t.Pieces) {
199 piece := t.Pieces[index]
200 pieceOff := pp.Integer(off % int64(t.UsualPieceSize()))
201 pieceLeft := int(t.PieceLength(index) - pieceOff)
206 if len(p) > pieceLeft {
209 for cs, _ := range piece.PendingChunkSpecs {
210 chunkOff := int64(pieceOff) - int64(cs.Begin)
211 if chunkOff >= int64(t.PieceLength(index)) {
214 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
215 // read begins in a pending chunk
216 err = ErrDataNotReady
219 // pending chunk caps available data
220 if chunkOff < 0 && int64(len(p)) > -chunkOff {
227 return t.Data.ReadAt(p, off)
230 func dhtAddr(listen net.Addr) (s string, err error) {
231 host, port, err := net.SplitHostPort(listen.String())
235 i64, err := strconv.ParseInt(port, 0, 0)
239 s = net.JoinHostPort(host, strconv.FormatInt(i64+1, 10))
243 func NewClient(cfg *Config) (cl *Client, err error) {
249 noUpload: cfg.NoUpload,
250 disableTrackers: cfg.DisableTrackers,
251 downloadStrategy: cfg.DownloadStrategy,
253 dataDir: cfg.DataDir,
255 quit: make(chan struct{}),
256 torrents: make(map[InfoHash]*torrent),
258 dataWaits: make(map[*torrent][]dataWait),
263 o := copy(cl.peerID[:], BEP20)
264 _, err = rand.Read(cl.peerID[o:])
266 panic("error generating peer id")
269 if cl.downloadStrategy == nil {
270 cl.downloadStrategy = &DefaultDownloadStrategy{}
273 // Returns the laddr string to listen on for the next Listen call.
274 listenAddr := func() string {
275 if addr := cl.ListenAddr(); addr != nil {
278 return cfg.ListenAddr
282 l, err = net.Listen("tcp", listenAddr())
286 cl.listeners = append(cl.listeners, l)
287 go cl.acceptConnections(l, false)
290 l, err = utp.Listen("utp", listenAddr())
294 cl.listeners = append(cl.listeners, l)
295 go cl.acceptConnections(l, true)
299 dhtAddr_, err = dhtAddr(cl.ListenAddr())
303 cl.dHT, err = dht.NewServer(&dht.ServerConfig{
314 func (cl *Client) stopped() bool {
323 // Stops the client. All connections to peers are closed and all activity will
325 func (me *Client) Stop() {
329 for _, t := range me.torrents {
335 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
337 // We accept all connections immediately, because we don't what
338 // torrent they're for.
339 conn, err := l.Accept()
353 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
360 func (me *Client) torrent(ih InfoHash) *torrent {
361 for _, t := range me.torrents {
362 if t.InfoHash == ih {
369 // Start the process of connecting to the given peer for the given torrent if
371 func (me *Client) initiateConn(peer Peer, t *torrent) {
372 if peer.Id == me.peerID {
375 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
376 if t.addrActive(addr) {
377 duplicateConnsAvoided.Add(1)
380 t.HalfOpen[addr] = struct{}{}
382 // Binding to the listener address and dialing via net.Dialer gives
383 // "address in use" error. It seems it's not possible to dial out from
384 // this address so that peers associate our local address with our
387 conn, err := net.DialTimeout("tcp", addr, dialTimeout)
389 conn, err := (&utp.Dialer{Timeout: dialTimeout}).Dial("utp", addr)
392 // Whether or not the connection attempt succeeds, the half open
393 // counter should be decremented, and new connection attempts made.
397 if _, ok := t.HalfOpen[addr]; !ok {
398 panic("invariant broken")
400 delete(t.HalfOpen, addr)
404 if netOpErr, ok := err.(*net.OpError); ok {
405 if netOpErr.Timeout() {
408 switch netOpErr.Err {
409 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
414 log.Printf("error connecting to peer: %s %#v", err, err)
417 // log.Printf("connected to %s", conn.RemoteAddr())
418 err = me.runConnection(conn, t, peer.Source, true)
425 // The port number for incoming peer connections. 0 if the client isn't
427 func (cl *Client) incomingPeerPort() int {
428 listenAddr := cl.ListenAddr()
429 if listenAddr == nil {
432 return addrPort(listenAddr)
435 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
436 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
437 func addrCompactIP(addr net.Addr) (string, error) {
438 host, _, err := net.SplitHostPort(addr.String())
442 ip := net.ParseIP(host)
443 if v4 := ip.To4(); v4 != nil {
447 return string(v4), nil
449 return string(ip.To16()), nil
452 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
464 type peerExtensionBytes [8]byte
467 type handshakeResult struct {
473 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
474 // Bytes to be sent to the peer. Should never block the sender.
475 postCh := make(chan []byte, 4)
476 // A single error value sent when the writer completes.
477 writeDone := make(chan error, 1)
478 // Performs writes to the socket and ensures posts don't block.
479 go handshakeWriter(sock, postCh, writeDone)
482 close(postCh) // Done writing.
489 // Wait until writes complete before returning from handshake.
492 err = fmt.Errorf("error writing during handshake: %s", err)
496 post := func(bb []byte) {
500 panic("mustn't block while posting")
504 post([]byte(pp.Protocol))
505 post([]byte(extensionBytes))
506 if ih != nil { // We already know what we want.
511 _, err = io.ReadFull(sock, b[:68])
516 if string(b[:20]) != pp.Protocol {
519 CopyExact(&res.peerExtensionBytes, b[20:28])
520 CopyExact(&res.InfoHash, b[28:48])
521 CopyExact(&res.peerID, b[48:68])
523 if ih == nil { // We were waiting for the peer to tell us what they wanted.
524 post(res.InfoHash[:])
532 type peerConn struct {
536 func (pc peerConn) Read(b []byte) (n int, err error) {
537 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
541 n, err = pc.Conn.Read(b)
543 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
545 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
555 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource, uTP bool) (err error) {
556 if tcpConn, ok := sock.(*net.TCPConn); ok {
563 // One minute to complete handshake.
564 sock.SetDeadline(time.Now().Add(time.Minute))
565 hsRes, ok, err := handshake(sock, func() *InfoHash {
569 return &torrent.InfoHash
574 if me.handshaking == 0 {
575 panic("handshake count invariant is broken")
579 err = fmt.Errorf("error during handshake: %s", err)
585 torrent = me.torrent(hsRes.InfoHash)
589 sock.SetWriteDeadline(time.Time{})
590 sock = peerConn{sock}
591 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
593 conn.Discovery = discovery
594 if !me.addConnection(torrent, conn) {
597 if conn.PeerExtensionBytes[5]&0x10 != 0 {
598 conn.Post(pp.Message{
600 ExtendedID: pp.HandshakeExtendedID,
601 ExtendedPayload: func() []byte {
602 d := map[string]interface{}{
607 "v": "go.torrent dev 20140825", // Just the date
608 // No upload queue is implemented yet.
611 // No need to look strange if it costs us nothing.
618 if torrent.metadataSizeKnown() {
619 d["metadata_size"] = torrent.metadataSize()
621 if p := me.incomingPeerPort(); p != 0 {
624 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
626 log.Printf("error calculating yourip field value in extension handshake: %s", err)
630 // log.Printf("sending %v", d)
631 b, err := bencode.Marshal(d)
639 if torrent.haveAnyPieces() {
640 conn.Post(pp.Message{
642 Bitfield: torrent.bitfield(),
645 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
646 addr, _ := me.dHT.LocalAddr().(*net.UDPAddr)
647 conn.Post(pp.Message{
649 Port: uint16(addr.Port),
652 err = me.connectionLoop(torrent, conn)
654 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
656 me.dropConnection(torrent, conn)
660 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
661 for piece >= len(c.PeerPieces) {
662 c.PeerPieces = append(c.PeerPieces, false)
664 c.PeerPieces[piece] = true
665 if !t.havePiece(piece) {
666 me.replenishConnRequests(t, c)
670 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
671 me.replenishConnRequests(torrent, conn)
674 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
678 cl.downloadStrategy.DeleteRequest(t, r)
683 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
684 if !cn.RequestPending(r) {
687 cl.downloadStrategy.DeleteRequest(t, r)
688 delete(cn.Requests, r)
691 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
696 for index := 0; index < t.MetadataPieceCount(); index++ {
697 if !t.HaveMetadataPiece(index) {
698 pending = append(pending, index)
701 for _, i := range mathRand.Perm(len(pending)) {
704 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
705 ExtendedPayload: func() []byte {
706 b, err := bencode.Marshal(map[string]int{
719 func (cl *Client) completedMetadata(t *torrent) {
723 CopyExact(&ih, h.Sum(nil))
724 if ih != t.InfoHash {
725 log.Print("bad metadata")
726 t.InvalidateMetadata()
729 var info metainfo.Info
730 err := bencode.Unmarshal(t.MetaData, &info)
732 log.Printf("error unmarshalling metadata: %s", err)
733 t.InvalidateMetadata()
736 // TODO(anacrolix): If this fails, I think something harsher should be
738 err = cl.setMetaData(t, info, t.MetaData)
740 log.Printf("error setting metadata: %s", err)
741 t.InvalidateMetadata()
744 log.Printf("%s: got metadata from peers", t)
747 // Process incoming ut_metadata message.
748 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
750 err = bencode.Unmarshal(payload, &d)
752 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
755 msgType, ok := d["msg_type"]
757 err = errors.New("missing msg_type field")
762 case pp.DataMetadataExtensionMsgType:
766 t.SaveMetadataPiece(piece, payload[len(payload)-metadataPieceSize(d["total_size"], piece):])
767 if !t.HaveAllMetadataPieces() {
770 cl.completedMetadata(t)
771 case pp.RequestMetadataExtensionMsgType:
772 if !t.HaveMetadataPiece(piece) {
773 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
776 start := (1 << 14) * piece
777 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
778 case pp.RejectMetadataExtensionMsgType:
780 err = errors.New("unknown msg_type value")
785 type peerExchangeMessage struct {
786 Added CompactPeers `bencode:"added"`
787 AddedFlags []byte `bencode:"added.f"`
788 Dropped []tracker.Peer `bencode:"dropped"`
791 // Extracts the port as an integer from an address string.
792 func addrPort(addr net.Addr) int {
793 _, port, err := net.SplitHostPort(addr.String())
797 i64, err := strconv.ParseInt(port, 0, 0)
804 // Processes incoming bittorrent messages. The client lock is held upon entry
806 func (me *Client) connectionLoop(t *torrent, c *connection) error {
807 decoder := pp.Decoder{
808 R: bufio.NewReaderSize(c.Socket, 20*1024),
809 MaxLength: 256 * 1024,
814 err := decoder.Decode(&msg)
816 c.lastMessageReceived = time.Now()
823 if me.stopped() || err == io.EOF {
834 for r := range c.Requests {
835 me.connDeleteRequest(t, c, r)
839 me.peerUnchoked(t, c)
841 c.PeerInterested = true
842 // TODO: This should be done from a dedicated unchoking routine.
847 case pp.NotInterested:
848 c.PeerInterested = false
851 me.peerGotPiece(t, c, int(msg.Index))
856 if c.PeerRequests == nil {
857 c.PeerRequests = make(map[request]struct{}, maxRequests)
859 request := newRequest(msg.Index, msg.Begin, msg.Length)
860 // TODO: Requests should be satisfied from a dedicated upload routine.
861 // c.PeerRequests[request] = struct{}{}
862 p := make([]byte, msg.Length)
863 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
865 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
867 if n != int(msg.Length) {
868 return fmt.Errorf("bad request: %v", msg)
876 uploadChunksPosted.Add(1)
878 req := newRequest(msg.Index, msg.Begin, msg.Length)
879 if !c.PeerCancel(req) {
880 unexpectedCancels.Add(1)
883 if c.PeerPieces != nil {
884 err = errors.New("received unexpected bitfield")
888 if len(msg.Bitfield) < t.NumPieces() {
889 err = errors.New("received invalid bitfield")
892 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
894 c.PeerPieces = msg.Bitfield
895 for index, has := range c.PeerPieces {
897 me.peerGotPiece(t, c, index)
901 err = me.downloadedChunk(t, c, &msg)
903 switch msg.ExtendedID {
904 case pp.HandshakeExtendedID:
905 // TODO: Create a bencode struct for this.
906 var d map[string]interface{}
907 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
909 err = fmt.Errorf("error decoding extended message payload: %s", err)
912 // log.Printf("got handshake: %v", d)
913 if reqq, ok := d["reqq"]; ok {
914 if i, ok := reqq.(int64); ok {
915 c.PeerMaxRequests = int(i)
918 if v, ok := d["v"]; ok {
919 c.PeerClientName = v.(string)
923 err = errors.New("handshake missing m item")
926 mTyped, ok := m.(map[string]interface{})
928 err = errors.New("handshake m value is not dict")
931 if c.PeerExtensionIDs == nil {
932 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
934 for name, v := range mTyped {
937 log.Printf("bad handshake m item extension ID type: %T", v)
941 delete(c.PeerExtensionIDs, name)
943 c.PeerExtensionIDs[name] = id
946 metadata_sizeUntyped, ok := d["metadata_size"]
948 metadata_size, ok := metadata_sizeUntyped.(int64)
950 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
952 t.SetMetadataSize(metadata_size)
955 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
956 me.requestPendingMetadata(t, c)
959 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
961 err = fmt.Errorf("error handling metadata extension message: %s", err)
964 var pexMsg peerExchangeMessage
965 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
967 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
971 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
972 for _, cp := range pexMsg.Added {
976 Source: peerSourcePEX,
978 if n := copy(p.IP, cp.IP[:]); n != 4 {
986 log.Printf("error adding PEX peers: %s", err)
989 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
992 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
995 // That client uses its own extension IDs for outgoing message
996 // types, which is incorrect.
997 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
998 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1001 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1007 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1012 pingAddr.Port = int(msg.Port)
1014 _, err = me.dHT.Ping(pingAddr)
1016 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1024 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1025 for r := range conn.Requests {
1026 me.connDeleteRequest(torrent, conn, r)
1029 for i0, c := range torrent.Conns {
1033 i1 := len(torrent.Conns) - 1
1035 torrent.Conns[i0] = torrent.Conns[i1]
1037 torrent.Conns = torrent.Conns[:i1]
1040 panic("connection not found")
1043 func (me *Client) addConnection(t *torrent, c *connection) bool {
1048 case <-t.ceasingNetworking:
1052 for _, c0 := range t.Conns {
1053 if c.PeerID == c0.PeerID {
1054 // Already connected to a client with that ID.
1058 t.Conns = append(t.Conns, c)
1059 if len(t.Conns) > socketsPerTorrent {
1060 wcs := t.worstConnsHeap()
1061 heap.Pop(wcs).(*connection).Close()
1066 func (me *Client) openNewConns() {
1067 for _, t := range me.torrents {
1069 case <-t.ceasingNetworking:
1073 for len(t.Peers) != 0 {
1074 if len(t.HalfOpen) >= me.halfOpenLimit {
1077 if len(t.HalfOpen)+me.handshaking+len(t.Conns) >= socketsPerTorrent {
1084 for k, p = range t.Peers {
1088 me.initiateConn(p, t)
1093 // Adds peers to the swarm for the torrent corresponding to infoHash.
1094 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1096 defer me.mu.Unlock()
1097 t := me.torrent(infoHash)
1099 return errors.New("no such torrent")
1106 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1107 err = t.setMetadata(md, cl.dataDir, bytes)
1111 // If the client intends to upload, it needs to know what state pieces are
1114 // Queue all pieces for hashing. This is done sequentially to avoid
1115 // spamming goroutines.
1116 for _, p := range t.Pieces {
1117 p.QueuedForHash = true
1120 for i := range t.Pieces {
1121 cl.verifyPiece(t, pp.Integer(i))
1126 cl.downloadStrategy.TorrentStarted(t)
1128 case t.gotMetainfo <- &metainfo.MetaInfo{
1129 Info: metainfo.InfoEx{
1132 CreationDate: time.Now().Unix(),
1133 Comment: "metadata set in client",
1134 CreatedBy: "go.torrent",
1135 // TODO(anacrolix): Expose trackers given when torrent added.
1138 panic("shouldn't block")
1140 close(t.gotMetainfo)
1145 // Prepare a Torrent without any attachment to a Client. That means we can
1146 // initialize fields all fields that don't require the Client without locking
1148 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1151 Peers: make(map[peersKey]Peer, 2000),
1153 closing: make(chan struct{}),
1154 ceasingNetworking: make(chan struct{}),
1156 gotMetainfo: make(chan *metainfo.MetaInfo, 1),
1158 HalfOpen: make(map[string]struct{}, halfOpenLimit),
1160 t.GotMetainfo = t.gotMetainfo
1161 t.Trackers = make([][]tracker.Client, len(announceList))
1162 for tierIndex := range announceList {
1163 tier := t.Trackers[tierIndex]
1164 for _, url := range announceList[tierIndex] {
1165 tr, err := tracker.New(url)
1170 tier = append(tier, tr)
1172 // The trackers within each tier must be shuffled before use.
1173 // http://stackoverflow.com/a/12267471/149482
1174 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1175 for i := range tier {
1176 j := mathRand.Intn(i + 1)
1177 tier[i], tier[j] = tier[j], tier[i]
1179 t.Trackers[tierIndex] = tier
1184 func (cl *Client) AddMagnet(uri string) (t *torrent, err error) {
1185 m, err := ParseMagnetURI(uri)
1189 t, err = newTorrent(m.InfoHash, [][]string{m.Trackers}, cl.halfOpenLimit)
1193 t.DisplayName = m.DisplayName
1195 defer cl.mu.Unlock()
1196 err = cl.addTorrent(t)
1203 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1205 defer me.mu.Unlock()
1206 t, ok := me.torrents[infoHash]
1208 err = fmt.Errorf("no such torrent")
1215 delete(me.torrents, infoHash)
1216 me.downloadStrategy.TorrentStopped(t)
1217 for _, dw := range me.dataWaits[t] {
1220 delete(me.dataWaits, t)
1224 func (me *Client) addTorrent(t *torrent) (err error) {
1225 if _, ok := me.torrents[t.InfoHash]; ok {
1226 err = fmt.Errorf("torrent infohash collision")
1229 me.torrents[t.InfoHash] = t
1230 if !me.disableTrackers {
1231 go me.announceTorrent(t)
1234 go me.announceTorrentDHT(t)
1239 // Adds the torrent to the client.
1240 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (err error) {
1242 CopyExact(&ih, metaInfo.Info.Hash)
1243 t, err := newTorrent(ih, metaInfo.AnnounceList, me.halfOpenLimit)
1248 defer me.mu.Unlock()
1249 err = me.addTorrent(t)
1253 err = me.setMetaData(t, metaInfo.Info.Info, metaInfo.Info.Bytes)
1260 func (me *Client) AddTorrentFromFile(name string) (err error) {
1261 mi, err := metainfo.LoadFromFile(name)
1263 err = fmt.Errorf("error loading metainfo from file: %s", err)
1266 return me.AddTorrent(mi)
1269 func (cl *Client) announceTorrentDHT(t *torrent) {
1271 ps, err := cl.dHT.GetPeers(string(t.InfoHash[:]))
1273 log.Printf("error getting peers from dht: %s", err)
1276 nextScrape := time.After(1 * time.Minute)
1282 case cps, ok := <-ps.Values:
1286 peersFoundByDHT.Add(int64(len(cps)))
1287 err = cl.AddPeers(t.InfoHash, func() (ret []Peer) {
1288 for _, cp := range cps {
1289 ret = append(ret, Peer{
1292 Source: peerSourceDHT,
1298 log.Printf("error adding peers from dht for torrent %q: %s", t, err)
1301 case <-t.ceasingNetworking:
1308 // After a GetPeers, we can announce on the best nodes that gave us an
1311 port := cl.incomingPeerPort()
1312 // If port is zero, then we're not listening, and there's nothing to
1315 // We can't allow the port to be implied as long as the UTP and
1316 // DHT ports are different.
1317 cl.dHT.AnnouncePeer(port, false, t.InfoHash.AsString())
1322 func (cl *Client) announceTorrent(t *torrent) {
1323 req := tracker.AnnounceRequest{
1324 Event: tracker.Started,
1326 Port: int16(cl.incomingPeerPort()),
1328 InfoHash: t.InfoHash,
1333 case <-t.ceasingNetworking:
1338 req.Left = t.BytesLeft()
1340 for _, tier := range t.Trackers {
1341 for trIndex, tr := range tier {
1342 if err := tr.Connect(); err != nil {
1346 resp, err := tr.Announce(&req)
1352 for _, peer := range resp.Peers {
1353 peers = append(peers, Peer{
1358 err = cl.AddPeers(t.InfoHash, peers)
1360 log.Printf("error adding peers to torrent %s: %s", t, err)
1362 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1364 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1365 time.Sleep(time.Second * time.Duration(resp.Interval))
1366 req.Event = tracker.None
1367 continue newAnnounce
1370 time.Sleep(5 * time.Second)
1374 func (cl *Client) allTorrentsCompleted() bool {
1375 for _, t := range cl.torrents {
1379 for e := t.IncompletePiecesByBytesLeft.Front(); e != nil; e = e.Next() {
1381 if t.Pieces[i].Complete() {
1384 // If the piece isn't complete, make sure it's not because it's
1385 // never been hashed.
1386 cl.queueFirstHash(t, i)
1393 // Returns true when all torrents are completely downloaded and false if the
1394 // client is stopped before that.
1395 func (me *Client) WaitAll() bool {
1397 defer me.mu.Unlock()
1398 for !me.allTorrentsCompleted() {
1407 func (cl *Client) assertRequestHeat() {
1408 dds, ok := cl.downloadStrategy.(*DefaultDownloadStrategy)
1412 for _, t := range cl.torrents {
1413 m := make(map[request]int, 3000)
1414 for _, cn := range t.Conns {
1415 for r := range cn.Requests {
1419 for r, h := range dds.heat[t] {
1421 panic(fmt.Sprintln(m[r], h))
1427 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
1431 for _, p := range me.downloadStrategy.FillRequests(t, c) {
1432 // Make sure the state of pieces that would have been requested is
1434 me.queueFirstHash(t, p)
1436 //me.assertRequestHeat()
1437 if len(c.Requests) == 0 && !c.PeerChoked {
1438 c.SetInterested(false)
1442 // Handle a received chunk from a peer.
1443 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
1444 chunksDownloadedCount.Add(1)
1446 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1448 // Request has been satisfied.
1449 me.connDeleteRequest(t, c, req)
1451 defer me.replenishConnRequests(t, c)
1453 // Do we actually want this chunk?
1454 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
1455 unusedDownloadedChunksCount.Add(1)
1456 c.UnwantedChunksReceived++
1460 c.UsefulChunksReceived++
1461 c.lastUsefulChunkReceived = time.Now()
1463 // Write the chunk out.
1464 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1466 return fmt.Errorf("error writing chunk: %s", err)
1469 // Record that we have the chunk.
1470 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
1471 me.dataReady(t, req)
1472 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
1473 me.queuePieceCheck(t, req.Index)
1475 t.PieceBytesLeftChanged(int(req.Index))
1477 // Unprioritize the chunk.
1478 me.downloadStrategy.TorrentGotChunk(t, req)
1480 // Cancel pending requests for this chunk.
1481 for _, c := range t.Conns {
1482 if me.connCancel(t, c, req) {
1483 me.replenishConnRequests(t, c)
1487 me.downloadStrategy.AssertNotRequested(t, req)
1492 func (cl *Client) dataReady(t *torrent, r request) {
1493 dws := cl.dataWaits[t]
1494 begin := t.requestOffset(r)
1495 end := begin + int64(r.Length)
1496 for i := 0; i < len(dws); {
1498 if begin <= dw.offset && dw.offset < end {
1500 dws[i] = dws[len(dws)-1]
1501 dws = dws[:len(dws)-1]
1506 cl.dataWaits[t] = dws
1509 // Returns a channel that is closed when new data has become available in the
1511 func (me *Client) DataWaiter(ih InfoHash, off int64) (ret <-chan struct{}) {
1513 defer me.mu.Unlock()
1514 ch := make(chan struct{})
1516 t := me.torrents[ih]
1521 if r, ok := t.offsetRequest(off); !ok || t.haveChunk(r) {
1525 me.dataWaits[t] = append(me.dataWaits[t], dataWait{
1532 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
1533 p := t.Pieces[piece]
1534 if p.EverHashed && !correct {
1535 log.Printf("%s: piece %d failed hash", t, piece)
1536 failedPieceHashes.Add(1)
1540 p.PendingChunkSpecs = nil
1541 me.downloadStrategy.TorrentGotPiece(t, int(piece))
1542 me.dataReady(t, request{
1544 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
1547 if len(p.PendingChunkSpecs) == 0 {
1548 t.pendAllChunkSpecs(piece)
1551 t.PieceBytesLeftChanged(int(piece))
1552 for _, conn := range t.Conns {
1554 conn.Post(pp.Message{
1556 Index: pp.Integer(piece),
1558 // TODO: Cancel requests for this piece.
1559 for r := range conn.Requests {
1560 if r.Index == piece {
1565 // Do this even if the piece is correct because new first-hashings may
1566 // need to be scheduled.
1567 if conn.PeerHasPiece(piece) {
1568 me.replenishConnRequests(t, conn)
1571 if t.haveAllPieces() && me.noUpload {
1574 me.event.Broadcast()
1577 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
1579 defer cl.mu.Unlock()
1580 p := t.Pieces[index]
1588 p.QueuedForHash = false
1590 sum := t.HashPiece(index)
1598 cl.pieceHashed(t, index, sum == p.Hash)
1601 func (me *Client) Torrents() (ret []*torrent) {
1603 for _, t := range me.torrents {
1604 ret = append(ret, t)