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.Cancel:
429 req := newRequest(msg.Index, msg.Begin, msg.Length)
430 if !conn.PeerCancel(req) {
431 log.Printf("received unexpected cancel: %v", req)
433 case peer_protocol.Bitfield:
434 if len(msg.Bitfield) < len(torrent.Pieces) {
435 err = errors.New("received invalid bitfield")
438 if conn.PeerPieces != nil {
439 err = errors.New("received unexpected bitfield")
442 conn.PeerPieces = msg.Bitfield[:len(torrent.Pieces)]
443 for index, has := range conn.PeerPieces {
445 me.peerGotPiece(torrent, conn, index)
448 case peer_protocol.Piece:
449 request_ := request{msg.Index, chunkSpec{msg.Begin, peer_protocol.Integer(len(msg.Piece))}}
450 if _, ok := conn.Requests[request_]; !ok {
451 err = fmt.Errorf("unexpected piece: %s", request_)
454 delete(conn.Requests, request_)
455 err = me.downloadedChunk(torrent, msg)
457 log.Printf("received unknown message type: %#v", msg.Type)
462 me.replenishConnRequests(torrent, conn)
466 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
468 for i0, c := range torrent.Conns {
472 i1 := len(torrent.Conns) - 1
474 torrent.Conns[i0] = torrent.Conns[i1]
476 torrent.Conns = torrent.Conns[:i1]
479 panic("no such Connection")
482 func (me *Client) addConnection(t *torrent, c *connection) bool {
483 for _, c0 := range t.Conns {
484 if c.PeerId == c0.PeerId {
485 log.Printf("%s and %s have the same ID: %s", c.Socket.RemoteAddr(), c0.Socket.RemoteAddr(), c.PeerId)
489 t.Conns = append(t.Conns, c)
493 func (me *Client) openNewConns() {
494 for _, t := range me.torrents {
495 for len(t.Peers) != 0 {
496 if me.halfOpen >= me.HalfOpenLimit {
500 t.Peers = t.Peers[1:]
501 me.initiateConn(p, t)
506 // Adds peers to the swarm for the torrent corresponding to infoHash.
507 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
509 t := me.torrent(infoHash)
511 return errors.New("no such torrent")
513 t.Peers = append(t.Peers, peers...)
519 // Prepare a Torrent without any attachment to a Client. That means we can
520 // initialize fields all fields that don't require the Client without locking
522 func newTorrent(metaInfo *metainfo.MetaInfo, dataDir string) (t *torrent, err error) {
524 InfoHash: BytesInfoHash(metaInfo.InfoHash),
527 t.Data, err = mmapTorrentData(metaInfo, dataDir)
531 for offset := 0; offset < len(metaInfo.Pieces); offset += pieceHash.Size() {
532 hash := metaInfo.Pieces[offset : offset+pieceHash.Size()]
533 if len(hash) != pieceHash.Size() {
534 err = errors.New("bad piece hash in metainfo")
538 copyHashSum(piece.Hash[:], hash)
539 t.Pieces = append(t.Pieces, piece)
540 t.pendAllChunkSpecs(peer_protocol.Integer(len(t.Pieces) - 1))
542 t.Trackers = make([][]tracker.Client, len(metaInfo.AnnounceList))
543 for tierIndex := range metaInfo.AnnounceList {
544 tier := t.Trackers[tierIndex]
545 for _, url := range metaInfo.AnnounceList[tierIndex] {
546 tr, err := tracker.New(url)
551 tier = append(tier, tr)
553 // The trackers within each tier must be shuffled before use.
554 // http://stackoverflow.com/a/12267471/149482
555 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
556 for i := range tier {
557 j := mathRand.Intn(i + 1)
558 tier[i], tier[j] = tier[j], tier[i]
560 t.Trackers[tierIndex] = tier
565 // Adds the torrent to the client.
566 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) error {
567 torrent, err := newTorrent(metaInfo, me.DataDir)
573 if _, ok := me.torrents[torrent.InfoHash]; ok {
574 return torrent.Close()
576 me.torrents[torrent.InfoHash] = torrent
577 if !me.DisableTrackers {
578 go me.announceTorrent(torrent)
580 for i := range torrent.Pieces {
581 me.queuePieceCheck(torrent, peer_protocol.Integer(i))
586 func (cl *Client) listenerAnnouncePort() (port int16) {
592 switch data := addr.(type) {
594 return int16(data.Port)
596 return int16(data.Port)
598 log.Printf("unknown listener addr type: %T", addr)
603 func (cl *Client) announceTorrent(t *torrent) {
604 req := tracker.AnnounceRequest{
605 Event: tracker.Started,
607 Port: cl.listenerAnnouncePort(),
609 req.PeerId = cl.PeerId
610 req.InfoHash = t.InfoHash
613 for _, tier := range t.Trackers {
614 for trIndex, tr := range tier {
615 if err := tr.Connect(); err != nil {
619 resp, err := tr.Announce(&req)
625 for _, peer := range resp.Peers {
626 peers = append(peers, Peer{
631 if err := cl.AddPeers(t.InfoHash, peers); err != nil {
635 log.Printf("%d new peers from %s", len(peers), "TODO")
636 tier[0], tier[trIndex] = tier[trIndex], tier[0]
637 time.Sleep(time.Second * time.Duration(resp.Interval))
641 time.Sleep(time.Second)
645 func (cl *Client) allTorrentsCompleted() bool {
646 for _, t := range cl.torrents {
647 if !t.haveAllPieces() {
654 // Returns true when all torrents are completely downloaded and false if the
655 // client is stopped.
656 func (me *Client) WaitAll() bool {
659 for !me.allTorrentsCompleted() {
668 func (me *Client) replenishConnRequests(torrent *torrent, conn *connection) {
669 requestHeatMap := torrent.requestHeat()
670 addRequest := func(req request) (again bool) {
671 piece := torrent.Pieces[req.Index]
673 // We can't be sure we want this.
676 if piece.Complete() {
677 // We already have this.
680 if requestHeatMap[req] > 0 {
681 // We've already requested this.
684 return conn.Request(req)
686 // First request prioritized chunks.
687 if torrent.Priorities != nil {
688 for e := torrent.Priorities.Front(); e != nil; e = e.Next() {
689 if !addRequest(e.Value.(request)) {
694 // Then finish off incomplete pieces in order of bytes remaining.
695 for _, index := range torrent.piecesByPendingBytesDesc() {
696 if torrent.PieceNumPendingBytes(index) == torrent.PieceLength(index) {
699 for chunkSpec := range torrent.Pieces[index].PendingChunkSpecs {
700 if !addRequest(request{index, chunkSpec}) {
705 if len(conn.Requests) == 0 {
706 conn.SetInterested(false)
710 func (me *Client) downloadedChunk(torrent *torrent, msg *peer_protocol.Message) (err error) {
711 req := request{msg.Index, chunkSpec{msg.Begin, peer_protocol.Integer(len(msg.Piece))}}
712 if _, ok := torrent.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
713 log.Printf("got unnecessary chunk: %s", req)
716 err = torrent.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
720 delete(torrent.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
721 if len(torrent.Pieces[req.Index].PendingChunkSpecs) == 0 {
722 me.queuePieceCheck(torrent, req.Index)
724 var next *list.Element
725 for e := torrent.Priorities.Front(); e != nil; e = next {
727 if e.Value.(request) == req {
728 torrent.Priorities.Remove(e)
731 me.dataReady(dataSpec{torrent.InfoHash, req})
735 func (cl *Client) dataReady(ds dataSpec) {
736 if cl.dataWaiter != nil {
742 // Returns a channel that is closed when new data has become available in the
744 func (me *Client) DataWaiter() <-chan struct{} {
747 if me.dataWaiter == nil {
748 me.dataWaiter = make(chan struct{})
753 func (me *Client) pieceHashed(t *torrent, piece peer_protocol.Integer, correct bool) {
757 p.PendingChunkSpecs = nil
758 log.Printf("got piece %d, (%d/%d)", piece, t.NumPiecesCompleted(), t.NumPieces())
759 var next *list.Element
760 if t.Priorities != nil {
761 for e := t.Priorities.Front(); e != nil; e = next {
763 if e.Value.(request).Index == piece {
764 t.Priorities.Remove(e)
768 me.dataReady(dataSpec{
771 peer_protocol.Integer(piece),
772 chunkSpec{0, peer_protocol.Integer(t.PieceLength(piece))},
776 if len(p.PendingChunkSpecs) == 0 {
777 t.pendAllChunkSpecs(piece)
780 for _, conn := range t.Conns {
782 conn.Post(peer_protocol.Message{
783 Type: peer_protocol.Have,
784 Index: peer_protocol.Integer(piece),
786 // TODO: Cancel requests for this piece.
788 if conn.PeerHasPiece(piece) {
789 me.replenishConnRequests(t, conn)
796 func (cl *Client) verifyPiece(t *torrent, index peer_protocol.Integer) {
803 p.QueuedForHash = false
805 sum := t.HashPiece(index)
808 cl.pieceHashed(t, index, sum == p.Hash)
812 func (me *Client) Torrents() (ret []*torrent) {
814 for _, t := range me.torrents {