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")
34 metainfo "github.com/nsf/libtorgo/torrent"
36 "bitbucket.org/anacrolix/go.torrent/peer_protocol"
37 "bitbucket.org/anacrolix/go.torrent/tracker"
38 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
41 // Currently doesn't really queue, but should in the future.
42 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex peer_protocol.Integer) {
43 piece := t.Pieces[pieceIndex]
44 if piece.QueuedForHash {
47 piece.QueuedForHash = true
48 go cl.verifyPiece(t, pieceIndex)
51 // Queues the torrent data for the given region for download. The beginning of
52 // the region is given highest priority to allow a subsequent read at the same
53 // offset to return data ASAP.
54 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
59 return errors.New("no such active torrent")
61 newPriorities := make([]Request, 0, (len_+chunkSize-1)/chunkSize)
63 req, ok := t.offsetRequest(off)
65 return errors.New("bad offset")
67 reqOff := t.requestOffset(req)
68 // Gain the alignment adjustment.
70 // Lose the length of this block.
71 len_ -= int64(req.Length)
72 off = reqOff + int64(req.Length)
73 if !t.wantPiece(int(req.Index)) {
76 newPriorities = append(newPriorities, req)
78 if len(newPriorities) == 0 {
81 if t.Priorities == nil {
82 t.Priorities = list.New()
84 t.Priorities.PushFront(newPriorities[0])
85 for _, req := range newPriorities[1:] {
86 t.Priorities.PushBack(req)
88 for _, cn := range t.Conns {
89 me.replenishConnRequests(t, cn)
94 type dataSpec struct {
103 Listener net.Listener
111 torrents map[InfoHash]*torrent
112 dataWaiter chan struct{}
115 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
117 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
122 err = errors.New("unknown torrent")
125 index := peer_protocol.Integer(off / t.MetaInfo.PieceLength)
126 // Reading outside the bounds of a file is an error.
131 if int(index) >= len(t.Pieces) {
135 piece := t.Pieces[index]
136 if !piece.EverHashed {
137 cl.queuePieceCheck(t, index)
140 err = ErrDataNotReady
143 pieceOff := peer_protocol.Integer(off % int64(t.PieceLength(0)))
144 high := int(t.PieceLength(index) - pieceOff)
148 for cs, _ := range piece.PendingChunkSpecs {
149 chunkOff := int64(pieceOff) - int64(cs.Begin)
150 if chunkOff >= int64(t.PieceLength(index)) {
153 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
154 // read begins in a pending chunk
155 err = ErrDataNotReady
158 // pending chunk caps available data
159 if chunkOff < 0 && int64(len(p)) > -chunkOff {
163 return t.Data.ReadAt(p, off)
166 // Starts the client. Defaults are applied. The client will begin accepting connections and tracking.
167 func (c *Client) Start() {
169 c.torrents = make(map[InfoHash]*torrent)
170 if c.HalfOpenLimit == 0 {
173 o := copy(c.PeerId[:], BEP20)
174 _, err := rand.Read(c.PeerId[o:])
176 panic("error generating peer id")
178 c.quit = make(chan struct{})
179 if c.Listener != nil {
180 go c.acceptConnections()
184 func (cl *Client) stopped() bool {
193 // Stops the client. All connections to peers are closed and all activity will
195 func (me *Client) Stop() {
199 for _, t := range me.torrents {
200 for _, c := range t.Conns {
207 func (cl *Client) acceptConnections() {
209 conn, err := cl.Listener.Accept()
220 if err := cl.runConnection(conn, nil); err != nil {
227 func (me *Client) torrent(ih InfoHash) *torrent {
228 for _, t := range me.torrents {
229 if t.InfoHash == ih {
236 func (me *Client) initiateConn(peer Peer, torrent *torrent) {
237 if peer.Id == me.PeerId {
242 addr := &net.TCPAddr{
246 conn, err := net.DialTimeout(addr.Network(), addr.String(), dialTimeout)
251 if me.halfOpen == 0 {
258 if netOpErr, ok := err.(*net.OpError); ok {
259 if netOpErr.Timeout() {
262 switch netOpErr.Err {
263 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
268 log.Printf("error connecting to peer: %s %#v", err, err)
271 log.Printf("connected to %s", conn.RemoteAddr())
272 err = me.runConnection(conn, torrent)
279 func (me *Client) runConnection(sock net.Conn, torrent *torrent) (err error) {
284 write: make(chan []byte),
285 post: make(chan encoding.BinaryMarshaler),
288 // There's a lock and deferred unlock later in this function. The
289 // client will not be locked when this deferred is invoked.
295 go conn.writeOptimizer()
296 conn.post <- peer_protocol.Bytes(peer_protocol.Protocol)
297 conn.post <- peer_protocol.Bytes("\x00\x00\x00\x00\x00\x00\x00\x00")
299 conn.post <- peer_protocol.Bytes(torrent.InfoHash[:])
300 conn.post <- peer_protocol.Bytes(me.PeerId[:])
303 _, err = io.ReadFull(conn.Socket, b[:])
308 err = fmt.Errorf("when reading protocol and extensions: %s", err)
311 if string(b[:20]) != peer_protocol.Protocol {
312 err = fmt.Errorf("wrong protocol: %#v", string(b[:20]))
315 if 8 != copy(conn.PeerExtensions[:], b[20:]) {
318 // log.Printf("peer extensions: %#v", string(conn.PeerExtensions[:]))
319 var infoHash [20]byte
320 _, err = io.ReadFull(conn.Socket, infoHash[:])
322 return fmt.Errorf("reading peer info hash: %s", err)
324 _, err = io.ReadFull(conn.Socket, conn.PeerId[:])
326 return fmt.Errorf("reading peer id: %s", err)
329 torrent = me.torrent(infoHash)
333 conn.post <- peer_protocol.Bytes(torrent.InfoHash[:])
334 conn.post <- peer_protocol.Bytes(me.PeerId[:])
338 if !me.addConnection(torrent, conn) {
341 if torrent.haveAnyPieces() {
342 conn.Post(peer_protocol.Message{
343 Type: peer_protocol.Bitfield,
344 Bitfield: torrent.bitfield(),
347 err = me.connectionLoop(torrent, conn)
349 err = fmt.Errorf("during Connection loop: %s", err)
351 me.dropConnection(torrent, conn)
355 func (me *Client) peerGotPiece(torrent *torrent, conn *connection, piece int) {
356 if conn.PeerPieces == nil {
357 conn.PeerPieces = make([]bool, len(torrent.Pieces))
359 conn.PeerPieces[piece] = true
360 if torrent.wantPiece(piece) {
361 me.replenishConnRequests(torrent, conn)
365 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
366 me.replenishConnRequests(torrent, conn)
369 func (me *Client) connectionLoop(torrent *torrent, conn *connection) error {
370 decoder := peer_protocol.Decoder{
371 R: bufio.NewReader(conn.Socket),
372 MaxLength: 256 * 1024,
376 // TODO: Can this be allocated on the stack?
377 msg := new(peer_protocol.Message)
378 err := decoder.Decode(msg)
381 if me.stopped() || err == io.EOF {
390 case peer_protocol.Choke:
391 conn.PeerChoked = true
393 case peer_protocol.Unchoke:
394 conn.PeerChoked = false
395 me.peerUnchoked(torrent, conn)
396 case peer_protocol.Interested:
397 conn.PeerInterested = true
398 // TODO: This should be done from a dedicated unchoking routine.
400 case peer_protocol.NotInterested:
401 conn.PeerInterested = false
402 case peer_protocol.Have:
403 me.peerGotPiece(torrent, conn, int(msg.Index))
404 case peer_protocol.Request:
405 if conn.PeerRequests == nil {
406 conn.PeerRequests = make(map[Request]struct{}, maxRequests)
410 chunkSpec: chunkSpec{msg.Begin, msg.Length},
412 conn.PeerRequests[request] = struct{}{}
413 // TODO: Requests should be satisfied from a dedicated upload routine.
414 p := make([]byte, msg.Length)
415 n, err := torrent.Data.ReadAt(p, int64(torrent.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
417 return fmt.Errorf("reading torrent data to serve request %s: %s", request, err)
419 if n != int(msg.Length) {
420 return fmt.Errorf("bad request: %s", msg)
422 conn.Post(peer_protocol.Message{
423 Type: peer_protocol.Piece,
428 case peer_protocol.Bitfield:
429 if len(msg.Bitfield) < len(torrent.Pieces) {
430 err = errors.New("received invalid bitfield")
433 if conn.PeerPieces != nil {
434 err = errors.New("received unexpected bitfield")
437 conn.PeerPieces = msg.Bitfield[:len(torrent.Pieces)]
438 for index, has := range conn.PeerPieces {
440 me.peerGotPiece(torrent, conn, index)
443 case peer_protocol.Piece:
444 request_ := Request{msg.Index, chunkSpec{msg.Begin, peer_protocol.Integer(len(msg.Piece))}}
445 if _, ok := conn.Requests[request_]; !ok {
446 err = fmt.Errorf("unexpected piece: %s", request_)
449 delete(conn.Requests, request_)
450 err = me.downloadedChunk(torrent, msg)
452 log.Printf("received unknown message type: %#v", msg.Type)
457 me.replenishConnRequests(torrent, conn)
461 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
463 for i0, c := range torrent.Conns {
467 i1 := len(torrent.Conns) - 1
469 torrent.Conns[i0] = torrent.Conns[i1]
471 torrent.Conns = torrent.Conns[:i1]
474 panic("no such Connection")
477 func (me *Client) addConnection(t *torrent, c *connection) bool {
478 for _, c0 := range t.Conns {
479 if c.PeerId == c0.PeerId {
480 log.Printf("%s and %s have the same ID: %s", c.Socket.RemoteAddr(), c0.Socket.RemoteAddr(), c.PeerId)
484 t.Conns = append(t.Conns, c)
488 func (me *Client) openNewConns() {
489 for _, t := range me.torrents {
490 for len(t.Peers) != 0 {
491 if me.halfOpen >= me.HalfOpenLimit {
495 t.Peers = t.Peers[1:]
496 me.initiateConn(p, t)
501 // Adds peers to the swarm for the torrent corresponding to infoHash.
502 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
504 t := me.torrent(infoHash)
506 return errors.New("no such torrent")
508 t.Peers = append(t.Peers, peers...)
514 // Prepare a Torrent without any attachment to a Client. That means we can
515 // initialize fields all fields that don't require the Client without locking
517 func newTorrent(metaInfo *metainfo.MetaInfo, dataDir string) (t *torrent, err error) {
519 InfoHash: BytesInfoHash(metaInfo.InfoHash),
522 t.Data, err = mmapTorrentData(metaInfo, dataDir)
526 for offset := 0; offset < len(metaInfo.Pieces); offset += pieceHash.Size() {
527 hash := metaInfo.Pieces[offset : offset+pieceHash.Size()]
528 if len(hash) != pieceHash.Size() {
529 err = errors.New("bad piece hash in metainfo")
533 copyHashSum(piece.Hash[:], hash)
534 t.Pieces = append(t.Pieces, piece)
535 t.pendAllChunkSpecs(peer_protocol.Integer(len(t.Pieces) - 1))
537 t.Trackers = make([][]tracker.Client, len(metaInfo.AnnounceList))
538 for tierIndex := range metaInfo.AnnounceList {
539 tier := t.Trackers[tierIndex]
540 for _, url := range metaInfo.AnnounceList[tierIndex] {
541 tr, err := tracker.New(url)
546 tier = append(tier, tr)
548 // The trackers within each tier must be shuffled before use.
549 // http://stackoverflow.com/a/12267471/149482
550 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
551 for i := range tier {
552 j := mathRand.Intn(i + 1)
553 tier[i], tier[j] = tier[j], tier[i]
555 t.Trackers[tierIndex] = tier
560 // Adds the torrent to the client.
561 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) error {
562 torrent, err := newTorrent(metaInfo, me.DataDir)
568 if _, ok := me.torrents[torrent.InfoHash]; ok {
569 return torrent.Close()
571 me.torrents[torrent.InfoHash] = torrent
572 if !me.DisableTrackers {
573 go me.announceTorrent(torrent)
575 for i := range torrent.Pieces {
576 me.queuePieceCheck(torrent, peer_protocol.Integer(i))
581 func (cl *Client) listenerAnnouncePort() (port int16) {
587 switch data := addr.(type) {
589 return int16(data.Port)
591 return int16(data.Port)
593 log.Printf("unknown listener addr type: %T", addr)
598 func (cl *Client) announceTorrent(t *torrent) {
599 req := tracker.AnnounceRequest{
600 Event: tracker.Started,
602 Port: cl.listenerAnnouncePort(),
604 req.PeerId = cl.PeerId
605 req.InfoHash = t.InfoHash
608 for _, tier := range t.Trackers {
609 for trIndex, tr := range tier {
610 if err := tr.Connect(); err != nil {
614 resp, err := tr.Announce(&req)
620 for _, peer := range resp.Peers {
621 peers = append(peers, Peer{
626 if err := cl.AddPeers(t.InfoHash, peers); err != nil {
630 log.Printf("%d new peers from %s", len(peers), "TODO")
631 tier[0], tier[trIndex] = tier[trIndex], tier[0]
632 time.Sleep(time.Second * time.Duration(resp.Interval))
636 time.Sleep(time.Second)
640 func (cl *Client) allTorrentsCompleted() bool {
641 for _, t := range cl.torrents {
642 if !t.haveAllPieces() {
649 // Returns true when all torrents are completely downloaded and false if the
650 // client is stopped.
651 func (me *Client) WaitAll() bool {
654 for !me.allTorrentsCompleted() {
663 func (me *Client) replenishConnRequests(torrent *torrent, conn *connection) {
664 requestHeatMap := torrent.requestHeat()
665 addRequest := func(req Request) (again bool) {
666 piece := torrent.Pieces[req.Index]
668 // We can't be sure we want this.
671 if piece.Complete() {
672 // We already have this.
675 if requestHeatMap[req] > 0 {
676 // We've already requested this.
679 return conn.Request(req)
681 // First request prioritized chunks.
682 if torrent.Priorities != nil {
683 for e := torrent.Priorities.Front(); e != nil; e = e.Next() {
684 if !addRequest(e.Value.(Request)) {
689 // Then finish off incomplete pieces in order of bytes remaining.
690 for _, index := range torrent.piecesByPendingBytesDesc() {
691 if torrent.PieceNumPendingBytes(index) == torrent.PieceLength(index) {
694 for chunkSpec := range torrent.Pieces[index].PendingChunkSpecs {
695 if !addRequest(Request{index, chunkSpec}) {
700 if len(conn.Requests) == 0 {
701 conn.SetInterested(false)
705 func (me *Client) downloadedChunk(torrent *torrent, msg *peer_protocol.Message) (err error) {
706 request := Request{msg.Index, chunkSpec{msg.Begin, peer_protocol.Integer(len(msg.Piece))}}
707 if _, ok := torrent.Pieces[request.Index].PendingChunkSpecs[request.chunkSpec]; !ok {
708 log.Printf("got unnecessary chunk: %s", request)
711 err = torrent.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
715 delete(torrent.Pieces[request.Index].PendingChunkSpecs, request.chunkSpec)
716 if len(torrent.Pieces[request.Index].PendingChunkSpecs) == 0 {
717 me.queuePieceCheck(torrent, request.Index)
719 var next *list.Element
720 for e := torrent.Priorities.Front(); e != nil; e = next {
722 if e.Value.(Request) == request {
723 torrent.Priorities.Remove(e)
726 me.dataReady(dataSpec{torrent.InfoHash, request})
730 func (cl *Client) dataReady(ds dataSpec) {
731 if cl.dataWaiter != nil {
737 // Returns a channel that is closed when new data has become available in the
739 func (me *Client) DataWaiter() <-chan struct{} {
742 if me.dataWaiter == nil {
743 me.dataWaiter = make(chan struct{})
748 func (me *Client) pieceHashed(t *torrent, piece peer_protocol.Integer, correct bool) {
752 p.PendingChunkSpecs = nil
753 log.Printf("got piece %d, (%d/%d)", piece, t.NumPiecesCompleted(), t.NumPieces())
754 var next *list.Element
755 if t.Priorities != nil {
756 for e := t.Priorities.Front(); e != nil; e = next {
758 if e.Value.(Request).Index == piece {
759 t.Priorities.Remove(e)
763 me.dataReady(dataSpec{
766 peer_protocol.Integer(piece),
767 chunkSpec{0, peer_protocol.Integer(t.PieceLength(piece))},
771 if len(p.PendingChunkSpecs) == 0 {
772 t.pendAllChunkSpecs(piece)
775 for _, conn := range t.Conns {
777 conn.Post(peer_protocol.Message{
778 Type: peer_protocol.Have,
779 Index: peer_protocol.Integer(piece),
781 // TODO: Cancel requests for this piece.
783 if conn.PeerHasPiece(piece) {
784 me.replenishConnRequests(t, conn)
791 func (cl *Client) verifyPiece(t *torrent, index peer_protocol.Integer) {
798 p.QueuedForHash = false
800 sum := t.HashPiece(index)
803 cl.pieceHashed(t, index, sum == p.Hash)
807 func (me *Client) Torrents() (ret []*torrent) {
809 for _, t := range me.torrents {