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")
34 "bitbucket.org/anacrolix/go.torrent/util/levelmu"
36 "bitbucket.org/anacrolix/go.torrent/dht"
37 . "bitbucket.org/anacrolix/go.torrent/util"
39 "github.com/anacrolix/libtorgo/metainfo"
40 "github.com/nsf/libtorgo/bencode"
42 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
43 "bitbucket.org/anacrolix/go.torrent/tracker"
44 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
48 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
49 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
50 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
51 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
52 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
53 unexpectedCancels = expvar.NewInt("unexpectedCancels")
54 postedCancels = expvar.NewInt("postedCancels")
57 const extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x00"
59 // Currently doesn't really queue, but should in the future.
60 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
61 piece := t.Pieces[pieceIndex]
62 if piece.QueuedForHash {
65 piece.QueuedForHash = true
66 go cl.verifyPiece(t, pieceIndex)
69 // Queues the torrent data for the given region for download. The beginning of
70 // the region is given highest priority to allow a subsequent read at the same
71 // offset to return data ASAP.
72 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
77 return errors.New("no such active torrent")
80 return errors.New("missing metadata")
82 me.downloadStrategy.TorrentPrioritize(t, off, len_)
83 for _, cn := range t.Conns {
84 me.replenishConnRequests(t, cn)
89 type dataSpec struct {
101 downloadStrategy DownloadStrategy
104 mu levelmu.LevelMutex
109 torrents map[InfoHash]*torrent
111 dataWaiterMutex sync.Mutex
112 dataWaiter chan struct{}
115 func (me *Client) ListenAddr() net.Addr {
116 return me.listener.Addr()
119 func (cl *Client) WriteStatus(w io.Writer) {
122 if cl.listener != nil {
123 fmt.Fprintf(w, "Listening on %s\n", cl.listener.Addr())
125 fmt.Fprintf(w, "No listening torrent port!\n")
127 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
128 fmt.Fprintf(w, "Half open outgoing connections: %d\n", cl.halfOpen)
130 fmt.Fprintf(w, "DHT nodes: %d\n", cl.dHT.NumNodes())
131 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
133 cl.downloadStrategy.WriteStatus(w)
135 for _, t := range cl.torrents {
136 fmt.Fprintf(w, "%s: %f%%\n", t.Name(), func() float32 {
140 return 100 * (1 - float32(t.BytesLeft())/float32(t.Length()))
148 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
150 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
155 err = errors.New("unknown torrent")
158 index := pp.Integer(off / int64(t.UsualPieceSize()))
159 // Reading outside the bounds of a file is an error.
164 if int(index) >= len(t.Pieces) {
168 piece := t.Pieces[index]
169 pieceOff := pp.Integer(off % int64(t.UsualPieceSize()))
170 pieceLeft := int(t.PieceLength(index) - pieceOff)
175 if len(p) > pieceLeft {
178 for cs, _ := range piece.PendingChunkSpecs {
179 chunkOff := int64(pieceOff) - int64(cs.Begin)
180 if chunkOff >= int64(t.PieceLength(index)) {
183 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
184 // read begins in a pending chunk
185 err = ErrDataNotReady
188 // pending chunk caps available data
189 if chunkOff < 0 && int64(len(p)) > -chunkOff {
196 return t.Data.ReadAt(p, off)
199 func NewClient(cfg *Config) (cl *Client, err error) {
205 noUpload: cfg.NoUpload,
206 disableTrackers: cfg.DisableTrackers,
207 downloadStrategy: cfg.DownloadStrategy,
209 dataDir: cfg.DataDir,
211 quit: make(chan struct{}),
212 torrents: make(map[InfoHash]*torrent),
217 o := copy(cl.peerID[:], BEP20)
218 _, err = rand.Read(cl.peerID[o:])
220 panic("error generating peer id")
223 if cl.downloadStrategy == nil {
224 cl.downloadStrategy = &DefaultDownloadStrategy{}
227 cl.listener, err = net.Listen("tcp", cfg.ListenAddr)
231 if cl.listener != nil {
232 go cl.acceptConnections()
236 cl.dHT, err = dht.NewServer(&dht.ServerConfig{
237 Addr: cfg.ListenAddr,
247 func (cl *Client) stopped() bool {
256 // Stops the client. All connections to peers are closed and all activity will
258 func (me *Client) Stop() {
262 for _, t := range me.torrents {
263 for _, c := range t.Conns {
270 func (cl *Client) acceptConnections() {
272 conn, err := cl.listener.Accept()
285 // log.Printf("accepted connection from %s", conn.RemoteAddr())
287 if err := cl.runConnection(conn, nil, peerSourceIncoming); err != nil {
294 func (me *Client) torrent(ih InfoHash) *torrent {
295 for _, t := range me.torrents {
296 if t.InfoHash == ih {
303 // Start the process of connecting to the given peer for the given torrent if
305 func (me *Client) initiateConn(peer Peer, torrent *torrent) {
306 if peer.Id == me.peerID {
311 addr := &net.TCPAddr{
315 // Binding to the listener address and dialing via net.Dialer gives
316 // "address in use" error. It seems it's not possible to dial out from
317 // this address so that peers associate our local address with our
319 conn, err := net.DialTimeout(addr.Network(), addr.String(), dialTimeout)
321 // Whether or not the connection attempt succeeds, the half open
322 // counter should be decremented, and new connection attempts made.
326 if me.halfOpen == 0 {
333 if netOpErr, ok := err.(*net.OpError); ok {
334 if netOpErr.Timeout() {
337 switch netOpErr.Err {
338 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
343 log.Printf("error connecting to peer: %s %#v", err, err)
346 // log.Printf("connected to %s", conn.RemoteAddr())
347 err = me.runConnection(conn, torrent, peer.Source)
354 func (cl *Client) incomingPeerPort() int {
355 if cl.listener == nil {
358 _, p, err := net.SplitHostPort(cl.listener.Addr().String())
363 _, err = fmt.Sscanf(p, "%d", &i)
370 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
371 func addrCompactIP(addr net.Addr) (string, error) {
372 switch typed := addr.(type) {
374 if v4 := typed.IP.To4(); v4 != nil {
378 return string(v4), nil
380 return string(typed.IP.To16()), nil
382 return "", fmt.Errorf("unhandled type: %T", addr)
386 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
398 type peerExtensionBytes [8]byte
401 type handshakeResult struct {
407 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
408 // Bytes to be sent to the peer. Should never block the sender.
409 postCh := make(chan []byte, 4)
410 // A single error value sent when the writer completes.
411 writeDone := make(chan error, 1)
412 // Performs writes to the socket and ensures posts don't block.
413 go handshakeWriter(sock, postCh, writeDone)
416 close(postCh) // Done writing.
423 // Wait until writes complete before returning from handshake.
426 err = fmt.Errorf("error writing during handshake: %s", err)
430 post := func(bb []byte) {
434 panic("mustn't block while posting")
438 post([]byte(pp.Protocol))
439 post([]byte(extensionBytes))
440 if ih != nil { // We already know what we want.
445 _, err = io.ReadFull(sock, b[:68])
450 if string(b[:20]) != pp.Protocol {
453 CopyExact(&res.peerExtensionBytes, b[20:28])
454 CopyExact(&res.InfoHash, b[28:48])
455 CopyExact(&res.peerID, b[48:68])
457 if ih == nil { // We were waiting for the peer to tell us what they wanted.
458 post(res.InfoHash[:])
466 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource) (err error) {
468 hsRes, ok, err := handshake(sock, func() *InfoHash {
472 return &torrent.InfoHash
476 err = fmt.Errorf("error during handshake: %s", err)
484 torrent = me.torrent(hsRes.InfoHash)
488 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID)
490 conn.Discovery = discovery
491 if !me.addConnection(torrent, conn) {
494 if conn.PeerExtensionBytes[5]&0x10 != 0 {
495 conn.Post(pp.Message{
497 ExtendedID: pp.HandshakeExtendedID,
498 ExtendedPayload: func() []byte {
499 d := map[string]interface{}{
504 "v": "go.torrent dev",
507 if torrent.metadataSizeKnown() {
508 d["metadata_size"] = torrent.metadataSize()
510 if p := me.incomingPeerPort(); p != 0 {
513 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
515 log.Printf("error calculating yourip field value in extension handshake: %s", err)
519 // log.Printf("sending %v", d)
520 b, err := bencode.Marshal(d)
528 if torrent.haveAnyPieces() {
529 conn.Post(pp.Message{
531 Bitfield: torrent.bitfield(),
534 err = me.connectionLoop(torrent, conn)
536 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
538 me.dropConnection(torrent, conn)
542 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
543 for piece >= len(c.PeerPieces) {
544 c.PeerPieces = append(c.PeerPieces, false)
546 c.PeerPieces[piece] = true
547 if t.wantPiece(piece) {
548 me.replenishConnRequests(t, c)
552 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
553 me.replenishConnRequests(torrent, conn)
556 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
560 cl.downloadStrategy.DeleteRequest(t, r)
565 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
566 if !cn.RequestPending(r) {
569 cl.downloadStrategy.DeleteRequest(t, r)
570 delete(cn.Requests, r)
573 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
578 for index := 0; index < t.MetadataPieceCount(); index++ {
579 if !t.HaveMetadataPiece(index) {
580 pending = append(pending, index)
583 for _, i := range mathRand.Perm(len(pending)) {
586 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
587 ExtendedPayload: func() []byte {
588 b, err := bencode.Marshal(map[string]int{
601 func (cl *Client) completedMetadata(t *torrent) {
605 CopyExact(&ih, h.Sum(nil))
606 if ih != t.InfoHash {
607 log.Print("bad metadata")
608 t.InvalidateMetadata()
611 var info metainfo.Info
612 err := bencode.Unmarshal(t.MetaData, &info)
614 log.Printf("error unmarshalling metadata: %s", err)
615 t.InvalidateMetadata()
618 // TODO(anacrolix): If this fails, I think something harsher should be
620 err = cl.setMetaData(t, info, t.MetaData)
622 log.Printf("error setting metadata: %s", err)
623 t.InvalidateMetadata()
626 log.Printf("%s: got metadata from peers", t)
629 // Process incoming ut_metadata message.
630 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
632 err = bencode.Unmarshal(payload, &d)
634 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
637 msgType, ok := d["msg_type"]
639 err = errors.New("missing msg_type field")
644 case pp.DataMetadataExtensionMsgType:
648 t.SaveMetadataPiece(piece, payload[len(payload)-metadataPieceSize(d["total_size"], piece):])
649 if !t.HaveAllMetadataPieces() {
652 cl.completedMetadata(t)
653 case pp.RequestMetadataExtensionMsgType:
654 if !t.HaveMetadataPiece(piece) {
655 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
658 start := (1 << 14) * piece
659 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
660 case pp.RejectMetadataExtensionMsgType:
662 err = errors.New("unknown msg_type value")
667 type peerExchangeMessage struct {
668 Added CompactPeers `bencode:"added"`
669 AddedFlags []byte `bencode:"added.f"`
670 Dropped []tracker.Peer `bencode:"dropped"`
673 // Processes incoming bittorrent messages. The client lock is held upon entry
675 func (me *Client) connectionLoop(t *torrent, c *connection) error {
676 decoder := pp.Decoder{
677 R: bufio.NewReader(c.Socket),
678 MaxLength: 256 * 1024,
683 err := decoder.Decode(&msg)
689 if me.stopped() || err == io.EOF {
700 for r := range c.Requests {
701 me.connDeleteRequest(t, c, r)
705 me.peerUnchoked(t, c)
707 c.PeerInterested = true
708 // TODO: This should be done from a dedicated unchoking routine.
713 case pp.NotInterested:
714 c.PeerInterested = false
717 me.peerGotPiece(t, c, int(msg.Index))
722 if c.PeerRequests == nil {
723 c.PeerRequests = make(map[request]struct{}, maxRequests)
725 request := newRequest(msg.Index, msg.Begin, msg.Length)
726 // TODO: Requests should be satisfied from a dedicated upload routine.
727 // c.PeerRequests[request] = struct{}{}
728 p := make([]byte, msg.Length)
729 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
731 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
733 if n != int(msg.Length) {
734 return fmt.Errorf("bad request: %v", msg)
742 uploadChunksPosted.Add(1)
744 req := newRequest(msg.Index, msg.Begin, msg.Length)
745 if !c.PeerCancel(req) {
746 unexpectedCancels.Add(1)
749 if c.PeerPieces != nil {
750 err = errors.New("received unexpected bitfield")
754 if len(msg.Bitfield) < t.NumPieces() {
755 err = errors.New("received invalid bitfield")
758 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
760 c.PeerPieces = msg.Bitfield
761 for index, has := range c.PeerPieces {
763 me.peerGotPiece(t, c, index)
767 err = me.downloadedChunk(t, c, &msg)
769 switch msg.ExtendedID {
770 case pp.HandshakeExtendedID:
771 // TODO: Create a bencode struct for this.
772 var d map[string]interface{}
773 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
775 err = fmt.Errorf("error decoding extended message payload: %s", err)
778 // log.Printf("got handshake: %v", d)
779 if reqq, ok := d["reqq"]; ok {
780 if i, ok := reqq.(int64); ok {
781 c.PeerMaxRequests = int(i)
784 if v, ok := d["v"]; ok {
785 c.PeerClientName = v.(string)
789 err = errors.New("handshake missing m item")
792 mTyped, ok := m.(map[string]interface{})
794 err = errors.New("handshake m value is not dict")
797 if c.PeerExtensionIDs == nil {
798 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
800 for name, v := range mTyped {
803 log.Printf("bad handshake m item extension ID type: %T", v)
807 delete(c.PeerExtensionIDs, name)
809 c.PeerExtensionIDs[name] = id
812 metadata_sizeUntyped, ok := d["metadata_size"]
814 metadata_size, ok := metadata_sizeUntyped.(int64)
816 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
818 t.SetMetadataSize(metadata_size)
821 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
822 me.requestPendingMetadata(t, c)
825 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
827 err = fmt.Errorf("error handling metadata extension message: %s", err)
830 var pexMsg peerExchangeMessage
831 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
833 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
837 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
838 for _, cp := range pexMsg.Added {
842 Source: peerSourcePEX,
844 if n := copy(p.IP, cp.IP[:]); n != 4 {
852 log.Printf("error adding PEX peers: %s", err)
855 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
858 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
861 log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
864 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
872 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
874 for r := range conn.Requests {
875 me.connDeleteRequest(torrent, conn, r)
877 for i0, c := range torrent.Conns {
881 i1 := len(torrent.Conns) - 1
883 torrent.Conns[i0] = torrent.Conns[i1]
885 torrent.Conns = torrent.Conns[:i1]
888 panic("connection not found")
891 func (me *Client) addConnection(t *torrent, c *connection) bool {
895 for _, c0 := range t.Conns {
896 if c.PeerID == c0.PeerID {
897 // Already connected to a client with that ID.
901 t.Conns = append(t.Conns, c)
905 func (me *Client) openNewConns() {
906 for _, t := range me.torrents {
907 for len(t.Peers) != 0 {
908 if me.halfOpen >= me.halfOpenLimit {
915 for k, p = range t.Peers {
919 me.initiateConn(p, t)
924 // Adds peers to the swarm for the torrent corresponding to infoHash.
925 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
928 t := me.torrent(infoHash)
930 return errors.New("no such torrent")
937 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
938 err = t.setMetadata(md, cl.dataDir, bytes)
942 // Queue all pieces for hashing. This is done sequentially to avoid
943 // spamming goroutines.
944 for _, p := range t.Pieces {
945 p.QueuedForHash = true
948 for i := range t.Pieces {
949 cl.verifyPiece(t, pp.Integer(i))
953 cl.downloadStrategy.TorrentStarted(t)
957 // Prepare a Torrent without any attachment to a Client. That means we can
958 // initialize fields all fields that don't require the Client without locking
960 func newTorrent(ih InfoHash, announceList [][]string) (t *torrent, err error) {
963 Peers: make(map[peersKey]Peer, 2000),
965 closing: make(chan struct{}),
967 t.Trackers = make([][]tracker.Client, len(announceList))
968 for tierIndex := range announceList {
969 tier := t.Trackers[tierIndex]
970 for _, url := range announceList[tierIndex] {
971 tr, err := tracker.New(url)
976 tier = append(tier, tr)
978 // The trackers within each tier must be shuffled before use.
979 // http://stackoverflow.com/a/12267471/149482
980 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
981 for i := range tier {
982 j := mathRand.Intn(i + 1)
983 tier[i], tier[j] = tier[j], tier[i]
985 t.Trackers[tierIndex] = tier
990 func (cl *Client) AddMagnet(uri string) (err error) {
991 m, err := ParseMagnetURI(uri)
995 t, err := newTorrent(m.InfoHash, [][]string{m.Trackers})
999 t.DisplayName = m.DisplayName
1001 defer cl.mu.Unlock()
1002 err = cl.addTorrent(t)
1009 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1011 defer me.mu.Unlock()
1012 t, ok := me.torrents[infoHash]
1014 err = fmt.Errorf("no such torrent")
1021 delete(me.torrents, infoHash)
1022 me.downloadStrategy.TorrentStopped(t)
1026 func (me *Client) addTorrent(t *torrent) (err error) {
1027 if _, ok := me.torrents[t.InfoHash]; ok {
1028 err = fmt.Errorf("torrent infohash collision")
1031 me.torrents[t.InfoHash] = t
1032 if !me.disableTrackers {
1033 go me.announceTorrent(t)
1036 go me.announceTorrentDHT(t)
1041 // Adds the torrent to the client.
1042 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (err error) {
1044 CopyExact(&ih, metaInfo.Info.Hash)
1045 t, err := newTorrent(ih, metaInfo.AnnounceList)
1050 defer me.mu.Unlock()
1051 err = me.addTorrent(t)
1055 err = me.setMetaData(t, metaInfo.Info.Info, metaInfo.Info.Bytes)
1062 func (me *Client) AddTorrentFromFile(name string) (err error) {
1063 mi, err := metainfo.LoadFromFile(name)
1065 err = fmt.Errorf("error loading metainfo from file: %s", err)
1068 return me.AddTorrent(mi)
1071 func (cl *Client) listenerAnnouncePort() (port int16) {
1077 switch data := addr.(type) {
1079 return int16(data.Port)
1081 return int16(data.Port)
1083 log.Printf("unknown listener addr type: %T", addr)
1088 func (cl *Client) announceTorrentDHT(t *torrent) {
1090 ps, err := cl.dHT.GetPeers(string(t.InfoHash[:]))
1092 log.Printf("error getting peers from dht: %s", err)
1095 nextScrape := time.After(1 * time.Minute)
1101 case cps, ok := <-ps.Values:
1105 peersFoundByDHT.Add(int64(len(cps)))
1106 err = cl.AddPeers(t.InfoHash, func() (ret []Peer) {
1107 for _, cp := range cps {
1108 ret = append(ret, Peer{
1111 Source: peerSourceDHT,
1117 log.Printf("error adding peers from dht for torrent %q: %s", t, err)
1129 func (cl *Client) announceTorrent(t *torrent) {
1130 req := tracker.AnnounceRequest{
1131 Event: tracker.Started,
1133 Port: cl.listenerAnnouncePort(),
1135 InfoHash: t.InfoHash,
1143 req.Left = t.BytesLeft()
1145 for _, tier := range t.Trackers {
1146 for trIndex, tr := range tier {
1147 if err := tr.Connect(); err != nil {
1151 resp, err := tr.Announce(&req)
1157 for _, peer := range resp.Peers {
1158 peers = append(peers, Peer{
1163 err = cl.AddPeers(t.InfoHash, peers)
1165 log.Printf("error adding peers to torrent %s: %s", t, err)
1167 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1169 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1170 time.Sleep(time.Second * time.Duration(resp.Interval))
1171 req.Event = tracker.None
1172 continue newAnnounce
1175 time.Sleep(5 * time.Second)
1179 func (cl *Client) allTorrentsCompleted() bool {
1180 for _, t := range cl.torrents {
1181 if !t.haveAllPieces() {
1188 // Returns true when all torrents are completely downloaded and false if the
1189 // client is stopped before that.
1190 func (me *Client) WaitAll() bool {
1192 defer me.mu.Unlock()
1193 for !me.allTorrentsCompleted() {
1202 func (cl *Client) assertRequestHeat() {
1203 dds, ok := cl.downloadStrategy.(*DefaultDownloadStrategy)
1207 for _, t := range cl.torrents {
1208 m := make(map[request]int, 3000)
1209 for _, cn := range t.Conns {
1210 for r := range cn.Requests {
1214 for r, h := range dds.heat[t] {
1216 panic(fmt.Sprintln(m[r], h))
1222 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
1226 me.downloadStrategy.FillRequests(t, c)
1227 //me.assertRequestHeat()
1228 if len(c.Requests) == 0 && !c.PeerChoked {
1229 c.SetInterested(false)
1233 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
1234 chunksDownloadedCount.Add(1)
1236 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1238 // Request has been satisfied.
1239 me.connDeleteRequest(t, c, req)
1241 defer me.replenishConnRequests(t, c)
1243 // Do we actually want this chunk?
1244 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
1245 unusedDownloadedChunksCount.Add(1)
1249 // Write the chunk out.
1250 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1255 // Record that we have the chunk.
1256 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
1257 me.dataReady(dataSpec{t.InfoHash, req})
1258 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
1259 me.queuePieceCheck(t, req.Index)
1261 t.PieceBytesLeftChanged(int(req.Index))
1263 // Unprioritize the chunk.
1264 me.downloadStrategy.TorrentGotChunk(t, req)
1266 // Cancel pending requests for this chunk.
1267 for _, c := range t.Conns {
1268 if me.connCancel(t, c, req) {
1269 me.replenishConnRequests(t, c)
1273 me.downloadStrategy.AssertNotRequested(t, req)
1278 func (cl *Client) dataReady(ds dataSpec) {
1279 cl.dataWaiterMutex.Lock()
1280 if cl.dataWaiter != nil {
1281 close(cl.dataWaiter)
1284 cl.dataWaiterMutex.Unlock()
1287 // Returns a channel that is closed when new data has become available in the
1289 func (me *Client) DataWaiter() (ret <-chan struct{}) {
1290 me.dataWaiterMutex.Lock()
1291 if me.dataWaiter == nil {
1292 me.dataWaiter = make(chan struct{})
1295 me.dataWaiterMutex.Unlock()
1299 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
1300 p := t.Pieces[piece]
1303 p.PendingChunkSpecs = nil
1304 me.downloadStrategy.TorrentGotPiece(t, int(piece))
1305 me.dataReady(dataSpec{
1309 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
1313 if len(p.PendingChunkSpecs) == 0 {
1314 t.pendAllChunkSpecs(piece)
1317 t.PieceBytesLeftChanged(int(piece))
1318 for _, conn := range t.Conns {
1320 conn.Post(pp.Message{
1322 Index: pp.Integer(piece),
1324 // TODO: Cancel requests for this piece.
1326 if conn.PeerHasPiece(piece) {
1327 me.replenishConnRequests(t, conn)
1331 me.event.Broadcast()
1334 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
1336 p := t.Pieces[index]
1345 p.QueuedForHash = false
1347 sum := t.HashPiece(index)
1350 cl.pieceHashed(t, index, sum == p.Hash)
1354 func (me *Client) Torrents() (ret []*torrent) {
1356 for _, t := range me.torrents {
1357 ret = append(ret, t)