2 Package torrent implements a torrent client.
7 t, _, c.AddMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU")
10 log.Print("erhmahgerd, torrent downloaded")
40 "github.com/bradfitz/iter"
42 "github.com/anacrolix/torrent/mse"
44 "github.com/anacrolix/torrent/data"
45 filePkg "github.com/anacrolix/torrent/data/file"
46 "github.com/anacrolix/torrent/dht"
47 "github.com/anacrolix/torrent/internal/pieceordering"
48 "github.com/anacrolix/torrent/iplist"
49 "github.com/anacrolix/torrent/logonce"
50 pp "github.com/anacrolix/torrent/peer_protocol"
51 "github.com/anacrolix/torrent/tracker"
52 _ "github.com/anacrolix/torrent/tracker/udp"
53 . "github.com/anacrolix/torrent/util"
54 "bitbucket.org/anacrolix/sync"
55 "github.com/anacrolix/utp"
56 "github.com/anacrolix/libtorgo/bencode"
57 "github.com/anacrolix/libtorgo/metainfo"
61 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
62 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
63 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
64 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
65 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
66 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
67 unexpectedCancels = expvar.NewInt("unexpectedCancels")
68 postedCancels = expvar.NewInt("postedCancels")
69 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
70 failedPieceHashes = expvar.NewInt("failedPieceHashes")
71 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
72 successfulDials = expvar.NewInt("successfulDials")
73 acceptedConns = expvar.NewInt("acceptedConns")
74 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
75 peerExtensions = expvar.NewMap("peerExtensions")
76 // Count of connections to peer with same client ID.
77 connsToSelf = expvar.NewInt("connsToSelf")
78 // Number of completed connections to a client we're already connected with.
79 duplicateClientConns = expvar.NewInt("duplicateClientConns")
80 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
81 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
85 // Justification for set bits follows.
87 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html ([5]|=0x10)
88 // DHT: http://www.bittorrent.org/beps/bep_0005.html ([7]|=1)
90 // http://bittorrent.org/beps/bep_0006.html ([7]|=4)
91 // Disabled until AllowedFast is implemented
92 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
94 socketsPerTorrent = 40
95 torrentPeersHighWater = 200
96 torrentPeersLowWater = 50
98 // Limit how long handshake can take. This is to reduce the lingering
99 // impact of a few bad apples. 4s loses 1% of successful handshakes that
100 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
101 btHandshakeTimeout = 4 * time.Second
102 handshakesTimeout = 20 * time.Second
104 pruneInterval = 10 * time.Second
107 // Currently doesn't really queue, but should in the future.
108 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
109 piece := t.Pieces[pieceIndex]
110 if piece.QueuedForHash {
113 piece.QueuedForHash = true
114 go cl.verifyPiece(t, pieceIndex)
117 // Queue a piece check if one isn't already queued, and the piece has never
118 // been checked before.
119 func (cl *Client) queueFirstHash(t *torrent, piece int) {
121 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
124 cl.queuePieceCheck(t, pp.Integer(piece))
132 listeners []net.Listener
138 ipBlockList *iplist.IPList
139 bannedTorrents map[InfoHash]struct{}
142 pruneTimer *time.Timer
143 extensionBytes peerExtensionBytes
144 // Set of addresses that have our client ID. This intentionally will
145 // include ourselves if we end up trying to connect to our own address
146 // through legitimate channels.
147 dopplegangerAddrs map[string]struct{}
149 torrentDataOpener TorrentDataOpener
155 torrents map[InfoHash]*torrent
158 func (me *Client) IPBlockList() *iplist.IPList {
161 return me.ipBlockList
164 func (me *Client) SetIPBlockList(list *iplist.IPList) {
167 me.ipBlockList = list
169 me.dHT.SetIPBlockList(list)
173 func (me *Client) PeerID() string {
174 return string(me.peerID[:])
177 func (me *Client) ListenAddr() (addr net.Addr) {
178 for _, l := range me.listeners {
179 if addr != nil && l.Addr().String() != addr.String() {
180 panic("listeners exist on different addresses")
187 type hashSorter struct {
191 func (me hashSorter) Len() int {
192 return len(me.Hashes)
195 func (me hashSorter) Less(a, b int) bool {
196 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
199 func (me hashSorter) Swap(a, b int) {
200 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
203 func (cl *Client) sortedTorrents() (ret []*torrent) {
205 for ih := range cl.torrents {
206 hs.Hashes = append(hs.Hashes, ih)
209 for _, ih := range hs.Hashes {
210 ret = append(ret, cl.torrent(ih))
215 // Writes out a human readable status of the client, such as for writing to a
217 func (cl *Client) WriteStatus(_w io.Writer) {
219 defer cl.mu.RUnlock()
220 w := bufio.NewWriter(_w)
222 if addr := cl.ListenAddr(); addr != nil {
223 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
225 fmt.Fprintln(w, "Not listening!")
227 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
229 dhtStats := cl.dHT.Stats()
230 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.NumNodes, dhtStats.NumGoodNodes)
231 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
232 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
233 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
234 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.NumOutstandingTransactions)
237 for _, t := range cl.sortedTorrents() {
239 fmt.Fprint(w, "<unknown name>")
241 fmt.Fprint(w, t.Name())
245 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
247 w.WriteString("<missing metainfo>")
255 // Read torrent data at the given offset. Will block until it is available.
256 func (cl *Client) torrentReadAt(t *torrent, off int64, p []byte) (n int, err error) {
259 index := int(off / int64(t.usualPieceSize()))
260 // Reading outside the bounds of a file is an error.
265 if int(index) >= len(t.Pieces) {
269 pieceOff := pp.Integer(off % int64(t.usualPieceSize()))
270 pieceLeft := int(t.PieceLength(index) - pieceOff)
275 if len(p) > pieceLeft {
281 // TODO: ReadAt should always try to fill the buffer.
283 avail := cl.prepareRead(t, off)
284 if avail < int64(len(p)) {
287 n, err = dataReadAt(t.data, p, off)
288 if n != 0 || err != io.ErrUnexpectedEOF {
291 // If we reach here, the data we thought was ready, isn't. So we
292 // prepare it again, and retry.
297 // Sets priorities to download from the given offset. Returns when the piece
298 // at the given offset can be read. Returns the number of bytes that are
299 // immediately available from the offset.
300 func (cl *Client) prepareRead(t *torrent, off int64) (n int64) {
301 index := int(off / int64(t.usualPieceSize()))
302 // Reading outside the bounds of a file is an error.
303 if index < 0 || index >= t.numPieces() {
306 piece := t.Pieces[index]
307 cl.readRaisePiecePriorities(t, off)
308 for !t.pieceComplete(index) && !t.isClosed() {
309 // This is to prevent being starved if a piece is dropped before we
311 cl.readRaisePiecePriorities(t, off)
314 return t.Info.Piece(index).Length() - off%t.Info.PieceLength
317 func (T Torrent) prepareRead(off int64) (avail int64) {
319 defer T.cl.mu.Unlock()
320 return T.cl.prepareRead(T.torrent, off)
323 // Data implements a streaming interface that's more efficient than ReadAt.
324 type SectionOpener interface {
325 OpenSection(off, n int64) (io.ReadCloser, error)
328 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
330 if ra, ok := d.(io.ReaderAt); ok {
331 return ra.ReadAt(b, off)
333 if so, ok := d.(SectionOpener); ok {
335 rc, err = so.OpenSection(off, int64(len(b)))
340 return io.ReadFull(rc, b)
342 if dp, ok := super(d); ok {
346 panic(fmt.Sprintf("can't read from %T", d))
349 // Calculates the number of pieces to set to Readahead priority, after the
350 // Now, and Next pieces.
351 func readaheadPieces(readahead, pieceLength int64) int {
352 return int((readahead+pieceLength-1)/pieceLength - 1)
355 func (cl *Client) readRaisePiecePriorities(t *torrent, off int64) {
356 index := int(off / int64(t.usualPieceSize()))
357 cl.raisePiecePriority(t, index, piecePriorityNow)
359 if index >= t.numPieces() {
362 cl.raisePiecePriority(t, index, piecePriorityNext)
363 for range iter.N(readaheadPieces(5*1024*1024, t.Info.PieceLength)) {
365 if index >= t.numPieces() {
368 cl.raisePiecePriority(t, index, piecePriorityReadahead)
372 func (cl *Client) configDir() string {
373 if cl._configDir == "" {
374 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
379 func (cl *Client) ConfigDir() string {
380 return cl.configDir()
383 func (t *torrent) connPendPiece(c *connection, piece int) {
384 c.pendPiece(piece, t.Pieces[piece].Priority)
387 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
388 if t.Pieces[piece].Priority < priority {
390 cl.prioritizePiece(t, piece, priority)
394 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
395 if t.havePiece(piece) {
398 cl.queueFirstHash(t, piece)
399 t.Pieces[piece].Priority = priority
400 cl.pieceChanged(t, piece)
403 func (cl *Client) setEnvBlocklist() (err error) {
404 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
405 defaultBlocklist := filename == ""
406 if defaultBlocklist {
407 filename = filepath.Join(cl.configDir(), "blocklist")
409 f, err := os.Open(filename)
411 if defaultBlocklist {
417 var ranges []iplist.Range
418 uniqStrs := make(map[string]string)
419 scanner := bufio.NewScanner(f)
422 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
424 err = fmt.Errorf("error reading torrent blocklist line %d: %s", lineNum, lineErr)
431 if s, ok := uniqStrs[r.Description]; ok {
434 uniqStrs[r.Description] = r.Description
436 ranges = append(ranges, r)
440 err = fmt.Errorf("error reading torrent blocklist: %s", err)
443 cl.ipBlockList = iplist.New(ranges)
447 func (cl *Client) initBannedTorrents() error {
448 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
450 if os.IsNotExist(err) {
453 return fmt.Errorf("error opening banned infohashes file: %s", err)
456 scanner := bufio.NewScanner(f)
457 cl.bannedTorrents = make(map[InfoHash]struct{})
459 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
463 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
465 return fmt.Errorf("error reading infohash: %s", err)
471 return errors.New("bad infohash")
475 cl.bannedTorrents[ih] = struct{}{}
477 if err := scanner.Err(); err != nil {
478 return fmt.Errorf("error scanning file: %s", err)
483 // Creates a new client. Clients contain zero or more Torrents.
484 func NewClient(cfg *Config) (cl *Client, err error) {
490 noUpload: cfg.NoUpload,
491 disableTrackers: cfg.DisableTrackers,
492 halfOpenLimit: socketsPerTorrent,
493 dataDir: cfg.DataDir,
494 disableUTP: cfg.DisableUTP,
495 disableTCP: cfg.DisableTCP,
496 _configDir: cfg.ConfigDir,
498 torrentDataOpener: func(md *metainfo.Info) data.Data {
499 return filePkg.TorrentData(md, cfg.DataDir)
501 dopplegangerAddrs: make(map[string]struct{}),
503 quit: make(chan struct{}),
504 torrents: make(map[InfoHash]*torrent),
506 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
508 if cfg.TorrentDataOpener != nil {
509 cl.torrentDataOpener = cfg.TorrentDataOpener
512 if !cfg.NoDefaultBlocklist {
513 err = cl.setEnvBlocklist()
519 if err = cl.initBannedTorrents(); err != nil {
520 err = fmt.Errorf("error initing banned torrents: %s", err)
524 if cfg.PeerID != "" {
525 CopyExact(&cl.peerID, cfg.PeerID)
527 o := copy(cl.peerID[:], bep20)
528 _, err = rand.Read(cl.peerID[o:])
530 panic("error generating peer id")
534 // Returns the laddr string to listen on for the next Listen call.
535 listenAddr := func() string {
536 if addr := cl.ListenAddr(); addr != nil {
539 if cfg.ListenAddr == "" {
540 // IPv6 isn't well supported with blocklists, or with trackers and
542 return "0.0.0.0:50007"
544 return cfg.ListenAddr
548 l, err = net.Listen("tcp", listenAddr())
552 cl.listeners = append(cl.listeners, l)
553 go cl.acceptConnections(l, false)
556 cl.utpSock, err = utp.NewSocket(listenAddr())
560 cl.listeners = append(cl.listeners, cl.utpSock)
561 go cl.acceptConnections(cl.utpSock, true)
564 dhtCfg := cfg.DHTConfig
566 dhtCfg = &dht.ServerConfig{}
568 if dhtCfg.Addr == "" {
569 dhtCfg.Addr = listenAddr()
571 if dhtCfg.Conn == nil && cl.utpSock != nil {
572 dhtCfg.Conn = cl.utpSock.PacketConn()
574 cl.dHT, err = dht.NewServer(dhtCfg)
575 if cl.ipBlockList != nil {
576 cl.dHT.SetIPBlockList(cl.ipBlockList)
586 func (cl *Client) stopped() bool {
595 // Stops the client. All connections to peers are closed and all activity will
597 func (me *Client) Close() {
601 for _, l := range me.listeners {
605 for _, t := range me.torrents {
610 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
612 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
613 if cl.ipBlockList == nil {
618 log.Printf("saw non-IPv4 address")
622 r = cl.ipBlockList.Lookup(ip)
626 func (cl *Client) waitAccept() {
630 for _, t := range cl.torrents {
639 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
642 // We accept all connections immediately, because we don't know what
643 // torrent they're for.
644 conn, err := l.Accept()
659 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
660 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
662 if blockRange != nil || doppleganger {
663 inboundConnsBlocked.Add(1)
664 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
668 go cl.incomingConnection(conn, utp)
672 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
674 if tc, ok := nc.(*net.TCPConn); ok {
680 c.Discovery = peerSourceIncoming
682 err := cl.runReceivedConn(c)
688 // Returns a handle to the given torrent, if it's present in the client.
689 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
692 t, ok := cl.torrents[ih]
700 func (me *Client) torrent(ih InfoHash) *torrent {
701 return me.torrents[ih]
704 type dialResult struct {
709 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
710 conn, err := dial(addr, t)
715 conn = nil // Pedantic
717 ch <- dialResult{conn, utp}
719 successfulDials.Add(1)
722 unsuccessfulDials.Add(1)
723 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
726 if netOpErr, ok := err.(*net.OpError); ok {
727 switch netOpErr.Err {
728 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
733 log.Printf("error dialing %s: %s", addr, err)
738 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
739 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
740 if ret < minDialTimeout {
746 func (me *Client) dopplegangerAddr(addr string) bool {
747 _, ok := me.dopplegangerAddrs[addr]
751 // Start the process of connecting to the given peer for the given torrent if
753 func (me *Client) initiateConn(peer Peer, t *torrent) {
754 if peer.Id == me.peerID {
757 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
758 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
759 duplicateConnsAvoided.Add(1)
762 if r := me.ipBlockRange(peer.IP); r != nil {
763 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
766 t.HalfOpen[addr] = struct{}{}
767 go me.outgoingConnection(t, addr, peer.Source)
770 func (me *Client) dialTimeout(t *torrent) time.Duration {
771 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
774 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
775 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
777 c.(*net.TCPConn).SetLinger(0)
782 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
783 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
786 // Returns a connection over UTP or TCP.
787 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
788 // Initiate connections via TCP and UTP simultaneously. Use the first one
797 resCh := make(chan dialResult, left)
799 go doDial(me.dialUTP, resCh, true, addr, t)
802 go doDial(me.dialTCP, resCh, false, addr, t)
805 // Wait for a successful connection.
806 for ; left > 0 && res.Conn == nil; left-- {
810 // There are still incompleted dials.
812 for ; left > 0; left-- {
813 conn := (<-resCh).Conn
825 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
826 if _, ok := t.HalfOpen[addr]; !ok {
827 panic("invariant broken")
829 delete(t.HalfOpen, addr)
833 // Returns nil connection and nil error if no connection could be established
834 // for valid reasons.
835 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
836 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
840 c.encrypted = encrypted
842 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
846 ok, err := me.initiateHandshakes(c, t)
852 nc, utp := me.dial(addr, t)
856 c, err = handshakesConnection(nc, true, utp)
865 nc, err = me.dialUTP(addr, t)
867 nc, err = me.dialTCP(addr, t)
870 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
873 c, err = handshakesConnection(nc, false, utp)
880 // Called to dial out and run a connection. The addr we're given is already
881 // considered half-open.
882 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
883 c, err := me.establishOutgoingConn(t, addr)
886 // Don't release lock between here and addConnection, unless it's for
888 me.noLongerHalfOpen(t, addr)
898 err = me.runInitiatedHandshookConn(c, t)
904 // The port number for incoming peer connections. 0 if the client isn't
906 func (cl *Client) incomingPeerPort() int {
907 listenAddr := cl.ListenAddr()
908 if listenAddr == nil {
911 return addrPort(listenAddr)
914 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
915 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
916 func addrCompactIP(addr net.Addr) (string, error) {
917 host, _, err := net.SplitHostPort(addr.String())
921 ip := net.ParseIP(host)
922 if v4 := ip.To4(); v4 != nil {
926 return string(v4), nil
928 return string(ip.To16()), nil
931 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
943 peerExtensionBytes [8]byte
947 func (me *peerExtensionBytes) SupportsExtended() bool {
948 return me[5]&0x10 != 0
951 func (me *peerExtensionBytes) SupportsDHT() bool {
952 return me[7]&0x01 != 0
955 func (me *peerExtensionBytes) SupportsFast() bool {
956 return me[7]&0x04 != 0
959 type handshakeResult struct {
965 // ih is nil if we expect the peer to declare the InfoHash, such as when the
966 // peer initiated the connection. Returns ok if the handshake was successful,
967 // and err if there was an unexpected condition other than the peer simply
968 // abandoning the handshake.
969 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
970 // Bytes to be sent to the peer. Should never block the sender.
971 postCh := make(chan []byte, 4)
972 // A single error value sent when the writer completes.
973 writeDone := make(chan error, 1)
974 // Performs writes to the socket and ensures posts don't block.
975 go handshakeWriter(sock, postCh, writeDone)
978 close(postCh) // Done writing.
985 // Wait until writes complete before returning from handshake.
988 err = fmt.Errorf("error writing: %s", err)
992 post := func(bb []byte) {
996 panic("mustn't block while posting")
1000 post([]byte(pp.Protocol))
1002 if ih != nil { // We already know what we want.
1007 _, err = io.ReadFull(sock, b[:68])
1012 if string(b[:20]) != pp.Protocol {
1015 CopyExact(&res.peerExtensionBytes, b[20:28])
1016 CopyExact(&res.InfoHash, b[28:48])
1017 CopyExact(&res.peerID, b[48:68])
1018 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
1020 // TODO: Maybe we can just drop peers here if we're not interested. This
1021 // could prevent them trying to reconnect, falsely believing there was
1023 if ih == nil { // We were waiting for the peer to tell us what they wanted.
1024 post(res.InfoHash[:])
1032 // Wraps a raw connection and provides the interface we want for using the
1033 // connection in the message loop.
1034 type deadlineReader struct {
1039 func (me deadlineReader) Read(b []byte) (n int, err error) {
1040 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1041 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1043 err = fmt.Errorf("error setting read deadline: %s", err)
1045 n, err = me.r.Read(b)
1046 // Convert common errors into io.EOF.
1048 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1050 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1060 type readWriter struct {
1065 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1066 var protocol [len(pp.Protocol)]byte
1067 _, err = io.ReadFull(rw, protocol[:])
1072 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1075 if string(protocol[:]) == pp.Protocol {
1079 ret, err = mse.ReceiveHandshake(ret, skeys)
1083 func (cl *Client) receiveSkeys() (ret [][]byte) {
1084 for ih := range cl.torrents {
1085 ret = append(ret, ih[:])
1090 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1092 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1097 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1098 if ih != t.InfoHash {
1104 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1106 skeys := cl.receiveSkeys()
1108 // TODO: Filter unmatching skey errors.
1109 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1111 if err == mse.ErrNoSecretKeyMatch {
1116 ih, ok, err := cl.connBTHandshake(c, nil)
1118 fmt.Errorf("error during bt handshake: %s", err)
1130 // Returns !ok if handshake failed for valid reasons.
1131 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1132 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1133 if err != nil || !ok {
1137 c.PeerExtensionBytes = res.peerExtensionBytes
1138 c.PeerID = res.peerID
1139 c.completedHandshake = time.Now()
1143 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1144 if c.PeerID == cl.peerID {
1145 // Only if we initiated the connection is the remote address a
1146 // listen addr for a doppleganger.
1148 addr := c.conn.RemoteAddr().String()
1149 cl.dopplegangerAddrs[addr] = struct{}{}
1152 return cl.runHandshookConn(c, t)
1155 func (cl *Client) runReceivedConn(c *connection) (err error) {
1156 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1160 t, err := cl.receiveHandshakes(c)
1162 logonce.Stderr.Printf("error receiving handshakes: %s", err)
1170 defer cl.mu.Unlock()
1171 if c.PeerID == cl.peerID {
1174 return cl.runHandshookConn(c, t)
1177 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1178 c.conn.SetWriteDeadline(time.Time{})
1180 deadlineReader{c.conn, c.rw},
1183 if !cl.addConnection(t, c) {
1186 defer cl.dropConnection(t, c)
1188 go c.writeOptimizer(time.Minute)
1189 cl.sendInitialMessages(c, t)
1191 t.initRequestOrdering(c)
1193 err = cl.connectionLoop(t, c)
1195 err = fmt.Errorf("error during connection loop: %s", err)
1200 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1201 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1202 conn.Post(pp.Message{
1204 ExtendedID: pp.HandshakeExtendedID,
1205 ExtendedPayload: func() []byte {
1206 d := map[string]interface{}{
1207 "m": map[string]int{
1211 "v": "go.torrent dev 20140825", // Just the date
1212 // No upload queue is implemented yet.
1213 "reqq": func() int {
1215 // No need to look strange if it costs us nothing.
1221 "e": 1, // Awwww yeah
1223 if torrent.metadataSizeKnown() {
1224 d["metadata_size"] = torrent.metadataSize()
1226 if p := me.incomingPeerPort(); p != 0 {
1229 yourip, err := addrCompactIP(conn.remoteAddr())
1231 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1233 d["yourip"] = yourip
1235 // log.Printf("sending %v", d)
1236 b, err := bencode.Marshal(d)
1244 if torrent.haveAnyPieces() {
1245 conn.Post(pp.Message{
1247 Bitfield: torrent.bitfield(),
1249 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1250 conn.Post(pp.Message{
1254 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1255 conn.Post(pp.Message{
1257 Port: uint16(AddrPort(me.dHT.LocalAddr())),
1262 // Randomizes the piece order for this connection. Every connection will be
1263 // given a different ordering. Having it stored per connection saves having to
1264 // randomize during request filling, and constantly recalculate the ordering
1265 // based on piece priorities.
1266 func (t *torrent) initRequestOrdering(c *connection) {
1267 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1268 panic("double init of request ordering")
1270 c.piecePriorities = mathRand.Perm(t.numPieces())
1271 c.pieceRequestOrder = pieceordering.New()
1272 for i := range iter.N(t.Info.NumPieces()) {
1273 if !c.PeerHasPiece(i) {
1276 if !t.wantPiece(i) {
1279 t.connPendPiece(c, i)
1283 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1286 if c.PeerPieces == nil {
1287 c.PeerPieces = make([]bool, t.numPieces())
1290 for piece >= len(c.PeerPieces) {
1291 c.PeerPieces = append(c.PeerPieces, false)
1294 c.PeerPieces[piece] = true
1296 if t.wantPiece(piece) {
1297 t.connPendPiece(c, piece)
1298 me.replenishConnRequests(t, c)
1302 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1303 me.replenishConnRequests(torrent, conn)
1306 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1309 postedCancels.Add(1)
1314 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1315 if !cn.RequestPending(r) {
1318 delete(cn.Requests, r)
1321 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1326 for index := 0; index < t.metadataPieceCount(); index++ {
1327 if !t.haveMetadataPiece(index) {
1328 pending = append(pending, index)
1331 for _, i := range mathRand.Perm(len(pending)) {
1334 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
1335 ExtendedPayload: func() []byte {
1336 b, err := bencode.Marshal(map[string]int{
1338 "piece": pending[i],
1349 func (cl *Client) completedMetadata(t *torrent) {
1353 CopyExact(&ih, h.Sum(nil))
1354 if ih != t.InfoHash {
1355 log.Print("bad metadata")
1356 t.invalidateMetadata()
1359 var info metainfo.Info
1360 err := bencode.Unmarshal(t.MetaData, &info)
1362 log.Printf("error unmarshalling metadata: %s", err)
1363 t.invalidateMetadata()
1366 // TODO(anacrolix): If this fails, I think something harsher should be
1368 err = cl.setMetaData(t, &info, t.MetaData)
1370 log.Printf("error setting metadata: %s", err)
1371 t.invalidateMetadata()
1374 log.Printf("%s: got metadata from peers", t)
1377 // Process incoming ut_metadata message.
1378 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1379 var d map[string]int
1380 err = bencode.Unmarshal(payload, &d)
1382 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1385 msgType, ok := d["msg_type"]
1387 err = errors.New("missing msg_type field")
1392 case pp.DataMetadataExtensionMsgType:
1396 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1397 if begin < 0 || begin >= len(payload) {
1398 log.Printf("got bad metadata piece")
1401 t.saveMetadataPiece(piece, payload[begin:])
1402 c.UsefulChunksReceived++
1403 c.lastUsefulChunkReceived = time.Now()
1404 if !t.haveAllMetadataPieces() {
1407 cl.completedMetadata(t)
1408 case pp.RequestMetadataExtensionMsgType:
1409 if !t.haveMetadataPiece(piece) {
1410 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1413 start := (1 << 14) * piece
1414 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1415 case pp.RejectMetadataExtensionMsgType:
1417 err = errors.New("unknown msg_type value")
1422 type peerExchangeMessage struct {
1423 Added CompactPeers `bencode:"added"`
1424 AddedFlags []byte `bencode:"added.f"`
1425 Dropped CompactPeers `bencode:"dropped"`
1428 // Extracts the port as an integer from an address string.
1429 func addrPort(addr net.Addr) int {
1430 return AddrPort(addr)
1433 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1434 cn.peerHasAll = true
1437 for i := 0; i < t.numPieces(); i++ {
1438 cl.peerGotPiece(t, cn, i)
1443 // Processes incoming bittorrent messages. The client lock is held upon entry
1445 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1446 decoder := pp.Decoder{
1447 R: bufio.NewReader(c.rw),
1448 MaxLength: 256 * 1024,
1453 err := decoder.Decode(&msg)
1454 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1456 c.lastMessageReceived = time.Now()
1463 if me.stopped() || err == io.EOF {
1474 for r := range c.Requests {
1475 me.connDeleteRequest(t, c, r)
1477 // We can then reset our interest.
1478 me.replenishConnRequests(t, c)
1480 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1481 me.replenishConnRequests(t, c)
1483 c.PeerChoked = false
1484 me.peerUnchoked(t, c)
1486 c.PeerInterested = true
1487 // TODO: This should be done from a dedicated unchoking routine.
1492 case pp.NotInterested:
1493 c.PeerInterested = false
1496 me.peerGotPiece(t, c, int(msg.Index))
1501 if c.PeerRequests == nil {
1502 c.PeerRequests = make(map[request]struct{}, maxRequests)
1504 request := newRequest(msg.Index, msg.Begin, msg.Length)
1505 // TODO: Requests should be satisfied from a dedicated upload
1507 // c.PeerRequests[request] = struct{}{}
1508 p := make([]byte, msg.Length)
1509 n, err := dataReadAt(t.data, p, int64(t.PieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1511 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1513 if n != int(msg.Length) {
1514 return fmt.Errorf("bad request: %v", msg)
1522 uploadChunksPosted.Add(1)
1524 req := newRequest(msg.Index, msg.Begin, msg.Length)
1525 if !c.PeerCancel(req) {
1526 unexpectedCancels.Add(1)
1529 if c.PeerPieces != nil || c.peerHasAll {
1530 err = errors.New("received unexpected bitfield")
1534 if len(msg.Bitfield) < t.numPieces() {
1535 err = errors.New("received invalid bitfield")
1538 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1540 c.PeerPieces = msg.Bitfield
1541 for index, has := range c.PeerPieces {
1543 me.peerGotPiece(t, c, index)
1547 if c.PeerPieces != nil || c.peerHasAll {
1548 err = errors.New("unexpected have-all")
1553 if c.peerHasAll || c.PeerPieces != nil {
1554 err = errors.New("unexpected have-none")
1557 c.PeerPieces = make([]bool, func() int {
1559 return t.numPieces()
1565 err = me.downloadedChunk(t, c, &msg)
1567 switch msg.ExtendedID {
1568 case pp.HandshakeExtendedID:
1569 // TODO: Create a bencode struct for this.
1570 var d map[string]interface{}
1571 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1573 err = fmt.Errorf("error decoding extended message payload: %s", err)
1576 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1577 if reqq, ok := d["reqq"]; ok {
1578 if i, ok := reqq.(int64); ok {
1579 c.PeerMaxRequests = int(i)
1582 if v, ok := d["v"]; ok {
1583 c.PeerClientName = v.(string)
1587 err = errors.New("handshake missing m item")
1590 mTyped, ok := m.(map[string]interface{})
1592 err = errors.New("handshake m value is not dict")
1595 if c.PeerExtensionIDs == nil {
1596 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1598 for name, v := range mTyped {
1601 log.Printf("bad handshake m item extension ID type: %T", v)
1605 delete(c.PeerExtensionIDs, name)
1607 if c.PeerExtensionIDs[name] == 0 {
1608 supportedExtensionMessages.Add(name, 1)
1610 c.PeerExtensionIDs[name] = id
1613 metadata_sizeUntyped, ok := d["metadata_size"]
1615 metadata_size, ok := metadata_sizeUntyped.(int64)
1617 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1619 t.setMetadataSize(metadata_size)
1622 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1623 me.requestPendingMetadata(t, c)
1626 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1628 err = fmt.Errorf("error handling metadata extension message: %s", err)
1631 var pexMsg peerExchangeMessage
1632 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1634 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1639 me.addPeers(t, func() (ret []Peer) {
1640 for i, cp := range pexMsg.Added {
1642 IP: make([]byte, 4),
1644 Source: peerSourcePEX,
1646 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1647 p.SupportsEncryption = true
1649 CopyExact(p.IP, cp.IP[:])
1650 ret = append(ret, p)
1655 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1658 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1661 // That client uses its own extension IDs for outgoing message
1662 // types, which is incorrect.
1663 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1664 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1667 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1673 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1678 pingAddr.Port = int(msg.Port)
1680 _, err = me.dHT.Ping(pingAddr)
1682 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1690 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1691 me.event.Broadcast()
1692 for r := range conn.Requests {
1693 me.connDeleteRequest(torrent, conn, r)
1696 for i0, c := range torrent.Conns {
1700 i1 := len(torrent.Conns) - 1
1702 torrent.Conns[i0] = torrent.Conns[i1]
1704 torrent.Conns = torrent.Conns[:i1]
1705 me.openNewConns(torrent)
1708 panic("connection not found")
1711 func (me *Client) addConnection(t *torrent, c *connection) bool {
1716 case <-t.ceasingNetworking:
1720 if !me.wantConns(t) {
1723 for _, c0 := range t.Conns {
1724 if c.PeerID == c0.PeerID {
1725 // Already connected to a client with that ID.
1726 duplicateClientConns.Add(1)
1730 t.Conns = append(t.Conns, c)
1731 // TODO: This should probably be done by a routine that kills off bad
1732 // connections, and extra connections killed here instead.
1733 if len(t.Conns) > socketsPerTorrent {
1734 wcs := t.worstConnsHeap()
1735 heap.Pop(wcs).(*connection).Close()
1740 func (t *torrent) needData() bool {
1744 for i := range t.Pieces {
1752 // TODO: I'm sure there's something here to do with seeding.
1753 func (t *torrent) badConn(c *connection) bool {
1754 // A 30 second grace for initial messages to go through.
1755 if time.Since(c.completedHandshake) < 30*time.Second {
1759 if !c.supportsExtension("ut_metadata") {
1762 if time.Since(c.completedHandshake) > 2*time.Minute {
1766 return !t.connHasWantedPieces(c)
1769 func (t *torrent) numGoodConns() (num int) {
1770 for _, c := range t.Conns {
1778 func (me *Client) wantConns(t *torrent) bool {
1779 if me.noUpload && !t.needData() {
1782 if t.numGoodConns() >= socketsPerTorrent {
1788 func (me *Client) openNewConns(t *torrent) {
1790 case <-t.ceasingNetworking:
1794 for len(t.Peers) != 0 {
1795 if !me.wantConns(t) {
1798 if len(t.HalfOpen) >= me.halfOpenLimit {
1805 for k, p = range t.Peers {
1809 me.initiateConn(p, t)
1811 t.wantPeers.Broadcast()
1814 func (me *Client) addPeers(t *torrent, peers []Peer) {
1815 for _, p := range peers {
1816 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1819 if me.ipBlockRange(p.IP) != nil {
1827 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1828 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1831 func (cl *Client) saveTorrentFile(t *torrent) error {
1832 path := cl.cachedMetaInfoFilename(t.InfoHash)
1833 os.MkdirAll(filepath.Dir(path), 0777)
1834 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1836 return fmt.Errorf("error opening file: %s", err)
1839 e := bencode.NewEncoder(f)
1840 err = e.Encode(t.MetaInfo())
1842 return fmt.Errorf("error marshalling metainfo: %s", err)
1844 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1846 // For example, a script kiddy makes us load too many files, and we're
1847 // able to save the torrent, but not load it again to check it.
1850 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1851 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1856 func (cl *Client) startTorrent(t *torrent) {
1857 if t.Info == nil || t.data == nil {
1860 // If the client intends to upload, it needs to know what state pieces are
1863 // Queue all pieces for hashing. This is done sequentially to avoid
1864 // spamming goroutines.
1865 for _, p := range t.Pieces {
1866 p.QueuedForHash = true
1869 for i := range t.Pieces {
1870 cl.verifyPiece(t, pp.Integer(i))
1876 // Storage cannot be changed once it's set.
1877 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1878 err = t.setStorage(td)
1879 cl.event.Broadcast()
1887 type TorrentDataOpener func(*metainfo.Info) data.Data
1889 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1890 err = t.setMetadata(md, bytes, &cl.mu)
1894 if !cl.config.DisableMetainfoCache {
1895 if err := cl.saveTorrentFile(t); err != nil {
1896 log.Printf("error saving torrent file for %s: %s", t, err)
1899 cl.event.Broadcast()
1900 if strings.Contains(strings.ToLower(md.Name), "porn") {
1901 cl.dropTorrent(t.InfoHash)
1902 err = errors.New("no porn plx")
1905 close(t.gotMetainfo)
1906 td := cl.torrentDataOpener(md)
1907 err = cl.setStorage(t, td)
1911 // Prepare a Torrent without any attachment to a Client. That means we can
1912 // initialize fields all fields that don't require the Client without locking
1914 func newTorrent(ih InfoHash) (t *torrent, err error) {
1917 Peers: make(map[peersKey]Peer),
1919 closing: make(chan struct{}),
1920 ceasingNetworking: make(chan struct{}),
1922 gotMetainfo: make(chan struct{}),
1924 HalfOpen: make(map[string]struct{}),
1926 t.wantPeers.L = &t.stateMu
1927 t.GotMetainfo = t.gotMetainfo
1932 // For shuffling the tracker tiers.
1933 mathRand.Seed(time.Now().Unix())
1936 // The trackers within each tier must be shuffled before use.
1937 // http://stackoverflow.com/a/12267471/149482
1938 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1939 func shuffleTier(tier []tracker.Client) {
1940 for i := range tier {
1941 j := mathRand.Intn(i + 1)
1942 tier[i], tier[j] = tier[j], tier[i]
1946 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1947 for _, tier := range base {
1948 copy = append(copy, append([]tracker.Client{}, tier...))
1953 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1955 for _, url := range newURLs {
1956 for _, tr := range tier {
1957 if tr.URL() == url {
1961 tr, err := tracker.New(url)
1963 log.Printf("error creating tracker client for %q: %s", url, err)
1966 tier = append(tier, tr)
1971 func (t *torrent) addTrackers(announceList [][]string) {
1972 newTrackers := copyTrackers(t.Trackers)
1973 for tierIndex, tier := range announceList {
1974 if tierIndex < len(newTrackers) {
1975 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1977 newTrackers = append(newTrackers, mergeTier(nil, tier))
1979 shuffleTier(newTrackers[tierIndex])
1981 t.Trackers = newTrackers
1984 // A handle to a live torrent within a Client.
1985 type Torrent struct {
1990 func (t Torrent) NumPieces() int {
1991 return t.numPieces()
1994 func (t Torrent) Drop() {
1996 t.cl.dropTorrent(t.InfoHash)
2000 // Provides access to regions of torrent data that correspond to its files.
2006 fi metainfo.FileInfo
2009 func (f File) FileInfo() metainfo.FileInfo {
2013 func (f File) Path() string {
2017 // A file-like handle to some torrent data resource.
2018 type Handle interface {
2025 // Implements a Handle within a subsection of another Handle.
2026 type sectionHandle struct {
2031 func (me *sectionHandle) Seek(offset int64, whence int) (ret int64, err error) {
2034 } else if whence == 2 {
2036 offset += me.off + me.n
2038 ret, err = me.h.Seek(offset, whence)
2044 func (me *sectionHandle) Close() error {
2048 func (me *sectionHandle) Read(b []byte) (n int, err error) {
2049 max := me.off + me.n - me.cur
2050 if int64(len(b)) > max {
2053 n, err = me.h.Read(b)
2058 if me.cur == me.off+me.n {
2064 func (me *sectionHandle) ReadAt(b []byte, off int64) (n int, err error) {
2069 if int64(len(b)) >= me.n-off {
2072 return me.h.ReadAt(b, me.off+off)
2075 func (f File) Open() (h Handle, err error) {
2076 h = f.t.NewReadHandle()
2077 _, err = h.Seek(f.offset, os.SEEK_SET)
2082 h = §ionHandle{h, f.offset, f.Length(), f.offset}
2086 func (f File) ReadAt(p []byte, off int64) (n int, err error) {
2087 maxLen := f.length - off
2088 if int64(len(p)) > maxLen {
2091 return f.t.ReadAt(p, off+f.offset)
2094 func (f *File) Length() int64 {
2098 type FilePieceState struct {
2103 func (f *File) Progress() (ret []FilePieceState) {
2104 pieceSize := int64(f.t.usualPieceSize())
2105 off := f.offset % pieceSize
2106 remaining := f.length
2107 for i := int(f.offset / pieceSize); ; i++ {
2111 len1 := pieceSize - off
2112 if len1 > remaining {
2115 ret = append(ret, FilePieceState{len1, f.t.pieceStatusChar(i)})
2122 func (f *File) PrioritizeRegion(off, len int64) {
2123 if off < 0 || off >= f.length {
2126 if off+len > f.length {
2127 len = f.length - off
2130 f.t.SetRegionPriority(off, len)
2133 // Returns handles to the files in the torrent. This requires the metainfo is
2135 func (t Torrent) Files() (ret []File) {
2143 for _, fi := range info.UpvertedFiles() {
2144 ret = append(ret, File{
2146 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2156 func (t Torrent) SetRegionPriority(off, len int64) {
2158 defer t.cl.mu.Unlock()
2159 pieceSize := int64(t.usualPieceSize())
2160 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2161 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
2165 func (t Torrent) AddPeers(pp []Peer) error {
2168 defer cl.mu.Unlock()
2169 cl.addPeers(t.torrent, pp)
2173 // Marks the entire torrent for download.
2174 func (t Torrent) DownloadAll() {
2176 defer t.cl.mu.Unlock()
2177 for i := range iter.N(t.numPieces()) {
2178 t.cl.raisePiecePriority(t.torrent, i, piecePriorityNormal)
2180 // Nice to have the first and last pieces sooner for various interactive
2182 t.cl.raisePiecePriority(t.torrent, 0, piecePriorityReadahead)
2183 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, piecePriorityReadahead)
2186 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
2187 return me.cl.torrentReadAt(me.torrent, off, p)
2190 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2191 // metainfo has the correct infohash.
2192 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2193 if cl.config.DisableMetainfoCache {
2196 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2198 if os.IsNotExist(err) {
2204 dec := bencode.NewDecoder(f)
2205 err = dec.Decode(&mi)
2209 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2210 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2216 // For adding new torrents to a client.
2217 type TorrentSpec struct {
2220 Info *metainfo.InfoEx
2224 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2225 m, err := ParseMagnetURI(uri)
2229 spec = &TorrentSpec{
2230 Trackers: [][]string{m.Trackers},
2231 DisplayName: m.DisplayName,
2233 CopyExact(&spec.InfoHash, &m.InfoHash)
2237 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2238 spec = &TorrentSpec{
2239 Trackers: mi.AnnounceList,
2242 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2246 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2249 defer cl.mu.Unlock()
2251 t, ok := cl.torrents[spec.InfoHash]
2259 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2260 err = errors.New("banned torrent")
2264 t, err = newTorrent(spec.InfoHash)
2268 if spec.DisplayName != "" {
2269 t.DisplayName = spec.DisplayName
2271 if spec.Info != nil {
2272 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2274 var mi *metainfo.MetaInfo
2275 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2277 log.Printf("error getting cached metainfo: %s", err)
2278 } else if mi != nil {
2279 t.addTrackers(mi.AnnounceList)
2280 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2287 cl.torrents[spec.InfoHash] = t
2290 T.torrent.pruneTimer = time.AfterFunc(0, func() {
2291 cl.pruneConnectionsUnlocked(T.torrent)
2293 t.addTrackers(spec.Trackers)
2294 if !cl.disableTrackers {
2295 go cl.announceTorrentTrackers(T.torrent)
2298 go cl.announceTorrentDHT(T.torrent, true)
2303 // Prunes unused connections. This is required to make space to dial for
2305 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
2307 case <-t.ceasingNetworking:
2314 license := len(t.Conns) - (socketsPerTorrent+1)/2
2315 for _, c := range t.Conns {
2319 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
2322 if time.Now().Sub(c.completedHandshake) < time.Minute {
2329 t.pruneTimer.Reset(pruneInterval)
2332 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2333 t, ok := me.torrents[infoHash]
2335 err = fmt.Errorf("no such torrent")
2342 delete(me.torrents, infoHash)
2346 // Returns true when peers are required, or false if the torrent is closing.
2347 func (cl *Client) waitWantPeers(t *torrent) bool {
2349 defer cl.mu.Unlock()
2351 defer t.stateMu.Unlock()
2354 case <-t.ceasingNetworking:
2358 if len(t.Peers) < torrentPeersLowWater && t.needData() {
2369 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2370 for cl.waitWantPeers(t) {
2371 log.Printf("getting peers for %q from DHT", t)
2372 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2374 log.Printf("error getting peers from dht: %s", err)
2377 allAddrs := make(map[string]struct{})
2381 case v, ok := <-ps.Values:
2385 peersFoundByDHT.Add(int64(len(v.Peers)))
2386 for _, p := range v.Peers {
2387 allAddrs[(&net.UDPAddr{
2390 }).String()] = struct{}{}
2392 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2394 cl.addPeers(t, func() (ret []Peer) {
2395 for _, cp := range v.Peers {
2396 ret = append(ret, Peer{
2399 Source: peerSourceDHT,
2404 numPeers := len(t.Peers)
2406 if numPeers >= torrentPeersHighWater {
2409 case <-t.ceasingNetworking:
2415 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2419 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2420 url_, err := url.Parse(tr.URL())
2424 host, _, err := net.SplitHostPort(url_.Host)
2428 addr, err := net.ResolveIPAddr("ip", host)
2433 if cl.ipBlockList != nil {
2434 if cl.ipBlockRange(addr.IP) != nil {
2442 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2443 blocked, err := cl.trackerBlockedUnlocked(tr)
2445 return fmt.Errorf("error determining if tracker blocked: %s", err)
2448 return fmt.Errorf("tracker blocked: %s", tr)
2450 if err := tr.Connect(); err != nil {
2451 return fmt.Errorf("error connecting: %s", err)
2453 resp, err := tr.Announce(req)
2455 return fmt.Errorf("error announcing: %s", err)
2458 for _, peer := range resp.Peers {
2459 peers = append(peers, Peer{
2465 cl.addPeers(t, peers)
2468 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2469 peersFoundByTracker.Add(int64(len(peers)))
2471 time.Sleep(time.Second * time.Duration(resp.Interval))
2475 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2476 oks := make(chan bool)
2478 for _, tier := range trackers {
2479 for _, tr := range tier {
2481 go func(tr tracker.Client) {
2482 err := cl.announceTorrentSingleTracker(tr, req, t)
2487 for outstanding > 0 {
2497 // Announce torrent to its trackers.
2498 func (cl *Client) announceTorrentTrackers(t *torrent) {
2499 req := tracker.AnnounceRequest{
2500 Event: tracker.Started,
2502 Port: int16(cl.incomingPeerPort()),
2504 InfoHash: t.InfoHash,
2506 if !cl.waitWantPeers(t) {
2510 req.Left = t.bytesLeft()
2511 trackers := t.Trackers
2513 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2514 req.Event = tracker.None
2517 for cl.waitWantPeers(t) {
2519 req.Left = t.bytesLeft()
2520 trackers = t.Trackers
2522 numTrackersTried := 0
2523 for _, tier := range trackers {
2524 for trIndex, tr := range tier {
2526 err := cl.announceTorrentSingleTracker(tr, &req, t)
2528 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2530 // Float the successful announce to the top of the tier. If
2531 // the trackers list has been changed, we'll be modifying an
2532 // old copy so it won't matter.
2534 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2537 req.Event = tracker.None
2538 continue newAnnounce
2541 if numTrackersTried != 0 {
2542 log.Printf("%s: all trackers failed", t)
2544 // TODO: Wait until trackers are added if there are none.
2545 time.Sleep(10 * time.Second)
2549 func (cl *Client) allTorrentsCompleted() bool {
2550 for _, t := range cl.torrents {
2554 if t.numPiecesCompleted() != t.numPieces() {
2561 // Returns true when all torrents are completely downloaded and false if the
2562 // client is stopped before that.
2563 func (me *Client) WaitAll() bool {
2565 defer me.mu.Unlock()
2566 for !me.allTorrentsCompleted() {
2575 func (me *Client) fillRequests(t *torrent, c *connection) {
2580 if len(c.Requests) > c.requestsLowWater {
2584 addRequest := func(req request) (again bool) {
2585 if len(c.Requests) >= 64 {
2588 return c.Request(req)
2590 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2591 pieceIndex := e.Piece()
2592 if !c.PeerHasPiece(pieceIndex) {
2593 panic("piece in request order but peer doesn't have it")
2595 if !t.wantPiece(pieceIndex) {
2596 panic("unwanted piece in connection request order")
2598 piece := t.Pieces[pieceIndex]
2599 for _, cs := range piece.shuffledPendingChunkSpecs() {
2600 r := request{pp.Integer(pieceIndex), cs}
2609 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2613 me.fillRequests(t, c)
2614 if len(c.Requests) == 0 && !c.PeerChoked {
2615 // So we're not choked, but we don't want anything right now. We may
2616 // have completed readahead, and the readahead window has not rolled
2617 // over to the next piece. Better to stay interested in case we're
2618 // going to want data in the near future.
2619 c.SetInterested(!t.haveAllPieces())
2623 // Handle a received chunk from a peer.
2624 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2625 chunksDownloadedCount.Add(1)
2627 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2629 // Request has been satisfied.
2630 me.connDeleteRequest(t, c, req)
2632 defer me.replenishConnRequests(t, c)
2634 piece := t.Pieces[req.Index]
2636 // Do we actually want this chunk?
2637 if _, ok := piece.PendingChunkSpecs[req.chunkSpec]; !ok || piece.Priority == piecePriorityNone {
2638 unusedDownloadedChunksCount.Add(1)
2639 c.UnwantedChunksReceived++
2643 c.UsefulChunksReceived++
2644 c.lastUsefulChunkReceived = time.Now()
2646 // Write the chunk out.
2647 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2649 return fmt.Errorf("error writing chunk: %s", err)
2652 // Record that we have the chunk.
2653 delete(piece.PendingChunkSpecs, req.chunkSpec)
2654 if len(piece.PendingChunkSpecs) == 0 {
2655 for _, c := range t.Conns {
2656 c.pieceRequestOrder.DeletePiece(int(req.Index))
2658 me.queuePieceCheck(t, req.Index)
2661 // Cancel pending requests for this chunk.
2662 for _, c := range t.Conns {
2663 if me.connCancel(t, c, req) {
2664 me.replenishConnRequests(t, c)
2671 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2672 p := t.Pieces[piece]
2673 if p.EverHashed && !correct {
2674 log.Printf("%s: piece %d failed hash", t, piece)
2675 failedPieceHashes.Add(1)
2679 if sd, ok := t.data.(StatefulData); ok {
2680 err := sd.PieceCompleted(int(piece))
2682 log.Printf("error completing piece: %s", err)
2687 me.pieceChanged(t, int(piece))
2690 func (me *Client) pieceChanged(t *torrent, piece int) {
2691 correct := t.pieceComplete(piece)
2692 p := t.Pieces[piece]
2694 p.Priority = piecePriorityNone
2695 p.PendingChunkSpecs = nil
2698 if len(p.PendingChunkSpecs) == 0 {
2699 t.pendAllChunkSpecs(int(piece))
2701 if p.Priority != piecePriorityNone {
2705 for _, conn := range t.Conns {
2707 conn.Post(pp.Message{
2709 Index: pp.Integer(piece),
2711 // TODO: Cancel requests for this piece.
2712 for r := range conn.Requests {
2713 if int(r.Index) == piece {
2717 conn.pieceRequestOrder.DeletePiece(int(piece))
2719 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2720 t.connPendPiece(conn, int(piece))
2721 me.replenishConnRequests(t, conn)
2724 if t.haveAllPieces() && me.noUpload {
2727 me.event.Broadcast()
2730 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2732 defer cl.mu.Unlock()
2733 p := t.Pieces[index]
2734 for p.Hashing || t.data == nil {
2737 p.QueuedForHash = false
2738 if t.isClosed() || t.pieceComplete(int(index)) {
2743 sum := t.hashPiece(index)
2751 cl.pieceHashed(t, index, sum == p.Hash)
2754 // Returns handles to all the torrents loaded in the Client.
2755 func (me *Client) Torrents() (ret []Torrent) {
2757 for _, t := range me.torrents {
2758 ret = append(ret, Torrent{me, t})
2764 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2765 spec, err := TorrentSpecFromMagnetURI(uri)
2769 T, _, err = me.AddTorrentSpec(spec)
2773 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2774 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2778 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2779 mi, err := metainfo.LoadFromFile(filename)
2783 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))