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")
37 "bitbucket.org/anacrolix/go.torrent/util/levelmu"
39 "bitbucket.org/anacrolix/go.torrent/dht"
40 . "bitbucket.org/anacrolix/go.torrent/util"
42 "github.com/anacrolix/libtorgo/metainfo"
43 "github.com/nsf/libtorgo/bencode"
45 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
46 "bitbucket.org/anacrolix/go.torrent/tracker"
47 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
51 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
52 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
53 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
54 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
55 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
56 unexpectedCancels = expvar.NewInt("unexpectedCancels")
57 postedCancels = expvar.NewInt("postedCancels")
58 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
59 failedPieceHashes = expvar.NewInt("failedPieceHashes")
63 // Justification for set bits follows.
65 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html
66 // DHT: http://www.bittorrent.org/beps/bep_0005.html
67 extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
69 socketsPerTorrent = 40
72 // Currently doesn't really queue, but should in the future.
73 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
74 piece := t.Pieces[pieceIndex]
75 if piece.QueuedForHash {
78 piece.QueuedForHash = true
79 go cl.verifyPiece(t, pieceIndex)
82 func (cl *Client) queueFirstHash(t *torrent, piece int) {
84 if p.EverHashed || p.Hashing || p.QueuedForHash {
87 cl.queuePieceCheck(t, pp.Integer(piece))
90 // Queues the torrent data for the given region for download. The beginning of
91 // the region is given highest priority to allow a subsequent read at the same
92 // offset to return data ASAP.
93 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
98 return errors.New("no such active torrent")
101 return errors.New("missing metadata")
103 me.downloadStrategy.TorrentPrioritize(t, off, len_)
104 for _, cn := range t.Conns {
105 me.replenishConnRequests(t, cn)
110 type dataWait struct {
120 listener net.Listener
122 downloadStrategy DownloadStrategy
125 mu levelmu.LevelMutex
131 torrents map[InfoHash]*torrent
133 dataWaits map[*torrent][]dataWait
136 func (me *Client) ListenAddr() (addr net.Addr) {
137 for _, l := range me.listeners {
138 if addr != nil && l.Addr().String() != addr.String() {
139 panic("listeners exist on different addresses")
146 func (cl *Client) WriteStatus(w io.Writer) {
149 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
150 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
151 fmt.Fprintf(w, "Half open outgoing connections: %d\n", cl.halfOpen)
152 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
154 fmt.Fprintf(w, "DHT nodes: %d\n", cl.dHT.NumNodes())
155 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
157 cl.downloadStrategy.WriteStatus(w)
159 for _, t := range cl.torrents {
160 fmt.Fprintf(w, "%s: %f%%\n", t.Name(), func() float32 {
164 return 100 * (1 - float32(t.BytesLeft())/float32(t.Length()))
167 fmt.Fprint(w, "Blocked reads:")
168 for _, dw := range cl.dataWaits[t] {
169 fmt.Fprintf(w, " %d", dw.offset)
177 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
179 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
184 err = errors.New("unknown torrent")
187 index := pp.Integer(off / int64(t.UsualPieceSize()))
188 // Reading outside the bounds of a file is an error.
193 if int(index) >= len(t.Pieces) {
197 piece := t.Pieces[index]
198 pieceOff := pp.Integer(off % int64(t.UsualPieceSize()))
199 pieceLeft := int(t.PieceLength(index) - pieceOff)
204 if len(p) > pieceLeft {
207 for cs, _ := range piece.PendingChunkSpecs {
208 chunkOff := int64(pieceOff) - int64(cs.Begin)
209 if chunkOff >= int64(t.PieceLength(index)) {
212 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
213 // read begins in a pending chunk
214 err = ErrDataNotReady
217 // pending chunk caps available data
218 if chunkOff < 0 && int64(len(p)) > -chunkOff {
225 return t.Data.ReadAt(p, off)
228 func NewClient(cfg *Config) (cl *Client, err error) {
234 noUpload: cfg.NoUpload,
235 disableTrackers: cfg.DisableTrackers,
236 downloadStrategy: cfg.DownloadStrategy,
238 dataDir: cfg.DataDir,
240 quit: make(chan struct{}),
241 torrents: make(map[InfoHash]*torrent),
243 dataWaits: make(map[*torrent][]dataWait),
248 o := copy(cl.peerID[:], BEP20)
249 _, err = rand.Read(cl.peerID[o:])
251 panic("error generating peer id")
254 if cl.downloadStrategy == nil {
255 cl.downloadStrategy = &DefaultDownloadStrategy{}
258 cl.listener, err = net.Listen("tcp", cfg.ListenAddr)
262 if cl.listener != nil {
263 go cl.acceptConnections()
267 cl.dHT, err = dht.NewServer(&dht.ServerConfig{
268 Addr: cfg.ListenAddr,
278 func (cl *Client) stopped() bool {
287 // Stops the client. All connections to peers are closed and all activity will
289 func (me *Client) Stop() {
293 for _, t := range me.torrents {
299 func (cl *Client) acceptConnections() {
301 // We accept all connections immediately, because we don't what
302 // torrent they're for.
303 conn, err := cl.listener.Accept()
317 if err := cl.runConnection(conn, nil, peerSourceIncoming); err != nil {
324 func (me *Client) torrent(ih InfoHash) *torrent {
325 for _, t := range me.torrents {
326 if t.InfoHash == ih {
333 // Start the process of connecting to the given peer for the given torrent if
335 func (me *Client) initiateConn(peer Peer, torrent *torrent) {
336 if peer.Id == me.peerID {
339 addr := &net.TCPAddr{
343 // Don't connect to the same address twice for the same torrent.
344 for _, c := range torrent.Conns {
345 if c.Socket.RemoteAddr().String() == addr.String() {
346 duplicateConnsAvoided.Add(1)
352 // Binding to the listener address and dialing via net.Dialer gives
353 // "address in use" error. It seems it's not possible to dial out from
354 // this address so that peers associate our local address with our
356 conn, err := net.DialTimeout(addr.Network(), addr.String(), dialTimeout)
358 // Whether or not the connection attempt succeeds, the half open
359 // counter should be decremented, and new connection attempts made.
363 if me.halfOpen == 0 {
370 if netOpErr, ok := err.(*net.OpError); ok {
371 if netOpErr.Timeout() {
374 switch netOpErr.Err {
375 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
380 log.Printf("error connecting to peer: %s %#v", err, err)
383 // log.Printf("connected to %s", conn.RemoteAddr())
384 err = me.runConnection(conn, torrent, peer.Source)
391 // The port number for incoming peer connections. 0 if the client isn't
393 func (cl *Client) incomingPeerPort() int {
394 listenAddr := cl.ListenAddr()
395 if listenAddr == nil {
398 return addrPort(listenAddr)
401 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
402 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
403 func addrCompactIP(addr net.Addr) (string, error) {
404 host, _, err := net.SplitHostPort(addr.String())
408 ip := net.ParseIP(host)
409 if v4 := ip.To4(); v4 != nil {
413 return string(v4), nil
415 return string(ip.To16()), nil
418 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
430 type peerExtensionBytes [8]byte
433 type handshakeResult struct {
439 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
440 // Bytes to be sent to the peer. Should never block the sender.
441 postCh := make(chan []byte, 4)
442 // A single error value sent when the writer completes.
443 writeDone := make(chan error, 1)
444 // Performs writes to the socket and ensures posts don't block.
445 go handshakeWriter(sock, postCh, writeDone)
448 close(postCh) // Done writing.
455 // Wait until writes complete before returning from handshake.
458 err = fmt.Errorf("error writing during handshake: %s", err)
462 post := func(bb []byte) {
466 panic("mustn't block while posting")
470 post([]byte(pp.Protocol))
471 post([]byte(extensionBytes))
472 if ih != nil { // We already know what we want.
477 _, err = io.ReadFull(sock, b[:68])
482 if string(b[:20]) != pp.Protocol {
485 CopyExact(&res.peerExtensionBytes, b[20:28])
486 CopyExact(&res.InfoHash, b[28:48])
487 CopyExact(&res.peerID, b[48:68])
489 if ih == nil { // We were waiting for the peer to tell us what they wanted.
490 post(res.InfoHash[:])
498 type peerConn struct {
502 func (pc peerConn) Read(b []byte) (n int, err error) {
503 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
507 n, err = pc.Conn.Read(b)
509 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
511 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
521 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource) (err error) {
522 if tcpConn, ok := sock.(*net.TCPConn); ok {
529 // One minute to complete handshake.
530 sock.SetDeadline(time.Now().Add(time.Minute))
531 hsRes, ok, err := handshake(sock, func() *InfoHash {
535 return &torrent.InfoHash
540 if me.handshaking == 0 {
541 panic("handshake count invariant is broken")
545 err = fmt.Errorf("error during handshake: %s", err)
551 torrent = me.torrent(hsRes.InfoHash)
555 sock.SetWriteDeadline(time.Time{})
556 sock = peerConn{sock}
557 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID)
559 conn.Discovery = discovery
560 if !me.addConnection(torrent, conn) {
563 if conn.PeerExtensionBytes[5]&0x10 != 0 {
564 conn.Post(pp.Message{
566 ExtendedID: pp.HandshakeExtendedID,
567 ExtendedPayload: func() []byte {
568 d := map[string]interface{}{
573 "v": "go.torrent dev 20140825", // Just the date
574 // No upload queue is implemented yet.
577 // No need to look strange if it costs us nothing.
584 if torrent.metadataSizeKnown() {
585 d["metadata_size"] = torrent.metadataSize()
587 if p := me.incomingPeerPort(); p != 0 {
590 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
592 log.Printf("error calculating yourip field value in extension handshake: %s", err)
596 // log.Printf("sending %v", d)
597 b, err := bencode.Marshal(d)
605 if torrent.haveAnyPieces() {
606 conn.Post(pp.Message{
608 Bitfield: torrent.bitfield(),
611 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
612 addr, _ := me.dHT.LocalAddr().(*net.UDPAddr)
613 conn.Post(pp.Message{
615 Port: uint16(addr.Port),
618 err = me.connectionLoop(torrent, conn)
620 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
622 me.dropConnection(torrent, conn)
626 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
627 for piece >= len(c.PeerPieces) {
628 c.PeerPieces = append(c.PeerPieces, false)
630 c.PeerPieces[piece] = true
631 if !t.havePiece(piece) {
632 me.replenishConnRequests(t, c)
636 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
637 me.replenishConnRequests(torrent, conn)
640 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
644 cl.downloadStrategy.DeleteRequest(t, r)
649 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
650 if !cn.RequestPending(r) {
653 cl.downloadStrategy.DeleteRequest(t, r)
654 delete(cn.Requests, r)
657 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
662 for index := 0; index < t.MetadataPieceCount(); index++ {
663 if !t.HaveMetadataPiece(index) {
664 pending = append(pending, index)
667 for _, i := range mathRand.Perm(len(pending)) {
670 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
671 ExtendedPayload: func() []byte {
672 b, err := bencode.Marshal(map[string]int{
685 func (cl *Client) completedMetadata(t *torrent) {
689 CopyExact(&ih, h.Sum(nil))
690 if ih != t.InfoHash {
691 log.Print("bad metadata")
692 t.InvalidateMetadata()
695 var info metainfo.Info
696 err := bencode.Unmarshal(t.MetaData, &info)
698 log.Printf("error unmarshalling metadata: %s", err)
699 t.InvalidateMetadata()
702 // TODO(anacrolix): If this fails, I think something harsher should be
704 err = cl.setMetaData(t, info, t.MetaData)
706 log.Printf("error setting metadata: %s", err)
707 t.InvalidateMetadata()
710 log.Printf("%s: got metadata from peers", t)
713 // Process incoming ut_metadata message.
714 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
716 err = bencode.Unmarshal(payload, &d)
718 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
721 msgType, ok := d["msg_type"]
723 err = errors.New("missing msg_type field")
728 case pp.DataMetadataExtensionMsgType:
732 t.SaveMetadataPiece(piece, payload[len(payload)-metadataPieceSize(d["total_size"], piece):])
733 if !t.HaveAllMetadataPieces() {
736 cl.completedMetadata(t)
737 case pp.RequestMetadataExtensionMsgType:
738 if !t.HaveMetadataPiece(piece) {
739 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
742 start := (1 << 14) * piece
743 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
744 case pp.RejectMetadataExtensionMsgType:
746 err = errors.New("unknown msg_type value")
751 type peerExchangeMessage struct {
752 Added CompactPeers `bencode:"added"`
753 AddedFlags []byte `bencode:"added.f"`
754 Dropped []tracker.Peer `bencode:"dropped"`
757 // Extracts the port as an integer from an address string.
758 func addrPort(addr net.Addr) int {
759 _, port, err := net.SplitHostPort(addr.String())
763 i64, err := strconv.ParseInt(port, 0, 0)
770 // Processes incoming bittorrent messages. The client lock is held upon entry
772 func (me *Client) connectionLoop(t *torrent, c *connection) error {
773 decoder := pp.Decoder{
774 R: bufio.NewReaderSize(c.Socket, 20*1024),
775 MaxLength: 256 * 1024,
780 err := decoder.Decode(&msg)
782 c.lastMessageReceived = time.Now()
789 if me.stopped() || err == io.EOF {
800 for r := range c.Requests {
801 me.connDeleteRequest(t, c, r)
805 me.peerUnchoked(t, c)
807 c.PeerInterested = true
808 // TODO: This should be done from a dedicated unchoking routine.
813 case pp.NotInterested:
814 c.PeerInterested = false
817 me.peerGotPiece(t, c, int(msg.Index))
822 if c.PeerRequests == nil {
823 c.PeerRequests = make(map[request]struct{}, maxRequests)
825 request := newRequest(msg.Index, msg.Begin, msg.Length)
826 // TODO: Requests should be satisfied from a dedicated upload routine.
827 // c.PeerRequests[request] = struct{}{}
828 p := make([]byte, msg.Length)
829 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
831 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
833 if n != int(msg.Length) {
834 return fmt.Errorf("bad request: %v", msg)
842 uploadChunksPosted.Add(1)
844 req := newRequest(msg.Index, msg.Begin, msg.Length)
845 if !c.PeerCancel(req) {
846 unexpectedCancels.Add(1)
849 if c.PeerPieces != nil {
850 err = errors.New("received unexpected bitfield")
854 if len(msg.Bitfield) < t.NumPieces() {
855 err = errors.New("received invalid bitfield")
858 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
860 c.PeerPieces = msg.Bitfield
861 for index, has := range c.PeerPieces {
863 me.peerGotPiece(t, c, index)
867 err = me.downloadedChunk(t, c, &msg)
869 switch msg.ExtendedID {
870 case pp.HandshakeExtendedID:
871 // TODO: Create a bencode struct for this.
872 var d map[string]interface{}
873 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
875 err = fmt.Errorf("error decoding extended message payload: %s", err)
878 // log.Printf("got handshake: %v", d)
879 if reqq, ok := d["reqq"]; ok {
880 if i, ok := reqq.(int64); ok {
881 c.PeerMaxRequests = int(i)
884 if v, ok := d["v"]; ok {
885 c.PeerClientName = v.(string)
889 err = errors.New("handshake missing m item")
892 mTyped, ok := m.(map[string]interface{})
894 err = errors.New("handshake m value is not dict")
897 if c.PeerExtensionIDs == nil {
898 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
900 for name, v := range mTyped {
903 log.Printf("bad handshake m item extension ID type: %T", v)
907 delete(c.PeerExtensionIDs, name)
909 c.PeerExtensionIDs[name] = id
912 metadata_sizeUntyped, ok := d["metadata_size"]
914 metadata_size, ok := metadata_sizeUntyped.(int64)
916 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
918 t.SetMetadataSize(metadata_size)
921 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
922 me.requestPendingMetadata(t, c)
925 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
927 err = fmt.Errorf("error handling metadata extension message: %s", err)
930 var pexMsg peerExchangeMessage
931 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
933 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
937 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
938 for _, cp := range pexMsg.Added {
942 Source: peerSourcePEX,
944 if n := copy(p.IP, cp.IP[:]); n != 4 {
952 log.Printf("error adding PEX peers: %s", err)
955 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
958 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
961 // That client uses its own extension IDs for outgoing message
962 // types, which is incorrect.
963 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
964 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
967 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
973 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
978 pingAddr.Port = int(msg.Port)
980 _, err = me.dHT.Ping(pingAddr)
982 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
990 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
991 for r := range conn.Requests {
992 me.connDeleteRequest(torrent, conn, r)
995 for i0, c := range torrent.Conns {
999 i1 := len(torrent.Conns) - 1
1001 torrent.Conns[i0] = torrent.Conns[i1]
1003 torrent.Conns = torrent.Conns[:i1]
1006 panic("connection not found")
1009 func (me *Client) addConnection(t *torrent, c *connection) bool {
1014 case <-t.ceasingNetworking:
1018 for _, c0 := range t.Conns {
1019 if c.PeerID == c0.PeerID {
1020 // Already connected to a client with that ID.
1024 t.Conns = append(t.Conns, c)
1025 if len(t.Conns) > socketsPerTorrent {
1026 wcs := t.worstConnsHeap()
1027 heap.Pop(wcs).(*connection).Close()
1032 func (me *Client) openNewConns() {
1033 for _, t := range me.torrents {
1035 case <-t.ceasingNetworking:
1039 for len(t.Peers) != 0 {
1040 if me.halfOpen >= me.halfOpenLimit {
1043 if me.halfOpen+me.handshaking+len(t.Conns) >= socketsPerTorrent {
1050 for k, p = range t.Peers {
1054 me.initiateConn(p, t)
1059 // Adds peers to the swarm for the torrent corresponding to infoHash.
1060 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1062 defer me.mu.Unlock()
1063 t := me.torrent(infoHash)
1065 return errors.New("no such torrent")
1072 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1073 err = t.setMetadata(md, cl.dataDir, bytes)
1077 // If the client intends to upload, it needs to know what state pieces are
1080 // Queue all pieces for hashing. This is done sequentially to avoid
1081 // spamming goroutines.
1082 for _, p := range t.Pieces {
1083 p.QueuedForHash = true
1086 for i := range t.Pieces {
1087 cl.verifyPiece(t, pp.Integer(i))
1092 cl.downloadStrategy.TorrentStarted(t)
1094 case t.gotMetainfo <- &metainfo.MetaInfo{
1095 Info: metainfo.InfoEx{
1098 CreationDate: time.Now().Unix(),
1099 Comment: "metadata set in client",
1100 CreatedBy: "go.torrent",
1101 // TODO(anacrolix): Expose trackers given when torrent added.
1104 panic("shouldn't block")
1106 close(t.gotMetainfo)
1111 // Prepare a Torrent without any attachment to a Client. That means we can
1112 // initialize fields all fields that don't require the Client without locking
1114 func newTorrent(ih InfoHash, announceList [][]string) (t *torrent, err error) {
1117 Peers: make(map[peersKey]Peer, 2000),
1119 closing: make(chan struct{}),
1120 ceasingNetworking: make(chan struct{}),
1122 gotMetainfo: make(chan *metainfo.MetaInfo, 1),
1124 t.GotMetainfo = t.gotMetainfo
1125 t.Trackers = make([][]tracker.Client, len(announceList))
1126 for tierIndex := range announceList {
1127 tier := t.Trackers[tierIndex]
1128 for _, url := range announceList[tierIndex] {
1129 tr, err := tracker.New(url)
1134 tier = append(tier, tr)
1136 // The trackers within each tier must be shuffled before use.
1137 // http://stackoverflow.com/a/12267471/149482
1138 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1139 for i := range tier {
1140 j := mathRand.Intn(i + 1)
1141 tier[i], tier[j] = tier[j], tier[i]
1143 t.Trackers[tierIndex] = tier
1148 func (cl *Client) AddMagnet(uri string) (t *torrent, err error) {
1149 m, err := ParseMagnetURI(uri)
1153 t, err = newTorrent(m.InfoHash, [][]string{m.Trackers})
1157 t.DisplayName = m.DisplayName
1159 defer cl.mu.Unlock()
1160 err = cl.addTorrent(t)
1167 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1169 defer me.mu.Unlock()
1170 t, ok := me.torrents[infoHash]
1172 err = fmt.Errorf("no such torrent")
1179 delete(me.torrents, infoHash)
1180 me.downloadStrategy.TorrentStopped(t)
1181 for _, dw := range me.dataWaits[t] {
1184 delete(me.dataWaits, t)
1188 func (me *Client) addTorrent(t *torrent) (err error) {
1189 if _, ok := me.torrents[t.InfoHash]; ok {
1190 err = fmt.Errorf("torrent infohash collision")
1193 me.torrents[t.InfoHash] = t
1194 if !me.disableTrackers {
1195 go me.announceTorrent(t)
1198 go me.announceTorrentDHT(t)
1203 // Adds the torrent to the client.
1204 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (err error) {
1206 CopyExact(&ih, metaInfo.Info.Hash)
1207 t, err := newTorrent(ih, metaInfo.AnnounceList)
1212 defer me.mu.Unlock()
1213 err = me.addTorrent(t)
1217 err = me.setMetaData(t, metaInfo.Info.Info, metaInfo.Info.Bytes)
1224 func (me *Client) AddTorrentFromFile(name string) (err error) {
1225 mi, err := metainfo.LoadFromFile(name)
1227 err = fmt.Errorf("error loading metainfo from file: %s", err)
1230 return me.AddTorrent(mi)
1233 func (cl *Client) announceTorrentDHT(t *torrent) {
1235 ps, err := cl.dHT.GetPeers(string(t.InfoHash[:]))
1237 log.Printf("error getting peers from dht: %s", err)
1240 nextScrape := time.After(1 * time.Minute)
1246 case cps, ok := <-ps.Values:
1250 peersFoundByDHT.Add(int64(len(cps)))
1251 err = cl.AddPeers(t.InfoHash, func() (ret []Peer) {
1252 for _, cp := range cps {
1253 ret = append(ret, Peer{
1256 Source: peerSourceDHT,
1262 log.Printf("error adding peers from dht for torrent %q: %s", t, err)
1265 case <-t.ceasingNetworking:
1272 // After a GetPeers, we can announce on the best nodes that gave us an
1275 port := cl.incomingPeerPort()
1276 // If port is zero, then we're not listening, and there's nothing to
1279 // We can't allow the port to be implied as long as the UTP and
1280 // DHT ports are different.
1281 cl.dHT.AnnouncePeer(port, false, t.InfoHash.AsString())
1286 func (cl *Client) announceTorrent(t *torrent) {
1287 req := tracker.AnnounceRequest{
1288 Event: tracker.Started,
1290 Port: int16(cl.incomingPeerPort()),
1292 InfoHash: t.InfoHash,
1297 case <-t.ceasingNetworking:
1302 req.Left = t.BytesLeft()
1304 for _, tier := range t.Trackers {
1305 for trIndex, tr := range tier {
1306 if err := tr.Connect(); err != nil {
1310 resp, err := tr.Announce(&req)
1316 for _, peer := range resp.Peers {
1317 peers = append(peers, Peer{
1322 err = cl.AddPeers(t.InfoHash, peers)
1324 log.Printf("error adding peers to torrent %s: %s", t, err)
1326 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1328 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1329 time.Sleep(time.Second * time.Duration(resp.Interval))
1330 req.Event = tracker.None
1331 continue newAnnounce
1334 time.Sleep(5 * time.Second)
1338 func (cl *Client) allTorrentsCompleted() bool {
1339 for _, t := range cl.torrents {
1343 for e := t.IncompletePiecesByBytesLeft.Front(); e != nil; e = e.Next() {
1345 if t.Pieces[i].Complete() {
1348 // If the piece isn't complete, make sure it's not because it's
1349 // never been hashed.
1350 cl.queueFirstHash(t, i)
1357 // Returns true when all torrents are completely downloaded and false if the
1358 // client is stopped before that.
1359 func (me *Client) WaitAll() bool {
1361 defer me.mu.Unlock()
1362 for !me.allTorrentsCompleted() {
1371 func (cl *Client) assertRequestHeat() {
1372 dds, ok := cl.downloadStrategy.(*DefaultDownloadStrategy)
1376 for _, t := range cl.torrents {
1377 m := make(map[request]int, 3000)
1378 for _, cn := range t.Conns {
1379 for r := range cn.Requests {
1383 for r, h := range dds.heat[t] {
1385 panic(fmt.Sprintln(m[r], h))
1391 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
1395 for _, p := range me.downloadStrategy.FillRequests(t, c) {
1396 // Make sure the state of pieces that would have been requested is
1398 me.queueFirstHash(t, p)
1400 //me.assertRequestHeat()
1401 if len(c.Requests) == 0 && !c.PeerChoked {
1402 c.SetInterested(false)
1406 // Handle a received chunk from a peer.
1407 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
1408 chunksDownloadedCount.Add(1)
1410 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1412 // Request has been satisfied.
1413 me.connDeleteRequest(t, c, req)
1415 defer me.replenishConnRequests(t, c)
1417 // Do we actually want this chunk?
1418 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
1419 unusedDownloadedChunksCount.Add(1)
1420 c.UnwantedChunksReceived++
1424 c.UsefulChunksReceived++
1425 c.lastUsefulChunkReceived = time.Now()
1427 // Write the chunk out.
1428 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1430 return fmt.Errorf("error writing chunk: %s", err)
1433 // Record that we have the chunk.
1434 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
1435 me.dataReady(t, req)
1436 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
1437 me.queuePieceCheck(t, req.Index)
1439 t.PieceBytesLeftChanged(int(req.Index))
1441 // Unprioritize the chunk.
1442 me.downloadStrategy.TorrentGotChunk(t, req)
1444 // Cancel pending requests for this chunk.
1445 for _, c := range t.Conns {
1446 if me.connCancel(t, c, req) {
1447 me.replenishConnRequests(t, c)
1451 me.downloadStrategy.AssertNotRequested(t, req)
1456 func (cl *Client) dataReady(t *torrent, r request) {
1457 dws := cl.dataWaits[t]
1458 begin := t.requestOffset(r)
1459 end := begin + int64(r.Length)
1460 for i := 0; i < len(dws); {
1462 if begin <= dw.offset && dw.offset < end {
1464 dws[i] = dws[len(dws)-1]
1465 dws = dws[:len(dws)-1]
1470 cl.dataWaits[t] = dws
1473 // Returns a channel that is closed when new data has become available in the
1475 func (me *Client) DataWaiter(ih InfoHash, off int64) (ret <-chan struct{}) {
1477 defer me.mu.Unlock()
1478 ch := make(chan struct{})
1480 t := me.torrents[ih]
1485 if r, ok := t.offsetRequest(off); !ok || t.haveChunk(r) {
1489 me.dataWaits[t] = append(me.dataWaits[t], dataWait{
1496 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
1497 p := t.Pieces[piece]
1498 if p.EverHashed && !correct {
1499 log.Printf("%s: piece %d failed hash", t, piece)
1500 failedPieceHashes.Add(1)
1504 p.PendingChunkSpecs = nil
1505 me.downloadStrategy.TorrentGotPiece(t, int(piece))
1506 me.dataReady(t, request{
1508 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
1511 if len(p.PendingChunkSpecs) == 0 {
1512 t.pendAllChunkSpecs(piece)
1515 t.PieceBytesLeftChanged(int(piece))
1516 for _, conn := range t.Conns {
1518 conn.Post(pp.Message{
1520 Index: pp.Integer(piece),
1522 // TODO: Cancel requests for this piece.
1523 for r := range conn.Requests {
1524 if r.Index == piece {
1529 // Do this even if the piece is correct because new first-hashings may
1530 // need to be scheduled.
1531 if conn.PeerHasPiece(piece) {
1532 me.replenishConnRequests(t, conn)
1535 if t.haveAllPieces() && me.noUpload {
1538 me.event.Broadcast()
1541 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
1543 defer cl.mu.Unlock()
1544 p := t.Pieces[index]
1552 p.QueuedForHash = false
1554 sum := t.HashPiece(index)
1562 cl.pieceHashed(t, index, sum == p.Hash)
1565 func (me *Client) Torrents() (ret []*torrent) {
1567 for _, t := range me.torrents {
1568 ret = append(ret, t)