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")
33 "bitbucket.org/anacrolix/go.torrent/dht"
34 . "bitbucket.org/anacrolix/go.torrent/util"
36 "github.com/anacrolix/libtorgo/metainfo"
37 "github.com/nsf/libtorgo/bencode"
39 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
40 "bitbucket.org/anacrolix/go.torrent/tracker"
41 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
44 const extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x00"
46 // Currently doesn't really queue, but should in the future.
47 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
48 piece := t.Pieces[pieceIndex]
49 if piece.QueuedForHash {
52 piece.QueuedForHash = true
53 go cl.verifyPiece(t, pieceIndex)
56 // Queues the torrent data for the given region for download. The beginning of
57 // the region is given highest priority to allow a subsequent read at the same
58 // offset to return data ASAP.
59 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
64 return errors.New("no such active torrent")
67 return errors.New("missing metadata")
69 me.downloadStrategy.TorrentPrioritize(t, off, len_)
70 for _, cn := range t.Conns {
71 me.replenishConnRequests(t, cn)
76 type dataSpec struct {
87 downloadStrategy DownloadStrategy
95 torrents map[InfoHash]*torrent
96 dataWaiter chan struct{}
99 func (me *Client) ListenAddr() net.Addr {
100 return me.listener.Addr()
103 func (cl *Client) WriteStatus(w io.Writer) {
106 if cl.listener != nil {
107 fmt.Fprintf(w, "Listening on %s\n", cl.listener.Addr())
109 fmt.Fprintf(w, "No listening torrent port!\n")
111 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
112 fmt.Fprintf(w, "Half open outgoing connections: %d\n", cl.halfOpen)
114 fmt.Fprintf(w, "DHT nodes: %d\n", cl.dHT.NumNodes())
115 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
118 for _, t := range cl.torrents {
119 fmt.Fprintf(w, "%s: %f%%\n", t.Name(), func() float32 {
123 return 100 * (1 - float32(t.BytesLeft())/float32(t.Length()))
131 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
133 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
138 err = errors.New("unknown torrent")
141 index := pp.Integer(off / int64(t.UsualPieceSize()))
142 // Reading outside the bounds of a file is an error.
147 if int(index) >= len(t.Pieces) {
151 piece := t.Pieces[index]
152 pieceOff := pp.Integer(off % int64(t.PieceLength(0)))
153 high := int(t.PieceLength(index) - pieceOff)
157 for cs, _ := range piece.PendingChunkSpecs {
158 chunkOff := int64(pieceOff) - int64(cs.Begin)
159 if chunkOff >= int64(t.PieceLength(index)) {
162 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
163 // read begins in a pending chunk
164 err = ErrDataNotReady
167 // pending chunk caps available data
168 if chunkOff < 0 && int64(len(p)) > -chunkOff {
172 return t.Data.ReadAt(p, off)
175 func NewClient(cfg *Config) (cl *Client, err error) {
181 disableTrackers: cfg.DisableTrackers,
182 downloadStrategy: cfg.DownloadStrategy,
184 dataDir: cfg.DataDir,
186 quit: make(chan struct{}),
187 torrents: make(map[InfoHash]*torrent),
191 o := copy(cl.peerID[:], BEP20)
192 _, err = rand.Read(cl.peerID[o:])
194 panic("error generating peer id")
197 if cl.downloadStrategy == nil {
198 cl.downloadStrategy = &DefaultDownloadStrategy{}
201 cl.listener, err = net.Listen("tcp", cfg.ListenAddr)
205 if cl.listener != nil {
206 go cl.acceptConnections()
210 cl.dHT, err = dht.NewServer(&dht.ServerConfig{
211 Addr: cfg.ListenAddr,
221 func (cl *Client) stopped() bool {
230 // Stops the client. All connections to peers are closed and all activity will
232 func (me *Client) Stop() {
236 for _, t := range me.torrents {
237 for _, c := range t.Conns {
244 func (cl *Client) acceptConnections() {
246 conn, err := cl.listener.Accept()
259 // log.Printf("accepted connection from %s", conn.RemoteAddr())
261 if err := cl.runConnection(conn, nil, peerSourceIncoming); err != nil {
268 func (me *Client) torrent(ih InfoHash) *torrent {
269 for _, t := range me.torrents {
270 if t.InfoHash == ih {
277 // Start the process of connecting to the given peer for the given torrent if
279 func (me *Client) initiateConn(peer Peer, torrent *torrent) {
280 if peer.Id == me.peerID {
285 addr := &net.TCPAddr{
289 // Binding to the listener address and dialing via net.Dialer gives
290 // "address in use" error. It seems it's not possible to dial out from
291 // this address so that peers associate our local address with our
293 conn, err := net.DialTimeout(addr.Network(), addr.String(), dialTimeout)
295 // Whether or not the connection attempt succeeds, the half open
296 // counter should be decremented, and new connection attempts made.
300 if me.halfOpen == 0 {
307 if netOpErr, ok := err.(*net.OpError); ok {
308 if netOpErr.Timeout() {
311 switch netOpErr.Err {
312 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
317 log.Printf("error connecting to peer: %s %#v", err, err)
320 // log.Printf("connected to %s", conn.RemoteAddr())
321 err = me.runConnection(conn, torrent, peer.Source)
328 func (cl *Client) incomingPeerPort() int {
329 if cl.listener == nil {
332 _, p, err := net.SplitHostPort(cl.listener.Addr().String())
337 _, err = fmt.Sscanf(p, "%d", &i)
344 // 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.
345 func addrCompactIP(addr net.Addr) (string, error) {
346 switch typed := addr.(type) {
348 if v4 := typed.IP.To4(); v4 != nil {
352 return string(v4), nil
354 return string(typed.IP.To16()), nil
356 return "", fmt.Errorf("unhandled type: %T", addr)
360 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
372 type peerExtensionBytes [8]byte
375 type handshakeResult struct {
381 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
382 // Bytes to be sent to the peer. Should never block the sender.
383 postCh := make(chan []byte, 4)
384 // A single error value sent when the writer completes.
385 writeDone := make(chan error, 1)
386 // Performs writes to the socket and ensures posts don't block.
387 go handshakeWriter(sock, postCh, writeDone)
390 close(postCh) // Done writing.
397 // Wait until writes complete before returning from handshake.
400 err = fmt.Errorf("error writing during handshake: %s", err)
404 post := func(bb []byte) {
408 panic("mustn't block while posting")
412 post([]byte(pp.Protocol))
413 post([]byte(extensionBytes))
414 if ih != nil { // We already know what we want.
419 _, err = io.ReadFull(sock, b[:68])
424 if string(b[:20]) != pp.Protocol {
427 copy(res.peerExtensionBytes[:], b[20:28])
428 copy(res.InfoHash[:], b[28:48])
429 copy(res.peerID[:], b[48:68])
431 if ih == nil { // We were waiting for the peer to tell us what they wanted.
432 post(res.InfoHash[:])
440 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource) (err error) {
442 hsRes, ok, err := handshake(sock, func() *InfoHash {
446 return &torrent.InfoHash
450 err = fmt.Errorf("error during handshake: %s", err)
458 torrent = me.torrent(hsRes.InfoHash)
462 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID)
464 conn.Discovery = discovery
465 if !me.addConnection(torrent, conn) {
468 if conn.PeerExtensionBytes[5]&0x10 != 0 {
469 conn.Post(pp.Message{
471 ExtendedID: pp.HandshakeExtendedID,
472 ExtendedPayload: func() []byte {
473 d := map[string]interface{}{
478 "v": "go.torrent dev",
481 if torrent.metadataSizeKnown() {
482 d["metadata_size"] = torrent.metadataSize()
484 if p := me.incomingPeerPort(); p != 0 {
487 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
489 log.Printf("error calculating yourip field value in extension handshake: %s", err)
493 // log.Printf("sending %v", d)
494 b, err := bencode.Marshal(d)
502 if torrent.haveAnyPieces() {
503 conn.Post(pp.Message{
505 Bitfield: torrent.bitfield(),
508 err = me.connectionLoop(torrent, conn)
510 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
512 me.dropConnection(torrent, conn)
516 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
517 for piece >= len(c.PeerPieces) {
518 c.PeerPieces = append(c.PeerPieces, false)
520 c.PeerPieces[piece] = true
521 if t.wantPiece(piece) {
522 me.replenishConnRequests(t, c)
526 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
527 me.replenishConnRequests(torrent, conn)
530 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
533 cl.downloadStrategy.DeleteRequest(t, r)
538 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
539 if !cn.RequestPending(r) {
542 cl.downloadStrategy.DeleteRequest(t, r)
543 delete(cn.Requests, r)
546 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
551 for index := 0; index < t.MetadataPieceCount(); index++ {
552 if !t.HaveMetadataPiece(index) {
553 pending = append(pending, index)
556 for _, i := range mathRand.Perm(len(pending)) {
559 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
560 ExtendedPayload: func() []byte {
561 b, err := bencode.Marshal(map[string]int{
574 func (cl *Client) completedMetadata(t *torrent) {
578 CopyExact(&ih, h.Sum(nil))
579 if ih != t.InfoHash {
580 log.Print("bad metadata")
581 t.InvalidateMetadata()
584 var info metainfo.Info
585 err := bencode.Unmarshal(t.MetaData, &info)
587 log.Printf("error unmarshalling metadata: %s", err)
588 t.InvalidateMetadata()
591 // TODO(anacrolix): If this fails, I think something harsher should be
593 err = cl.setMetaData(t, info, t.MetaData)
595 log.Printf("error setting metadata: %s", err)
596 t.InvalidateMetadata()
599 log.Printf("%s: got metadata from peers", t)
602 // Process incoming ut_metadata message.
603 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
605 err = bencode.Unmarshal(payload, &d)
607 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
610 msgType, ok := d["msg_type"]
612 err = errors.New("missing msg_type field")
617 case pp.DataMetadataExtensionMsgType:
621 t.SaveMetadataPiece(piece, payload[len(payload)-metadataPieceSize(d["total_size"], piece):])
622 if !t.HaveAllMetadataPieces() {
625 cl.completedMetadata(t)
626 case pp.RequestMetadataExtensionMsgType:
627 if !t.HaveMetadataPiece(piece) {
628 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
631 start := (1 << 14) * piece
632 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
633 case pp.RejectMetadataExtensionMsgType:
635 err = errors.New("unknown msg_type value")
640 type peerExchangeMessage struct {
641 Added CompactPeers `bencode:"added"`
642 AddedFlags []byte `bencode:"added.f"`
643 Dropped []tracker.Peer `bencode:"dropped"`
646 // Processes incoming bittorrent messages. The client lock is held upon entry
648 func (me *Client) connectionLoop(t *torrent, c *connection) error {
649 decoder := pp.Decoder{
650 R: bufio.NewReader(c.Socket),
651 MaxLength: 256 * 1024,
656 err := decoder.Decode(&msg)
662 if me.stopped() || err == io.EOF {
673 for r := range c.Requests {
674 me.connDeleteRequest(t, c, r)
678 me.peerUnchoked(t, c)
680 c.PeerInterested = true
681 // TODO: This should be done from a dedicated unchoking routine.
683 case pp.NotInterested:
684 c.PeerInterested = false
687 me.peerGotPiece(t, c, int(msg.Index))
689 if c.PeerRequests == nil {
690 c.PeerRequests = make(map[request]struct{}, maxRequests)
692 request := newRequest(msg.Index, msg.Begin, msg.Length)
693 // TODO: Requests should be satisfied from a dedicated upload routine.
694 // c.PeerRequests[request] = struct{}{}
695 p := make([]byte, msg.Length)
696 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
698 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
700 if n != int(msg.Length) {
701 return fmt.Errorf("bad request: %v", msg)
710 req := newRequest(msg.Index, msg.Begin, msg.Length)
711 if !c.PeerCancel(req) {
712 log.Printf("received unexpected cancel: %v", req)
715 if c.PeerPieces != nil {
716 err = errors.New("received unexpected bitfield")
720 if len(msg.Bitfield) < t.NumPieces() {
721 err = errors.New("received invalid bitfield")
724 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
726 c.PeerPieces = msg.Bitfield
727 for index, has := range c.PeerPieces {
729 me.peerGotPiece(t, c, index)
733 err = me.downloadedChunk(t, c, &msg)
735 switch msg.ExtendedID {
736 case pp.HandshakeExtendedID:
737 // TODO: Create a bencode struct for this.
738 var d map[string]interface{}
739 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
741 err = fmt.Errorf("error decoding extended message payload: %s", err)
744 // log.Printf("got handshake: %v", d)
745 if reqq, ok := d["reqq"]; ok {
746 if i, ok := reqq.(int64); ok {
747 c.PeerMaxRequests = int(i)
750 if v, ok := d["v"]; ok {
751 c.PeerClientName = v.(string)
755 err = errors.New("handshake missing m item")
758 mTyped, ok := m.(map[string]interface{})
760 err = errors.New("handshake m value is not dict")
763 if c.PeerExtensionIDs == nil {
764 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
766 for name, v := range mTyped {
769 log.Printf("bad handshake m item extension ID type: %T", v)
773 delete(c.PeerExtensionIDs, name)
775 c.PeerExtensionIDs[name] = id
778 metadata_sizeUntyped, ok := d["metadata_size"]
780 metadata_size, ok := metadata_sizeUntyped.(int64)
782 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
784 t.SetMetadataSize(metadata_size)
787 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
788 me.requestPendingMetadata(t, c)
791 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
793 err = fmt.Errorf("error handling metadata extension message: %s", err)
796 var pexMsg peerExchangeMessage
797 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
799 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
803 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
804 for _, cp := range pexMsg.Added {
808 Source: peerSourcePEX,
810 if n := copy(p.IP, cp.IP[:]); n != 4 {
818 log.Printf("error adding PEX peers: %s", err)
821 log.Printf("added %d peers from PEX", len(pexMsg.Added))
824 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
827 log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
830 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
838 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
840 for r := range conn.Requests {
841 me.connDeleteRequest(torrent, conn, r)
843 for i0, c := range torrent.Conns {
847 i1 := len(torrent.Conns) - 1
849 torrent.Conns[i0] = torrent.Conns[i1]
851 torrent.Conns = torrent.Conns[:i1]
854 panic("connection not found")
857 func (me *Client) addConnection(t *torrent, c *connection) bool {
861 for _, c0 := range t.Conns {
862 if c.PeerID == c0.PeerID {
863 // Already connected to a client with that ID.
867 t.Conns = append(t.Conns, c)
871 func (me *Client) openNewConns() {
872 for _, t := range me.torrents {
873 for len(t.Peers) != 0 {
874 if me.halfOpen >= me.halfOpenLimit {
878 t.Peers = t.Peers[1:]
879 me.initiateConn(p, t)
884 // Adds peers to the swarm for the torrent corresponding to infoHash.
885 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
888 t := me.torrent(infoHash)
890 return errors.New("no such torrent")
892 t.Peers = append(t.Peers, peers...)
897 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
898 err = t.setMetadata(md, cl.dataDir, bytes)
902 // Queue all pieces for hashing. This is done sequentially to avoid
903 // spamming goroutines.
904 for _, p := range t.Pieces {
905 p.QueuedForHash = true
908 for i := range t.Pieces {
909 cl.verifyPiece(t, pp.Integer(i))
913 cl.downloadStrategy.TorrentStarted(t)
917 // Prepare a Torrent without any attachment to a Client. That means we can
918 // initialize fields all fields that don't require the Client without locking
920 func newTorrent(ih InfoHash, announceList [][]string) (t *torrent, err error) {
924 t.Trackers = make([][]tracker.Client, len(announceList))
925 for tierIndex := range announceList {
926 tier := t.Trackers[tierIndex]
927 for _, url := range announceList[tierIndex] {
928 tr, err := tracker.New(url)
933 tier = append(tier, tr)
935 // The trackers within each tier must be shuffled before use.
936 // http://stackoverflow.com/a/12267471/149482
937 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
938 for i := range tier {
939 j := mathRand.Intn(i + 1)
940 tier[i], tier[j] = tier[j], tier[i]
942 t.Trackers[tierIndex] = tier
947 func (cl *Client) AddMagnet(uri string) (err error) {
948 m, err := ParseMagnetURI(uri)
952 t, err := newTorrent(m.InfoHash, [][]string{m.Trackers})
956 t.DisplayName = m.DisplayName
959 err = cl.addTorrent(t)
966 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
969 t, ok := me.torrents[infoHash]
971 err = fmt.Errorf("no such torrent")
978 delete(me.torrents, infoHash)
982 func (me *Client) addTorrent(t *torrent) (err error) {
983 if _, ok := me.torrents[t.InfoHash]; ok {
984 err = fmt.Errorf("torrent infohash collision")
987 me.torrents[t.InfoHash] = t
988 if !me.disableTrackers {
989 go me.announceTorrent(t)
992 go me.announceTorrentDHT(t)
997 // Adds the torrent to the client.
998 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (err error) {
999 t, err := newTorrent(BytesInfoHash(metaInfo.Info.Hash), metaInfo.AnnounceList)
1004 defer me.mu.Unlock()
1005 err = me.addTorrent(t)
1009 err = me.setMetaData(t, metaInfo.Info.Info, metaInfo.Info.Bytes)
1016 func (me *Client) AddTorrentFromFile(name string) (err error) {
1017 mi, err := metainfo.LoadFromFile(name)
1019 err = fmt.Errorf("error loading metainfo from file: %s", err)
1022 return me.AddTorrent(mi)
1025 func (cl *Client) listenerAnnouncePort() (port int16) {
1031 switch data := addr.(type) {
1033 return int16(data.Port)
1035 return int16(data.Port)
1037 log.Printf("unknown listener addr type: %T", addr)
1042 func (cl *Client) announceTorrentDHT(t *torrent) {
1044 ps, err := cl.dHT.GetPeers(string(t.InfoHash[:]))
1046 log.Printf("error getting peers from dht: %s", err)
1049 nextScrape := time.After(1 * time.Minute)
1055 case cps, ok := <-ps.Values:
1059 err = cl.AddPeers(t.InfoHash, func() (ret []Peer) {
1060 for _, cp := range cps {
1061 ret = append(ret, Peer{
1064 Source: peerSourceDHT,
1066 // log.Printf("peer from dht: %s", &net.UDPAddr{
1068 // Port: int(cp.Port),
1074 log.Printf("error adding peers from dht for torrent %q: %s", t, err)
1077 // log.Printf("got %d peers from dht for torrent %q", len(cps), t)
1084 func (cl *Client) announceTorrent(t *torrent) {
1085 req := tracker.AnnounceRequest{
1086 Event: tracker.Started,
1088 Port: cl.listenerAnnouncePort(),
1090 InfoHash: t.InfoHash,
1098 req.Left = t.BytesLeft()
1100 for _, tier := range t.Trackers {
1101 for trIndex, tr := range tier {
1102 if err := tr.Connect(); err != nil {
1106 resp, err := tr.Announce(&req)
1112 for _, peer := range resp.Peers {
1113 peers = append(peers, Peer{
1118 err = cl.AddPeers(t.InfoHash, peers)
1120 log.Printf("error adding peers to torrent %s: %s", t, err)
1122 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1124 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1125 time.Sleep(time.Second * time.Duration(resp.Interval))
1126 req.Event = tracker.None
1127 continue newAnnounce
1130 time.Sleep(5 * time.Second)
1134 func (cl *Client) allTorrentsCompleted() bool {
1135 for _, t := range cl.torrents {
1136 if !t.haveAllPieces() {
1143 // Returns true when all torrents are completely downloaded and false if the
1144 // client is stopped before that.
1145 func (me *Client) WaitAll() bool {
1147 defer me.mu.Unlock()
1148 for !me.allTorrentsCompleted() {
1157 func (cl *Client) assertRequestHeat() {
1158 dds, ok := cl.downloadStrategy.(*DefaultDownloadStrategy)
1162 for _, t := range cl.torrents {
1163 m := make(map[request]int, 3000)
1164 for _, cn := range t.Conns {
1165 for r := range cn.Requests {
1169 for r, h := range dds.heat[t] {
1171 panic(fmt.Sprintln(m[r], h))
1177 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
1181 me.downloadStrategy.FillRequests(t, c)
1182 //me.assertRequestHeat()
1183 if len(c.Requests) == 0 && !c.PeerChoked {
1184 c.SetInterested(false)
1188 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
1189 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1191 // Request has been satisfied.
1192 me.connDeleteRequest(t, c, req)
1194 defer me.replenishConnRequests(t, c)
1196 // Do we actually want this chunk?
1197 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
1198 log.Printf("got unnecessary chunk from %v: %q", req, string(c.PeerId[:]))
1202 // Write the chunk out.
1203 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1208 // Record that we have the chunk.
1209 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
1210 t.PiecesByBytesLeft.ValueChanged(t.Pieces[req.Index].bytesLeftElement)
1211 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
1212 me.queuePieceCheck(t, req.Index)
1215 // Unprioritize the chunk.
1216 me.downloadStrategy.TorrentGotChunk(t, req)
1218 // Cancel pending requests for this chunk.
1220 for _, c := range t.Conns {
1221 if me.connCancel(t, c, req) {
1223 me.replenishConnRequests(t, c)
1227 log.Printf("cancelled concurrent requests for %v", req)
1230 me.dataReady(dataSpec{t.InfoHash, req})
1234 func (cl *Client) dataReady(ds dataSpec) {
1235 if cl.dataWaiter != nil {
1236 close(cl.dataWaiter)
1241 // Returns a channel that is closed when new data has become available in the
1243 func (me *Client) DataWaiter() <-chan struct{} {
1245 defer me.mu.Unlock()
1246 if me.dataWaiter == nil {
1247 me.dataWaiter = make(chan struct{})
1249 return me.dataWaiter
1252 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
1253 p := t.Pieces[piece]
1256 p.PendingChunkSpecs = nil
1257 me.downloadStrategy.TorrentGotPiece(t, int(piece))
1258 me.dataReady(dataSpec{
1262 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
1266 if len(p.PendingChunkSpecs) == 0 {
1267 t.pendAllChunkSpecs(piece)
1270 for _, conn := range t.Conns {
1272 conn.Post(pp.Message{
1274 Index: pp.Integer(piece),
1276 // TODO: Cancel requests for this piece.
1278 if conn.PeerHasPiece(piece) {
1279 me.replenishConnRequests(t, conn)
1283 me.event.Broadcast()
1286 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
1288 p := t.Pieces[index]
1297 p.QueuedForHash = false
1299 sum := t.HashPiece(index)
1302 cl.pieceHashed(t, index, sum == p.Hash)
1306 func (me *Client) Torrents() (ret []*torrent) {
1308 for _, t := range me.torrents {
1309 ret = append(ret, t)