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 scanner := bufio.NewScanner(f)
350 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Text())
352 err = fmt.Errorf("error reading torrent blocklist line: %s", lineErr)
358 ranges = append(ranges, r)
362 err = fmt.Errorf("error reading torrent blocklist: %s", err)
365 cl.ipBlockList = iplist.New(ranges)
369 func (cl *Client) initBannedTorrents() error {
370 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
372 if os.IsNotExist(err) {
375 return fmt.Errorf("error opening banned infohashes file: %s", err)
378 scanner := bufio.NewScanner(f)
379 cl.bannedTorrents = make(map[InfoHash]struct{})
382 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
384 return fmt.Errorf("error reading infohash: %s", err)
390 return errors.New("bad infohash")
394 cl.bannedTorrents[ih] = struct{}{}
396 if err := scanner.Err(); err != nil {
397 return fmt.Errorf("error scanning file: %s", err)
402 func NewClient(cfg *Config) (cl *Client, err error) {
408 noUpload: cfg.NoUpload,
409 disableTrackers: cfg.DisableTrackers,
410 downloadStrategy: cfg.DownloadStrategy,
411 halfOpenLimit: socketsPerTorrent,
412 dataDir: cfg.DataDir,
413 disableUTP: cfg.DisableUTP,
414 disableTCP: cfg.DisableTCP,
416 quit: make(chan struct{}),
417 torrents: make(map[InfoHash]*torrent),
419 dataWaits: make(map[*torrent][]dataWait),
421 // TODO: Write my own UTP library ಠ_à²
422 // cl.disableUTP = true
425 if !cfg.NoDefaultBlocklist {
426 err = cl.setEnvBlocklist()
432 if err = cl.initBannedTorrents(); err != nil {
433 err = fmt.Errorf("error initing banned torrents: %s", err)
437 if cfg.PeerID != "" {
438 CopyExact(&cl.peerID, cfg.PeerID)
440 o := copy(cl.peerID[:], BEP20)
441 _, err = rand.Read(cl.peerID[o:])
443 panic("error generating peer id")
447 if cl.downloadStrategy == nil {
448 cl.downloadStrategy = &DefaultDownloadStrategy{}
451 // Returns the laddr string to listen on for the next Listen call.
452 listenAddr := func() string {
453 if addr := cl.ListenAddr(); addr != nil {
456 if cfg.ListenAddr == "" {
459 return cfg.ListenAddr
463 l, err = net.Listen("tcp", listenAddr())
467 cl.listeners = append(cl.listeners, l)
468 go cl.acceptConnections(l, false)
471 cl.utpSock, err = utp.NewSocket(listenAddr())
475 cl.listeners = append(cl.listeners, cl.utpSock)
476 go cl.acceptConnections(cl.utpSock, true)
479 dhtCfg := cfg.DHTConfig
481 dhtCfg = &dht.ServerConfig{}
483 if dhtCfg.Addr == "" {
484 dhtCfg.Addr = listenAddr()
486 if dhtCfg.Conn == nil && cl.utpSock != nil {
487 dhtCfg.Conn = cl.utpSock
489 cl.dHT, err = dht.NewServer(dhtCfg)
490 if cl.ipBlockList != nil {
491 cl.dHT.SetIPBlockList(cl.ipBlockList)
501 func (cl *Client) stopped() bool {
510 // Stops the client. All connections to peers are closed and all activity will
512 func (me *Client) Stop() {
515 for _, l := range me.listeners {
519 for _, t := range me.torrents {
525 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
527 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
528 if cl.ipBlockList == nil {
533 log.Printf("saw non-IPv4 address")
537 r = cl.ipBlockList.Lookup(ip)
541 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
543 // We accept all connections immediately, because we don't know what
544 // torrent they're for.
545 conn, err := l.Accept()
560 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
562 if blockRange != nil {
563 inboundConnsBlocked.Add(1)
564 log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
569 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
576 func (me *Client) torrent(ih InfoHash) *torrent {
577 for _, t := range me.torrents {
578 if t.InfoHash == ih {
585 type dialResult struct {
590 func doDial(dial func() (net.Conn, error), ch chan dialResult, utp bool) {
596 conn = nil // Pedantic
598 ch <- dialResult{conn, utp}
600 successfulDials.Add(1)
603 unsuccessfulDials.Add(1)
604 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
607 if netOpErr, ok := err.(*net.OpError); ok {
608 switch netOpErr.Err {
609 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
614 log.Printf("error connecting to peer: %s %#v", err, err)
619 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
620 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
621 if ret < minDialTimeout {
627 // Start the process of connecting to the given peer for the given torrent if
629 func (me *Client) initiateConn(peer Peer, t *torrent) {
630 if peer.Id == me.peerID {
633 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
634 if t.addrActive(addr) {
635 duplicateConnsAvoided.Add(1)
638 if r := me.ipBlockRange(peer.IP); r != nil {
639 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
642 dialTimeout := reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
643 t.HalfOpen[addr] = struct{}{}
645 // Binding to the listen address and dialing via net.Dialer gives
646 // "address in use" error. It seems it's not possible to dial out from
647 // this address so that peers associate our local address with our
650 // Initiate connections via TCP and UTP simultaneously. Use the first
651 // one that succeeds.
659 resCh := make(chan dialResult, left)
661 go doDial(func() (net.Conn, error) {
662 return me.utpSock.DialTimeout(addr, dialTimeout)
666 go doDial(func() (net.Conn, error) {
667 // time.Sleep(time.Second) // Give uTP a bit of a head start.
668 return net.DialTimeout("tcp", addr, dialTimeout)
672 for ; left > 0 && res.Conn == nil; left-- {
675 // Whether or not the connection attempt succeeds, the half open
676 // counter should be decremented, and new connection attempts made.
680 if _, ok := t.HalfOpen[addr]; !ok {
681 panic("invariant broken")
683 delete(t.HalfOpen, addr)
691 for ; left > 0; left-- {
692 conn := (<-resCh).Conn
700 // log.Printf("connected to %s", conn.RemoteAddr())
701 err := me.runConnection(res.Conn, t, peer.Source, res.UTP)
708 // The port number for incoming peer connections. 0 if the client isn't
710 func (cl *Client) incomingPeerPort() int {
711 listenAddr := cl.ListenAddr()
712 if listenAddr == nil {
715 return addrPort(listenAddr)
718 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
719 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
720 func addrCompactIP(addr net.Addr) (string, error) {
721 host, _, err := net.SplitHostPort(addr.String())
725 ip := net.ParseIP(host)
726 if v4 := ip.To4(); v4 != nil {
730 return string(v4), nil
732 return string(ip.To16()), nil
735 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
747 type peerExtensionBytes [8]byte
750 type handshakeResult struct {
756 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
757 // Bytes to be sent to the peer. Should never block the sender.
758 postCh := make(chan []byte, 4)
759 // A single error value sent when the writer completes.
760 writeDone := make(chan error, 1)
761 // Performs writes to the socket and ensures posts don't block.
762 go handshakeWriter(sock, postCh, writeDone)
765 close(postCh) // Done writing.
772 // Wait until writes complete before returning from handshake.
775 err = fmt.Errorf("error writing during handshake: %s", err)
779 post := func(bb []byte) {
783 panic("mustn't block while posting")
787 post([]byte(pp.Protocol))
788 post([]byte(extensionBytes))
789 if ih != nil { // We already know what we want.
794 _, err = io.ReadFull(sock, b[:68])
799 if string(b[:20]) != pp.Protocol {
802 CopyExact(&res.peerExtensionBytes, b[20:28])
803 CopyExact(&res.InfoHash, b[28:48])
804 CopyExact(&res.peerID, b[48:68])
806 if ih == nil { // We were waiting for the peer to tell us what they wanted.
807 post(res.InfoHash[:])
815 type peerConn struct {
819 func (pc peerConn) Read(b []byte) (n int, err error) {
820 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
821 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
823 err = fmt.Errorf("error setting read deadline: %s", err)
825 n, err = pc.Conn.Read(b)
827 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
829 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
839 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource, uTP bool) (err error) {
840 if tcpConn, ok := sock.(*net.TCPConn); ok {
847 // One minute to complete handshake.
848 sock.SetDeadline(time.Now().Add(time.Minute))
849 hsRes, ok, err := handshake(sock, func() *InfoHash {
853 return &torrent.InfoHash
858 if me.handshaking == 0 {
859 panic("handshake count invariant is broken")
863 err = fmt.Errorf("error during handshake: %s", err)
869 if hsRes.peerID == me.peerID {
872 torrent = me.torrent(hsRes.InfoHash)
876 sock.SetWriteDeadline(time.Time{})
877 sock = peerConn{sock}
878 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
880 conn.Discovery = discovery
881 if !me.addConnection(torrent, conn) {
884 if conn.PeerExtensionBytes[5]&0x10 != 0 {
885 conn.Post(pp.Message{
887 ExtendedID: pp.HandshakeExtendedID,
888 ExtendedPayload: func() []byte {
889 d := map[string]interface{}{
894 "v": "go.torrent dev 20140825", // Just the date
895 // No upload queue is implemented yet.
898 // No need to look strange if it costs us nothing.
905 if torrent.metadataSizeKnown() {
906 d["metadata_size"] = torrent.metadataSize()
908 if p := me.incomingPeerPort(); p != 0 {
911 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
913 log.Printf("error calculating yourip field value in extension handshake: %s", err)
917 // log.Printf("sending %v", d)
918 b, err := bencode.Marshal(d)
926 if torrent.haveAnyPieces() {
927 conn.Post(pp.Message{
929 Bitfield: torrent.bitfield(),
932 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
933 conn.Post(pp.Message{
935 Port: uint16(AddrPort(me.dHT.LocalAddr())),
938 if torrent.haveInfo() {
939 torrent.initRequestOrdering(conn)
940 me.replenishConnRequests(torrent, conn)
942 err = me.connectionLoop(torrent, conn)
944 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
946 me.dropConnection(torrent, conn)
950 func (t *torrent) initRequestOrdering(c *connection) {
951 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
952 panic("double init of request ordering")
954 c.piecePriorities = mathRand.Perm(t.NumPieces())
955 c.pieceRequestOrder = pieceordering.New()
956 for i := 0; i < t.NumPieces(); i++ {
957 if !c.PeerHasPiece(pp.Integer(i)) {
963 t.connPendPiece(c, i)
967 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
969 if c.PeerPieces == nil {
970 c.PeerPieces = make([]bool, t.NumPieces())
973 for piece >= len(c.PeerPieces) {
974 c.PeerPieces = append(c.PeerPieces, false)
977 c.PeerPieces[piece] = true
978 if t.wantPiece(piece) {
979 t.connPendPiece(c, piece)
980 me.replenishConnRequests(t, c)
984 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
985 me.replenishConnRequests(torrent, conn)
988 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
992 cl.downloadStrategy.DeleteRequest(t, r)
997 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
998 if !cn.RequestPending(r) {
1001 cl.downloadStrategy.DeleteRequest(t, r)
1002 delete(cn.Requests, r)
1005 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1010 for index := 0; index < t.MetadataPieceCount(); index++ {
1011 if !t.HaveMetadataPiece(index) {
1012 pending = append(pending, index)
1015 for _, i := range mathRand.Perm(len(pending)) {
1018 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
1019 ExtendedPayload: func() []byte {
1020 b, err := bencode.Marshal(map[string]int{
1022 "piece": pending[i],
1033 func (cl *Client) completedMetadata(t *torrent) {
1037 CopyExact(&ih, h.Sum(nil))
1038 if ih != t.InfoHash {
1039 log.Print("bad metadata")
1040 t.InvalidateMetadata()
1043 var info metainfo.Info
1044 err := bencode.Unmarshal(t.MetaData, &info)
1046 log.Printf("error unmarshalling metadata: %s", err)
1047 t.InvalidateMetadata()
1050 // TODO(anacrolix): If this fails, I think something harsher should be
1052 err = cl.setMetaData(t, info, t.MetaData)
1054 log.Printf("error setting metadata: %s", err)
1055 t.InvalidateMetadata()
1058 log.Printf("%s: got metadata from peers", t)
1061 // Process incoming ut_metadata message.
1062 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1063 var d map[string]int
1064 err = bencode.Unmarshal(payload, &d)
1066 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1069 msgType, ok := d["msg_type"]
1071 err = errors.New("missing msg_type field")
1076 case pp.DataMetadataExtensionMsgType:
1080 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1081 if begin < 0 || begin >= len(payload) {
1082 log.Printf("got bad metadata piece")
1085 t.SaveMetadataPiece(piece, payload[begin:])
1086 c.UsefulChunksReceived++
1087 c.lastUsefulChunkReceived = time.Now()
1088 if !t.HaveAllMetadataPieces() {
1091 cl.completedMetadata(t)
1092 case pp.RequestMetadataExtensionMsgType:
1093 if !t.HaveMetadataPiece(piece) {
1094 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1097 start := (1 << 14) * piece
1098 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1099 case pp.RejectMetadataExtensionMsgType:
1101 err = errors.New("unknown msg_type value")
1106 type peerExchangeMessage struct {
1107 Added CompactPeers `bencode:"added"`
1108 AddedFlags []byte `bencode:"added.f"`
1109 Dropped []tracker.Peer `bencode:"dropped"`
1112 // Extracts the port as an integer from an address string.
1113 func addrPort(addr net.Addr) int {
1114 return AddrPort(addr)
1117 // Processes incoming bittorrent messages. The client lock is held upon entry
1119 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1120 decoder := pp.Decoder{
1121 R: bufio.NewReader(c.Socket),
1122 MaxLength: 256 * 1024,
1127 err := decoder.Decode(&msg)
1129 c.lastMessageReceived = time.Now()
1136 if me.stopped() || err == io.EOF {
1147 for r := range c.Requests {
1148 me.connDeleteRequest(t, c, r)
1150 // We can then reset our interest.
1151 me.replenishConnRequests(t, c)
1153 c.PeerChoked = false
1154 me.peerUnchoked(t, c)
1156 c.PeerInterested = true
1157 // TODO: This should be done from a dedicated unchoking routine.
1162 case pp.NotInterested:
1163 c.PeerInterested = false
1166 me.peerGotPiece(t, c, int(msg.Index))
1171 if c.PeerRequests == nil {
1172 c.PeerRequests = make(map[request]struct{}, maxRequests)
1174 request := newRequest(msg.Index, msg.Begin, msg.Length)
1175 // TODO: Requests should be satisfied from a dedicated upload routine.
1176 // c.PeerRequests[request] = struct{}{}
1177 p := make([]byte, msg.Length)
1178 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1180 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1182 if n != int(msg.Length) {
1183 return fmt.Errorf("bad request: %v", msg)
1191 uploadChunksPosted.Add(1)
1193 req := newRequest(msg.Index, msg.Begin, msg.Length)
1194 if !c.PeerCancel(req) {
1195 unexpectedCancels.Add(1)
1198 if c.PeerPieces != nil {
1199 err = errors.New("received unexpected bitfield")
1203 if len(msg.Bitfield) < t.NumPieces() {
1204 err = errors.New("received invalid bitfield")
1207 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
1209 c.PeerPieces = msg.Bitfield
1210 for index, has := range c.PeerPieces {
1212 me.peerGotPiece(t, c, index)
1216 err = me.downloadedChunk(t, c, &msg)
1218 switch msg.ExtendedID {
1219 case pp.HandshakeExtendedID:
1220 // TODO: Create a bencode struct for this.
1221 var d map[string]interface{}
1222 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1224 err = fmt.Errorf("error decoding extended message payload: %s", err)
1227 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1228 if reqq, ok := d["reqq"]; ok {
1229 if i, ok := reqq.(int64); ok {
1230 c.PeerMaxRequests = int(i)
1233 if v, ok := d["v"]; ok {
1234 c.PeerClientName = v.(string)
1238 err = errors.New("handshake missing m item")
1241 mTyped, ok := m.(map[string]interface{})
1243 err = errors.New("handshake m value is not dict")
1246 if c.PeerExtensionIDs == nil {
1247 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1249 for name, v := range mTyped {
1252 log.Printf("bad handshake m item extension ID type: %T", v)
1256 delete(c.PeerExtensionIDs, name)
1258 c.PeerExtensionIDs[name] = id
1261 metadata_sizeUntyped, ok := d["metadata_size"]
1263 metadata_size, ok := metadata_sizeUntyped.(int64)
1265 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1267 t.SetMetadataSize(metadata_size)
1270 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1271 me.requestPendingMetadata(t, c)
1274 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1276 err = fmt.Errorf("error handling metadata extension message: %s", err)
1279 var pexMsg peerExchangeMessage
1280 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1282 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1286 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
1287 for _, cp := range pexMsg.Added {
1289 IP: make([]byte, 4),
1291 Source: peerSourcePEX,
1293 if n := copy(p.IP, cp.IP[:]); n != 4 {
1296 ret = append(ret, p)
1301 log.Printf("error adding PEX peers: %s", err)
1304 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1307 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1310 // That client uses its own extension IDs for outgoing message
1311 // types, which is incorrect.
1312 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1313 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1316 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1322 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1327 pingAddr.Port = int(msg.Port)
1329 _, err = me.dHT.Ping(pingAddr)
1331 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1339 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1340 for r := range conn.Requests {
1341 me.connDeleteRequest(torrent, conn, r)
1344 for i0, c := range torrent.Conns {
1348 i1 := len(torrent.Conns) - 1
1350 torrent.Conns[i0] = torrent.Conns[i1]
1352 torrent.Conns = torrent.Conns[:i1]
1353 me.openNewConns(torrent)
1356 panic("connection not found")
1359 func (me *Client) addConnection(t *torrent, c *connection) bool {
1364 case <-t.ceasingNetworking:
1368 if !me.wantConns(t) {
1371 for _, c0 := range t.Conns {
1372 if c.PeerID == c0.PeerID {
1373 // Already connected to a client with that ID.
1377 t.Conns = append(t.Conns, c)
1378 // TODO: This should probably be done by a routine that kills off bad
1379 // connections, and extra connections killed here instead.
1380 if len(t.Conns) > socketsPerTorrent {
1381 wcs := t.worstConnsHeap()
1382 heap.Pop(wcs).(*connection).Close()
1387 func (t *torrent) needData() bool {
1391 for i := range t.Pieces {
1399 // TODO: I'm sure there's something here to do with seeding.
1400 func (t *torrent) badConn(c *connection) bool {
1401 if time.Now().Sub(c.completedHandshake) < 30*time.Second {
1405 return !c.supportsExtension("ut_metadata")
1407 return !t.connHasWantedPieces(c)
1410 func (t *torrent) numGoodConns() (num int) {
1411 for _, c := range t.Conns {
1419 func (me *Client) wantConns(t *torrent) bool {
1420 if !t.needData() && me.noUpload {
1423 if t.numGoodConns() >= socketsPerTorrent {
1429 func (me *Client) openNewConns(t *torrent) {
1431 case <-t.ceasingNetworking:
1435 for len(t.Peers) != 0 {
1436 if !me.wantConns(t) {
1439 if len(t.HalfOpen) >= me.halfOpenLimit {
1446 for k, p = range t.Peers {
1450 me.initiateConn(p, t)
1452 t.wantPeers.Broadcast()
1455 func (me *Client) addPeers(t *torrent, peers []Peer) {
1457 for i, p := range peers {
1458 if me.ipBlockRange(p.IP) == nil {
1461 peers[i] = peers[len(peers)-1]
1462 peers = peers[:len(peers)-1]
1467 log.Printf("IP blocklist screened %d peers from being added", blocked)
1473 // Adds peers to the swarm for the torrent corresponding to infoHash.
1474 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1476 defer me.mu.Unlock()
1477 t := me.torrent(infoHash)
1479 return errors.New("no such torrent")
1481 me.addPeers(t, peers)
1485 func (cl *Client) torrentFileCachePath(ih InfoHash) string {
1486 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1489 func (cl *Client) saveTorrentFile(t *torrent) error {
1490 path := cl.torrentFileCachePath(t.InfoHash)
1491 os.MkdirAll(filepath.Dir(path), 0777)
1492 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1494 return fmt.Errorf("error opening file: %s", err)
1497 e := bencode.NewEncoder(f)
1498 err = e.Encode(t.MetaInfo())
1500 return fmt.Errorf("error marshalling metainfo: %s", err)
1502 mi, _ := cl.torrentCacheMetaInfo(t.InfoHash)
1503 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1504 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1509 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1510 err = t.setMetadata(md, cl.dataDir, bytes, &cl.mu)
1514 // If the client intends to upload, it needs to know what state pieces are
1517 // Queue all pieces for hashing. This is done sequentially to avoid
1518 // spamming goroutines.
1519 for _, p := range t.Pieces {
1520 p.QueuedForHash = true
1523 for i := range t.Pieces {
1524 cl.verifyPiece(t, pp.Integer(i))
1529 cl.downloadStrategy.TorrentStarted(t)
1530 if err := cl.saveTorrentFile(t); err != nil {
1531 log.Printf("error saving torrent file for %s: %s", t, err)
1533 close(t.gotMetainfo)
1537 // Prepare a Torrent without any attachment to a Client. That means we can
1538 // initialize fields all fields that don't require the Client without locking
1540 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1543 Peers: make(map[peersKey]Peer),
1545 closing: make(chan struct{}),
1546 ceasingNetworking: make(chan struct{}),
1548 gotMetainfo: make(chan struct{}),
1550 HalfOpen: make(map[string]struct{}),
1552 t.wantPeers.L = &t.stateMu
1553 t.GotMetainfo = t.gotMetainfo
1554 t.addTrackers(announceList)
1559 // For shuffling the tracker tiers.
1560 mathRand.Seed(time.Now().Unix())
1563 // The trackers within each tier must be shuffled before use.
1564 // http://stackoverflow.com/a/12267471/149482
1565 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1566 func shuffleTier(tier []tracker.Client) {
1567 for i := range tier {
1568 j := mathRand.Intn(i + 1)
1569 tier[i], tier[j] = tier[j], tier[i]
1573 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1574 for _, tier := range base {
1575 copy = append(copy, append([]tracker.Client{}, tier...))
1580 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1582 for _, url := range newURLs {
1583 for _, tr := range tier {
1584 if tr.URL() == url {
1588 tr, err := tracker.New(url)
1590 log.Printf("error creating tracker client for %q: %s", url, err)
1593 tier = append(tier, tr)
1598 func (t *torrent) addTrackers(announceList [][]string) {
1599 newTrackers := copyTrackers(t.Trackers)
1600 for tierIndex, tier := range announceList {
1601 if tierIndex < len(newTrackers) {
1602 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1604 newTrackers = append(newTrackers, mergeTier(nil, tier))
1606 shuffleTier(newTrackers[tierIndex])
1608 t.Trackers = newTrackers
1611 type Torrent struct {
1623 func (f *File) Length() int64 {
1627 func (f *File) PrioritizeRegion(off, len int64) {
1628 if off < 0 || off >= f.length {
1631 if off+len > f.length {
1632 len = f.length - off
1635 f.t.SetRegionPriority(off, len)
1638 // Returns handles to the files in the torrent. This requires the metainfo is
1640 func (t Torrent) Files() (ret []File) {
1642 for _, fi := range t.Info.UpvertedFiles() {
1643 ret = append(ret, File{
1645 strings.Join(fi.Path, "/"),
1654 func (t Torrent) SetRegionPriority(off, len int64) {
1656 defer t.cl.mu.Unlock()
1657 pieceSize := int64(t.UsualPieceSize())
1658 for i := off / pieceSize; i*pieceSize < off+len; i++ {
1659 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
1663 func (t Torrent) MetainfoFilepath() string {
1664 return filepath.Join(t.cl.ConfigDir(), "torrents", t.InfoHash.HexString()+".torrent")
1667 func (t Torrent) AddPeers(pp []Peer) error {
1668 return t.cl.AddPeers(t.torrent.InfoHash, pp)
1671 func (t Torrent) DownloadAll() {
1673 for i := 0; i < t.NumPieces(); i++ {
1674 // TODO: Leave higher priorities as they were?
1675 t.cl.prioritizePiece(t.torrent, i, piecePriorityNormal)
1677 // Nice to have the first and last pieces soon for various interactive
1679 t.cl.prioritizePiece(t.torrent, 0, piecePriorityReadahead)
1680 t.cl.prioritizePiece(t.torrent, t.NumPieces()-1, piecePriorityReadahead)
1684 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
1685 return me.cl.torrentReadAt(me.torrent, off, p)
1688 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1689 f, err := os.Open(cl.torrentFileCachePath(ih))
1691 if os.IsNotExist(err) {
1697 dec := bencode.NewDecoder(f)
1698 err = dec.Decode(&mi)
1702 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1703 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1709 func (cl *Client) AddMagnet(uri string) (T Torrent, err error) {
1710 m, err := ParseMagnetURI(uri)
1714 mi, err := cl.torrentCacheMetaInfo(m.InfoHash)
1716 log.Printf("error getting cached metainfo for %x: %s", m.InfoHash[:], err)
1717 } else if mi != nil {
1721 defer cl.mu.Unlock()
1722 T, err = cl.addOrMergeTorrent(m.InfoHash, [][]string{m.Trackers})
1726 if m.DisplayName != "" {
1727 T.DisplayName = m.DisplayName
1732 // Actively prunes unused connections. This is required to make space to dial
1733 // for replacements.
1734 func (cl *Client) connectionPruner(t *torrent) {
1736 time.Sleep(15 * time.Second)
1739 case <-t.ceasingNetworking:
1742 license := len(t.Conns) - (socketsPerTorrent+1)/2
1743 for _, c := range t.Conns {
1747 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
1750 if time.Now().Sub(c.completedHandshake) < time.Minute {
1760 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1762 defer me.mu.Unlock()
1763 t, ok := me.torrents[infoHash]
1765 err = fmt.Errorf("no such torrent")
1772 delete(me.torrents, infoHash)
1773 me.downloadStrategy.TorrentStopped(t)
1774 for _, dw := range me.dataWaits[t] {
1777 delete(me.dataWaits, t)
1781 func (me *Client) addOrMergeTorrent(ih InfoHash, announceList [][]string) (T Torrent, err error) {
1782 if _, ok := me.bannedTorrents[ih]; ok {
1783 err = errors.New("banned torrent")
1788 T.torrent, ok = me.torrents[ih]
1790 T.torrent.addTrackers(announceList)
1792 T.torrent, err = newTorrent(ih, announceList, me.halfOpenLimit)
1796 me.torrents[ih] = T.torrent
1797 if !me.disableTrackers {
1798 go me.announceTorrentTrackers(T.torrent)
1801 go me.announceTorrentDHT(T.torrent, true)
1803 go me.connectionPruner(T.torrent)
1808 // Adds the torrent to the client.
1809 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (t Torrent, err error) {
1811 CopyExact(&ih, metaInfo.Info.Hash)
1813 defer me.mu.Unlock()
1814 t, err = me.addOrMergeTorrent(ih, metaInfo.AnnounceList)
1818 if !t.torrent.haveInfo() {
1819 err = me.setMetaData(t.torrent, metaInfo.Info.Info, metaInfo.Info.Bytes)
1827 func (me *Client) AddTorrentFromFile(name string) (t Torrent, err error) {
1828 mi, err := metainfo.LoadFromFile(name)
1830 err = fmt.Errorf("error loading metainfo from file: %s", err)
1833 return me.AddTorrent(mi)
1836 // Returns true when peers are required, or false if the torrent is closing.
1837 func (cl *Client) waitWantPeers(t *torrent) bool {
1839 defer cl.mu.Unlock()
1841 defer t.stateMu.Unlock()
1844 case <-t.ceasingNetworking:
1848 if len(t.Peers) < torrentPeersLowWater {
1859 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
1860 for cl.waitWantPeers(t) {
1861 log.Printf("getting peers for %q from DHT", t)
1862 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
1864 log.Printf("error getting peers from dht: %s", err)
1867 allAddrs := make(map[string]struct{})
1871 case v, ok := <-ps.Values:
1875 peersFoundByDHT.Add(int64(len(v.Peers)))
1876 for _, p := range v.Peers {
1877 allAddrs[(&net.UDPAddr{
1880 }).String()] = struct{}{}
1882 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
1884 cl.addPeers(t, func() (ret []Peer) {
1885 for _, cp := range v.Peers {
1886 ret = append(ret, Peer{
1889 Source: peerSourceDHT,
1894 numPeers := len(t.Peers)
1896 if numPeers >= torrentPeersHighWater {
1899 case <-t.ceasingNetworking:
1905 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
1910 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
1911 if err := tr.Connect(); err != nil {
1912 return fmt.Errorf("error connecting: %s", err)
1914 resp, err := tr.Announce(req)
1916 return fmt.Errorf("error announcing: %s", err)
1919 for _, peer := range resp.Peers {
1920 peers = append(peers, Peer{
1925 err = cl.AddPeers(t.InfoHash, peers)
1927 log.Printf("error adding peers to torrent %s: %s", t, err)
1929 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1932 time.Sleep(time.Second * time.Duration(resp.Interval))
1936 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
1937 oks := make(chan bool)
1939 for _, tier := range trackers {
1940 for _, tr := range tier {
1942 go func(tr tracker.Client) {
1943 err := cl.announceTorrentSingleTracker(tr, req, t)
1948 for outstanding > 0 {
1958 // Announce torrent to its trackers.
1959 func (cl *Client) announceTorrentTrackers(t *torrent) {
1960 req := tracker.AnnounceRequest{
1961 Event: tracker.Started,
1963 Port: int16(cl.incomingPeerPort()),
1965 InfoHash: t.InfoHash,
1968 req.Left = t.BytesLeft()
1969 trackers := t.Trackers
1971 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
1972 req.Event = tracker.None
1975 for cl.waitWantPeers(t) {
1977 req.Left = t.BytesLeft()
1978 trackers = t.Trackers
1980 numTrackersTried := 0
1981 for _, tier := range trackers {
1982 for trIndex, tr := range tier {
1984 err := cl.announceTorrentSingleTracker(tr, &req, t)
1988 // Float the successful announce to the top of the tier. If
1989 // the trackers list has been changed, we'll be modifying an
1990 // old copy so it won't matter.
1992 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1995 req.Event = tracker.None
1996 continue newAnnounce
1999 if numTrackersTried != 0 {
2000 log.Printf("%s: all trackers failed", t)
2002 // TODO: Wait until trackers are added if there are none.
2003 time.Sleep(10 * time.Second)
2007 func (cl *Client) allTorrentsCompleted() bool {
2008 for _, t := range cl.torrents {
2012 if t.NumPiecesCompleted() != t.NumPieces() {
2019 // Returns true when all torrents are completely downloaded and false if the
2020 // client is stopped before that.
2021 func (me *Client) WaitAll() bool {
2023 defer me.mu.Unlock()
2024 for !me.allTorrentsCompleted() {
2033 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2037 me.downloadStrategy.FillRequests(t, c)
2038 if len(c.Requests) == 0 && !c.PeerChoked {
2039 c.SetInterested(false)
2043 // Handle a received chunk from a peer.
2044 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2045 chunksDownloadedCount.Add(1)
2047 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2049 // Request has been satisfied.
2050 me.connDeleteRequest(t, c, req)
2052 defer me.replenishConnRequests(t, c)
2054 // Do we actually want this chunk?
2055 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
2056 unusedDownloadedChunksCount.Add(1)
2057 c.UnwantedChunksReceived++
2061 c.UsefulChunksReceived++
2062 c.lastUsefulChunkReceived = time.Now()
2064 // Write the chunk out.
2065 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2067 return fmt.Errorf("error writing chunk: %s", err)
2070 // Record that we have the chunk.
2071 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
2072 me.dataReady(t, req)
2073 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
2074 for _, c := range t.Conns {
2075 c.pieceRequestOrder.DeletePiece(int(req.Index))
2077 me.queuePieceCheck(t, req.Index)
2080 // Unprioritize the chunk.
2081 me.downloadStrategy.TorrentGotChunk(t, req)
2083 // Cancel pending requests for this chunk.
2084 for _, c := range t.Conns {
2085 if me.connCancel(t, c, req) {
2086 me.replenishConnRequests(t, c)
2090 me.downloadStrategy.AssertNotRequested(t, req)
2095 func (cl *Client) dataReady(t *torrent, r request) {
2096 dws := cl.dataWaits[t]
2097 begin := t.requestOffset(r)
2098 end := begin + int64(r.Length)
2099 for i := 0; i < len(dws); {
2101 if begin <= dw.offset && dw.offset < end {
2103 dws[i] = dws[len(dws)-1]
2104 dws = dws[:len(dws)-1]
2109 cl.dataWaits[t] = dws
2112 // Returns a channel that is closed when new data has become available in the
2114 func (me *Client) DataWaiter(ih InfoHash, off int64) (ret <-chan struct{}) {
2116 defer me.mu.Unlock()
2117 ch := make(chan struct{})
2119 t := me.torrents[ih]
2124 if r, ok := t.offsetRequest(off); !ok || t.haveChunk(r) {
2128 me.dataWaits[t] = append(me.dataWaits[t], dataWait{
2135 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2136 p := t.Pieces[piece]
2137 if p.EverHashed && !correct {
2138 log.Printf("%s: piece %d failed hash", t, piece)
2139 failedPieceHashes.Add(1)
2143 p.Priority = piecePriorityNone
2144 p.PendingChunkSpecs = nil
2146 me.downloadStrategy.TorrentGotPiece(t, int(piece))
2147 me.dataReady(t, request{
2149 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
2152 if len(p.PendingChunkSpecs) == 0 {
2153 t.pendAllChunkSpecs(piece)
2155 if p.Priority != piecePriorityNone {
2159 for _, conn := range t.Conns {
2161 conn.Post(pp.Message{
2163 Index: pp.Integer(piece),
2165 // TODO: Cancel requests for this piece.
2166 for r := range conn.Requests {
2167 if r.Index == piece {
2171 conn.pieceRequestOrder.DeletePiece(int(piece))
2173 if t.wantPiece(int(piece)) && conn.PeerHasPiece(piece) {
2174 t.connPendPiece(conn, int(piece))
2175 me.replenishConnRequests(t, conn)
2178 if t.haveAllPieces() && me.noUpload {
2181 me.event.Broadcast()
2184 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2186 defer cl.mu.Unlock()
2187 p := t.Pieces[index]
2195 p.QueuedForHash = false
2197 sum := t.HashPiece(index)
2205 cl.pieceHashed(t, index, sum == p.Hash)
2208 func (me *Client) Torrents() (ret []Torrent) {
2210 for _, t := range me.torrents {
2211 ret = append(ret, Torrent{me, t})