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/data"
40 filePkg "bitbucket.org/anacrolix/go.torrent/data/file"
41 "bitbucket.org/anacrolix/go.torrent/dht"
42 "bitbucket.org/anacrolix/go.torrent/internal/pieceordering"
43 "bitbucket.org/anacrolix/go.torrent/iplist"
44 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
45 "bitbucket.org/anacrolix/go.torrent/tracker"
46 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
47 . "bitbucket.org/anacrolix/go.torrent/util"
48 "bitbucket.org/anacrolix/sync"
49 "bitbucket.org/anacrolix/utp"
50 "github.com/anacrolix/libtorgo/bencode"
51 "github.com/anacrolix/libtorgo/metainfo"
55 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
56 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
57 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
58 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
59 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
60 unexpectedCancels = expvar.NewInt("unexpectedCancels")
61 postedCancels = expvar.NewInt("postedCancels")
62 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
63 failedPieceHashes = expvar.NewInt("failedPieceHashes")
64 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
65 successfulDials = expvar.NewInt("successfulDials")
66 acceptedConns = expvar.NewInt("acceptedConns")
67 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
71 // Justification for set bits follows.
73 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html
74 // DHT: http://www.bittorrent.org/beps/bep_0005.html
75 extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
77 socketsPerTorrent = 40
78 torrentPeersHighWater = 200
79 torrentPeersLowWater = 50
81 // Limit how long handshake can take. This is to reduce the lingering
82 // impact of a few bad apples. 4s loses 1% of successful handshakes that
83 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
84 handshakeTimeout = 4 * time.Second
86 pruneInterval = 10 * time.Second
89 // Currently doesn't really queue, but should in the future.
90 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
91 piece := t.Pieces[pieceIndex]
92 if piece.QueuedForHash {
95 piece.QueuedForHash = true
96 go cl.verifyPiece(t, pieceIndex)
99 // Queue a piece check if one isn't already queued, and the piece has never
100 // been checked before.
101 func (cl *Client) queueFirstHash(t *torrent, piece int) {
103 if p.EverHashed || p.Hashing || p.QueuedForHash || p.Complete() {
106 cl.queuePieceCheck(t, pp.Integer(piece))
114 listeners []net.Listener
117 downloadStrategy downloadStrategy
121 ipBlockList *iplist.IPList
122 bannedTorrents map[InfoHash]struct{}
125 pruneTimer *time.Timer
127 torrentDataOpener TorrentDataOpener
135 torrents map[InfoHash]*torrent
138 func (me *Client) IPBlockList() *iplist.IPList {
141 return me.ipBlockList
144 func (me *Client) SetIPBlockList(list *iplist.IPList) {
147 me.ipBlockList = list
149 me.dHT.SetIPBlockList(list)
153 func (me *Client) PeerID() string {
154 return string(me.peerID[:])
157 func (me *Client) ListenAddr() (addr net.Addr) {
158 for _, l := range me.listeners {
159 if addr != nil && l.Addr().String() != addr.String() {
160 panic("listeners exist on different addresses")
167 type hashSorter struct {
171 func (me hashSorter) Len() int {
172 return len(me.Hashes)
175 func (me hashSorter) Less(a, b int) bool {
176 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
179 func (me hashSorter) Swap(a, b int) {
180 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
183 func (cl *Client) sortedTorrents() (ret []*torrent) {
185 for ih := range cl.torrents {
186 hs.Hashes = append(hs.Hashes, ih)
189 for _, ih := range hs.Hashes {
190 ret = append(ret, cl.torrent(ih))
195 // Writes out a human readable status of the client, such as for writing to a
197 func (cl *Client) WriteStatus(_w io.Writer) {
199 defer cl.mu.RUnlock()
200 w := bufio.NewWriter(_w)
202 if addr := cl.ListenAddr(); addr != nil {
203 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
205 fmt.Fprintln(w, "Not listening!")
207 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
208 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
210 dhtStats := cl.dHT.Stats()
211 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.NumNodes, dhtStats.NumGoodNodes)
212 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
213 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
214 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
215 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.NumOutstandingTransactions)
218 for _, t := range cl.sortedTorrents() {
220 fmt.Fprint(w, "<unknown name>")
222 fmt.Fprint(w, t.Name())
226 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
228 w.WriteString("<missing metainfo>")
236 // Read torrent data at the given offset. Will block until it is available.
237 func (cl *Client) torrentReadAt(t *torrent, off int64, p []byte) (n int, err error) {
240 index := int(off / int64(t.usualPieceSize()))
241 // Reading outside the bounds of a file is an error.
246 if int(index) >= len(t.Pieces) {
250 pieceOff := pp.Integer(off % int64(t.usualPieceSize()))
251 pieceLeft := int(t.PieceLength(index) - pieceOff)
256 if len(p) > pieceLeft {
262 cl.prepareRead(t, off)
263 return dataReadAt(t.data, p, off)
266 // Sets priorities to download from the given offset. Returns when the piece
267 // at the given offset can be read. Returns the number of bytes that
268 // immediately available from the offset.
269 func (cl *Client) prepareRead(t *torrent, off int64) (n int64) {
270 index := int(off / int64(t.usualPieceSize()))
271 // Reading outside the bounds of a file is an error.
272 if index < 0 || index >= t.numPieces() {
275 piece := t.Pieces[index]
276 cl.readRaisePiecePriorities(t, off)
277 for !piece.Complete() && !t.isClosed() {
280 return t.Info.Piece(index).Length() - off%t.Info.PieceLength
283 func (T Torrent) prepareRead(off int64) (avail int64) {
285 defer T.cl.mu.Unlock()
286 return T.cl.prepareRead(T.torrent, off)
289 // Data implements a streaming interface that's more efficient than ReadAt.
290 type SectionOpener interface {
291 OpenSection(off, n int64) (io.ReadCloser, error)
294 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
295 if ra, ok := d.(io.ReaderAt); ok {
296 return ra.ReadAt(b, off)
298 if so, ok := d.(SectionOpener); ok {
300 rc, err = so.OpenSection(off, int64(len(b)))
305 return io.ReadFull(rc, b)
307 panic(fmt.Sprintf("can't read from %T", d))
310 func readaheadPieces(readahead, pieceLength int64) int {
311 return int((readahead+pieceLength-1)/pieceLength - 1)
314 func (cl *Client) readRaisePiecePriorities(t *torrent, off int64) {
315 index := int(off / int64(t.usualPieceSize()))
316 cl.raisePiecePriority(t, index, piecePriorityNow)
318 if index >= t.numPieces() {
321 cl.raisePiecePriority(t, index, piecePriorityNext)
322 for i := 0; i < readaheadPieces(5*1024*1024, t.Info.PieceLength); i++ {
324 if index >= t.numPieces() {
327 cl.raisePiecePriority(t, index, piecePriorityReadahead)
331 func (cl *Client) configDir() string {
332 if cl._configDir == "" {
333 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
338 func (cl *Client) ConfigDir() string {
339 return cl.configDir()
342 func (t *torrent) connPendPiece(c *connection, piece int) {
343 c.pendPiece(piece, t.Pieces[piece].Priority)
346 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
347 if t.Pieces[piece].Priority < priority {
348 cl.prioritizePiece(t, piece, priority)
352 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
353 if t.havePiece(piece) {
356 cl.queueFirstHash(t, piece)
357 t.Pieces[piece].Priority = priority
358 if t.wantPiece(piece) {
359 for _, c := range t.Conns {
360 if c.PeerHasPiece(pp.Integer(piece)) {
361 t.connPendPiece(c, piece)
362 cl.replenishConnRequests(t, c)
368 func (cl *Client) setEnvBlocklist() (err error) {
369 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
370 defaultBlocklist := filename == ""
371 if defaultBlocklist {
372 filename = filepath.Join(cl.configDir(), "blocklist")
374 f, err := os.Open(filename)
376 if defaultBlocklist {
382 var ranges []iplist.Range
383 uniqStrs := make(map[string]string)
384 scanner := bufio.NewScanner(f)
387 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
389 err = fmt.Errorf("error reading torrent blocklist line %d: %s", lineNum, lineErr)
396 if s, ok := uniqStrs[r.Description]; ok {
399 uniqStrs[r.Description] = r.Description
401 ranges = append(ranges, r)
405 err = fmt.Errorf("error reading torrent blocklist: %s", err)
408 cl.ipBlockList = iplist.New(ranges)
412 func (cl *Client) initBannedTorrents() error {
413 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
415 if os.IsNotExist(err) {
418 return fmt.Errorf("error opening banned infohashes file: %s", err)
421 scanner := bufio.NewScanner(f)
422 cl.bannedTorrents = make(map[InfoHash]struct{})
425 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
427 return fmt.Errorf("error reading infohash: %s", err)
433 return errors.New("bad infohash")
437 cl.bannedTorrents[ih] = struct{}{}
439 if err := scanner.Err(); err != nil {
440 return fmt.Errorf("error scanning file: %s", err)
445 func NewClient(cfg *Config) (cl *Client, err error) {
451 noUpload: cfg.NoUpload,
452 disableTrackers: cfg.DisableTrackers,
453 halfOpenLimit: socketsPerTorrent,
454 dataDir: cfg.DataDir,
455 disableUTP: cfg.DisableUTP,
456 disableTCP: cfg.DisableTCP,
457 _configDir: cfg.ConfigDir,
459 torrentDataOpener: func(md *metainfo.Info) data.Data {
460 return filePkg.TorrentData(md, cfg.DataDir)
463 quit: make(chan struct{}),
464 torrents: make(map[InfoHash]*torrent),
467 if cfg.TorrentDataOpener != nil {
468 cl.torrentDataOpener = cfg.TorrentDataOpener
471 if !cfg.NoDefaultBlocklist {
472 err = cl.setEnvBlocklist()
478 if err = cl.initBannedTorrents(); err != nil {
479 err = fmt.Errorf("error initing banned torrents: %s", err)
483 if cfg.PeerID != "" {
484 CopyExact(&cl.peerID, cfg.PeerID)
486 o := copy(cl.peerID[:], bep20)
487 _, err = rand.Read(cl.peerID[o:])
489 panic("error generating peer id")
493 // Returns the laddr string to listen on for the next Listen call.
494 listenAddr := func() string {
495 if addr := cl.ListenAddr(); addr != nil {
498 if cfg.ListenAddr == "" {
499 // IPv6 isn't well supported with blocklists, or with trackers and
501 return "0.0.0.0:50007"
503 return cfg.ListenAddr
507 l, err = net.Listen("tcp", listenAddr())
511 cl.listeners = append(cl.listeners, l)
512 go cl.acceptConnections(l, false)
515 cl.utpSock, err = utp.NewSocket(listenAddr())
519 cl.listeners = append(cl.listeners, cl.utpSock)
520 go cl.acceptConnections(cl.utpSock, true)
523 dhtCfg := cfg.DHTConfig
525 dhtCfg = &dht.ServerConfig{}
527 if dhtCfg.Addr == "" {
528 dhtCfg.Addr = listenAddr()
530 if dhtCfg.Conn == nil && cl.utpSock != nil {
531 dhtCfg.Conn = cl.utpSock.PacketConn()
533 cl.dHT, err = dht.NewServer(dhtCfg)
534 if cl.ipBlockList != nil {
535 cl.dHT.SetIPBlockList(cl.ipBlockList)
545 func (cl *Client) stopped() bool {
554 // Stops the client. All connections to peers are closed and all activity will
556 func (me *Client) Close() {
560 for _, l := range me.listeners {
564 for _, t := range me.torrents {
569 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
571 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
572 if cl.ipBlockList == nil {
577 log.Printf("saw non-IPv4 address")
581 r = cl.ipBlockList.Lookup(ip)
585 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
587 // We accept all connections immediately, because we don't know what
588 // torrent they're for.
589 conn, err := l.Accept()
604 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
606 if blockRange != nil {
607 inboundConnsBlocked.Add(1)
608 log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
613 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
620 func (me *Client) torrent(ih InfoHash) *torrent {
621 return me.torrents[ih]
624 type dialResult struct {
629 func doDial(dial func(addr string) (net.Conn, error), ch chan dialResult, utp bool, addr string) {
630 conn, err := dial(addr)
635 conn = nil // Pedantic
637 ch <- dialResult{conn, utp}
639 successfulDials.Add(1)
642 unsuccessfulDials.Add(1)
643 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
646 if netOpErr, ok := err.(*net.OpError); ok {
647 switch netOpErr.Err {
648 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
653 log.Printf("error dialing %s: %s", addr, err)
658 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
659 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
660 if ret < minDialTimeout {
666 // Start the process of connecting to the given peer for the given torrent if
668 func (me *Client) initiateConn(peer Peer, t *torrent) {
669 if peer.Id == me.peerID {
672 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
673 if t.addrActive(addr) {
674 duplicateConnsAvoided.Add(1)
677 if r := me.ipBlockRange(peer.IP); r != nil {
678 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
681 dialTimeout := reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
682 t.HalfOpen[addr] = struct{}{}
684 // Binding to the listen address and dialing via net.Dialer gives
685 // "address in use" error. It seems it's not possible to dial out from
686 // this address so that peers associate our local address with our
689 // Initiate connections via TCP and UTP simultaneously. Use the first
690 // one that succeeds.
698 resCh := make(chan dialResult, left)
700 go doDial(func(addr string) (net.Conn, error) {
701 return me.utpSock.DialTimeout(addr, dialTimeout)
702 }, resCh, true, addr)
705 go doDial(func(addr string) (net.Conn, error) {
706 // time.Sleep(time.Second) // Give uTP a bit of a head start.
707 return net.DialTimeout("tcp", addr, dialTimeout)
708 }, resCh, false, addr)
711 for ; left > 0 && res.Conn == nil; left-- {
714 // Whether or not the connection attempt succeeds, the half open
715 // counter should be decremented, and new connection attempts made.
719 if _, ok := t.HalfOpen[addr]; !ok {
720 panic("invariant broken")
722 delete(t.HalfOpen, addr)
730 for ; left > 0; left-- {
731 conn := (<-resCh).Conn
739 // log.Printf("connected to %s", conn.RemoteAddr())
740 err := me.runConnection(res.Conn, t, peer.Source, res.UTP)
747 // The port number for incoming peer connections. 0 if the client isn't
749 func (cl *Client) incomingPeerPort() int {
750 listenAddr := cl.ListenAddr()
751 if listenAddr == nil {
754 return addrPort(listenAddr)
757 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
758 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
759 func addrCompactIP(addr net.Addr) (string, error) {
760 host, _, err := net.SplitHostPort(addr.String())
764 ip := net.ParseIP(host)
765 if v4 := ip.To4(); v4 != nil {
769 return string(v4), nil
771 return string(ip.To16()), nil
774 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
786 type peerExtensionBytes [8]byte
789 type handshakeResult struct {
795 // ih is nil if we expect the peer to declare the InfoHash, such as when the
796 // peer initiated the connection. Returns ok if the handshake was successful,
797 // and err if there was an unexpected condition other than the peer simply
798 // abandoning the handshake.
799 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
800 // Bytes to be sent to the peer. Should never block the sender.
801 postCh := make(chan []byte, 4)
802 // A single error value sent when the writer completes.
803 writeDone := make(chan error, 1)
804 // Performs writes to the socket and ensures posts don't block.
805 go handshakeWriter(sock, postCh, writeDone)
808 close(postCh) // Done writing.
815 // Wait until writes complete before returning from handshake.
818 err = fmt.Errorf("error writing during handshake: %s", err)
822 post := func(bb []byte) {
826 panic("mustn't block while posting")
830 post([]byte(pp.Protocol))
831 post([]byte(extensionBytes))
832 if ih != nil { // We already know what we want.
837 _, err = io.ReadFull(sock, b[:68])
842 if string(b[:20]) != pp.Protocol {
845 CopyExact(&res.peerExtensionBytes, b[20:28])
846 CopyExact(&res.InfoHash, b[28:48])
847 CopyExact(&res.peerID, b[48:68])
849 if ih == nil { // We were waiting for the peer to tell us what they wanted.
850 post(res.InfoHash[:])
858 // Wraps a raw connection and provides the interface we want for using the
859 // connection in the message loop.
860 type peerConn struct {
864 func (pc peerConn) Read(b []byte) (n int, err error) {
865 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
866 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
868 err = fmt.Errorf("error setting read deadline: %s", err)
870 n, err = pc.Conn.Read(b)
871 // Convert common errors into io.EOF.
873 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
875 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
885 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource, uTP bool) (err error) {
886 if tcpConn, ok := sock.(*net.TCPConn); ok {
890 err = sock.SetDeadline(time.Now().Add(handshakeTimeout))
892 err = fmt.Errorf("couldn't set handshake deadline: %s", err)
898 hsRes, ok, err := handshake(sock, func() *InfoHash {
902 return &torrent.InfoHash
907 if me.handshaking == 0 {
908 panic("handshake count invariant is broken")
912 err = fmt.Errorf("error during handshake: %s", err)
918 if hsRes.peerID == me.peerID {
921 torrent = me.torrent(hsRes.InfoHash)
925 sock.SetWriteDeadline(time.Time{})
926 sock = peerConn{sock}
927 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
929 conn.Discovery = discovery
930 if !me.addConnection(torrent, conn) {
933 if conn.PeerExtensionBytes[5]&0x10 != 0 {
934 conn.Post(pp.Message{
936 ExtendedID: pp.HandshakeExtendedID,
937 ExtendedPayload: func() []byte {
938 d := map[string]interface{}{
943 "v": "go.torrent dev 20140825", // Just the date
944 // No upload queue is implemented yet.
947 // No need to look strange if it costs us nothing.
954 if torrent.metadataSizeKnown() {
955 d["metadata_size"] = torrent.metadataSize()
957 if p := me.incomingPeerPort(); p != 0 {
960 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
962 log.Printf("error calculating yourip field value in extension handshake: %s", err)
966 // log.Printf("sending %v", d)
967 b, err := bencode.Marshal(d)
975 if torrent.haveAnyPieces() {
976 conn.Post(pp.Message{
978 Bitfield: torrent.bitfield(),
981 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
982 conn.Post(pp.Message{
984 Port: uint16(AddrPort(me.dHT.LocalAddr())),
987 if torrent.haveInfo() {
988 torrent.initRequestOrdering(conn)
989 me.replenishConnRequests(torrent, conn)
991 err = me.connectionLoop(torrent, conn)
993 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
995 me.dropConnection(torrent, conn)
999 func (t *torrent) initRequestOrdering(c *connection) {
1000 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1001 panic("double init of request ordering")
1003 c.piecePriorities = mathRand.Perm(t.numPieces())
1004 c.pieceRequestOrder = pieceordering.New()
1005 for i := 0; i < t.numPieces(); i++ {
1006 if !c.PeerHasPiece(pp.Integer(i)) {
1009 if !t.wantPiece(i) {
1012 t.connPendPiece(c, i)
1016 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1018 if c.PeerPieces == nil {
1019 c.PeerPieces = make([]bool, t.numPieces())
1022 for piece >= len(c.PeerPieces) {
1023 c.PeerPieces = append(c.PeerPieces, false)
1026 c.PeerPieces[piece] = true
1027 if t.wantPiece(piece) {
1028 t.connPendPiece(c, piece)
1029 me.replenishConnRequests(t, c)
1033 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1034 me.replenishConnRequests(torrent, conn)
1037 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1040 postedCancels.Add(1)
1045 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1046 if !cn.RequestPending(r) {
1049 delete(cn.Requests, r)
1052 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1057 for index := 0; index < t.metadataPieceCount(); index++ {
1058 if !t.haveMetadataPiece(index) {
1059 pending = append(pending, index)
1062 for _, i := range mathRand.Perm(len(pending)) {
1065 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
1066 ExtendedPayload: func() []byte {
1067 b, err := bencode.Marshal(map[string]int{
1069 "piece": pending[i],
1080 func (cl *Client) completedMetadata(t *torrent) {
1084 CopyExact(&ih, h.Sum(nil))
1085 if ih != t.InfoHash {
1086 log.Print("bad metadata")
1087 t.invalidateMetadata()
1090 var info metainfo.Info
1091 err := bencode.Unmarshal(t.MetaData, &info)
1093 log.Printf("error unmarshalling metadata: %s", err)
1094 t.invalidateMetadata()
1097 // TODO(anacrolix): If this fails, I think something harsher should be
1099 err = cl.setMetaData(t, info, t.MetaData)
1101 log.Printf("error setting metadata: %s", err)
1102 t.invalidateMetadata()
1105 log.Printf("%s: got metadata from peers", t)
1108 // Process incoming ut_metadata message.
1109 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1110 var d map[string]int
1111 err = bencode.Unmarshal(payload, &d)
1113 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1116 msgType, ok := d["msg_type"]
1118 err = errors.New("missing msg_type field")
1123 case pp.DataMetadataExtensionMsgType:
1127 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1128 if begin < 0 || begin >= len(payload) {
1129 log.Printf("got bad metadata piece")
1132 t.SaveMetadataPiece(piece, payload[begin:])
1133 c.UsefulChunksReceived++
1134 c.lastUsefulChunkReceived = time.Now()
1135 if !t.haveAllMetadataPieces() {
1138 cl.completedMetadata(t)
1139 case pp.RequestMetadataExtensionMsgType:
1140 if !t.haveMetadataPiece(piece) {
1141 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1144 start := (1 << 14) * piece
1145 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1146 case pp.RejectMetadataExtensionMsgType:
1148 err = errors.New("unknown msg_type value")
1153 type peerExchangeMessage struct {
1154 Added CompactPeers `bencode:"added"`
1155 AddedFlags []byte `bencode:"added.f"`
1156 Dropped []tracker.Peer `bencode:"dropped"`
1159 // Extracts the port as an integer from an address string.
1160 func addrPort(addr net.Addr) int {
1161 return AddrPort(addr)
1164 // Processes incoming bittorrent messages. The client lock is held upon entry
1166 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1167 decoder := pp.Decoder{
1168 R: bufio.NewReader(c.Socket),
1169 MaxLength: 256 * 1024,
1174 err := decoder.Decode(&msg)
1176 c.lastMessageReceived = time.Now()
1183 if me.stopped() || err == io.EOF {
1194 for r := range c.Requests {
1195 me.connDeleteRequest(t, c, r)
1197 // We can then reset our interest.
1198 me.replenishConnRequests(t, c)
1200 c.PeerChoked = false
1201 me.peerUnchoked(t, c)
1203 c.PeerInterested = true
1204 // TODO: This should be done from a dedicated unchoking routine.
1209 case pp.NotInterested:
1210 c.PeerInterested = false
1213 me.peerGotPiece(t, c, int(msg.Index))
1218 if c.PeerRequests == nil {
1219 c.PeerRequests = make(map[request]struct{}, maxRequests)
1221 request := newRequest(msg.Index, msg.Begin, msg.Length)
1222 // TODO: Requests should be satisfied from a dedicated upload
1224 // c.PeerRequests[request] = struct{}{}
1225 p := make([]byte, msg.Length)
1226 n, err := dataReadAt(t.data, p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1228 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1230 if n != int(msg.Length) {
1231 return fmt.Errorf("bad request: %v", msg)
1239 uploadChunksPosted.Add(1)
1241 req := newRequest(msg.Index, msg.Begin, msg.Length)
1242 if !c.PeerCancel(req) {
1243 unexpectedCancels.Add(1)
1246 if c.PeerPieces != nil {
1247 err = errors.New("received unexpected bitfield")
1251 if len(msg.Bitfield) < t.numPieces() {
1252 err = errors.New("received invalid bitfield")
1255 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1257 c.PeerPieces = msg.Bitfield
1258 for index, has := range c.PeerPieces {
1260 me.peerGotPiece(t, c, index)
1264 err = me.downloadedChunk(t, c, &msg)
1266 switch msg.ExtendedID {
1267 case pp.HandshakeExtendedID:
1268 // TODO: Create a bencode struct for this.
1269 var d map[string]interface{}
1270 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1272 err = fmt.Errorf("error decoding extended message payload: %s", err)
1275 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1276 if reqq, ok := d["reqq"]; ok {
1277 if i, ok := reqq.(int64); ok {
1278 c.PeerMaxRequests = int(i)
1281 if v, ok := d["v"]; ok {
1282 c.PeerClientName = v.(string)
1286 err = errors.New("handshake missing m item")
1289 mTyped, ok := m.(map[string]interface{})
1291 err = errors.New("handshake m value is not dict")
1294 if c.PeerExtensionIDs == nil {
1295 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1297 for name, v := range mTyped {
1300 log.Printf("bad handshake m item extension ID type: %T", v)
1304 delete(c.PeerExtensionIDs, name)
1306 c.PeerExtensionIDs[name] = id
1309 metadata_sizeUntyped, ok := d["metadata_size"]
1311 metadata_size, ok := metadata_sizeUntyped.(int64)
1313 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1315 t.SetMetadataSize(metadata_size)
1318 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1319 me.requestPendingMetadata(t, c)
1322 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1324 err = fmt.Errorf("error handling metadata extension message: %s", err)
1327 var pexMsg peerExchangeMessage
1328 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1330 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1335 me.addPeers(t, func() (ret []Peer) {
1336 for _, cp := range pexMsg.Added {
1338 IP: make([]byte, 4),
1340 Source: peerSourcePEX,
1342 if n := copy(p.IP, cp.IP[:]); n != 4 {
1345 ret = append(ret, p)
1350 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1353 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1356 // That client uses its own extension IDs for outgoing message
1357 // types, which is incorrect.
1358 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1359 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1362 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1368 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1373 pingAddr.Port = int(msg.Port)
1375 _, err = me.dHT.Ping(pingAddr)
1377 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1385 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1386 for r := range conn.Requests {
1387 me.connDeleteRequest(torrent, conn, r)
1390 for i0, c := range torrent.Conns {
1394 i1 := len(torrent.Conns) - 1
1396 torrent.Conns[i0] = torrent.Conns[i1]
1398 torrent.Conns = torrent.Conns[:i1]
1399 me.openNewConns(torrent)
1402 panic("connection not found")
1405 func (me *Client) addConnection(t *torrent, c *connection) bool {
1410 case <-t.ceasingNetworking:
1414 if !me.wantConns(t) {
1417 for _, c0 := range t.Conns {
1418 if c.PeerID == c0.PeerID {
1419 // Already connected to a client with that ID.
1423 t.Conns = append(t.Conns, c)
1424 // TODO: This should probably be done by a routine that kills off bad
1425 // connections, and extra connections killed here instead.
1426 if len(t.Conns) > socketsPerTorrent {
1427 wcs := t.worstConnsHeap()
1428 heap.Pop(wcs).(*connection).Close()
1433 func (t *torrent) needData() bool {
1437 for i := range t.Pieces {
1445 // TODO: I'm sure there's something here to do with seeding.
1446 func (t *torrent) badConn(c *connection) bool {
1447 if time.Now().Sub(c.completedHandshake) < 30*time.Second {
1451 return !c.supportsExtension("ut_metadata")
1453 return !t.connHasWantedPieces(c)
1456 func (t *torrent) numGoodConns() (num int) {
1457 for _, c := range t.Conns {
1465 func (me *Client) wantConns(t *torrent) bool {
1466 if !t.needData() && me.noUpload {
1469 if t.numGoodConns() >= socketsPerTorrent {
1475 func (me *Client) openNewConns(t *torrent) {
1477 case <-t.ceasingNetworking:
1481 for len(t.Peers) != 0 {
1482 if !me.wantConns(t) {
1485 if len(t.HalfOpen) >= me.halfOpenLimit {
1492 for k, p = range t.Peers {
1496 me.initiateConn(p, t)
1498 t.wantPeers.Broadcast()
1501 func (me *Client) addPeers(t *torrent, peers []Peer) {
1503 for _, p := range peers {
1504 if me.ipBlockRange(p.IP) != nil {
1511 log.Printf("IP blocklist screened %d peers from being added", blocked)
1516 func (cl *Client) torrentFileCachePath(ih InfoHash) string {
1517 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1520 func (cl *Client) saveTorrentFile(t *torrent) error {
1521 path := cl.torrentFileCachePath(t.InfoHash)
1522 os.MkdirAll(filepath.Dir(path), 0777)
1523 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1525 return fmt.Errorf("error opening file: %s", err)
1528 e := bencode.NewEncoder(f)
1529 err = e.Encode(t.MetaInfo())
1531 return fmt.Errorf("error marshalling metainfo: %s", err)
1533 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1535 // For example, a script kiddy makes us load too many files, and we're
1536 // able to save the torrent, but not load it again to check it.
1539 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1540 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1545 func (cl *Client) startTorrent(t *torrent) {
1546 if t.Info == nil || t.data == nil {
1549 // If the client intends to upload, it needs to know what state pieces are
1552 // Queue all pieces for hashing. This is done sequentially to avoid
1553 // spamming goroutines.
1554 for _, p := range t.Pieces {
1555 p.QueuedForHash = true
1558 for i := range t.Pieces {
1559 cl.verifyPiece(t, pp.Integer(i))
1565 // Storage cannot be changed once it's set.
1566 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1567 err = t.setStorage(td)
1568 cl.event.Broadcast()
1576 type TorrentDataOpener func(*metainfo.Info) data.Data
1578 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1579 err = t.setMetadata(md, bytes, &cl.mu)
1583 if !cl.config.DisableMetainfoCache {
1584 if err := cl.saveTorrentFile(t); err != nil {
1585 log.Printf("error saving torrent file for %s: %s", t, err)
1588 if strings.Contains(strings.ToLower(md.Name), "porn") {
1589 cl.dropTorrent(t.InfoHash)
1590 err = errors.New("no porn plx")
1593 close(t.gotMetainfo)
1594 td := cl.torrentDataOpener(&md)
1595 err = cl.setStorage(t, td)
1599 // Prepare a Torrent without any attachment to a Client. That means we can
1600 // initialize fields all fields that don't require the Client without locking
1602 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1605 Peers: make(map[peersKey]Peer),
1607 closing: make(chan struct{}),
1608 ceasingNetworking: make(chan struct{}),
1610 gotMetainfo: make(chan struct{}),
1612 HalfOpen: make(map[string]struct{}),
1614 t.wantPeers.L = &t.stateMu
1615 t.GotMetainfo = t.gotMetainfo
1616 t.addTrackers(announceList)
1621 // For shuffling the tracker tiers.
1622 mathRand.Seed(time.Now().Unix())
1625 // The trackers within each tier must be shuffled before use.
1626 // http://stackoverflow.com/a/12267471/149482
1627 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1628 func shuffleTier(tier []tracker.Client) {
1629 for i := range tier {
1630 j := mathRand.Intn(i + 1)
1631 tier[i], tier[j] = tier[j], tier[i]
1635 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1636 for _, tier := range base {
1637 copy = append(copy, append([]tracker.Client{}, tier...))
1642 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1644 for _, url := range newURLs {
1645 for _, tr := range tier {
1646 if tr.URL() == url {
1650 tr, err := tracker.New(url)
1652 log.Printf("error creating tracker client for %q: %s", url, err)
1655 tier = append(tier, tr)
1660 func (t *torrent) addTrackers(announceList [][]string) {
1661 newTrackers := copyTrackers(t.Trackers)
1662 for tierIndex, tier := range announceList {
1663 if tierIndex < len(newTrackers) {
1664 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1666 newTrackers = append(newTrackers, mergeTier(nil, tier))
1668 shuffleTier(newTrackers[tierIndex])
1670 t.Trackers = newTrackers
1673 type Torrent struct {
1678 func (t Torrent) NumPieces() int {
1679 return t.numPieces()
1682 func (t Torrent) Drop() {
1683 t.cl.dropTorrent(t.InfoHash)
1691 fi metainfo.FileInfo
1694 func (f File) FileInfo() metainfo.FileInfo {
1698 func (f File) Path() string {
1702 // A file-like handle to some torrent data resource.
1703 type Handle interface {
1710 // Implements a Handle within a subsection of another Handle.
1711 type sectionHandle struct {
1716 func (me *sectionHandle) Seek(offset int64, whence int) (ret int64, err error) {
1719 } else if whence == 2 {
1721 offset += me.off + me.n
1723 ret, err = me.h.Seek(offset, whence)
1729 func (me *sectionHandle) Close() error {
1733 func (me *sectionHandle) Read(b []byte) (n int, err error) {
1734 max := me.off + me.n - me.cur
1735 if int64(len(b)) > max {
1738 n, err = me.h.Read(b)
1743 if me.cur == me.off+me.n {
1749 func (me *sectionHandle) ReadAt(b []byte, off int64) (n int, err error) {
1754 if int64(len(b)) >= me.n-off {
1757 return me.h.ReadAt(b, me.off+off)
1760 func (f File) Open() (h Handle, err error) {
1761 h = f.t.NewReadHandle()
1762 _, err = h.Seek(f.offset, os.SEEK_SET)
1767 h = §ionHandle{h, f.offset, f.Length(), f.offset}
1771 func (f File) ReadAt(p []byte, off int64) (n int, err error) {
1772 maxLen := f.length - off
1773 if int64(len(p)) > maxLen {
1776 return f.t.ReadAt(p, off+f.offset)
1779 func (f *File) Length() int64 {
1783 type FilePieceState struct {
1788 func (f *File) Progress() (ret []FilePieceState) {
1789 pieceSize := int64(f.t.usualPieceSize())
1790 off := f.offset % pieceSize
1791 remaining := f.length
1792 for i := int(f.offset / pieceSize); ; i++ {
1796 len1 := pieceSize - off
1797 if len1 > remaining {
1800 ret = append(ret, FilePieceState{len1, f.t.pieceStatusChar(i)})
1807 func (f *File) PrioritizeRegion(off, len int64) {
1808 if off < 0 || off >= f.length {
1811 if off+len > f.length {
1812 len = f.length - off
1815 f.t.SetRegionPriority(off, len)
1818 // Returns handles to the files in the torrent. This requires the metainfo is
1820 func (t Torrent) Files() (ret []File) {
1828 for _, fi := range info.UpvertedFiles() {
1829 ret = append(ret, File{
1831 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1841 func (t Torrent) SetRegionPriority(off, len int64) {
1843 defer t.cl.mu.Unlock()
1844 pieceSize := int64(t.usualPieceSize())
1845 for i := off / pieceSize; i*pieceSize < off+len; i++ {
1846 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
1850 func (t Torrent) MetainfoFilepath() string {
1851 return filepath.Join(t.cl.ConfigDir(), "torrents", t.InfoHash.HexString()+".torrent")
1854 func (t Torrent) AddPeers(pp []Peer) error {
1857 defer cl.mu.Unlock()
1858 cl.addPeers(t.torrent, pp)
1862 func (t Torrent) DownloadAll() {
1864 for i := 0; i < t.numPieces(); i++ {
1865 // TODO: Leave higher priorities as they were?
1866 t.cl.prioritizePiece(t.torrent, i, piecePriorityNormal)
1868 // Nice to have the first and last pieces soon for various interactive
1870 t.cl.prioritizePiece(t.torrent, 0, piecePriorityReadahead)
1871 t.cl.prioritizePiece(t.torrent, t.numPieces()-1, piecePriorityReadahead)
1875 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
1876 return me.cl.torrentReadAt(me.torrent, off, p)
1879 // Returns nil metainfo if it isn't in the cache.
1880 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1881 if cl.config.DisableMetainfoCache {
1884 f, err := os.Open(cl.torrentFileCachePath(ih))
1886 if os.IsNotExist(err) {
1892 dec := bencode.NewDecoder(f)
1893 err = dec.Decode(&mi)
1897 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1898 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1904 func (cl *Client) AddMagnet(uri string) (T Torrent, err error) {
1905 m, err := ParseMagnetURI(uri)
1909 mi, err := cl.torrentCacheMetaInfo(m.InfoHash)
1911 log.Printf("error getting cached metainfo for %x: %s", m.InfoHash[:], err)
1912 } else if mi != nil {
1913 _, err = cl.AddTorrent(mi)
1919 defer cl.mu.Unlock()
1920 T, err = cl.addOrMergeTorrent(m.InfoHash, [][]string{m.Trackers})
1924 if m.DisplayName != "" {
1925 T.DisplayName = m.DisplayName
1930 // Prunes unused connections. This is required to make space to dial for
1932 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
1934 case <-t.ceasingNetworking:
1941 license := len(t.Conns) - (socketsPerTorrent+1)/2
1942 for _, c := range t.Conns {
1946 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
1949 if time.Now().Sub(c.completedHandshake) < time.Minute {
1956 t.pruneTimer.Reset(pruneInterval)
1959 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
1960 t, ok := me.torrents[infoHash]
1962 err = fmt.Errorf("no such torrent")
1969 delete(me.torrents, infoHash)
1973 func (me *Client) addOrMergeTorrent(ih InfoHash, announceList [][]string) (T Torrent, err error) {
1974 if _, ok := me.bannedTorrents[ih]; ok {
1975 err = errors.New("banned torrent")
1980 T.torrent, ok = me.torrents[ih]
1982 T.torrent.addTrackers(announceList)
1984 T.torrent, err = newTorrent(ih, announceList, me.halfOpenLimit)
1988 me.torrents[ih] = T.torrent
1989 if !me.disableTrackers {
1990 go me.announceTorrentTrackers(T.torrent)
1993 go me.announceTorrentDHT(T.torrent, true)
1995 T.torrent.pruneTimer = time.AfterFunc(0, func() {
1996 me.pruneConnectionsUnlocked(T.torrent)
2002 // Adds a torrent to the client.
2003 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (t Torrent, err error) {
2005 CopyExact(&ih, metaInfo.Info.Hash)
2007 defer me.mu.Unlock()
2008 t, err = me.addOrMergeTorrent(ih, metaInfo.AnnounceList)
2012 if !t.torrent.haveInfo() {
2013 err = me.setMetaData(t.torrent, metaInfo.Info.Info, metaInfo.Info.Bytes)
2021 func (me *Client) AddTorrentFromFile(name string) (t Torrent, err error) {
2022 mi, err := metainfo.LoadFromFile(name)
2024 err = fmt.Errorf("error loading metainfo from file: %s", err)
2027 return me.AddTorrent(mi)
2030 // Returns true when peers are required, or false if the torrent is closing.
2031 func (cl *Client) waitWantPeers(t *torrent) bool {
2033 defer cl.mu.Unlock()
2035 defer t.stateMu.Unlock()
2038 case <-t.ceasingNetworking:
2042 if len(t.Peers) < torrentPeersLowWater && t.needData() {
2053 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2054 for cl.waitWantPeers(t) {
2055 log.Printf("getting peers for %q from DHT", t)
2056 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2058 log.Printf("error getting peers from dht: %s", err)
2061 allAddrs := make(map[string]struct{})
2065 case v, ok := <-ps.Values:
2069 peersFoundByDHT.Add(int64(len(v.Peers)))
2070 for _, p := range v.Peers {
2071 allAddrs[(&net.UDPAddr{
2074 }).String()] = struct{}{}
2076 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2078 cl.addPeers(t, func() (ret []Peer) {
2079 for _, cp := range v.Peers {
2080 ret = append(ret, Peer{
2083 Source: peerSourceDHT,
2088 numPeers := len(t.Peers)
2090 if numPeers >= torrentPeersHighWater {
2093 case <-t.ceasingNetworking:
2099 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2103 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2104 if err := tr.Connect(); err != nil {
2105 return fmt.Errorf("error connecting: %s", err)
2107 resp, err := tr.Announce(req)
2109 return fmt.Errorf("error announcing: %s", err)
2112 for _, peer := range resp.Peers {
2113 peers = append(peers, Peer{
2119 cl.addPeers(t, peers)
2121 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2123 time.Sleep(time.Second * time.Duration(resp.Interval))
2127 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2128 oks := make(chan bool)
2130 for _, tier := range trackers {
2131 for _, tr := range tier {
2133 go func(tr tracker.Client) {
2134 err := cl.announceTorrentSingleTracker(tr, req, t)
2139 for outstanding > 0 {
2149 // Announce torrent to its trackers.
2150 func (cl *Client) announceTorrentTrackers(t *torrent) {
2151 req := tracker.AnnounceRequest{
2152 Event: tracker.Started,
2154 Port: int16(cl.incomingPeerPort()),
2156 InfoHash: t.InfoHash,
2158 if !cl.waitWantPeers(t) {
2162 req.Left = t.bytesLeft()
2163 trackers := t.Trackers
2165 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2166 req.Event = tracker.None
2169 for cl.waitWantPeers(t) {
2171 req.Left = t.bytesLeft()
2172 trackers = t.Trackers
2174 numTrackersTried := 0
2175 for _, tier := range trackers {
2176 for trIndex, tr := range tier {
2178 err := cl.announceTorrentSingleTracker(tr, &req, t)
2182 // Float the successful announce to the top of the tier. If
2183 // the trackers list has been changed, we'll be modifying an
2184 // old copy so it won't matter.
2186 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2189 req.Event = tracker.None
2190 continue newAnnounce
2193 if numTrackersTried != 0 {
2194 log.Printf("%s: all trackers failed", t)
2196 // TODO: Wait until trackers are added if there are none.
2197 time.Sleep(10 * time.Second)
2201 func (cl *Client) allTorrentsCompleted() bool {
2202 for _, t := range cl.torrents {
2206 if t.numPiecesCompleted() != t.numPieces() {
2213 // Returns true when all torrents are completely downloaded and false if the
2214 // client is stopped before that.
2215 func (me *Client) WaitAll() bool {
2217 defer me.mu.Unlock()
2218 for !me.allTorrentsCompleted() {
2227 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2231 me.downloadStrategy.FillRequests(t, c)
2232 if len(c.Requests) == 0 && !c.PeerChoked {
2233 c.SetInterested(false)
2237 // Handle a received chunk from a peer.
2238 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2239 chunksDownloadedCount.Add(1)
2241 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2243 // Request has been satisfied.
2244 me.connDeleteRequest(t, c, req)
2246 defer me.replenishConnRequests(t, c)
2248 piece := t.Pieces[req.Index]
2250 // Do we actually want this chunk?
2251 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
2252 unusedDownloadedChunksCount.Add(1)
2253 c.UnwantedChunksReceived++
2257 c.UsefulChunksReceived++
2258 c.lastUsefulChunkReceived = time.Now()
2260 // Write the chunk out.
2261 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2263 return fmt.Errorf("error writing chunk: %s", err)
2266 // Record that we have the chunk.
2267 delete(piece.PendingChunkSpecs, req.chunkSpec)
2268 if len(piece.PendingChunkSpecs) == 0 {
2269 for _, c := range t.Conns {
2270 c.pieceRequestOrder.DeletePiece(int(req.Index))
2272 me.queuePieceCheck(t, req.Index)
2275 // Cancel pending requests for this chunk.
2276 for _, c := range t.Conns {
2277 if me.connCancel(t, c, req) {
2278 me.replenishConnRequests(t, c)
2285 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2286 p := t.Pieces[piece]
2287 if p.EverHashed && !correct {
2288 log.Printf("%s: piece %d failed hash", t, piece)
2289 failedPieceHashes.Add(1)
2293 if sd, ok := t.data.(StatefulData); ok {
2294 err := sd.PieceCompleted(int(piece))
2296 log.Printf("error completing piece: %s", err)
2302 p.Priority = piecePriorityNone
2303 p.PendingChunkSpecs = nil
2307 if len(p.PendingChunkSpecs) == 0 {
2308 t.pendAllChunkSpecs(int(piece))
2310 if p.Priority != piecePriorityNone {
2314 for _, conn := range t.Conns {
2316 conn.Post(pp.Message{
2318 Index: pp.Integer(piece),
2320 // TODO: Cancel requests for this piece.
2321 for r := range conn.Requests {
2322 if int(r.Index) == piece {
2326 conn.pieceRequestOrder.DeletePiece(int(piece))
2328 if t.wantPiece(int(piece)) && conn.PeerHasPiece(pp.Integer(piece)) {
2329 t.connPendPiece(conn, int(piece))
2330 me.replenishConnRequests(t, conn)
2333 if t.haveAllPieces() && me.noUpload {
2336 me.event.Broadcast()
2339 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2341 defer cl.mu.Unlock()
2342 p := t.Pieces[index]
2343 for p.Hashing || t.data == nil {
2346 p.QueuedForHash = false
2347 if t.isClosed() || p.complete {
2352 sum := t.hashPiece(index)
2360 cl.pieceHashed(t, index, sum == p.Hash)
2363 // Returns handles to all the torrents loaded in the Client.
2364 func (me *Client) Torrents() (ret []Torrent) {
2366 for _, t := range me.torrents {
2367 ret = append(ret, Torrent{me, t})