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")
40 "github.com/h2so5/utp"
42 "github.com/anacrolix/libtorgo/bencode"
43 "github.com/anacrolix/libtorgo/metainfo"
45 "bitbucket.org/anacrolix/go.torrent/dht"
46 "bitbucket.org/anacrolix/go.torrent/iplist"
47 pp "bitbucket.org/anacrolix/go.torrent/peer_protocol"
48 "bitbucket.org/anacrolix/go.torrent/tracker"
49 _ "bitbucket.org/anacrolix/go.torrent/tracker/udp"
50 . "bitbucket.org/anacrolix/go.torrent/util"
54 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
55 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
56 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
57 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
58 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
59 unexpectedCancels = expvar.NewInt("unexpectedCancels")
60 postedCancels = expvar.NewInt("postedCancels")
61 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
62 failedPieceHashes = expvar.NewInt("failedPieceHashes")
63 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
64 successfulDials = expvar.NewInt("successfulDials")
65 acceptedConns = expvar.NewInt("acceptedConns")
66 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
70 // Justification for set bits follows.
72 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html
73 // DHT: http://www.bittorrent.org/beps/bep_0005.html
74 extensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
76 socketsPerTorrent = 40
79 // Currently doesn't really queue, but should in the future.
80 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
81 piece := t.Pieces[pieceIndex]
82 if piece.QueuedForHash {
85 piece.QueuedForHash = true
86 go cl.verifyPiece(t, pieceIndex)
89 func (cl *Client) queueFirstHash(t *torrent, piece int) {
91 if p.EverHashed || p.Hashing || p.QueuedForHash {
94 cl.queuePieceCheck(t, pp.Integer(piece))
97 // Queues the torrent data for the given region for download. The beginning of
98 // the region is given highest priority to allow a subsequent read at the same
99 // offset to return data ASAP.
100 func (me *Client) PrioritizeDataRegion(ih InfoHash, off, len_ int64) error {
105 return errors.New("no such active torrent")
108 return errors.New("missing metadata")
110 firstIndex := int(off / int64(t.UsualPieceSize()))
111 for i := 0; i < 5; i++ {
112 index := firstIndex + i
113 if index >= t.NumPieces() {
116 me.queueFirstHash(t, index)
118 me.downloadStrategy.TorrentPrioritize(t, off, len_)
119 for _, cn := range t.Conns {
120 me.replenishConnRequests(t, cn)
126 type dataWait struct {
136 listeners []net.Listener
138 downloadStrategy DownloadStrategy
141 ipBlockList *iplist.IPList
142 bannedTorrents map[InfoHash]struct{}
150 torrents map[InfoHash]*torrent
152 dataWaits map[*torrent][]dataWait
155 func (me *Client) SetIPBlockList(list *iplist.IPList) {
158 me.ipBlockList = list
160 me.dHT.SetIPBlockList(list)
164 func (me *Client) PeerID() string {
165 return string(me.peerID[:])
168 func (me *Client) ListenAddr() (addr net.Addr) {
169 for _, l := range me.listeners {
170 if addr != nil && l.Addr().String() != addr.String() {
171 panic("listeners exist on different addresses")
178 type hashSorter struct {
182 func (me hashSorter) Len() int {
183 return len(me.Hashes)
186 func (me hashSorter) Less(a, b int) bool {
187 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
190 func (me hashSorter) Swap(a, b int) {
191 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
194 func (cl *Client) sortedTorrents() (ret []*torrent) {
196 for ih := range cl.torrents {
197 hs.Hashes = append(hs.Hashes, ih)
200 for _, ih := range hs.Hashes {
201 ret = append(ret, cl.torrent(ih))
206 func (cl *Client) WriteStatus(_w io.Writer) {
208 defer cl.mu.RUnlock()
209 w := bufio.NewWriter(_w)
211 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
212 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
213 fmt.Fprintf(w, "Handshaking: %d\n", cl.handshaking)
215 fmt.Fprintf(w, "DHT nodes: %d\n", cl.dHT.NumNodes())
216 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
217 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
218 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
220 cl.downloadStrategy.WriteStatus(w)
222 for _, t := range cl.sortedTorrents() {
224 fmt.Fprint(w, "<unknown name>")
226 fmt.Fprint(w, t.Name())
229 fmt.Fprintf(w, ": %f%% of %d bytes", 100*(1-float32(t.BytesLeft())/float32(t.Length())), t.Length())
232 fmt.Fprint(w, "Blocked reads:")
233 for _, dw := range cl.dataWaits[t] {
234 fmt.Fprintf(w, " %d", dw.offset)
242 // Read torrent data at the given offset. Returns ErrDataNotReady if the data
244 func (cl *Client) TorrentReadAt(ih InfoHash, off int64, p []byte) (n int, err error) {
246 defer cl.mu.RUnlock()
249 err = errors.New("unknown torrent")
252 index := pp.Integer(off / int64(t.UsualPieceSize()))
253 // Reading outside the bounds of a file is an error.
258 if int(index) >= len(t.Pieces) {
262 piece := t.Pieces[index]
263 pieceOff := pp.Integer(off % int64(t.UsualPieceSize()))
264 pieceLeft := int(t.PieceLength(index) - pieceOff)
269 if len(p) > pieceLeft {
272 for cs, _ := range piece.PendingChunkSpecs {
273 chunkOff := int64(pieceOff) - int64(cs.Begin)
274 if chunkOff >= int64(t.PieceLength(index)) {
277 if 0 <= chunkOff && chunkOff < int64(cs.Length) {
278 // read begins in a pending chunk
279 err = ErrDataNotReady
282 // pending chunk caps available data
283 if chunkOff < 0 && int64(len(p)) > -chunkOff {
290 return t.Data.ReadAt(p, off)
293 func (cl *Client) configDir() string {
294 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
297 func (cl *Client) setEnvBlocklist() (err error) {
298 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
299 defaultBlocklist := filename == ""
300 if defaultBlocklist {
301 filename = filepath.Join(cl.configDir(), "blocklist")
303 f, err := os.Open(filename)
305 if defaultBlocklist {
311 var ranges []iplist.Range
312 scanner := bufio.NewScanner(f)
314 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Text())
316 err = fmt.Errorf("error reading torrent blocklist line: %s", lineErr)
322 ranges = append(ranges, r)
326 err = fmt.Errorf("error reading torrent blocklist: %s", err)
329 cl.ipBlockList = iplist.New(ranges)
333 func (cl *Client) initBannedTorrents() error {
334 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
336 if os.IsNotExist(err) {
339 return fmt.Errorf("error opening banned infohashes file: %s", err)
342 scanner := bufio.NewScanner(f)
343 cl.bannedTorrents = make(map[InfoHash]struct{})
346 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
348 return fmt.Errorf("error reading infohash: %s", err)
354 return errors.New("bad infohash")
358 cl.bannedTorrents[ih] = struct{}{}
360 if err := scanner.Err(); err != nil {
361 return fmt.Errorf("error scanning file: %s", err)
366 func NewClient(cfg *Config) (cl *Client, err error) {
372 noUpload: cfg.NoUpload,
373 disableTrackers: cfg.DisableTrackers,
374 downloadStrategy: cfg.DownloadStrategy,
375 halfOpenLimit: socketsPerTorrent,
376 dataDir: cfg.DataDir,
377 disableUTP: cfg.DisableUTP,
379 quit: make(chan struct{}),
380 torrents: make(map[InfoHash]*torrent),
382 dataWaits: make(map[*torrent][]dataWait),
386 if !cfg.NoDefaultBlocklist {
387 err = cl.setEnvBlocklist()
393 if err = cl.initBannedTorrents(); err != nil {
394 err = fmt.Errorf("error initing banned torrents: %s", err)
398 if cfg.PeerID != "" {
399 CopyExact(&cl.peerID, cfg.PeerID)
401 o := copy(cl.peerID[:], BEP20)
402 _, err = rand.Read(cl.peerID[o:])
404 panic("error generating peer id")
408 if cl.downloadStrategy == nil {
409 cl.downloadStrategy = &DefaultDownloadStrategy{}
412 // Returns the laddr string to listen on for the next Listen call.
413 listenAddr := func() string {
414 if addr := cl.ListenAddr(); addr != nil {
417 if cfg.ListenAddr == "" {
420 return cfg.ListenAddr
424 l, err = net.Listen("tcp", listenAddr())
428 cl.listeners = append(cl.listeners, l)
429 go cl.acceptConnections(l, false)
431 var utpL *utp.UTPListener
433 utpL, err = utp.Listen("utp", listenAddr())
437 cl.listeners = append(cl.listeners, utpL)
438 go cl.acceptConnections(utpL, true)
441 dhtCfg := cfg.DHTConfig
443 dhtCfg = &dht.ServerConfig{}
445 if dhtCfg.Addr == "" {
446 dhtCfg.Addr = listenAddr()
448 if dhtCfg.Conn == nil && utpL != nil {
449 dhtCfg.Conn = utpL.RawConn
451 cl.dHT, err = dht.NewServer(dhtCfg)
452 if cl.ipBlockList != nil {
453 cl.dHT.SetIPBlockList(cl.ipBlockList)
463 func (cl *Client) stopped() bool {
472 // Stops the client. All connections to peers are closed and all activity will
474 func (me *Client) Stop() {
477 for _, l := range me.listeners {
481 for _, t := range me.torrents {
487 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
489 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
490 if cl.ipBlockList == nil {
495 log.Printf("saw non-IPv4 address")
499 r = cl.ipBlockList.Lookup(ip)
503 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
505 // We accept all connections immediately, because we don't know what
506 // torrent they're for.
507 conn, err := l.Accept()
522 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
524 if blockRange != nil {
525 inboundConnsBlocked.Add(1)
526 log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
530 if err := cl.runConnection(conn, nil, peerSourceIncoming, utp); err != nil {
537 func (me *Client) torrent(ih InfoHash) *torrent {
538 for _, t := range me.torrents {
539 if t.InfoHash == ih {
546 type dialResult struct {
551 func doDial(dial func() (net.Conn, error), ch chan dialResult, utp bool) {
554 conn = nil // Pedantic
556 ch <- dialResult{conn, utp}
558 successfulDials.Add(1)
561 unsuccessfulDials.Add(1)
562 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
565 if netOpErr, ok := err.(*net.OpError); ok {
566 switch netOpErr.Err {
567 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
572 log.Printf("error connecting to peer: %s %#v", err, err)
577 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
578 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
579 if ret < minDialTimeout {
585 // Start the process of connecting to the given peer for the given torrent if
587 func (me *Client) initiateConn(peer Peer, t *torrent) {
588 if peer.Id == me.peerID {
591 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
592 if t.addrActive(addr) {
593 duplicateConnsAvoided.Add(1)
596 if r := me.ipBlockRange(peer.IP); r != nil {
597 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
600 dialTimeout := reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
601 t.HalfOpen[addr] = struct{}{}
603 // Binding to the listen address and dialing via net.Dialer gives
604 // "address in use" error. It seems it's not possible to dial out from
605 // this address so that peers associate our local address with our
608 // Initiate connections via TCP and UTP simultaneously. Use the first
609 // one that succeeds.
614 resCh := make(chan dialResult, left)
616 go doDial(func() (net.Conn, error) {
617 return (&utp.Dialer{Timeout: dialTimeout}).Dial("utp", addr)
620 go doDial(func() (net.Conn, error) {
621 // time.Sleep(time.Second) // Give uTP a bit of a head start.
622 return net.DialTimeout("tcp", addr, dialTimeout)
625 for ; left > 0 && res.Conn == nil; left-- {
628 // Whether or not the connection attempt succeeds, the half open
629 // counter should be decremented, and new connection attempts made.
633 if _, ok := t.HalfOpen[addr]; !ok {
634 panic("invariant broken")
636 delete(t.HalfOpen, addr)
644 for ; left > 0; left-- {
645 conn := (<-resCh).Conn
653 // log.Printf("connected to %s", conn.RemoteAddr())
654 err := me.runConnection(res.Conn, t, peer.Source, res.UTP)
661 // The port number for incoming peer connections. 0 if the client isn't
663 func (cl *Client) incomingPeerPort() int {
664 listenAddr := cl.ListenAddr()
665 if listenAddr == nil {
668 return addrPort(listenAddr)
671 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
672 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
673 func addrCompactIP(addr net.Addr) (string, error) {
674 host, _, err := net.SplitHostPort(addr.String())
678 ip := net.ParseIP(host)
679 if v4 := ip.To4(); v4 != nil {
683 return string(v4), nil
685 return string(ip.To16()), nil
688 func handshakeWriter(w io.WriteCloser, bb <-chan []byte, done chan<- error) {
700 type peerExtensionBytes [8]byte
703 type handshakeResult struct {
709 func handshake(sock io.ReadWriteCloser, ih *InfoHash, peerID [20]byte) (res handshakeResult, ok bool, err error) {
710 // Bytes to be sent to the peer. Should never block the sender.
711 postCh := make(chan []byte, 4)
712 // A single error value sent when the writer completes.
713 writeDone := make(chan error, 1)
714 // Performs writes to the socket and ensures posts don't block.
715 go handshakeWriter(sock, postCh, writeDone)
718 close(postCh) // Done writing.
725 // Wait until writes complete before returning from handshake.
728 err = fmt.Errorf("error writing during handshake: %s", err)
732 post := func(bb []byte) {
736 panic("mustn't block while posting")
740 post([]byte(pp.Protocol))
741 post([]byte(extensionBytes))
742 if ih != nil { // We already know what we want.
747 _, err = io.ReadFull(sock, b[:68])
752 if string(b[:20]) != pp.Protocol {
755 CopyExact(&res.peerExtensionBytes, b[20:28])
756 CopyExact(&res.InfoHash, b[28:48])
757 CopyExact(&res.peerID, b[48:68])
759 if ih == nil { // We were waiting for the peer to tell us what they wanted.
760 post(res.InfoHash[:])
768 type peerConn struct {
772 func (pc peerConn) Read(b []byte) (n int, err error) {
773 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
774 err = pc.Conn.SetReadDeadline(time.Now().Add(150 * time.Second))
778 n, err = pc.Conn.Read(b)
780 if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
782 } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
792 func (me *Client) runConnection(sock net.Conn, torrent *torrent, discovery peerSource, uTP bool) (err error) {
793 if tcpConn, ok := sock.(*net.TCPConn); ok {
800 // One minute to complete handshake.
801 sock.SetDeadline(time.Now().Add(time.Minute))
802 hsRes, ok, err := handshake(sock, func() *InfoHash {
806 return &torrent.InfoHash
811 if me.handshaking == 0 {
812 panic("handshake count invariant is broken")
816 err = fmt.Errorf("error during handshake: %s", err)
822 if hsRes.peerID == me.peerID {
825 torrent = me.torrent(hsRes.InfoHash)
829 sock.SetWriteDeadline(time.Time{})
830 sock = peerConn{sock}
831 conn := newConnection(sock, hsRes.peerExtensionBytes, hsRes.peerID, uTP)
833 conn.Discovery = discovery
834 if !me.addConnection(torrent, conn) {
837 if conn.PeerExtensionBytes[5]&0x10 != 0 {
838 conn.Post(pp.Message{
840 ExtendedID: pp.HandshakeExtendedID,
841 ExtendedPayload: func() []byte {
842 d := map[string]interface{}{
847 "v": "go.torrent dev 20140825", // Just the date
848 // No upload queue is implemented yet.
851 // No need to look strange if it costs us nothing.
858 if torrent.metadataSizeKnown() {
859 d["metadata_size"] = torrent.metadataSize()
861 if p := me.incomingPeerPort(); p != 0 {
864 yourip, err := addrCompactIP(conn.Socket.RemoteAddr())
866 log.Printf("error calculating yourip field value in extension handshake: %s", err)
870 // log.Printf("sending %v", d)
871 b, err := bencode.Marshal(d)
879 if torrent.haveAnyPieces() {
880 conn.Post(pp.Message{
882 Bitfield: torrent.bitfield(),
885 if conn.PeerExtensionBytes[7]&0x01 != 0 && me.dHT != nil {
886 addr, _ := me.dHT.LocalAddr().(*net.UDPAddr)
887 conn.Post(pp.Message{
889 Port: uint16(addr.Port),
892 if torrent.haveInfo() {
893 conn.initPieceOrder(torrent.NumPieces())
895 err = me.connectionLoop(torrent, conn)
897 err = fmt.Errorf("during Connection loop with peer %q: %s", conn.PeerID, err)
899 me.dropConnection(torrent, conn)
903 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
904 for piece >= len(c.PeerPieces) {
905 c.PeerPieces = append(c.PeerPieces, false)
907 c.PeerPieces[piece] = true
908 if t.wantPiece(piece) {
909 me.replenishConnRequests(t, c)
913 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
914 me.replenishConnRequests(torrent, conn)
917 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
921 cl.downloadStrategy.DeleteRequest(t, r)
926 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
927 if !cn.RequestPending(r) {
930 cl.downloadStrategy.DeleteRequest(t, r)
931 delete(cn.Requests, r)
934 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
939 for index := 0; index < t.MetadataPieceCount(); index++ {
940 if !t.HaveMetadataPiece(index) {
941 pending = append(pending, index)
944 for _, i := range mathRand.Perm(len(pending)) {
947 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
948 ExtendedPayload: func() []byte {
949 b, err := bencode.Marshal(map[string]int{
962 func (cl *Client) completedMetadata(t *torrent) {
966 CopyExact(&ih, h.Sum(nil))
967 if ih != t.InfoHash {
968 log.Print("bad metadata")
969 t.InvalidateMetadata()
972 var info metainfo.Info
973 err := bencode.Unmarshal(t.MetaData, &info)
975 log.Printf("error unmarshalling metadata: %s", err)
976 t.InvalidateMetadata()
979 // TODO(anacrolix): If this fails, I think something harsher should be
981 err = cl.setMetaData(t, info, t.MetaData)
983 log.Printf("error setting metadata: %s", err)
984 t.InvalidateMetadata()
987 log.Printf("%s: got metadata from peers", t)
990 // Process incoming ut_metadata message.
991 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
993 err = bencode.Unmarshal(payload, &d)
995 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
998 msgType, ok := d["msg_type"]
1000 err = errors.New("missing msg_type field")
1005 case pp.DataMetadataExtensionMsgType:
1009 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1010 if begin < 0 || begin >= len(payload) {
1011 log.Printf("got bad metadata piece")
1014 t.SaveMetadataPiece(piece, payload[begin:])
1015 c.UsefulChunksReceived++
1016 c.lastUsefulChunkReceived = time.Now()
1017 if !t.HaveAllMetadataPieces() {
1020 cl.completedMetadata(t)
1021 case pp.RequestMetadataExtensionMsgType:
1022 if !t.HaveMetadataPiece(piece) {
1023 c.Post(t.NewMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1026 start := (1 << 14) * piece
1027 c.Post(t.NewMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1028 case pp.RejectMetadataExtensionMsgType:
1030 err = errors.New("unknown msg_type value")
1035 type peerExchangeMessage struct {
1036 Added CompactPeers `bencode:"added"`
1037 AddedFlags []byte `bencode:"added.f"`
1038 Dropped []tracker.Peer `bencode:"dropped"`
1041 // Extracts the port as an integer from an address string.
1042 func addrPort(addr net.Addr) int {
1043 return AddrPort(addr)
1046 // Processes incoming bittorrent messages. The client lock is held upon entry
1048 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1049 decoder := pp.Decoder{
1050 R: bufio.NewReader(c.Socket),
1051 MaxLength: 256 * 1024,
1056 err := decoder.Decode(&msg)
1058 c.lastMessageReceived = time.Now()
1065 if me.stopped() || err == io.EOF {
1076 for r := range c.Requests {
1077 me.connDeleteRequest(t, c, r)
1080 c.PeerChoked = false
1081 me.peerUnchoked(t, c)
1083 c.PeerInterested = true
1084 // TODO: This should be done from a dedicated unchoking routine.
1089 case pp.NotInterested:
1090 c.PeerInterested = false
1093 me.peerGotPiece(t, c, int(msg.Index))
1098 if c.PeerRequests == nil {
1099 c.PeerRequests = make(map[request]struct{}, maxRequests)
1101 request := newRequest(msg.Index, msg.Begin, msg.Length)
1102 // TODO: Requests should be satisfied from a dedicated upload routine.
1103 // c.PeerRequests[request] = struct{}{}
1104 p := make([]byte, msg.Length)
1105 n, err := t.Data.ReadAt(p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1107 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1109 if n != int(msg.Length) {
1110 return fmt.Errorf("bad request: %v", msg)
1118 uploadChunksPosted.Add(1)
1120 req := newRequest(msg.Index, msg.Begin, msg.Length)
1121 if !c.PeerCancel(req) {
1122 unexpectedCancels.Add(1)
1125 if c.PeerPieces != nil {
1126 err = errors.New("received unexpected bitfield")
1130 if len(msg.Bitfield) < t.NumPieces() {
1131 err = errors.New("received invalid bitfield")
1134 msg.Bitfield = msg.Bitfield[:t.NumPieces()]
1136 c.PeerPieces = msg.Bitfield
1137 for index, has := range c.PeerPieces {
1139 me.peerGotPiece(t, c, index)
1143 err = me.downloadedChunk(t, c, &msg)
1145 switch msg.ExtendedID {
1146 case pp.HandshakeExtendedID:
1147 // TODO: Create a bencode struct for this.
1148 var d map[string]interface{}
1149 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1151 err = fmt.Errorf("error decoding extended message payload: %s", err)
1154 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1155 if reqq, ok := d["reqq"]; ok {
1156 if i, ok := reqq.(int64); ok {
1157 c.PeerMaxRequests = int(i)
1160 if v, ok := d["v"]; ok {
1161 c.PeerClientName = v.(string)
1165 err = errors.New("handshake missing m item")
1168 mTyped, ok := m.(map[string]interface{})
1170 err = errors.New("handshake m value is not dict")
1173 if c.PeerExtensionIDs == nil {
1174 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1176 for name, v := range mTyped {
1179 log.Printf("bad handshake m item extension ID type: %T", v)
1183 delete(c.PeerExtensionIDs, name)
1185 c.PeerExtensionIDs[name] = id
1188 metadata_sizeUntyped, ok := d["metadata_size"]
1190 metadata_size, ok := metadata_sizeUntyped.(int64)
1192 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1194 t.SetMetadataSize(metadata_size)
1197 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1198 me.requestPendingMetadata(t, c)
1201 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1203 err = fmt.Errorf("error handling metadata extension message: %s", err)
1206 var pexMsg peerExchangeMessage
1207 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1209 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1213 err := me.AddPeers(t.InfoHash, func() (ret []Peer) {
1214 for _, cp := range pexMsg.Added {
1216 IP: make([]byte, 4),
1218 Source: peerSourcePEX,
1220 if n := copy(p.IP, cp.IP[:]); n != 4 {
1223 ret = append(ret, p)
1228 log.Printf("error adding PEX peers: %s", err)
1231 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1234 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1237 // That client uses its own extension IDs for outgoing message
1238 // types, which is incorrect.
1239 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1240 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1243 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1249 pingAddr, err := net.ResolveUDPAddr("", c.Socket.RemoteAddr().String())
1254 pingAddr.Port = int(msg.Port)
1256 _, err = me.dHT.Ping(pingAddr)
1258 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1266 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1267 for r := range conn.Requests {
1268 me.connDeleteRequest(torrent, conn, r)
1271 for i0, c := range torrent.Conns {
1275 i1 := len(torrent.Conns) - 1
1277 torrent.Conns[i0] = torrent.Conns[i1]
1279 torrent.Conns = torrent.Conns[:i1]
1280 me.openNewConns(torrent)
1283 panic("connection not found")
1286 func (me *Client) addConnection(t *torrent, c *connection) bool {
1291 case <-t.ceasingNetworking:
1295 for _, c0 := range t.Conns {
1296 if c.PeerID == c0.PeerID {
1297 // Already connected to a client with that ID.
1301 t.Conns = append(t.Conns, c)
1302 // TODO: This should probably be done by a routine that kills off bad
1303 // connections, and extra connections killed here instead.
1304 if len(t.Conns) > socketsPerTorrent {
1305 wcs := t.worstConnsHeap()
1306 heap.Pop(wcs).(*connection).Close()
1311 func (me *Client) openNewConns(t *torrent) {
1313 case <-t.ceasingNetworking:
1317 if t.haveInfo() && !me.downloadStrategy.PendingData(t) {
1320 for len(t.Peers) != 0 {
1321 if len(t.Conns) >= socketsPerTorrent {
1324 if len(t.HalfOpen)+me.handshaking >= me.halfOpenLimit {
1331 for k, p = range t.Peers {
1335 me.initiateConn(p, t)
1337 t.wantPeers.Broadcast()
1340 // Adds peers to the swarm for the torrent corresponding to infoHash.
1341 func (me *Client) AddPeers(infoHash InfoHash, peers []Peer) error {
1343 defer me.mu.Unlock()
1344 t := me.torrent(infoHash)
1346 return errors.New("no such torrent")
1349 for i, p := range peers {
1350 if me.ipBlockRange(p.IP) == nil {
1353 peers[i] = peers[len(peers)-1]
1354 peers = peers[:len(peers)-1]
1359 log.Printf("IP blocklist screened %d peers from being added", blocked)
1366 func (cl *Client) torrentFileCachePath(ih InfoHash) string {
1367 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1370 func (cl *Client) saveTorrentFile(t *torrent) error {
1371 path := cl.torrentFileCachePath(t.InfoHash)
1372 os.MkdirAll(filepath.Dir(path), 0777)
1373 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1375 return fmt.Errorf("error opening file: %s", err)
1378 e := bencode.NewEncoder(f)
1379 err = e.Encode(t.MetaInfo())
1381 return fmt.Errorf("error marshalling metainfo: %s", err)
1383 mi, _ := cl.torrentCacheMetaInfo(t.InfoHash)
1384 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1385 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1390 func (cl *Client) setMetaData(t *torrent, md metainfo.Info, bytes []byte) (err error) {
1391 err = t.setMetadata(md, cl.dataDir, bytes)
1395 // If the client intends to upload, it needs to know what state pieces are
1398 // Queue all pieces for hashing. This is done sequentially to avoid
1399 // spamming goroutines.
1400 for _, p := range t.Pieces {
1401 p.QueuedForHash = true
1404 for i := range t.Pieces {
1405 cl.verifyPiece(t, pp.Integer(i))
1410 cl.downloadStrategy.TorrentStarted(t)
1411 // TODO(anacrolix): I think this should be made available as a method, the
1412 // channel only acts as a signal that the metadata has become available.
1414 // case t.gotMetainfo <- &metainfo.MetaInfo{
1415 // Info: metainfo.InfoEx{
1418 // CreationDate: time.Now().Unix(),
1419 // Comment: "metadata set in client",
1420 // CreatedBy: "go.torrent",
1421 // // TODO(anacrolix): Expose trackers given when torrent added.
1424 // panic("shouldn't block")
1426 if err := cl.saveTorrentFile(t); err != nil {
1427 log.Printf("error saving torrent file for %s: %s", t, err)
1429 close(t.gotMetainfo)
1430 // t.gotMetainfo = nil
1434 // Prepare a Torrent without any attachment to a Client. That means we can
1435 // initialize fields all fields that don't require the Client without locking
1437 func newTorrent(ih InfoHash, announceList [][]string, halfOpenLimit int) (t *torrent, err error) {
1440 Peers: make(map[peersKey]Peer, 2000),
1442 closing: make(chan struct{}),
1443 ceasingNetworking: make(chan struct{}),
1445 gotMetainfo: make(chan struct{}),
1447 HalfOpen: make(map[string]struct{}, halfOpenLimit),
1449 t.wantPeers.L = &t.stateMu
1450 t.GotMetainfo = t.gotMetainfo
1451 t.addTrackers(announceList)
1456 // For shuffling the tracker tiers.
1457 mathRand.Seed(time.Now().Unix())
1460 // The trackers within each tier must be shuffled before use.
1461 // http://stackoverflow.com/a/12267471/149482
1462 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1463 func shuffleTier(tier []tracker.Client) {
1464 for i := range tier {
1465 j := mathRand.Intn(i + 1)
1466 tier[i], tier[j] = tier[j], tier[i]
1470 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1471 for _, tier := range base {
1472 copy = append(copy, append([]tracker.Client{}, tier...))
1477 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1479 for _, url := range newURLs {
1480 for _, tr := range tier {
1481 if tr.URL() == url {
1485 tr, err := tracker.New(url)
1487 log.Printf("error creating tracker client for %q: %s", url, err)
1490 tier = append(tier, tr)
1495 func (t *torrent) addTrackers(announceList [][]string) {
1496 newTrackers := copyTrackers(t.Trackers)
1497 for tierIndex, tier := range announceList {
1498 if tierIndex < len(newTrackers) {
1499 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1501 newTrackers = append(newTrackers, mergeTier(nil, tier))
1503 shuffleTier(newTrackers[tierIndex])
1505 t.Trackers = newTrackers
1508 type Torrent struct {
1513 func (t Torrent) AddPeers(pp []Peer) error {
1514 return t.cl.AddPeers(t.torrent.InfoHash, pp)
1517 func (t Torrent) DownloadAll() {
1519 for i := 0; i < t.NumPieces(); i++ {
1520 t.cl.queueFirstHash(t.torrent, i)
1525 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
1526 err = me.cl.PrioritizeDataRegion(me.InfoHash, off, int64(len(p)))
1528 err = fmt.Errorf("error prioritizing: %s", err)
1531 <-me.cl.DataWaiter(me.InfoHash, off)
1532 return me.cl.TorrentReadAt(me.InfoHash, off, p)
1535 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1536 f, err := os.Open(cl.torrentFileCachePath(ih))
1538 if os.IsNotExist(err) {
1544 dec := bencode.NewDecoder(f)
1545 err = dec.Decode(&mi)
1549 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1550 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1556 func (cl *Client) AddMagnet(uri string) (T Torrent, err error) {
1557 m, err := ParseMagnetURI(uri)
1561 mi, err := cl.torrentCacheMetaInfo(m.InfoHash)
1563 log.Printf("error getting cached metainfo for %x: %s", m.InfoHash[:], err)
1564 } else if mi != nil {
1568 defer cl.mu.Unlock()
1569 T, err = cl.addOrMergeTorrent(m.InfoHash, [][]string{m.Trackers})
1573 if m.DisplayName != "" {
1574 T.DisplayName = m.DisplayName
1579 func (cl *Client) connectionPruner(t *torrent) {
1581 time.Sleep(15 * time.Second)
1583 license := len(t.Conns) - (socketsPerTorrent+1)/2
1584 for _, c := range t.Conns {
1588 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
1591 if time.Now().Sub(c.completedHandshake) < time.Minute {
1601 func (me *Client) DropTorrent(infoHash InfoHash) (err error) {
1603 defer me.mu.Unlock()
1604 t, ok := me.torrents[infoHash]
1606 err = fmt.Errorf("no such torrent")
1613 delete(me.torrents, infoHash)
1614 me.downloadStrategy.TorrentStopped(t)
1615 for _, dw := range me.dataWaits[t] {
1618 delete(me.dataWaits, t)
1622 func (me *Client) addOrMergeTorrent(ih InfoHash, announceList [][]string) (T Torrent, err error) {
1623 if _, ok := me.bannedTorrents[ih]; ok {
1624 err = errors.New("banned torrent")
1629 T.torrent, ok = me.torrents[ih]
1631 T.torrent.addTrackers(announceList)
1633 T.torrent, err = newTorrent(ih, announceList, me.halfOpenLimit)
1637 me.torrents[ih] = T.torrent
1638 if !me.disableTrackers {
1639 go me.announceTorrentTrackers(T.torrent)
1642 go me.announceTorrentDHT(T.torrent, true)
1644 go me.connectionPruner(T.torrent)
1649 // Adds the torrent to the client.
1650 func (me *Client) AddTorrent(metaInfo *metainfo.MetaInfo) (t Torrent, err error) {
1652 CopyExact(&ih, metaInfo.Info.Hash)
1654 defer me.mu.Unlock()
1655 t, err = me.addOrMergeTorrent(ih, metaInfo.AnnounceList)
1659 if !t.torrent.haveInfo() {
1660 err = me.setMetaData(t.torrent, metaInfo.Info.Info, metaInfo.Info.Bytes)
1668 func (me *Client) AddTorrentFromFile(name string) (t Torrent, err error) {
1669 mi, err := metainfo.LoadFromFile(name)
1671 err = fmt.Errorf("error loading metainfo from file: %s", err)
1674 return me.AddTorrent(mi)
1677 // Returns true when peers are required, or false if the torrent is closing.
1678 func (cl *Client) waitWantPeers(t *torrent) bool {
1680 defer cl.mu.Unlock()
1682 defer t.stateMu.Unlock()
1685 case <-t.ceasingNetworking:
1689 if len(t.Peers) < socketsPerTorrent*5 {
1700 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
1701 for cl.waitWantPeers(t) {
1702 log.Printf("getting peers for %q from DHT", t)
1703 ps, err := cl.dHT.GetPeers(string(t.InfoHash[:]))
1705 log.Printf("error getting peers from dht: %s", err)
1711 case v, ok := <-ps.Values:
1715 peersFoundByDHT.Add(int64(len(v.Peers)))
1716 err = cl.AddPeers(t.InfoHash, func() (ret []Peer) {
1717 for _, cp := range v.Peers {
1718 ret = append(ret, Peer{
1721 Source: peerSourceDHT,
1727 log.Printf("error adding peers from dht for torrent %q: %s", t, err)
1730 case <-t.ceasingNetworking:
1736 log.Printf("finished DHT peer scrape for %s", t)
1738 // After a GetPeers, we can announce on the best nodes that gave us an
1741 port := cl.incomingPeerPort()
1742 // If port is zero, then we're not listening, and there's nothing to
1745 // We can't allow the port to be implied as long as the UTP and
1746 // DHT ports are different.
1747 err := cl.dHT.AnnouncePeer(port, impliedPort, t.InfoHash.AsString())
1749 log.Printf("error announcing torrent to DHT: %s", err)
1751 log.Printf("announced %q to DHT", t)
1757 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
1758 if err := tr.Connect(); err != nil {
1759 return fmt.Errorf("error connecting: %s", err)
1761 resp, err := tr.Announce(req)
1763 return fmt.Errorf("error announcing: %s", err)
1766 for _, peer := range resp.Peers {
1767 peers = append(peers, Peer{
1772 err = cl.AddPeers(t.InfoHash, peers)
1774 log.Printf("error adding peers to torrent %s: %s", t, err)
1776 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1779 time.Sleep(time.Second * time.Duration(resp.Interval))
1783 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
1784 oks := make(chan bool)
1786 for _, tier := range trackers {
1787 for _, tr := range tier {
1789 go func(tr tracker.Client) {
1790 err := cl.announceTorrentSingleTracker(tr, req, t)
1792 log.Printf("error announcing to %s: %s", tr, err)
1798 for outstanding > 0 {
1808 // Announce torrent to its trackers.
1809 func (cl *Client) announceTorrentTrackers(t *torrent) {
1810 req := tracker.AnnounceRequest{
1811 Event: tracker.Started,
1813 Port: int16(cl.incomingPeerPort()),
1815 InfoHash: t.InfoHash,
1818 req.Left = t.BytesLeft()
1819 trackers := t.Trackers
1821 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
1822 req.Event = tracker.None
1825 for cl.waitWantPeers(t) {
1827 req.Left = t.BytesLeft()
1828 trackers = t.Trackers
1830 for _, tier := range trackers {
1831 for trIndex, tr := range tier {
1832 err := cl.announceTorrentSingleTracker(tr, &req, t)
1834 log.Printf("error announcing to %s: %s", tr, err)
1837 // Float the successful announce to the top of the tier. If
1838 // the trackers list has been changed, we'll be modifying an
1839 // old copy so it won't matter.
1841 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1844 req.Event = tracker.None
1845 continue newAnnounce
1848 // TODO: Wait until trackers are added if there are none.
1849 time.Sleep(10 * time.Second)
1853 func (cl *Client) allTorrentsCompleted() bool {
1854 for _, t := range cl.torrents {
1858 for e := t.IncompletePiecesByBytesLeft.Front(); e != nil; e = e.Next() {
1860 if t.Pieces[i].Complete() {
1863 // If the piece isn't complete, make sure it's not because it's
1864 // never been hashed.
1865 cl.queueFirstHash(t, i)
1872 // Returns true when all torrents are completely downloaded and false if the
1873 // client is stopped before that.
1874 func (me *Client) WaitAll() bool {
1876 defer me.mu.Unlock()
1877 for !me.allTorrentsCompleted() {
1886 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
1890 me.downloadStrategy.FillRequests(t, c)
1891 if len(c.Requests) == 0 && !c.PeerChoked {
1892 c.SetInterested(false)
1896 // Handle a received chunk from a peer.
1897 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
1898 chunksDownloadedCount.Add(1)
1900 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1902 // Request has been satisfied.
1903 me.connDeleteRequest(t, c, req)
1905 defer me.replenishConnRequests(t, c)
1907 // Do we actually want this chunk?
1908 if _, ok := t.Pieces[req.Index].PendingChunkSpecs[req.chunkSpec]; !ok {
1909 unusedDownloadedChunksCount.Add(1)
1910 c.UnwantedChunksReceived++
1914 c.UsefulChunksReceived++
1915 c.lastUsefulChunkReceived = time.Now()
1917 // Write the chunk out.
1918 err := t.WriteChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1920 return fmt.Errorf("error writing chunk: %s", err)
1923 // Record that we have the chunk.
1924 delete(t.Pieces[req.Index].PendingChunkSpecs, req.chunkSpec)
1925 me.dataReady(t, req)
1926 if len(t.Pieces[req.Index].PendingChunkSpecs) == 0 {
1927 me.queuePieceCheck(t, req.Index)
1929 t.PieceBytesLeftChanged(int(req.Index))
1931 // Unprioritize the chunk.
1932 me.downloadStrategy.TorrentGotChunk(t, req)
1934 // Cancel pending requests for this chunk.
1935 for _, c := range t.Conns {
1936 if me.connCancel(t, c, req) {
1937 me.replenishConnRequests(t, c)
1941 me.downloadStrategy.AssertNotRequested(t, req)
1946 func (cl *Client) dataReady(t *torrent, r request) {
1947 dws := cl.dataWaits[t]
1948 begin := t.requestOffset(r)
1949 end := begin + int64(r.Length)
1950 for i := 0; i < len(dws); {
1952 if begin <= dw.offset && dw.offset < end {
1954 dws[i] = dws[len(dws)-1]
1955 dws = dws[:len(dws)-1]
1960 cl.dataWaits[t] = dws
1963 // Returns a channel that is closed when new data has become available in the
1965 func (me *Client) DataWaiter(ih InfoHash, off int64) (ret <-chan struct{}) {
1967 defer me.mu.Unlock()
1968 ch := make(chan struct{})
1970 t := me.torrents[ih]
1975 if r, ok := t.offsetRequest(off); !ok || t.haveChunk(r) {
1979 me.dataWaits[t] = append(me.dataWaits[t], dataWait{
1986 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
1987 p := t.Pieces[piece]
1988 if p.EverHashed && !correct {
1989 log.Printf("%s: piece %d failed hash", t, piece)
1990 failedPieceHashes.Add(1)
1994 p.PendingChunkSpecs = nil
1995 me.downloadStrategy.TorrentGotPiece(t, int(piece))
1996 me.dataReady(t, request{
1998 chunkSpec{0, pp.Integer(t.PieceLength(piece))},
2001 if len(p.PendingChunkSpecs) == 0 {
2002 t.pendAllChunkSpecs(piece)
2005 t.PieceBytesLeftChanged(int(piece))
2006 for _, conn := range t.Conns {
2008 conn.Post(pp.Message{
2010 Index: pp.Integer(piece),
2012 // TODO: Cancel requests for this piece.
2013 for r := range conn.Requests {
2014 if r.Index == piece {
2020 if t.haveAllPieces() && me.noUpload {
2023 me.event.Broadcast()
2026 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2028 defer cl.mu.Unlock()
2029 p := t.Pieces[index]
2037 p.QueuedForHash = false
2039 sum := t.HashPiece(index)
2047 cl.pieceHashed(t, index, sum == p.Hash)
2050 func (me *Client) Torrents() (ret []*torrent) {
2052 for _, t := range me.torrents {
2053 ret = append(ret, t)