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 filePkg "bitbucket.org/anacrolix/go.torrent/data/file"
40 "bitbucket.org/anacrolix/go.torrent/dht"
41 "bitbucket.org/anacrolix/go.torrent/internal/pieceordering"
42 "bitbucket.org/anacrolix/go.torrent/iplist"
43 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
44 "bitbucket.org/anacrolix/go.torrent/tracker"
45 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
46 . "bitbucket.org/anacrolix/go.torrent/util"
47 "bitbucket.org/anacrolix/sync"
48 "bitbucket.org/anacrolix/utp"
49 "github.com/anacrolix/libtorgo/bencode"
50 "github.com/anacrolix/libtorgo/metainfo"
54 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
55 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
56 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
57 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
58 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
59 unexpectedCancels = expvar.NewInt("unexpectedCancels")
60 postedCancels = expvar.NewInt("postedCancels")
61 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
62 failedPieceHashes = expvar.NewInt("failedPieceHashes")
63 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
64 successfulDials = expvar.NewInt("successfulDials")
65 acceptedConns = expvar.NewInt("acceptedConns")
66 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
70 // Justification for set bits follows.
72 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html
73 // DHT: http://www.bittorrent.org/beps/bep_0005.html
74 extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
76 socketsPerTorrent = 40
77 torrentPeersHighWater = 200
78 torrentPeersLowWater = 50
80 // Limit how long handshake can take. This is to reduce the lingering
81 // impact of a few bad apples. 4s loses 1% of successful handshakes that
82 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
83 handshakeTimeout = 4 * time.Second
85 pruneInterval = 10 * time.Second
88 // Currently doesn't really queue, but should in the future.
89 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
90 piece := t.Pieces[pieceIndex]
91 if piece.QueuedForHash {
94 piece.QueuedForHash = true
95 go cl.verifyPiece(t, pieceIndex)
98 // Queue a piece check if one isn't already queued, and the piece has never
99 // been checked before.
100 func (cl *Client) queueFirstHash(t *torrent, piece int) {
102 if p.EverHashed || p.Hashing || p.QueuedForHash || p.Complete() {
105 cl.queuePieceCheck(t, pp.Integer(piece))
113 listeners []net.Listener
116 downloadStrategy DownloadStrategy
120 ipBlockList *iplist.IPList
121 bannedTorrents map[InfoHash]struct{}
124 pruneTimer *time.Timer
126 torrentDataOpener TorrentDataOpener
134 torrents map[InfoHash]*torrent
137 func (me *Client) IPBlockList() *iplist.IPList {
140 return me.ipBlockList
143 func (me *Client) SetIPBlockList(list *iplist.IPList) {
146 me.ipBlockList = list
148 me.dHT.SetIPBlockList(list)
152 func (me *Client) PeerID() string {
153 return string(me.peerID[:])
156 func (me *Client) ListenAddr() (addr net.Addr) {
157 for _, l := range me.listeners {
158 if addr != nil && l.Addr().String() != addr.String() {
159 panic("listeners exist on different addresses")
166 type hashSorter struct {
170 func (me hashSorter) Len() int {
171 return len(me.Hashes)
174 func (me hashSorter) Less(a, b int) bool {
175 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
178 func (me hashSorter) Swap(a, b int) {
179 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
182 func (cl *Client) sortedTorrents() (ret []*torrent) {
184 for ih := range cl.torrents {
185 hs.Hashes = append(hs.Hashes, ih)
188 for _, ih := range hs.Hashes {
189 ret = append(ret, cl.torrent(ih))
194 func (cl *Client) WriteStatus(_w io.Writer) {
196 defer cl.mu.RUnlock()
197 w := bufio.NewWriter(_w)
199 if addr := cl.ListenAddr(); addr != nil {
200 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
202 fmt.Println("Not listening!")
204 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
205 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
207 dhtStats := cl.dHT.Stats()
208 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.NumNodes, dhtStats.NumGoodNodes)
209 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
210 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
211 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
212 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.NumOutstandingTransactions)
214 cl.downloadStrategy.WriteStatus(w)
216 for _, t := range cl.sortedTorrents() {
218 fmt.Fprint(w, "<unknown name>")
220 fmt.Fprint(w, t.Name())
224 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
226 w.WriteString("<missing metainfo>")
234 // Read torrent data at the given offset. Will block until it is available.
235 func (cl *Client) torrentReadAt(t *torrent, off int64, p []byte) (n int, err error) {
238 index := int(off / int64(t.usualPieceSize()))
239 // Reading outside the bounds of a file is an error.
244 if int(index) >= len(t.Pieces) {
248 piece := t.Pieces[index]
249 pieceOff := pp.Integer(off % int64(t.usualPieceSize()))
250 pieceLeft := int(t.PieceLength(pp.Integer(index)) - pieceOff)
255 cl.readRaisePiecePriorities(t, off, int64(len(p)))
256 if len(p) > pieceLeft {
262 for !piece.Complete() && !t.isClosed() {
265 return t.data.ReadAt(p, off)
268 func (cl *Client) readRaisePiecePriorities(t *torrent, off, _len int64) {
269 index := int(off / int64(t.usualPieceSize()))
270 cl.raisePiecePriority(t, index, piecePriorityNow)
272 if index >= t.numPieces() {
275 cl.raisePiecePriority(t, index, piecePriorityNext)
276 for i := 0; i < t.numConnsUnchoked()/2; i++ {
278 if index >= t.numPieces() {
281 cl.raisePiecePriority(t, index, piecePriorityReadahead)
285 func (cl *Client) configDir() string {
286 if cl._configDir == "" {
287 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
292 func (cl *Client) ConfigDir() string {
293 return cl.configDir()
296 func (t *torrent) connPendPiece(c *connection, piece int) {
297 c.pendPiece(piece, t.Pieces[piece].Priority)
300 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
301 if t.Pieces[piece].Priority < priority {
302 cl.prioritizePiece(t, piece, priority)
306 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
307 if t.havePiece(piece) {
310 cl.queueFirstHash(t, piece)
311 t.Pieces[piece].Priority = priority
312 if t.wantPiece(piece) {
313 for _, c := range t.Conns {
314 if c.PeerHasPiece(pp.Integer(piece)) {
315 t.connPendPiece(c, piece)
316 cl.replenishConnRequests(t, c)
322 func (cl *Client) setEnvBlocklist() (err error) {
323 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
324 defaultBlocklist := filename == ""
325 if defaultBlocklist {
326 filename = filepath.Join(cl.configDir(), "blocklist")
328 f, err := os.Open(filename)
330 if defaultBlocklist {
336 var ranges []iplist.Range
337 uniqStrs := make(map[string]string)
338 scanner := bufio.NewScanner(f)
340 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
342 err = fmt.Errorf("error reading torrent blocklist line: %s", lineErr)
348 if s, ok := uniqStrs[r.Description]; ok {
351 uniqStrs[r.Description] = r.Description
353 ranges = append(ranges, r)
357 err = fmt.Errorf("error reading torrent blocklist: %s", err)
360 cl.ipBlockList = iplist.New(ranges)
364 func (cl *Client) initBannedTorrents() error {
365 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
367 if os.IsNotExist(err) {
370 return fmt.Errorf("error opening banned infohashes file: %s", err)
373 scanner := bufio.NewScanner(f)
374 cl.bannedTorrents = make(map[InfoHash]struct{})
377 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
379 return fmt.Errorf("error reading infohash: %s", err)
385 return errors.New("bad infohash")
389 cl.bannedTorrents[ih] = struct{}{}
391 if err := scanner.Err(); err != nil {
392 return fmt.Errorf("error scanning file: %s", err)
397 func NewClient(cfg *Config) (cl *Client, err error) {
403 noUpload: cfg.NoUpload,
404 disableTrackers: cfg.DisableTrackers,
405 downloadStrategy: cfg.DownloadStrategy,
406 halfOpenLimit: socketsPerTorrent,
407 dataDir: cfg.DataDir,
408 disableUTP: cfg.DisableUTP,
409 disableTCP: cfg.DisableTCP,
410 _configDir: cfg.ConfigDir,
412 torrentDataOpener: func(md *metainfo.Info) (StatelessData, error) {
413 return filePkg.TorrentData(md, cfg.DataDir), nil
416 quit: make(chan struct{}),
417 torrents: make(map[InfoHash]*torrent),
420 if cfg.TorrentDataOpener != nil {
421 cl.torrentDataOpener = cfg.TorrentDataOpener
424 if !cfg.NoDefaultBlocklist {
425 err = cl.setEnvBlocklist()
431 if err = cl.initBannedTorrents(); err != nil {
432 err = fmt.Errorf("error initing banned torrents: %s", err)
436 if cfg.PeerID != "" {
437 CopyExact(&cl.peerID, cfg.PeerID)
439 o := copy(cl.peerID[:], BEP20)
440 _, err = rand.Read(cl.peerID[o:])
442 panic("error generating peer id")
446 if cl.downloadStrategy == nil {
447 cl.downloadStrategy = &DefaultDownloadStrategy{}
450 // Returns the laddr string to listen on for the next Listen call.
451 listenAddr := func() string {
452 if addr := cl.ListenAddr(); addr != nil {
455 if cfg.ListenAddr == "" {
458 return cfg.ListenAddr
462 l, err = net.Listen("tcp", listenAddr())
466 cl.listeners = append(cl.listeners, l)
467 go cl.acceptConnections(l, false)
470 cl.utpSock, err = utp.NewSocket(listenAddr())
474 cl.listeners = append(cl.listeners, cl.utpSock)
475 go cl.acceptConnections(cl.utpSock, true)
478 dhtCfg := cfg.DHTConfig
480 dhtCfg = &dht.ServerConfig{}
482 if dhtCfg.Addr == "" {
483 dhtCfg.Addr = listenAddr()
485 if dhtCfg.Conn == nil && cl.utpSock != nil {
486 dhtCfg.Conn = cl.utpSock.PacketConn()
488 cl.dHT, err = dht.NewServer(dhtCfg)
489 if cl.ipBlockList != nil {
490 cl.dHT.SetIPBlockList(cl.ipBlockList)
500 func (cl *Client) stopped() bool {
509 // Stops the client. All connections to peers are closed and all activity will
511 func (me *Client) Stop() {
515 for _, l := range me.listeners {
519 for _, t := range me.torrents {
524 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
526 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
527 if cl.ipBlockList == nil {
532 log.Printf("saw non-IPv4 address")
536 r = cl.ipBlockList.Lookup(ip)
540 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
542 // We accept all connections immediately, because we don't know what
543 // torrent they're for.
544 conn, err := l.Accept()
559 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
561 if blockRange != nil {
562 inboundConnsBlocked.Add(1)
563 log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
568 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
575 func (me *Client) torrent(ih InfoHash) *torrent {
576 for _, t := range me.torrents {
577 if t.InfoHash == ih {
584 type dialResult struct {
589 func doDial(dial func(addr string) (net.Conn, error), ch chan dialResult, utp bool, addr string) {
590 conn, err := dial(addr)
595 conn = nil // Pedantic
597 ch <- dialResult{conn, utp}
599 successfulDials.Add(1)
602 unsuccessfulDials.Add(1)
603 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
606 if netOpErr, ok := err.(*net.OpError); ok {
607 switch netOpErr.Err {
608 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
613 log.Printf("error dialing %s: %s", addr, err)
618 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
619 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
620 if ret < minDialTimeout {
626 // Start the process of connecting to the given peer for the given torrent if
628 func (me *Client) initiateConn(peer Peer, t *torrent) {
629 if peer.Id == me.peerID {
632 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
633 if t.addrActive(addr) {
634 duplicateConnsAvoided.Add(1)
637 if r := me.ipBlockRange(peer.IP); r != nil {
638 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
641 dialTimeout := reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
642 t.HalfOpen[addr] = struct{}{}
644 // Binding to the listen address and dialing via net.Dialer gives
645 // "address in use" error. It seems it's not possible to dial out from
646 // this address so that peers associate our local address with our
649 // Initiate connections via TCP and UTP simultaneously. Use the first
650 // one that succeeds.
658 resCh := make(chan dialResult, left)
660 go doDial(func(addr string) (net.Conn, error) {
661 return me.utpSock.DialTimeout(addr, dialTimeout)
662 }, resCh, true, addr)
665 go doDial(func(addr string) (net.Conn, error) {
666 // time.Sleep(time.Second) // Give uTP a bit of a head start.
667 return net.DialTimeout("tcp", addr, dialTimeout)
668 }, resCh, false, addr)
671 for ; left > 0 && res.Conn == nil; left-- {
674 // Whether or not the connection attempt succeeds, the half open
675 // counter should be decremented, and new connection attempts made.
679 if _, ok := t.HalfOpen[addr]; !ok {
680 panic("invariant broken")
682 delete(t.HalfOpen, addr)
690 for ; left > 0; left-- {
691 conn := (<-resCh).Conn
699 // log.Printf("connected to %s", conn.RemoteAddr())
700 err := me.runConnection(res.Conn, t, peer.Source, res.UTP)
707 // The port number for incoming peer connections. 0 if the client isn't
709 func (cl *Client) incomingPeerPort() int {
710 listenAddr := cl.ListenAddr()
711 if listenAddr == nil {
714 return addrPort(listenAddr)
717 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
718 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
719 func addrCompactIP(addr net.Addr) (string, error) {
720 host, _, err := net.SplitHostPort(addr.String())
724 ip := net.ParseIP(host)
725 if v4 := ip.To4(); v4 != nil {
729 return string(v4), nil
731 return string(ip.To16()), nil
734 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
746 type peerExtensionBytes [8]byte
749 type handshakeResult struct {
755 // ih is nil if we expect the peer to declare the InfoHash, such as when the
756 // peer initiated the connection. Returns ok if the handshake was successful,
757 // and err if there was an unexpected condition other than the peer simply
758 // abandoning the handshake.
759 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
760 // Bytes to be sent to the peer. Should never block the sender.
761 postCh := make(chan []byte, 4)
762 // A single error value sent when the writer completes.
763 writeDone := make(chan error, 1)
764 // Performs writes to the socket and ensures posts don't block.
765 go handshakeWriter(sock, postCh, writeDone)
768 close(postCh) // Done writing.
775 // Wait until writes complete before returning from handshake.
778 err = fmt.Errorf("error writing during handshake: %s", err)
782 post := func(bb []byte) {
786 panic("mustn't block while posting")
790 post([]byte(pp.Protocol))
791 post([]byte(extensionBytes))
792 if ih != nil { // We already know what we want.
797 _, err = io.ReadFull(sock, b[:68])
802 if string(b[:20]) != pp.Protocol {
805 CopyExact(&res.peerExtensionBytes, b[20:28])
806 CopyExact(&res.InfoHash, b[28:48])
807 CopyExact(&res.peerID, b[48:68])
809 if ih == nil { // We were waiting for the peer to tell us what they wanted.
810 post(res.InfoHash[:])
818 // Wraps a raw connection and provides the interface we want for using the
819 // connection in the message loop.
820 type peerConn struct {
824 func (pc peerConn) Read(b []byte) (n int, err error) {
825 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
826 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
828 err = fmt.Errorf("error setting read deadline: %s", err)
830 n, err = pc.Conn.Read(b)
831 // Convert common errors into io.EOF.
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 {
850 err = sock.SetDeadline(time.Now().Add(handshakeTimeout))
852 err = fmt.Errorf("couldn't set handshake deadline: %s", err)
858 hsRes, ok, err := handshake(sock, func() *InfoHash {
862 return &torrent.InfoHash
867 if me.handshaking == 0 {
868 panic("handshake count invariant is broken")
872 err = fmt.Errorf("error during handshake: %s", err)
878 if hsRes.peerID == me.peerID {
881 torrent = me.torrent(hsRes.InfoHash)
885 sock.SetWriteDeadline(time.Time{})
886 sock = peerConn{sock}
887 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
889 conn.Discovery = discovery
890 if !me.addConnection(torrent, conn) {
893 if conn.PeerExtensionBytes[5]&0x10 != 0 {
894 conn.Post(pp.Message{
896 ExtendedID: pp.HandshakeExtendedID,
897 ExtendedPayload: func() []byte {
898 d := map[string]interface{}{
903 "v": "go.torrent dev 20140825", // Just the date
904 // No upload queue is implemented yet.
907 // No need to look strange if it costs us nothing.
914 if torrent.metadataSizeKnown() {
915 d["metadata_size"] = torrent.metadataSize()
917 if p := me.incomingPeerPort(); p != 0 {
920 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
922 log.Printf("error calculating yourip field value in extension handshake: %s", err)
926 // log.Printf("sending %v", d)
927 b, err := bencode.Marshal(d)
935 if torrent.haveAnyPieces() {
936 conn.Post(pp.Message{
938 Bitfield: torrent.bitfield(),
941 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
942 conn.Post(pp.Message{
944 Port: uint16(AddrPort(me.dHT.LocalAddr())),
947 if torrent.haveInfo() {
948 torrent.initRequestOrdering(conn)
949 me.replenishConnRequests(torrent, conn)
951 err = me.connectionLoop(torrent, conn)
953 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
955 me.dropConnection(torrent, conn)
959 func (t *torrent) initRequestOrdering(c *connection) {
960 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
961 panic("double init of request ordering")
963 c.piecePriorities = mathRand.Perm(t.numPieces())
964 c.pieceRequestOrder = pieceordering.New()
965 for i := 0; i < t.numPieces(); i++ {
966 if !c.PeerHasPiece(pp.Integer(i)) {
972 t.connPendPiece(c, i)
976 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
978 if c.PeerPieces == nil {
979 c.PeerPieces = make([]bool, t.numPieces())
982 for piece >= len(c.PeerPieces) {
983 c.PeerPieces = append(c.PeerPieces, false)
986 c.PeerPieces[piece] = true
987 if t.wantPiece(piece) {
988 t.connPendPiece(c, piece)
989 me.replenishConnRequests(t, c)
993 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
994 me.replenishConnRequests(torrent, conn)
997 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1000 postedCancels.Add(1)
1001 cl.downloadStrategy.DeleteRequest(t, r)
1006 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1007 if !cn.RequestPending(r) {
1010 cl.downloadStrategy.DeleteRequest(t, r)
1011 delete(cn.Requests, r)
1014 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1019 for index := 0; index < t.metadataPieceCount(); index++ {
1020 if !t.haveMetadataPiece(index) {
1021 pending = append(pending, index)
1024 for _, i := range mathRand.Perm(len(pending)) {
1027 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
1028 ExtendedPayload: func() []byte {
1029 b, err := bencode.Marshal(map[string]int{
1031 "piece": pending[i],
1042 func (cl *Client) completedMetadata(t *torrent) {
1046 CopyExact(&ih, h.Sum(nil))
1047 if ih != t.InfoHash {
1048 log.Print("bad metadata")
1049 t.invalidateMetadata()
1052 var info metainfo.Info
1053 err := bencode.Unmarshal(t.MetaData, &info)
1055 log.Printf("error unmarshalling metadata: %s", err)
1056 t.invalidateMetadata()
1059 // TODO(anacrolix): If this fails, I think something harsher should be
1061 err = cl.setMetaData(t, info, t.MetaData)
1063 log.Printf("error setting metadata: %s", err)
1064 t.invalidateMetadata()
1067 log.Printf("%s: got metadata from peers", t)
1070 // Process incoming ut_metadata message.
1071 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1072 var d map[string]int
1073 err = bencode.Unmarshal(payload, &d)
1075 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1078 msgType, ok := d["msg_type"]
1080 err = errors.New("missing msg_type field")
1085 case pp.DataMetadataExtensionMsgType:
1089 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1090 if begin < 0 || begin >= len(payload) {
1091 log.Printf("got bad metadata piece")
1094 t.SaveMetadataPiece(piece, payload[begin:])
1095 c.UsefulChunksReceived++
1096 c.lastUsefulChunkReceived = time.Now()
1097 if !t.haveAllMetadataPieces() {
1100 cl.completedMetadata(t)
1101 case pp.RequestMetadataExtensionMsgType:
1102 if !t.haveMetadataPiece(piece) {
1103 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1106 start := (1 << 14) * piece
1107 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1108 case pp.RejectMetadataExtensionMsgType:
1110 err = errors.New("unknown msg_type value")
1115 type peerExchangeMessage struct {
1116 Added CompactPeers `bencode:"added"`
1117 AddedFlags []byte `bencode:"added.f"`
1118 Dropped []tracker.Peer `bencode:"dropped"`
1121 // Extracts the port as an integer from an address string.
1122 func addrPort(addr net.Addr) int {
1123 return AddrPort(addr)
1126 // Processes incoming bittorrent messages. The client lock is held upon entry
1128 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1129 decoder := pp.Decoder{
1130 R: bufio.NewReader(c.Socket),
1131 MaxLength: 256 * 1024,
1136 err := decoder.Decode(&msg)
1138 c.lastMessageReceived = time.Now()
1145 if me.stopped() || err == io.EOF {
1156 for r := range c.Requests {
1157 me.connDeleteRequest(t, c, r)
1159 // We can then reset our interest.
1160 me.replenishConnRequests(t, c)
1162 c.PeerChoked = false
1163 me.peerUnchoked(t, c)
1165 c.PeerInterested = true
1166 // TODO: This should be done from a dedicated unchoking routine.
1171 case pp.NotInterested:
1172 c.PeerInterested = false
1175 me.peerGotPiece(t, c, int(msg.Index))
1180 if c.PeerRequests == nil {
1181 c.PeerRequests = make(map[request]struct{}, maxRequests)
1183 request := newRequest(msg.Index, msg.Begin, msg.Length)
1184 // TODO: Requests should be satisfied from a dedicated upload
1186 // c.PeerRequests[request] = struct{}{}
1187 p := make([]byte, msg.Length)
1188 n, err := t.data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1190 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1192 if n != int(msg.Length) {
1193 return fmt.Errorf("bad request: %v", msg)
1201 uploadChunksPosted.Add(1)
1203 req := newRequest(msg.Index, msg.Begin, msg.Length)
1204 if !c.PeerCancel(req) {
1205 unexpectedCancels.Add(1)
1208 if c.PeerPieces != nil {
1209 err = errors.New("received unexpected bitfield")
1213 if len(msg.Bitfield) < t.numPieces() {
1214 err = errors.New("received invalid bitfield")
1217 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1219 c.PeerPieces = msg.Bitfield
1220 for index, has := range c.PeerPieces {
1222 me.peerGotPiece(t, c, index)
1226 err = me.downloadedChunk(t, c, &msg)
1228 switch msg.ExtendedID {
1229 case pp.HandshakeExtendedID:
1230 // TODO: Create a bencode struct for this.
1231 var d map[string]interface{}
1232 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1234 err = fmt.Errorf("error decoding extended message payload: %s", err)
1237 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1238 if reqq, ok := d["reqq"]; ok {
1239 if i, ok := reqq.(int64); ok {
1240 c.PeerMaxRequests = int(i)
1243 if v, ok := d["v"]; ok {
1244 c.PeerClientName = v.(string)
1248 err = errors.New("handshake missing m item")
1251 mTyped, ok := m.(map[string]interface{})
1253 err = errors.New("handshake m value is not dict")
1256 if c.PeerExtensionIDs == nil {
1257 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1259 for name, v := range mTyped {
1262 log.Printf("bad handshake m item extension ID type: %T", v)
1266 delete(c.PeerExtensionIDs, name)
1268 c.PeerExtensionIDs[name] = id
1271 metadata_sizeUntyped, ok := d["metadata_size"]
1273 metadata_size, ok := metadata_sizeUntyped.(int64)
1275 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1277 t.SetMetadataSize(metadata_size)
1280 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1281 me.requestPendingMetadata(t, c)
1284 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1286 err = fmt.Errorf("error handling metadata extension message: %s", err)
1289 var pexMsg peerExchangeMessage
1290 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1292 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1296 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
1297 for _, cp := range pexMsg.Added {
1299 IP: make([]byte, 4),
1301 Source: peerSourcePEX,
1303 if n := copy(p.IP, cp.IP[:]); n != 4 {
1306 ret = append(ret, p)
1311 log.Printf("error adding PEX peers: %s", err)
1314 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1317 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1320 // That client uses its own extension IDs for outgoing message
1321 // types, which is incorrect.
1322 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1323 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1326 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1332 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1337 pingAddr.Port = int(msg.Port)
1339 _, err = me.dHT.Ping(pingAddr)
1341 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1349 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1350 for r := range conn.Requests {
1351 me.connDeleteRequest(torrent, conn, r)
1354 for i0, c := range torrent.Conns {
1358 i1 := len(torrent.Conns) - 1
1360 torrent.Conns[i0] = torrent.Conns[i1]
1362 torrent.Conns = torrent.Conns[:i1]
1363 me.openNewConns(torrent)
1366 panic("connection not found")
1369 func (me *Client) addConnection(t *torrent, c *connection) bool {
1374 case <-t.ceasingNetworking:
1378 if !me.wantConns(t) {
1381 for _, c0 := range t.Conns {
1382 if c.PeerID == c0.PeerID {
1383 // Already connected to a client with that ID.
1387 t.Conns = append(t.Conns, c)
1388 // TODO: This should probably be done by a routine that kills off bad
1389 // connections, and extra connections killed here instead.
1390 if len(t.Conns) > socketsPerTorrent {
1391 wcs := t.worstConnsHeap()
1392 heap.Pop(wcs).(*connection).Close()
1397 func (t *torrent) needData() bool {
1401 for i := range t.Pieces {
1409 // TODO: I'm sure there's something here to do with seeding.
1410 func (t *torrent) badConn(c *connection) bool {
1411 if time.Now().Sub(c.completedHandshake) < 30*time.Second {
1415 return !c.supportsExtension("ut_metadata")
1417 return !t.connHasWantedPieces(c)
1420 func (t *torrent) numGoodConns() (num int) {
1421 for _, c := range t.Conns {
1429 func (me *Client) wantConns(t *torrent) bool {
1430 if !t.needData() && me.noUpload {
1433 if t.numGoodConns() >= socketsPerTorrent {
1439 func (me *Client) openNewConns(t *torrent) {
1441 case <-t.ceasingNetworking:
1445 for len(t.Peers) != 0 {
1446 if !me.wantConns(t) {
1449 if len(t.HalfOpen) >= me.halfOpenLimit {
1456 for k, p = range t.Peers {
1460 me.initiateConn(p, t)
1462 t.wantPeers.Broadcast()
1465 func (me *Client) addPeers(t *torrent, peers []Peer) {
1467 for i, p := range peers {
1468 if me.ipBlockRange(p.IP) == nil {
1471 peers[i] = peers[len(peers)-1]
1472 peers = peers[:len(peers)-1]
1477 log.Printf("IP blocklist screened %d peers from being added", blocked)
1483 // Adds peers to the swarm for the torrent corresponding to infoHash.
1484 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1486 defer me.mu.Unlock()
1487 t := me.torrent(infoHash)
1489 return errors.New("no such torrent")
1491 me.addPeers(t, peers)
1495 func (cl *Client) torrentFileCachePath(ih InfoHash) string {
1496 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1499 func (cl *Client) saveTorrentFile(t *torrent) error {
1500 path := cl.torrentFileCachePath(t.InfoHash)
1501 os.MkdirAll(filepath.Dir(path), 0777)
1502 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1504 return fmt.Errorf("error opening file: %s", err)
1507 e := bencode.NewEncoder(f)
1508 err = e.Encode(t.MetaInfo())
1510 return fmt.Errorf("error marshalling metainfo: %s", err)
1512 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1514 // For example, a script kiddy makes us load too many files, and we're
1515 // able to save the torrent, but not load it again to check it.
1518 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1519 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1524 func (cl *Client) startTorrent(t *torrent) {
1525 if t.Info == nil || t.data == nil {
1528 // If the client intends to upload, it needs to know what state pieces are
1531 // Queue all pieces for hashing. This is done sequentially to avoid
1532 // spamming goroutines.
1533 for _, p := range t.Pieces {
1534 p.QueuedForHash = true
1537 for i := range t.Pieces {
1538 cl.verifyPiece(t, pp.Integer(i))
1542 cl.downloadStrategy.TorrentStarted(t)
1545 // Storage cannot be changed once it's set.
1546 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1547 err = t.setStorage(td)
1548 cl.event.Broadcast()
1556 type TorrentDataOpener func(*metainfo.Info) (StatelessData, error)
1558 type statelessDataWrapper struct {
1562 func (statelessDataWrapper) PieceComplete(int) bool { return false }
1563 func (statelessDataWrapper) PieceCompleted(int) error { return nil }
1565 var _ Data = statelessDataWrapper{}
1567 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1568 err = t.setMetadata(md, bytes, &cl.mu)
1572 if !cl.config.DisableMetainfoCache {
1573 if err := cl.saveTorrentFile(t); err != nil {
1574 log.Printf("error saving torrent file for %s: %s", t, err)
1577 if strings.Contains(strings.ToLower(md.Name), "porn") {
1578 cl.dropTorrent(t.InfoHash)
1579 err = errors.New("no porn plx")
1582 close(t.gotMetainfo)
1583 stateless, err := cl.torrentDataOpener(&md)
1587 td, ok := stateless.(Data)
1589 td = statelessDataWrapper{stateless}
1591 err = cl.setStorage(t, td)
1595 // Prepare a Torrent without any attachment to a Client. That means we can
1596 // initialize fields all fields that don't require the Client without locking
1598 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1601 Peers: make(map[peersKey]Peer),
1603 closing: make(chan struct{}),
1604 ceasingNetworking: make(chan struct{}),
1606 gotMetainfo: make(chan struct{}),
1608 HalfOpen: make(map[string]struct{}),
1610 t.wantPeers.L = &t.stateMu
1611 t.GotMetainfo = t.gotMetainfo
1612 t.addTrackers(announceList)
1617 // For shuffling the tracker tiers.
1618 mathRand.Seed(time.Now().Unix())
1621 // The trackers within each tier must be shuffled before use.
1622 // http://stackoverflow.com/a/12267471/149482
1623 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1624 func shuffleTier(tier []tracker.Client) {
1625 for i := range tier {
1626 j := mathRand.Intn(i + 1)
1627 tier[i], tier[j] = tier[j], tier[i]
1631 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1632 for _, tier := range base {
1633 copy = append(copy, append([]tracker.Client{}, tier...))
1638 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1640 for _, url := range newURLs {
1641 for _, tr := range tier {
1642 if tr.URL() == url {
1646 tr, err := tracker.New(url)
1648 log.Printf("error creating tracker client for %q: %s", url, err)
1651 tier = append(tier, tr)
1656 func (t *torrent) addTrackers(announceList [][]string) {
1657 newTrackers := copyTrackers(t.Trackers)
1658 for tierIndex, tier := range announceList {
1659 if tierIndex < len(newTrackers) {
1660 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1662 newTrackers = append(newTrackers, mergeTier(nil, tier))
1664 shuffleTier(newTrackers[tierIndex])
1666 t.Trackers = newTrackers
1669 type Torrent struct {
1674 func (t Torrent) NumPieces() int {
1675 return t.numPieces()
1678 func (t Torrent) Drop() {
1679 t.cl.dropTorrent(t.InfoHash)
1687 fi metainfo.FileInfo
1690 func (f File) FileInfo() metainfo.FileInfo {
1694 func (f File) Path() string {
1698 func (f File) ReadAt(p []byte, off int64) (n int, err error) {
1699 maxLen := f.length - off
1700 if int64(len(p)) > maxLen {
1703 return f.t.ReadAt(p, off+f.offset)
1706 func (f *File) Length() int64 {
1710 type FilePieceState struct {
1715 func (f *File) Progress() (ret []FilePieceState) {
1716 pieceSize := int64(f.t.usualPieceSize())
1717 off := f.offset % pieceSize
1718 remaining := f.length
1719 for i := int(f.offset / pieceSize); ; i++ {
1723 len1 := pieceSize - off
1724 if len1 > remaining {
1727 ret = append(ret, FilePieceState{len1, f.t.pieceStatusChar(i)})
1734 func (f *File) PrioritizeRegion(off, len int64) {
1735 if off < 0 || off >= f.length {
1738 if off+len > f.length {
1739 len = f.length - off
1742 f.t.SetRegionPriority(off, len)
1745 // Returns handles to the files in the torrent. This requires the metainfo is
1747 func (t Torrent) Files() (ret []File) {
1749 case <-t.GotMetainfo:
1754 for _, fi := range t.Info.UpvertedFiles() {
1755 ret = append(ret, File{
1757 strings.Join(append([]string{t.Info.Name}, fi.Path...), "/"),
1767 func (t Torrent) SetRegionPriority(off, len int64) {
1769 defer t.cl.mu.Unlock()
1770 pieceSize := int64(t.usualPieceSize())
1771 for i := off / pieceSize; i*pieceSize < off+len; i++ {
1772 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
1776 func (t Torrent) MetainfoFilepath() string {
1777 return filepath.Join(t.cl.ConfigDir(), "torrents", t.InfoHash.HexString()+".torrent")
1780 func (t Torrent) AddPeers(pp []Peer) error {
1781 return t.cl.AddPeers(t.torrent.InfoHash, pp)
1784 func (t Torrent) DownloadAll() {
1786 for i := 0; i < t.numPieces(); i++ {
1787 // TODO: Leave higher priorities as they were?
1788 t.cl.prioritizePiece(t.torrent, i, piecePriorityNormal)
1790 // Nice to have the first and last pieces soon for various interactive
1792 t.cl.prioritizePiece(t.torrent, 0, piecePriorityReadahead)
1793 t.cl.prioritizePiece(t.torrent, t.numPieces()-1, piecePriorityReadahead)
1797 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
1798 return me.cl.torrentReadAt(me.torrent, off, p)
1801 // Returns nil metainfo if it isn't in the cache.
1802 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1803 if cl.config.DisableMetainfoCache {
1806 f, err := os.Open(cl.torrentFileCachePath(ih))
1808 if os.IsNotExist(err) {
1814 dec := bencode.NewDecoder(f)
1815 err = dec.Decode(&mi)
1819 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1820 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1826 func (cl *Client) AddMagnet(uri string) (T Torrent, err error) {
1827 m, err := ParseMagnetURI(uri)
1831 mi, err := cl.torrentCacheMetaInfo(m.InfoHash)
1833 log.Printf("error getting cached metainfo for %x: %s", m.InfoHash[:], err)
1834 } else if mi != nil {
1835 _, err = cl.AddTorrent(mi)
1841 defer cl.mu.Unlock()
1842 T, err = cl.addOrMergeTorrent(m.InfoHash, [][]string{m.Trackers})
1846 if m.DisplayName != "" {
1847 T.DisplayName = m.DisplayName
1852 // Prunes unused connections. This is required to make space to dial for
1854 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
1856 case <-t.ceasingNetworking:
1863 license := len(t.Conns) - (socketsPerTorrent+1)/2
1864 for _, c := range t.Conns {
1868 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
1871 if time.Now().Sub(c.completedHandshake) < time.Minute {
1878 t.pruneTimer.Reset(pruneInterval)
1881 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
1882 t, ok := me.torrents[infoHash]
1884 err = fmt.Errorf("no such torrent")
1891 delete(me.torrents, infoHash)
1892 me.downloadStrategy.TorrentStopped(t)
1896 func (me *Client) addOrMergeTorrent(ih InfoHash, announceList [][]string) (T Torrent, err error) {
1897 if _, ok := me.bannedTorrents[ih]; ok {
1898 err = errors.New("banned torrent")
1903 T.torrent, ok = me.torrents[ih]
1905 T.torrent.addTrackers(announceList)
1907 T.torrent, err = newTorrent(ih, announceList, me.halfOpenLimit)
1911 me.torrents[ih] = T.torrent
1912 if !me.disableTrackers {
1913 go me.announceTorrentTrackers(T.torrent)
1916 go me.announceTorrentDHT(T.torrent, true)
1918 T.torrent.pruneTimer = time.AfterFunc(0, func() {
1919 me.pruneConnectionsUnlocked(T.torrent)
1925 // Adds a torrent to the client.
1926 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (t Torrent, err error) {
1928 CopyExact(&ih, metaInfo.Info.Hash)
1930 defer me.mu.Unlock()
1931 t, err = me.addOrMergeTorrent(ih, metaInfo.AnnounceList)
1935 if !t.torrent.haveInfo() {
1936 err = me.setMetaData(t.torrent, metaInfo.Info.Info, metaInfo.Info.Bytes)
1944 func (me *Client) AddTorrentFromFile(name string) (t Torrent, err error) {
1945 mi, err := metainfo.LoadFromFile(name)
1947 err = fmt.Errorf("error loading metainfo from file: %s", err)
1950 return me.AddTorrent(mi)
1953 // Returns true when peers are required, or false if the torrent is closing.
1954 func (cl *Client) waitWantPeers(t *torrent) bool {
1956 defer cl.mu.Unlock()
1958 defer t.stateMu.Unlock()
1961 case <-t.ceasingNetworking:
1965 if len(t.Peers) < torrentPeersLowWater && t.needData() {
1976 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
1977 for cl.waitWantPeers(t) {
1978 log.Printf("getting peers for %q from DHT", t)
1979 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
1981 log.Printf("error getting peers from dht: %s", err)
1984 allAddrs := make(map[string]struct{})
1988 case v, ok := <-ps.Values:
1992 peersFoundByDHT.Add(int64(len(v.Peers)))
1993 for _, p := range v.Peers {
1994 allAddrs[(&net.UDPAddr{
1997 }).String()] = struct{}{}
1999 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2001 cl.addPeers(t, func() (ret []Peer) {
2002 for _, cp := range v.Peers {
2003 ret = append(ret, Peer{
2006 Source: peerSourceDHT,
2011 numPeers := len(t.Peers)
2013 if numPeers >= torrentPeersHighWater {
2016 case <-t.ceasingNetworking:
2022 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2027 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2028 if err := tr.Connect(); err != nil {
2029 return fmt.Errorf("error connecting: %s", err)
2031 resp, err := tr.Announce(req)
2033 return fmt.Errorf("error announcing: %s", err)
2036 for _, peer := range resp.Peers {
2037 peers = append(peers, Peer{
2042 err = cl.AddPeers(t.InfoHash, peers)
2044 log.Printf("error adding peers to torrent %s: %s", t, err)
2046 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2049 time.Sleep(time.Second * time.Duration(resp.Interval))
2053 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2054 oks := make(chan bool)
2056 for _, tier := range trackers {
2057 for _, tr := range tier {
2059 go func(tr tracker.Client) {
2060 err := cl.announceTorrentSingleTracker(tr, req, t)
2065 for outstanding > 0 {
2075 // Announce torrent to its trackers.
2076 func (cl *Client) announceTorrentTrackers(t *torrent) {
2077 req := tracker.AnnounceRequest{
2078 Event: tracker.Started,
2080 Port: int16(cl.incomingPeerPort()),
2082 InfoHash: t.InfoHash,
2084 if !cl.waitWantPeers(t) {
2088 req.Left = t.bytesLeft()
2089 trackers := t.Trackers
2091 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2092 req.Event = tracker.None
2095 for cl.waitWantPeers(t) {
2097 req.Left = t.bytesLeft()
2098 trackers = t.Trackers
2100 numTrackersTried := 0
2101 for _, tier := range trackers {
2102 for trIndex, tr := range tier {
2104 err := cl.announceTorrentSingleTracker(tr, &req, t)
2108 // Float the successful announce to the top of the tier. If
2109 // the trackers list has been changed, we'll be modifying an
2110 // old copy so it won't matter.
2112 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2115 req.Event = tracker.None
2116 continue newAnnounce
2119 if numTrackersTried != 0 {
2120 log.Printf("%s: all trackers failed", t)
2122 // TODO: Wait until trackers are added if there are none.
2123 time.Sleep(10 * time.Second)
2127 func (cl *Client) allTorrentsCompleted() bool {
2128 for _, t := range cl.torrents {
2132 if t.numPiecesCompleted() != t.numPieces() {
2139 // Returns true when all torrents are completely downloaded and false if the
2140 // client is stopped before that.
2141 func (me *Client) WaitAll() bool {
2143 defer me.mu.Unlock()
2144 for !me.allTorrentsCompleted() {
2153 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2157 me.downloadStrategy.FillRequests(t, c)
2158 if len(c.Requests) == 0 && !c.PeerChoked {
2159 c.SetInterested(false)
2163 // Handle a received chunk from a peer.
2164 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2165 chunksDownloadedCount.Add(1)
2167 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2169 // Request has been satisfied.
2170 me.connDeleteRequest(t, c, req)
2172 defer me.replenishConnRequests(t, c)
2174 // Do we actually want this chunk?
2175 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
2176 unusedDownloadedChunksCount.Add(1)
2177 c.UnwantedChunksReceived++
2181 c.UsefulChunksReceived++
2182 c.lastUsefulChunkReceived = time.Now()
2184 // Write the chunk out.
2185 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2187 return fmt.Errorf("error writing chunk: %s", err)
2190 // Record that we have the chunk.
2191 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
2192 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
2193 for _, c := range t.Conns {
2194 c.pieceRequestOrder.DeletePiece(int(req.Index))
2196 me.queuePieceCheck(t, req.Index)
2199 // Unprioritize the chunk.
2200 me.downloadStrategy.TorrentGotChunk(t, req)
2202 // Cancel pending requests for this chunk.
2203 for _, c := range t.Conns {
2204 if me.connCancel(t, c, req) {
2205 me.replenishConnRequests(t, c)
2209 me.downloadStrategy.AssertNotRequested(t, req)
2214 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2215 p := t.Pieces[piece]
2216 if p.EverHashed && !correct {
2217 log.Printf("%s: piece %d failed hash", t, piece)
2218 failedPieceHashes.Add(1)
2222 err := t.data.PieceCompleted(int(piece))
2224 log.Printf("error completing piece: %s", err)
2229 p.Priority = piecePriorityNone
2230 p.PendingChunkSpecs = nil
2233 me.downloadStrategy.TorrentGotPiece(t, int(piece))
2235 if len(p.PendingChunkSpecs) == 0 {
2236 t.pendAllChunkSpecs(piece)
2238 if p.Priority != piecePriorityNone {
2242 for _, conn := range t.Conns {
2244 conn.Post(pp.Message{
2246 Index: pp.Integer(piece),
2248 // TODO: Cancel requests for this piece.
2249 for r := range conn.Requests {
2250 if r.Index == piece {
2254 conn.pieceRequestOrder.DeletePiece(int(piece))
2256 if t.wantPiece(int(piece)) && conn.PeerHasPiece(piece) {
2257 t.connPendPiece(conn, int(piece))
2258 me.replenishConnRequests(t, conn)
2261 if t.haveAllPieces() && me.noUpload {
2264 me.event.Broadcast()
2267 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2269 defer cl.mu.Unlock()
2270 p := t.Pieces[index]
2271 for p.Hashing || t.data == nil {
2274 p.QueuedForHash = false
2275 if t.isClosed() || p.complete {
2280 sum := t.hashPiece(index)
2288 cl.pieceHashed(t, index, sum == p.Hash)
2291 func (cl *Client) Torrent(ih InfoHash) (t Torrent, ok bool) {
2293 defer cl.mu.Unlock()
2294 t.torrent, ok = cl.torrents[ih]
2299 func (me *Client) Torrents() (ret []Torrent) {
2301 for _, t := range me.torrents {
2302 ret = append(ret, Torrent{me, t})