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")
39 "bitbucket.org/anacrolix/go.torrent/dht"
40 "bitbucket.org/anacrolix/go.torrent/internal/pieceordering"
41 "bitbucket.org/anacrolix/go.torrent/iplist"
42 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
43 "bitbucket.org/anacrolix/go.torrent/tracker"
44 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
45 . "bitbucket.org/anacrolix/go.torrent/util"
46 "bitbucket.org/anacrolix/sync"
47 "bitbucket.org/anacrolix/utp"
48 "github.com/anacrolix/libtorgo/bencode"
49 "github.com/anacrolix/libtorgo/metainfo"
53 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
54 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
55 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
56 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
57 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
58 unexpectedCancels = expvar.NewInt("unexpectedCancels")
59 postedCancels = expvar.NewInt("postedCancels")
60 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
61 failedPieceHashes = expvar.NewInt("failedPieceHashes")
62 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
63 successfulDials = expvar.NewInt("successfulDials")
64 acceptedConns = expvar.NewInt("acceptedConns")
65 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
69 // Justification for set bits follows.
71 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html
72 // DHT: http://www.bittorrent.org/beps/bep_0005.html
73 extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
75 socketsPerTorrent = 40
76 torrentPeersHighWater = 1000
77 torrentPeersLowWater = socketsPerTorrent * 5
80 // Currently doesn't really queue, but should in the future.
81 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
82 piece := t.Pieces[pieceIndex]
83 if piece.QueuedForHash {
86 piece.QueuedForHash = true
87 go cl.verifyPiece(t, pieceIndex)
90 func (cl *Client) queueFirstHash(t *torrent, piece int) {
92 if p.EverHashed || p.Hashing || p.QueuedForHash {
95 cl.queuePieceCheck(t, pp.Integer(piece))
98 // Queues the torrent data for the given region for download. The beginning of
99 // the region is given highest priority to allow a subsequent read at the same
100 // offset to return data ASAP.
101 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
106 return errors.New("no such active torrent")
109 return errors.New("missing metadata")
111 firstIndex := int(off / int64(t.UsualPieceSize()))
112 for i := 0; i < 5; i++ {
113 index := firstIndex + i
114 if index >= t.numPieces() {
117 me.queueFirstHash(t, index)
119 me.downloadStrategy.TorrentPrioritize(t, off, len_)
120 for _, cn := range t.Conns {
121 me.replenishConnRequests(t, cn)
127 type dataWait struct {
137 listeners []net.Listener
140 downloadStrategy DownloadStrategy
144 ipBlockList *iplist.IPList
145 bannedTorrents map[InfoHash]struct{}
153 torrents map[InfoHash]*torrent
155 dataWaits map[*torrent][]dataWait
158 func (me *Client) SetIPBlockList(list *iplist.IPList) {
161 me.ipBlockList = list
163 me.dHT.SetIPBlockList(list)
167 func (me *Client) PeerID() string {
168 return string(me.peerID[:])
171 func (me *Client) ListenAddr() (addr net.Addr) {
172 for _, l := range me.listeners {
173 if addr != nil && l.Addr().String() != addr.String() {
174 panic("listeners exist on different addresses")
181 type hashSorter struct {
185 func (me hashSorter) Len() int {
186 return len(me.Hashes)
189 func (me hashSorter) Less(a, b int) bool {
190 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
193 func (me hashSorter) Swap(a, b int) {
194 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
197 func (cl *Client) sortedTorrents() (ret []*torrent) {
199 for ih := range cl.torrents {
200 hs.Hashes = append(hs.Hashes, ih)
203 for _, ih := range hs.Hashes {
204 ret = append(ret, cl.torrent(ih))
209 func (cl *Client) WriteStatus(_w io.Writer) {
211 defer cl.mu.RUnlock()
212 w := bufio.NewWriter(_w)
214 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
215 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
216 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
218 dhtStats := cl.dHT.Stats()
219 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.NumNodes, dhtStats.NumGoodNodes)
220 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
221 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
222 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
223 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.NumOutstandingTransactions)
225 cl.downloadStrategy.WriteStatus(w)
227 for _, t := range cl.sortedTorrents() {
229 fmt.Fprint(w, "<unknown name>")
231 fmt.Fprint(w, t.Name())
234 fmt.Fprintf(w, ": %f%% of %d bytes", 100*(1-float32(t.BytesLeft())/float32(t.Length())), t.Length())
237 fmt.Fprint(w, "Blocked reads:")
238 for _, dw := range cl.dataWaits[t] {
239 fmt.Fprintf(w, " %d", dw.offset)
247 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
249 func (cl *Client) torrentReadAt(t *torrent, off int64, p []byte) (n int, err error) {
252 index := int(off / int64(t.UsualPieceSize()))
253 // Reading outside the bounds of a file is an error.
258 if int(index) >= len(t.Pieces) {
262 piece := t.Pieces[index]
263 pieceOff := pp.Integer(off % int64(t.UsualPieceSize()))
264 pieceLeft := int(t.PieceLength(pp.Integer(index)) - pieceOff)
269 cl.readRaisePiecePriorities(t, off, int64(len(p)))
270 if len(p) > pieceLeft {
276 for !piece.Complete() {
279 return t.Data.ReadAt(p, off)
282 func (cl *Client) readRaisePiecePriorities(t *torrent, off, _len int64) {
283 index := int(off / int64(t.UsualPieceSize()))
284 cl.raisePiecePriority(t, index, piecePriorityNow)
286 if index >= t.numPieces() {
289 cl.raisePiecePriority(t, index, piecePriorityNext)
290 for i := 0; i < t.numConnsUnchoked()-2; i++ {
292 if index >= t.numPieces() {
295 cl.raisePiecePriority(t, index, piecePriorityReadahead)
299 func (cl *Client) configDir() string {
300 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
303 func (cl *Client) ConfigDir() string {
304 return cl.configDir()
307 func (t *torrent) connPendPiece(c *connection, piece int) {
308 c.pendPiece(piece, t.Pieces[piece].Priority)
311 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
312 if t.Pieces[piece].Priority < priority {
313 cl.prioritizePiece(t, piece, priority)
317 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
318 if t.havePiece(piece) {
321 cl.queueFirstHash(t, piece)
322 t.Pieces[piece].Priority = priority
323 if t.wantPiece(piece) {
324 for _, c := range t.Conns {
325 if c.PeerHasPiece(pp.Integer(piece)) {
326 t.connPendPiece(c, piece)
327 cl.replenishConnRequests(t, c)
333 func (cl *Client) setEnvBlocklist() (err error) {
334 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
335 defaultBlocklist := filename == ""
336 if defaultBlocklist {
337 filename = filepath.Join(cl.configDir(), "blocklist")
339 f, err := os.Open(filename)
341 if defaultBlocklist {
347 var ranges []iplist.Range
348 uniqStrs := make(map[string]string)
349 scanner := bufio.NewScanner(f)
351 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
353 err = fmt.Errorf("error reading torrent blocklist line: %s", lineErr)
359 if s, ok := uniqStrs[r.Description]; ok {
362 uniqStrs[r.Description] = r.Description
364 ranges = append(ranges, r)
368 err = fmt.Errorf("error reading torrent blocklist: %s", err)
371 cl.ipBlockList = iplist.New(ranges)
375 func (cl *Client) initBannedTorrents() error {
376 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
378 if os.IsNotExist(err) {
381 return fmt.Errorf("error opening banned infohashes file: %s", err)
384 scanner := bufio.NewScanner(f)
385 cl.bannedTorrents = make(map[InfoHash]struct{})
388 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
390 return fmt.Errorf("error reading infohash: %s", err)
396 return errors.New("bad infohash")
400 cl.bannedTorrents[ih] = struct{}{}
402 if err := scanner.Err(); err != nil {
403 return fmt.Errorf("error scanning file: %s", err)
408 func NewClient(cfg *Config) (cl *Client, err error) {
414 noUpload: cfg.NoUpload,
415 disableTrackers: cfg.DisableTrackers,
416 downloadStrategy: cfg.DownloadStrategy,
417 halfOpenLimit: socketsPerTorrent,
418 dataDir: cfg.DataDir,
419 disableUTP: cfg.DisableUTP,
420 disableTCP: cfg.DisableTCP,
422 quit: make(chan struct{}),
423 torrents: make(map[InfoHash]*torrent),
425 dataWaits: make(map[*torrent][]dataWait),
427 // TODO: Write my own UTP library ಠ_à²
428 // cl.disableUTP = true
431 if !cfg.NoDefaultBlocklist {
432 err = cl.setEnvBlocklist()
438 if err = cl.initBannedTorrents(); err != nil {
439 err = fmt.Errorf("error initing banned torrents: %s", err)
443 if cfg.PeerID != "" {
444 CopyExact(&cl.peerID, cfg.PeerID)
446 o := copy(cl.peerID[:], BEP20)
447 _, err = rand.Read(cl.peerID[o:])
449 panic("error generating peer id")
453 if cl.downloadStrategy == nil {
454 cl.downloadStrategy = &DefaultDownloadStrategy{}
457 // Returns the laddr string to listen on for the next Listen call.
458 listenAddr := func() string {
459 if addr := cl.ListenAddr(); addr != nil {
462 if cfg.ListenAddr == "" {
465 return cfg.ListenAddr
469 l, err = net.Listen("tcp", listenAddr())
473 cl.listeners = append(cl.listeners, l)
474 go cl.acceptConnections(l, false)
477 cl.utpSock, err = utp.NewSocket(listenAddr())
481 cl.listeners = append(cl.listeners, cl.utpSock)
482 go cl.acceptConnections(cl.utpSock, true)
485 dhtCfg := cfg.DHTConfig
487 dhtCfg = &dht.ServerConfig{}
489 if dhtCfg.Addr == "" {
490 dhtCfg.Addr = listenAddr()
492 if dhtCfg.Conn == nil && cl.utpSock != nil {
493 dhtCfg.Conn = cl.utpSock
495 cl.dHT, err = dht.NewServer(dhtCfg)
496 if cl.ipBlockList != nil {
497 cl.dHT.SetIPBlockList(cl.ipBlockList)
507 func (cl *Client) stopped() bool {
516 // Stops the client. All connections to peers are closed and all activity will
518 func (me *Client) Stop() {
521 for _, l := range me.listeners {
525 for _, t := range me.torrents {
531 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
533 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
534 if cl.ipBlockList == nil {
539 log.Printf("saw non-IPv4 address")
543 r = cl.ipBlockList.Lookup(ip)
547 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
549 // We accept all connections immediately, because we don't know what
550 // torrent they're for.
551 conn, err := l.Accept()
566 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
568 if blockRange != nil {
569 inboundConnsBlocked.Add(1)
570 log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
575 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
582 func (me *Client) torrent(ih InfoHash) *torrent {
583 for _, t := range me.torrents {
584 if t.InfoHash == ih {
591 type dialResult struct {
596 func doDial(dial func(addr string) (net.Conn, error), ch chan dialResult, utp bool, addr string) {
597 conn, err := dial(addr)
602 conn = nil // Pedantic
604 ch <- dialResult{conn, utp}
606 successfulDials.Add(1)
609 unsuccessfulDials.Add(1)
610 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
613 if netOpErr, ok := err.(*net.OpError); ok {
614 switch netOpErr.Err {
615 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
620 log.Printf("error dialing %s: %s", addr, err)
625 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
626 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
627 if ret < minDialTimeout {
633 // Start the process of connecting to the given peer for the given torrent if
635 func (me *Client) initiateConn(peer Peer, t *torrent) {
636 if peer.Id == me.peerID {
639 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
640 if t.addrActive(addr) {
641 duplicateConnsAvoided.Add(1)
644 if r := me.ipBlockRange(peer.IP); r != nil {
645 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
648 dialTimeout := reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
649 t.HalfOpen[addr] = struct{}{}
651 // Binding to the listen address and dialing via net.Dialer gives
652 // "address in use" error. It seems it's not possible to dial out from
653 // this address so that peers associate our local address with our
656 // Initiate connections via TCP and UTP simultaneously. Use the first
657 // one that succeeds.
665 resCh := make(chan dialResult, left)
667 go doDial(func(addr string) (net.Conn, error) {
668 return me.utpSock.DialTimeout(addr, dialTimeout)
669 }, resCh, true, addr)
672 go doDial(func(addr string) (net.Conn, error) {
673 // time.Sleep(time.Second) // Give uTP a bit of a head start.
674 return net.DialTimeout("tcp", addr, dialTimeout)
675 }, resCh, false, addr)
678 for ; left > 0 && res.Conn == nil; left-- {
681 // Whether or not the connection attempt succeeds, the half open
682 // counter should be decremented, and new connection attempts made.
686 if _, ok := t.HalfOpen[addr]; !ok {
687 panic("invariant broken")
689 delete(t.HalfOpen, addr)
697 for ; left > 0; left-- {
698 conn := (<-resCh).Conn
706 // log.Printf("connected to %s", conn.RemoteAddr())
707 err := me.runConnection(res.Conn, t, peer.Source, res.UTP)
714 // The port number for incoming peer connections. 0 if the client isn't
716 func (cl *Client) incomingPeerPort() int {
717 listenAddr := cl.ListenAddr()
718 if listenAddr == nil {
721 return addrPort(listenAddr)
724 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
725 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
726 func addrCompactIP(addr net.Addr) (string, error) {
727 host, _, err := net.SplitHostPort(addr.String())
731 ip := net.ParseIP(host)
732 if v4 := ip.To4(); v4 != nil {
736 return string(v4), nil
738 return string(ip.To16()), nil
741 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
753 type peerExtensionBytes [8]byte
756 type handshakeResult struct {
762 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
763 // Bytes to be sent to the peer. Should never block the sender.
764 postCh := make(chan []byte, 4)
765 // A single error value sent when the writer completes.
766 writeDone := make(chan error, 1)
767 // Performs writes to the socket and ensures posts don't block.
768 go handshakeWriter(sock, postCh, writeDone)
771 close(postCh) // Done writing.
778 // Wait until writes complete before returning from handshake.
781 err = fmt.Errorf("error writing during handshake: %s", err)
785 post := func(bb []byte) {
789 panic("mustn't block while posting")
793 post([]byte(pp.Protocol))
794 post([]byte(extensionBytes))
795 if ih != nil { // We already know what we want.
800 _, err = io.ReadFull(sock, b[:68])
805 if string(b[:20]) != pp.Protocol {
808 CopyExact(&res.peerExtensionBytes, b[20:28])
809 CopyExact(&res.InfoHash, b[28:48])
810 CopyExact(&res.peerID, b[48:68])
812 if ih == nil { // We were waiting for the peer to tell us what they wanted.
813 post(res.InfoHash[:])
821 type peerConn struct {
825 func (pc peerConn) Read(b []byte) (n int, err error) {
826 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
827 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
829 err = fmt.Errorf("error setting read deadline: %s", err)
831 n, err = pc.Conn.Read(b)
833 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
835 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
845 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource, uTP bool) (err error) {
846 if tcpConn, ok := sock.(*net.TCPConn); ok {
853 // One minute to complete handshake.
854 sock.SetDeadline(time.Now().Add(time.Minute))
855 hsRes, ok, err := handshake(sock, func() *InfoHash {
859 return &torrent.InfoHash
864 if me.handshaking == 0 {
865 panic("handshake count invariant is broken")
869 err = fmt.Errorf("error during handshake: %s", err)
875 if hsRes.peerID == me.peerID {
878 torrent = me.torrent(hsRes.InfoHash)
882 sock.SetWriteDeadline(time.Time{})
883 sock = peerConn{sock}
884 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
886 conn.Discovery = discovery
887 if !me.addConnection(torrent, conn) {
890 if conn.PeerExtensionBytes[5]&0x10 != 0 {
891 conn.Post(pp.Message{
893 ExtendedID: pp.HandshakeExtendedID,
894 ExtendedPayload: func() []byte {
895 d := map[string]interface{}{
900 "v": "go.torrent dev 20140825", // Just the date
901 // No upload queue is implemented yet.
904 // No need to look strange if it costs us nothing.
911 if torrent.metadataSizeKnown() {
912 d["metadata_size"] = torrent.metadataSize()
914 if p := me.incomingPeerPort(); p != 0 {
917 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
919 log.Printf("error calculating yourip field value in extension handshake: %s", err)
923 // log.Printf("sending %v", d)
924 b, err := bencode.Marshal(d)
932 if torrent.haveAnyPieces() {
933 conn.Post(pp.Message{
935 Bitfield: torrent.bitfield(),
938 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
939 conn.Post(pp.Message{
941 Port: uint16(AddrPort(me.dHT.LocalAddr())),
944 if torrent.haveInfo() {
945 torrent.initRequestOrdering(conn)
946 me.replenishConnRequests(torrent, conn)
948 err = me.connectionLoop(torrent, conn)
950 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
952 me.dropConnection(torrent, conn)
956 func (t *torrent) initRequestOrdering(c *connection) {
957 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
958 panic("double init of request ordering")
960 c.piecePriorities = mathRand.Perm(t.numPieces())
961 c.pieceRequestOrder = pieceordering.New()
962 for i := 0; i < t.numPieces(); i++ {
963 if !c.PeerHasPiece(pp.Integer(i)) {
969 t.connPendPiece(c, i)
973 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
975 if c.PeerPieces == nil {
976 c.PeerPieces = make([]bool, t.numPieces())
979 for piece >= len(c.PeerPieces) {
980 c.PeerPieces = append(c.PeerPieces, false)
983 c.PeerPieces[piece] = true
984 if t.wantPiece(piece) {
985 t.connPendPiece(c, piece)
986 me.replenishConnRequests(t, c)
990 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
991 me.replenishConnRequests(torrent, conn)
994 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
998 cl.downloadStrategy.DeleteRequest(t, r)
1003 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1004 if !cn.RequestPending(r) {
1007 cl.downloadStrategy.DeleteRequest(t, r)
1008 delete(cn.Requests, r)
1011 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1016 for index := 0; index < t.MetadataPieceCount(); index++ {
1017 if !t.HaveMetadataPiece(index) {
1018 pending = append(pending, index)
1021 for _, i := range mathRand.Perm(len(pending)) {
1024 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
1025 ExtendedPayload: func() []byte {
1026 b, err := bencode.Marshal(map[string]int{
1028 "piece": pending[i],
1039 func (cl *Client) completedMetadata(t *torrent) {
1043 CopyExact(&ih, h.Sum(nil))
1044 if ih != t.InfoHash {
1045 log.Print("bad metadata")
1046 t.InvalidateMetadata()
1049 var info metainfo.Info
1050 err := bencode.Unmarshal(t.MetaData, &info)
1052 log.Printf("error unmarshalling metadata: %s", err)
1053 t.InvalidateMetadata()
1056 // TODO(anacrolix): If this fails, I think something harsher should be
1058 err = cl.setMetaData(t, info, t.MetaData)
1060 log.Printf("error setting metadata: %s", err)
1061 t.InvalidateMetadata()
1064 log.Printf("%s: got metadata from peers", t)
1067 // Process incoming ut_metadata message.
1068 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1069 var d map[string]int
1070 err = bencode.Unmarshal(payload, &d)
1072 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1075 msgType, ok := d["msg_type"]
1077 err = errors.New("missing msg_type field")
1082 case pp.DataMetadataExtensionMsgType:
1086 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1087 if begin < 0 || begin >= len(payload) {
1088 log.Printf("got bad metadata piece")
1091 t.SaveMetadataPiece(piece, payload[begin:])
1092 c.UsefulChunksReceived++
1093 c.lastUsefulChunkReceived = time.Now()
1094 if !t.HaveAllMetadataPieces() {
1097 cl.completedMetadata(t)
1098 case pp.RequestMetadataExtensionMsgType:
1099 if !t.HaveMetadataPiece(piece) {
1100 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1103 start := (1 << 14) * piece
1104 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1105 case pp.RejectMetadataExtensionMsgType:
1107 err = errors.New("unknown msg_type value")
1112 type peerExchangeMessage struct {
1113 Added CompactPeers `bencode:"added"`
1114 AddedFlags []byte `bencode:"added.f"`
1115 Dropped []tracker.Peer `bencode:"dropped"`
1118 // Extracts the port as an integer from an address string.
1119 func addrPort(addr net.Addr) int {
1120 return AddrPort(addr)
1123 // Processes incoming bittorrent messages. The client lock is held upon entry
1125 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1126 decoder := pp.Decoder{
1127 R: bufio.NewReader(c.Socket),
1128 MaxLength: 256 * 1024,
1133 err := decoder.Decode(&msg)
1135 c.lastMessageReceived = time.Now()
1142 if me.stopped() || err == io.EOF {
1153 for r := range c.Requests {
1154 me.connDeleteRequest(t, c, r)
1156 // We can then reset our interest.
1157 me.replenishConnRequests(t, c)
1159 c.PeerChoked = false
1160 me.peerUnchoked(t, c)
1162 c.PeerInterested = true
1163 // TODO: This should be done from a dedicated unchoking routine.
1168 case pp.NotInterested:
1169 c.PeerInterested = false
1172 me.peerGotPiece(t, c, int(msg.Index))
1177 if c.PeerRequests == nil {
1178 c.PeerRequests = make(map[request]struct{}, maxRequests)
1180 request := newRequest(msg.Index, msg.Begin, msg.Length)
1181 // TODO: Requests should be satisfied from a dedicated upload routine.
1182 // c.PeerRequests[request] = struct{}{}
1183 p := make([]byte, msg.Length)
1184 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1186 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1188 if n != int(msg.Length) {
1189 return fmt.Errorf("bad request: %v", msg)
1197 uploadChunksPosted.Add(1)
1199 req := newRequest(msg.Index, msg.Begin, msg.Length)
1200 if !c.PeerCancel(req) {
1201 unexpectedCancels.Add(1)
1204 if c.PeerPieces != nil {
1205 err = errors.New("received unexpected bitfield")
1209 if len(msg.Bitfield) < t.numPieces() {
1210 err = errors.New("received invalid bitfield")
1213 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1215 c.PeerPieces = msg.Bitfield
1216 for index, has := range c.PeerPieces {
1218 me.peerGotPiece(t, c, index)
1222 err = me.downloadedChunk(t, c, &msg)
1224 switch msg.ExtendedID {
1225 case pp.HandshakeExtendedID:
1226 // TODO: Create a bencode struct for this.
1227 var d map[string]interface{}
1228 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1230 err = fmt.Errorf("error decoding extended message payload: %s", err)
1233 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1234 if reqq, ok := d["reqq"]; ok {
1235 if i, ok := reqq.(int64); ok {
1236 c.PeerMaxRequests = int(i)
1239 if v, ok := d["v"]; ok {
1240 c.PeerClientName = v.(string)
1244 err = errors.New("handshake missing m item")
1247 mTyped, ok := m.(map[string]interface{})
1249 err = errors.New("handshake m value is not dict")
1252 if c.PeerExtensionIDs == nil {
1253 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1255 for name, v := range mTyped {
1258 log.Printf("bad handshake m item extension ID type: %T", v)
1262 delete(c.PeerExtensionIDs, name)
1264 c.PeerExtensionIDs[name] = id
1267 metadata_sizeUntyped, ok := d["metadata_size"]
1269 metadata_size, ok := metadata_sizeUntyped.(int64)
1271 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1273 t.SetMetadataSize(metadata_size)
1276 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1277 me.requestPendingMetadata(t, c)
1280 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1282 err = fmt.Errorf("error handling metadata extension message: %s", err)
1285 var pexMsg peerExchangeMessage
1286 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1288 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1292 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
1293 for _, cp := range pexMsg.Added {
1295 IP: make([]byte, 4),
1297 Source: peerSourcePEX,
1299 if n := copy(p.IP, cp.IP[:]); n != 4 {
1302 ret = append(ret, p)
1307 log.Printf("error adding PEX peers: %s", err)
1310 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1313 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1316 // That client uses its own extension IDs for outgoing message
1317 // types, which is incorrect.
1318 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1319 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1322 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1328 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1333 pingAddr.Port = int(msg.Port)
1335 _, err = me.dHT.Ping(pingAddr)
1337 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1345 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1346 for r := range conn.Requests {
1347 me.connDeleteRequest(torrent, conn, r)
1350 for i0, c := range torrent.Conns {
1354 i1 := len(torrent.Conns) - 1
1356 torrent.Conns[i0] = torrent.Conns[i1]
1358 torrent.Conns = torrent.Conns[:i1]
1359 me.openNewConns(torrent)
1362 panic("connection not found")
1365 func (me *Client) addConnection(t *torrent, c *connection) bool {
1370 case <-t.ceasingNetworking:
1374 if !me.wantConns(t) {
1377 for _, c0 := range t.Conns {
1378 if c.PeerID == c0.PeerID {
1379 // Already connected to a client with that ID.
1383 t.Conns = append(t.Conns, c)
1384 // TODO: This should probably be done by a routine that kills off bad
1385 // connections, and extra connections killed here instead.
1386 if len(t.Conns) > socketsPerTorrent {
1387 wcs := t.worstConnsHeap()
1388 heap.Pop(wcs).(*connection).Close()
1393 func (t *torrent) needData() bool {
1397 for i := range t.Pieces {
1405 // TODO: I'm sure there's something here to do with seeding.
1406 func (t *torrent) badConn(c *connection) bool {
1407 if time.Now().Sub(c.completedHandshake) < 30*time.Second {
1411 return !c.supportsExtension("ut_metadata")
1413 return !t.connHasWantedPieces(c)
1416 func (t *torrent) numGoodConns() (num int) {
1417 for _, c := range t.Conns {
1425 func (me *Client) wantConns(t *torrent) bool {
1426 if !t.needData() && me.noUpload {
1429 if t.numGoodConns() >= socketsPerTorrent {
1435 func (me *Client) openNewConns(t *torrent) {
1437 case <-t.ceasingNetworking:
1441 for len(t.Peers) != 0 {
1442 if !me.wantConns(t) {
1445 if len(t.HalfOpen) >= me.halfOpenLimit {
1452 for k, p = range t.Peers {
1456 me.initiateConn(p, t)
1458 t.wantPeers.Broadcast()
1461 func (me *Client) addPeers(t *torrent, peers []Peer) {
1463 for i, p := range peers {
1464 if me.ipBlockRange(p.IP) == nil {
1467 peers[i] = peers[len(peers)-1]
1468 peers = peers[:len(peers)-1]
1473 log.Printf("IP blocklist screened %d peers from being added", blocked)
1479 // Adds peers to the swarm for the torrent corresponding to infoHash.
1480 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1482 defer me.mu.Unlock()
1483 t := me.torrent(infoHash)
1485 return errors.New("no such torrent")
1487 me.addPeers(t, peers)
1491 func (cl *Client) torrentFileCachePath(ih InfoHash) string {
1492 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1495 func (cl *Client) saveTorrentFile(t *torrent) error {
1496 path := cl.torrentFileCachePath(t.InfoHash)
1497 os.MkdirAll(filepath.Dir(path), 0777)
1498 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1500 return fmt.Errorf("error opening file: %s", err)
1503 e := bencode.NewEncoder(f)
1504 err = e.Encode(t.MetaInfo())
1506 return fmt.Errorf("error marshalling metainfo: %s", err)
1508 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1510 // For example, a script kiddy makes us load too many files, and we're
1511 // able to save the torrent, but not load it again to check it.
1514 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1515 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1520 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1521 err = t.setMetadata(md, cl.dataDir, bytes, &cl.mu)
1526 if err := cl.saveTorrentFile(t); err != nil {
1527 log.Printf("error saving torrent file for %s: %s", t, err)
1530 if strings.Contains(strings.ToLower(md.Name), "porn") {
1531 cl.dropTorrent(t.InfoHash)
1532 err = errors.New("no porn plx")
1536 // If the client intends to upload, it needs to know what state pieces are
1539 // Queue all pieces for hashing. This is done sequentially to avoid
1540 // spamming goroutines.
1541 for _, p := range t.Pieces {
1542 p.QueuedForHash = true
1545 for i := range t.Pieces {
1546 cl.verifyPiece(t, pp.Integer(i))
1551 cl.downloadStrategy.TorrentStarted(t)
1552 close(t.gotMetainfo)
1556 // Prepare a Torrent without any attachment to a Client. That means we can
1557 // initialize fields all fields that don't require the Client without locking
1559 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1562 Peers: make(map[peersKey]Peer),
1564 closing: make(chan struct{}),
1565 ceasingNetworking: make(chan struct{}),
1567 gotMetainfo: make(chan struct{}),
1569 HalfOpen: make(map[string]struct{}),
1571 t.wantPeers.L = &t.stateMu
1572 t.GotMetainfo = t.gotMetainfo
1573 t.addTrackers(announceList)
1578 // For shuffling the tracker tiers.
1579 mathRand.Seed(time.Now().Unix())
1582 // The trackers within each tier must be shuffled before use.
1583 // http://stackoverflow.com/a/12267471/149482
1584 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1585 func shuffleTier(tier []tracker.Client) {
1586 for i := range tier {
1587 j := mathRand.Intn(i + 1)
1588 tier[i], tier[j] = tier[j], tier[i]
1592 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1593 for _, tier := range base {
1594 copy = append(copy, append([]tracker.Client{}, tier...))
1599 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1601 for _, url := range newURLs {
1602 for _, tr := range tier {
1603 if tr.URL() == url {
1607 tr, err := tracker.New(url)
1609 log.Printf("error creating tracker client for %q: %s", url, err)
1612 tier = append(tier, tr)
1617 func (t *torrent) addTrackers(announceList [][]string) {
1618 newTrackers := copyTrackers(t.Trackers)
1619 for tierIndex, tier := range announceList {
1620 if tierIndex < len(newTrackers) {
1621 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1623 newTrackers = append(newTrackers, mergeTier(nil, tier))
1625 shuffleTier(newTrackers[tierIndex])
1627 t.Trackers = newTrackers
1630 type Torrent struct {
1635 func (t Torrent) NumPieces() int {
1636 return t.numPieces()
1639 func (t Torrent) Drop() {
1640 t.cl.dropTorrent(t.InfoHash)
1650 func (f *File) Length() int64 {
1654 func (f *File) PrioritizeRegion(off, len int64) {
1655 if off < 0 || off >= f.length {
1658 if off+len > f.length {
1659 len = f.length - off
1662 f.t.SetRegionPriority(off, len)
1665 // Returns handles to the files in the torrent. This requires the metainfo is
1667 func (t Torrent) Files() (ret []File) {
1669 for _, fi := range t.Info.UpvertedFiles() {
1670 ret = append(ret, File{
1672 strings.Join(fi.Path, "/"),
1681 func (t Torrent) SetRegionPriority(off, len int64) {
1683 defer t.cl.mu.Unlock()
1684 pieceSize := int64(t.UsualPieceSize())
1685 for i := off / pieceSize; i*pieceSize < off+len; i++ {
1686 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
1690 func (t Torrent) MetainfoFilepath() string {
1691 return filepath.Join(t.cl.ConfigDir(), "torrents", t.InfoHash.HexString()+".torrent")
1694 func (t Torrent) AddPeers(pp []Peer) error {
1695 return t.cl.AddPeers(t.torrent.InfoHash, pp)
1698 func (t Torrent) DownloadAll() {
1700 for i := 0; i < t.numPieces(); i++ {
1701 // TODO: Leave higher priorities as they were?
1702 t.cl.prioritizePiece(t.torrent, i, piecePriorityNormal)
1704 // Nice to have the first and last pieces soon for various interactive
1706 t.cl.prioritizePiece(t.torrent, 0, piecePriorityReadahead)
1707 t.cl.prioritizePiece(t.torrent, t.numPieces()-1, piecePriorityReadahead)
1711 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
1712 return me.cl.torrentReadAt(me.torrent, off, p)
1715 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1716 f, err := os.Open(cl.torrentFileCachePath(ih))
1718 if os.IsNotExist(err) {
1724 dec := bencode.NewDecoder(f)
1725 err = dec.Decode(&mi)
1729 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1730 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1736 func (cl *Client) AddMagnet(uri string) (T Torrent, err error) {
1737 m, err := ParseMagnetURI(uri)
1741 mi, err := cl.torrentCacheMetaInfo(m.InfoHash)
1743 log.Printf("error getting cached metainfo for %x: %s", m.InfoHash[:], err)
1744 } else if mi != nil {
1745 _, err = cl.AddTorrent(mi)
1751 defer cl.mu.Unlock()
1752 T, err = cl.addOrMergeTorrent(m.InfoHash, [][]string{m.Trackers})
1756 if m.DisplayName != "" {
1757 T.DisplayName = m.DisplayName
1762 // Actively prunes unused connections. This is required to make space to dial
1763 // for replacements.
1764 func (cl *Client) connectionPruner(t *torrent) {
1766 time.Sleep(15 * time.Second)
1769 case <-t.ceasingNetworking:
1772 license := len(t.Conns) - (socketsPerTorrent+1)/2
1773 for _, c := range t.Conns {
1777 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
1780 if time.Now().Sub(c.completedHandshake) < time.Minute {
1790 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1792 defer me.mu.Unlock()
1793 return me.dropTorrent(infoHash)
1796 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
1797 t, ok := me.torrents[infoHash]
1799 err = fmt.Errorf("no such torrent")
1806 delete(me.torrents, infoHash)
1807 me.downloadStrategy.TorrentStopped(t)
1808 for _, dw := range me.dataWaits[t] {
1811 delete(me.dataWaits, t)
1815 func (me *Client) addOrMergeTorrent(ih InfoHash, announceList [][]string) (T Torrent, err error) {
1816 if _, ok := me.bannedTorrents[ih]; ok {
1817 err = errors.New("banned torrent")
1822 T.torrent, ok = me.torrents[ih]
1824 T.torrent.addTrackers(announceList)
1826 T.torrent, err = newTorrent(ih, announceList, me.halfOpenLimit)
1830 me.torrents[ih] = T.torrent
1831 if !me.disableTrackers {
1832 go me.announceTorrentTrackers(T.torrent)
1835 go me.announceTorrentDHT(T.torrent, true)
1837 go me.connectionPruner(T.torrent)
1842 // Adds the torrent to the client.
1843 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (t Torrent, err error) {
1845 CopyExact(&ih, metaInfo.Info.Hash)
1847 defer me.mu.Unlock()
1848 t, err = me.addOrMergeTorrent(ih, metaInfo.AnnounceList)
1852 if !t.torrent.haveInfo() {
1853 err = me.setMetaData(t.torrent, metaInfo.Info.Info, metaInfo.Info.Bytes)
1861 func (me *Client) AddTorrentFromFile(name string) (t Torrent, err error) {
1862 mi, err := metainfo.LoadFromFile(name)
1864 err = fmt.Errorf("error loading metainfo from file: %s", err)
1867 return me.AddTorrent(mi)
1870 // Returns true when peers are required, or false if the torrent is closing.
1871 func (cl *Client) waitWantPeers(t *torrent) bool {
1873 defer cl.mu.Unlock()
1875 defer t.stateMu.Unlock()
1878 case <-t.ceasingNetworking:
1882 if len(t.Peers) < torrentPeersLowWater {
1893 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
1894 for cl.waitWantPeers(t) {
1895 log.Printf("getting peers for %q from DHT", t)
1896 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
1898 log.Printf("error getting peers from dht: %s", err)
1901 allAddrs := make(map[string]struct{})
1905 case v, ok := <-ps.Values:
1909 peersFoundByDHT.Add(int64(len(v.Peers)))
1910 for _, p := range v.Peers {
1911 allAddrs[(&net.UDPAddr{
1914 }).String()] = struct{}{}
1916 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
1918 cl.addPeers(t, func() (ret []Peer) {
1919 for _, cp := range v.Peers {
1920 ret = append(ret, Peer{
1923 Source: peerSourceDHT,
1928 numPeers := len(t.Peers)
1930 if numPeers >= torrentPeersHighWater {
1933 case <-t.ceasingNetworking:
1939 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
1944 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
1945 if err := tr.Connect(); err != nil {
1946 return fmt.Errorf("error connecting: %s", err)
1948 resp, err := tr.Announce(req)
1950 return fmt.Errorf("error announcing: %s", err)
1953 for _, peer := range resp.Peers {
1954 peers = append(peers, Peer{
1959 err = cl.AddPeers(t.InfoHash, peers)
1961 log.Printf("error adding peers to torrent %s: %s", t, err)
1963 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1966 time.Sleep(time.Second * time.Duration(resp.Interval))
1970 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
1971 oks := make(chan bool)
1973 for _, tier := range trackers {
1974 for _, tr := range tier {
1976 go func(tr tracker.Client) {
1977 err := cl.announceTorrentSingleTracker(tr, req, t)
1982 for outstanding > 0 {
1992 // Announce torrent to its trackers.
1993 func (cl *Client) announceTorrentTrackers(t *torrent) {
1994 req := tracker.AnnounceRequest{
1995 Event: tracker.Started,
1997 Port: int16(cl.incomingPeerPort()),
1999 InfoHash: t.InfoHash,
2002 req.Left = t.BytesLeft()
2003 trackers := t.Trackers
2005 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2006 req.Event = tracker.None
2009 for cl.waitWantPeers(t) {
2011 req.Left = t.BytesLeft()
2012 trackers = t.Trackers
2014 numTrackersTried := 0
2015 for _, tier := range trackers {
2016 for trIndex, tr := range tier {
2018 err := cl.announceTorrentSingleTracker(tr, &req, t)
2022 // Float the successful announce to the top of the tier. If
2023 // the trackers list has been changed, we'll be modifying an
2024 // old copy so it won't matter.
2026 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2029 req.Event = tracker.None
2030 continue newAnnounce
2033 if numTrackersTried != 0 {
2034 log.Printf("%s: all trackers failed", t)
2036 // TODO: Wait until trackers are added if there are none.
2037 time.Sleep(10 * time.Second)
2041 func (cl *Client) allTorrentsCompleted() bool {
2042 for _, t := range cl.torrents {
2046 if t.NumPiecesCompleted() != t.numPieces() {
2053 // Returns true when all torrents are completely downloaded and false if the
2054 // client is stopped before that.
2055 func (me *Client) WaitAll() bool {
2057 defer me.mu.Unlock()
2058 for !me.allTorrentsCompleted() {
2067 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2071 me.downloadStrategy.FillRequests(t, c)
2072 if len(c.Requests) == 0 && !c.PeerChoked {
2073 c.SetInterested(false)
2077 // Handle a received chunk from a peer.
2078 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2079 chunksDownloadedCount.Add(1)
2081 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2083 // Request has been satisfied.
2084 me.connDeleteRequest(t, c, req)
2086 defer me.replenishConnRequests(t, c)
2088 // Do we actually want this chunk?
2089 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
2090 unusedDownloadedChunksCount.Add(1)
2091 c.UnwantedChunksReceived++
2095 c.UsefulChunksReceived++
2096 c.lastUsefulChunkReceived = time.Now()
2098 // Write the chunk out.
2099 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2101 return fmt.Errorf("error writing chunk: %s", err)
2104 // Record that we have the chunk.
2105 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
2106 me.dataReady(t, req)
2107 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
2108 for _, c := range t.Conns {
2109 c.pieceRequestOrder.DeletePiece(int(req.Index))
2111 me.queuePieceCheck(t, req.Index)
2114 // Unprioritize the chunk.
2115 me.downloadStrategy.TorrentGotChunk(t, req)
2117 // Cancel pending requests for this chunk.
2118 for _, c := range t.Conns {
2119 if me.connCancel(t, c, req) {
2120 me.replenishConnRequests(t, c)
2124 me.downloadStrategy.AssertNotRequested(t, req)
2129 func (cl *Client) dataReady(t *torrent, r request) {
2130 dws := cl.dataWaits[t]
2131 begin := t.requestOffset(r)
2132 end := begin + int64(r.Length)
2133 for i := 0; i < len(dws); {
2135 if begin <= dw.offset && dw.offset < end {
2137 dws[i] = dws[len(dws)-1]
2138 dws = dws[:len(dws)-1]
2143 cl.dataWaits[t] = dws
2146 // Returns a channel that is closed when new data has become available in the
2148 func (me *Client) DataWaiter(ih InfoHash, off int64) (ret <-chan struct{}) {
2150 defer me.mu.Unlock()
2151 ch := make(chan struct{})
2153 t := me.torrents[ih]
2158 if r, ok := t.offsetRequest(off); !ok || t.haveChunk(r) {
2162 me.dataWaits[t] = append(me.dataWaits[t], dataWait{
2169 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2170 p := t.Pieces[piece]
2171 if p.EverHashed && !correct {
2172 log.Printf("%s: piece %d failed hash", t, piece)
2173 failedPieceHashes.Add(1)
2177 p.Priority = piecePriorityNone
2178 p.PendingChunkSpecs = nil
2180 me.downloadStrategy.TorrentGotPiece(t, int(piece))
2181 me.dataReady(t, request{
2183 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
2186 if len(p.PendingChunkSpecs) == 0 {
2187 t.pendAllChunkSpecs(piece)
2189 if p.Priority != piecePriorityNone {
2193 for _, conn := range t.Conns {
2195 conn.Post(pp.Message{
2197 Index: pp.Integer(piece),
2199 // TODO: Cancel requests for this piece.
2200 for r := range conn.Requests {
2201 if r.Index == piece {
2205 conn.pieceRequestOrder.DeletePiece(int(piece))
2207 if t.wantPiece(int(piece)) && conn.PeerHasPiece(piece) {
2208 t.connPendPiece(conn, int(piece))
2209 me.replenishConnRequests(t, conn)
2212 if t.haveAllPieces() && me.noUpload {
2215 me.event.Broadcast()
2218 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2220 defer cl.mu.Unlock()
2221 p := t.Pieces[index]
2229 p.QueuedForHash = false
2231 sum := t.HashPiece(index)
2239 cl.pieceHashed(t, index, sum == p.Hash)
2242 func (me *Client) Torrents() (ret []Torrent) {
2244 for _, t := range me.torrents {
2245 ret = append(ret, Torrent{me, t})