2 Package torrent implements a torrent client.
6 c, _ := torrent.NewClient(&torrent.Config{})
8 t, _ := c.AddMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU")
11 log.Print("ermahgerd, torrent downloaded")
41 "github.com/bradfitz/iter"
43 "github.com/anacrolix/torrent/mse"
45 "github.com/anacrolix/libtorgo/bencode"
46 "github.com/anacrolix/libtorgo/metainfo"
47 "github.com/anacrolix/sync"
48 "github.com/anacrolix/torrent/data"
49 filePkg "github.com/anacrolix/torrent/data/file"
50 "github.com/anacrolix/torrent/dht"
51 "github.com/anacrolix/torrent/internal/pieceordering"
52 "github.com/anacrolix/torrent/iplist"
53 "github.com/anacrolix/torrent/logonce"
54 pp "github.com/anacrolix/torrent/peer_protocol"
55 "github.com/anacrolix/torrent/tracker"
56 _ "github.com/anacrolix/torrent/tracker/udp"
57 . "github.com/anacrolix/torrent/util"
58 "github.com/anacrolix/utp"
62 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
63 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
64 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
65 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
66 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
67 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
68 unexpectedCancels = expvar.NewInt("unexpectedCancels")
69 postedCancels = expvar.NewInt("postedCancels")
70 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
71 failedPieceHashes = expvar.NewInt("failedPieceHashes")
72 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
73 successfulDials = expvar.NewInt("successfulDials")
74 acceptedConns = expvar.NewInt("acceptedConns")
75 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
76 peerExtensions = expvar.NewMap("peerExtensions")
77 // Count of connections to peer with same client ID.
78 connsToSelf = expvar.NewInt("connsToSelf")
79 // Number of completed connections to a client we're already connected with.
80 duplicateClientConns = expvar.NewInt("duplicateClientConns")
81 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
82 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
86 // Justification for set bits follows.
88 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html ([5]|=0x10)
89 // DHT: http://www.bittorrent.org/beps/bep_0005.html ([7]|=1)
91 // http://bittorrent.org/beps/bep_0006.html ([7]|=4)
92 // Disabled until AllowedFast is implemented
93 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
95 socketsPerTorrent = 40
96 torrentPeersHighWater = 200
97 torrentPeersLowWater = 50
99 // Limit how long handshake can take. This is to reduce the lingering
100 // impact of a few bad apples. 4s loses 1% of successful handshakes that
101 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
102 btHandshakeTimeout = 4 * time.Second
103 handshakesTimeout = 20 * time.Second
105 pruneInterval = 10 * time.Second
108 // Currently doesn't really queue, but should in the future.
109 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
110 piece := t.Pieces[pieceIndex]
111 if piece.QueuedForHash {
114 piece.QueuedForHash = true
115 go cl.verifyPiece(t, pieceIndex)
118 // Queue a piece check if one isn't already queued, and the piece has never
119 // been checked before.
120 func (cl *Client) queueFirstHash(t *torrent, piece int) {
122 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
125 cl.queuePieceCheck(t, pp.Integer(piece))
133 listeners []net.Listener
139 ipBlockList *iplist.IPList
140 bannedTorrents map[InfoHash]struct{}
143 pruneTimer *time.Timer
144 extensionBytes peerExtensionBytes
145 // Set of addresses that have our client ID. This intentionally will
146 // include ourselves if we end up trying to connect to our own address
147 // through legitimate channels.
148 dopplegangerAddrs map[string]struct{}
150 torrentDataOpener TorrentDataOpener
156 torrents map[InfoHash]*torrent
159 func (me *Client) IPBlockList() *iplist.IPList {
162 return me.ipBlockList
165 func (me *Client) SetIPBlockList(list *iplist.IPList) {
168 me.ipBlockList = list
170 me.dHT.SetIPBlockList(list)
174 func (me *Client) PeerID() string {
175 return string(me.peerID[:])
178 func (me *Client) ListenAddr() (addr net.Addr) {
179 for _, l := range me.listeners {
180 if addr != nil && l.Addr().String() != addr.String() {
181 panic("listeners exist on different addresses")
188 type hashSorter struct {
192 func (me hashSorter) Len() int {
193 return len(me.Hashes)
196 func (me hashSorter) Less(a, b int) bool {
197 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
200 func (me hashSorter) Swap(a, b int) {
201 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
204 func (cl *Client) sortedTorrents() (ret []*torrent) {
206 for ih := range cl.torrents {
207 hs.Hashes = append(hs.Hashes, ih)
210 for _, ih := range hs.Hashes {
211 ret = append(ret, cl.torrent(ih))
216 // Writes out a human readable status of the client, such as for writing to a
218 func (cl *Client) WriteStatus(_w io.Writer) {
220 defer cl.mu.RUnlock()
221 w := bufio.NewWriter(_w)
223 if addr := cl.ListenAddr(); addr != nil {
224 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
226 fmt.Fprintln(w, "Not listening!")
228 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
230 dhtStats := cl.dHT.Stats()
231 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.NumNodes, dhtStats.NumGoodNodes)
232 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.IDString())
233 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.LocalAddr()))
234 fmt.Fprintf(w, "DHT announces: %d\n", cl.dHT.NumConfirmedAnnounces)
235 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.NumOutstandingTransactions)
238 for _, t := range cl.sortedTorrents() {
240 fmt.Fprint(w, "<unknown name>")
242 fmt.Fprint(w, t.Name())
246 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
248 w.WriteString("<missing metainfo>")
256 // Read torrent data at the given offset. Will block until it is available.
257 func (cl *Client) torrentReadAt(t *torrent, off int64, p []byte) (n int, err error) {
260 index := int(off / int64(t.usualPieceSize()))
261 // Reading outside the bounds of a file is an error.
266 if int(index) >= len(t.Pieces) {
270 pieceOff := pp.Integer(off % int64(t.usualPieceSize()))
271 pieceLeft := int(t.pieceLength(index) - pieceOff)
276 if len(p) > pieceLeft {
282 // TODO: ReadAt should always try to fill the buffer.
284 avail := cl.prepareRead(t, off)
285 if avail < int64(len(p)) {
288 n, err = dataReadAt(t.data, p, off)
289 if n != 0 || err != io.ErrUnexpectedEOF {
292 // If we reach here, the data we thought was ready, isn't. So we
293 // prepare it again, and retry.
298 // Sets priorities to download from the given offset. Returns when the piece
299 // at the given offset can be read. Returns the number of bytes that are
300 // immediately available from the offset.
301 func (cl *Client) prepareRead(t *torrent, off int64) (n int64) {
302 index := int(off / int64(t.usualPieceSize()))
303 // Reading outside the bounds of a file is an error.
304 if index < 0 || index >= t.numPieces() {
307 piece := t.Pieces[index]
308 cl.readRaisePiecePriorities(t, off)
309 for !t.pieceComplete(index) && !t.isClosed() {
310 // This is to prevent being starved if a piece is dropped before we
312 cl.readRaisePiecePriorities(t, off)
315 return t.Info.Piece(index).Length() - off%t.Info.PieceLength
318 func (T Torrent) prepareRead(off int64) (avail int64) {
320 defer T.cl.mu.Unlock()
321 return T.cl.prepareRead(T.torrent, off)
324 // Data implements a streaming interface that's more efficient than ReadAt.
325 type SectionOpener interface {
326 OpenSection(off, n int64) (io.ReadCloser, error)
329 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
331 if ra, ok := d.(io.ReaderAt); ok {
332 return ra.ReadAt(b, off)
334 if so, ok := d.(SectionOpener); ok {
336 rc, err = so.OpenSection(off, int64(len(b)))
341 return io.ReadFull(rc, b)
343 if dp, ok := super(d); ok {
347 panic(fmt.Sprintf("can't read from %T", d))
350 // Calculates the number of pieces to set to Readahead priority, after the
351 // Now, and Next pieces.
352 func readaheadPieces(readahead, pieceLength int64) int {
353 return int((readahead+pieceLength-1)/pieceLength - 1)
356 func (cl *Client) readRaisePiecePriorities(t *torrent, off int64) {
357 index := int(off / int64(t.usualPieceSize()))
358 cl.raisePiecePriority(t, index, piecePriorityNow)
360 if index >= t.numPieces() {
363 cl.raisePiecePriority(t, index, piecePriorityNext)
364 for range iter.N(readaheadPieces(5*1024*1024, t.Info.PieceLength)) {
366 if index >= t.numPieces() {
369 cl.raisePiecePriority(t, index, piecePriorityReadahead)
373 func (cl *Client) configDir() string {
374 if cl._configDir == "" {
375 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
380 func (cl *Client) ConfigDir() string {
381 return cl.configDir()
384 func (t *torrent) connPendPiece(c *connection, piece int) {
385 c.pendPiece(piece, t.Pieces[piece].Priority)
388 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
389 if t.Pieces[piece].Priority < priority {
391 cl.prioritizePiece(t, piece, priority)
395 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
396 if t.havePiece(piece) {
399 cl.queueFirstHash(t, piece)
400 t.Pieces[piece].Priority = priority
401 cl.pieceChanged(t, piece)
404 func (cl *Client) setEnvBlocklist() (err error) {
405 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
406 defaultBlocklist := filename == ""
407 if defaultBlocklist {
408 filename = filepath.Join(cl.configDir(), "blocklist")
410 f, err := os.Open(filename)
412 if defaultBlocklist {
418 var ranges []iplist.Range
419 uniqStrs := make(map[string]string)
420 scanner := bufio.NewScanner(f)
423 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
425 err = fmt.Errorf("error reading torrent blocklist line %d: %s", lineNum, lineErr)
432 if s, ok := uniqStrs[r.Description]; ok {
435 uniqStrs[r.Description] = r.Description
437 ranges = append(ranges, r)
441 err = fmt.Errorf("error reading torrent blocklist: %s", err)
444 cl.ipBlockList = iplist.New(ranges)
448 func (cl *Client) initBannedTorrents() error {
449 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
451 if os.IsNotExist(err) {
454 return fmt.Errorf("error opening banned infohashes file: %s", err)
457 scanner := bufio.NewScanner(f)
458 cl.bannedTorrents = make(map[InfoHash]struct{})
460 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
464 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
466 return fmt.Errorf("error reading infohash: %s", err)
472 return errors.New("bad infohash")
476 cl.bannedTorrents[ih] = struct{}{}
478 if err := scanner.Err(); err != nil {
479 return fmt.Errorf("error scanning file: %s", err)
484 // Creates a new client. Clients contain zero or more Torrents.
485 func NewClient(cfg *Config) (cl *Client, err error) {
491 noUpload: cfg.NoUpload,
492 disableTrackers: cfg.DisableTrackers,
493 halfOpenLimit: socketsPerTorrent,
494 dataDir: cfg.DataDir,
495 disableUTP: cfg.DisableUTP,
496 disableTCP: cfg.DisableTCP,
497 _configDir: cfg.ConfigDir,
499 torrentDataOpener: func(md *metainfo.Info) data.Data {
500 return filePkg.TorrentData(md, cfg.DataDir)
502 dopplegangerAddrs: make(map[string]struct{}),
504 quit: make(chan struct{}),
505 torrents: make(map[InfoHash]*torrent),
507 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
509 if cfg.TorrentDataOpener != nil {
510 cl.torrentDataOpener = cfg.TorrentDataOpener
513 if !cfg.NoDefaultBlocklist {
514 err = cl.setEnvBlocklist()
520 if err = cl.initBannedTorrents(); err != nil {
521 err = fmt.Errorf("error initing banned torrents: %s", err)
525 if cfg.PeerID != "" {
526 CopyExact(&cl.peerID, cfg.PeerID)
528 o := copy(cl.peerID[:], bep20)
529 _, err = rand.Read(cl.peerID[o:])
531 panic("error generating peer id")
535 // Returns the laddr string to listen on for the next Listen call.
536 listenAddr := func() string {
537 if addr := cl.ListenAddr(); addr != nil {
540 if cfg.ListenAddr == "" {
541 // IPv6 isn't well supported with blocklists, or with trackers and
543 return "0.0.0.0:50007"
545 return cfg.ListenAddr
549 l, err = net.Listen("tcp", listenAddr())
553 cl.listeners = append(cl.listeners, l)
554 go cl.acceptConnections(l, false)
557 cl.utpSock, err = utp.NewSocket(listenAddr())
561 cl.listeners = append(cl.listeners, cl.utpSock)
562 go cl.acceptConnections(cl.utpSock, true)
565 dhtCfg := cfg.DHTConfig
567 dhtCfg = &dht.ServerConfig{}
569 if dhtCfg.Addr == "" {
570 dhtCfg.Addr = listenAddr()
572 if dhtCfg.Conn == nil && cl.utpSock != nil {
573 dhtCfg.Conn = cl.utpSock.PacketConn()
575 cl.dHT, err = dht.NewServer(dhtCfg)
576 if cl.ipBlockList != nil {
577 cl.dHT.SetIPBlockList(cl.ipBlockList)
587 func (cl *Client) stopped() bool {
596 // Stops the client. All connections to peers are closed and all activity will
598 func (me *Client) Close() {
602 for _, l := range me.listeners {
606 for _, t := range me.torrents {
611 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
613 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
614 if cl.ipBlockList == nil {
619 log.Printf("saw non-IPv4 address")
623 r = cl.ipBlockList.Lookup(ip)
627 func (cl *Client) waitAccept() {
631 for _, t := range cl.torrents {
640 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
643 // We accept all connections immediately, because we don't know what
644 // torrent they're for.
645 conn, err := l.Accept()
660 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
661 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
663 if blockRange != nil || doppleganger {
664 inboundConnsBlocked.Add(1)
665 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
669 go cl.incomingConnection(conn, utp)
673 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
675 if tc, ok := nc.(*net.TCPConn); ok {
681 c.Discovery = peerSourceIncoming
683 err := cl.runReceivedConn(c)
689 // Returns a handle to the given torrent, if it's present in the client.
690 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
693 t, ok := cl.torrents[ih]
701 func (me *Client) torrent(ih InfoHash) *torrent {
702 return me.torrents[ih]
705 type dialResult struct {
710 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
711 conn, err := dial(addr, t)
716 conn = nil // Pedantic
718 ch <- dialResult{conn, utp}
720 successfulDials.Add(1)
723 unsuccessfulDials.Add(1)
724 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
727 if netOpErr, ok := err.(*net.OpError); ok {
728 switch netOpErr.Err {
729 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
734 log.Printf("error dialing %s: %s", addr, err)
739 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
740 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
741 if ret < minDialTimeout {
747 func (me *Client) dopplegangerAddr(addr string) bool {
748 _, ok := me.dopplegangerAddrs[addr]
752 // Start the process of connecting to the given peer for the given torrent if
754 func (me *Client) initiateConn(peer Peer, t *torrent) {
755 if peer.Id == me.peerID {
758 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
759 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
760 duplicateConnsAvoided.Add(1)
763 if r := me.ipBlockRange(peer.IP); r != nil {
764 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
767 t.HalfOpen[addr] = struct{}{}
768 go me.outgoingConnection(t, addr, peer.Source)
771 func (me *Client) dialTimeout(t *torrent) time.Duration {
772 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, len(t.Peers))
775 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
776 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
778 c.(*net.TCPConn).SetLinger(0)
783 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
784 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
787 // Returns a connection over UTP or TCP.
788 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
789 // Initiate connections via TCP and UTP simultaneously. Use the first one
798 resCh := make(chan dialResult, left)
800 go doDial(me.dialUTP, resCh, true, addr, t)
803 go doDial(me.dialTCP, resCh, false, addr, t)
806 // Wait for a successful connection.
807 for ; left > 0 && res.Conn == nil; left-- {
811 // There are still incompleted dials.
813 for ; left > 0; left-- {
814 conn := (<-resCh).Conn
826 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
827 if _, ok := t.HalfOpen[addr]; !ok {
828 panic("invariant broken")
830 delete(t.HalfOpen, addr)
834 // Returns nil connection and nil error if no connection could be established
835 // for valid reasons.
836 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
837 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
841 c.encrypted = encrypted
843 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
847 ok, err := me.initiateHandshakes(c, t)
853 nc, utp := me.dial(addr, t)
857 c, err = handshakesConnection(nc, true, utp)
866 nc, err = me.dialUTP(addr, t)
868 nc, err = me.dialTCP(addr, t)
871 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
874 c, err = handshakesConnection(nc, false, utp)
881 // Called to dial out and run a connection. The addr we're given is already
882 // considered half-open.
883 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
884 c, err := me.establishOutgoingConn(t, addr)
887 // Don't release lock between here and addConnection, unless it's for
889 me.noLongerHalfOpen(t, addr)
899 err = me.runInitiatedHandshookConn(c, t)
905 // The port number for incoming peer connections. 0 if the client isn't
907 func (cl *Client) incomingPeerPort() int {
908 listenAddr := cl.ListenAddr()
909 if listenAddr == nil {
912 return addrPort(listenAddr)
915 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
916 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
917 func addrCompactIP(addr net.Addr) (string, error) {
918 host, _, err := net.SplitHostPort(addr.String())
922 ip := net.ParseIP(host)
923 if v4 := ip.To4(); v4 != nil {
927 return string(v4), nil
929 return string(ip.To16()), nil
932 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
944 peerExtensionBytes [8]byte
948 func (me *peerExtensionBytes) SupportsExtended() bool {
949 return me[5]&0x10 != 0
952 func (me *peerExtensionBytes) SupportsDHT() bool {
953 return me[7]&0x01 != 0
956 func (me *peerExtensionBytes) SupportsFast() bool {
957 return me[7]&0x04 != 0
960 type handshakeResult struct {
966 // ih is nil if we expect the peer to declare the InfoHash, such as when the
967 // peer initiated the connection. Returns ok if the handshake was successful,
968 // and err if there was an unexpected condition other than the peer simply
969 // abandoning the handshake.
970 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
971 // Bytes to be sent to the peer. Should never block the sender.
972 postCh := make(chan []byte, 4)
973 // A single error value sent when the writer completes.
974 writeDone := make(chan error, 1)
975 // Performs writes to the socket and ensures posts don't block.
976 go handshakeWriter(sock, postCh, writeDone)
979 close(postCh) // Done writing.
986 // Wait until writes complete before returning from handshake.
989 err = fmt.Errorf("error writing: %s", err)
993 post := func(bb []byte) {
997 panic("mustn't block while posting")
1001 post([]byte(pp.Protocol))
1003 if ih != nil { // We already know what we want.
1008 _, err = io.ReadFull(sock, b[:68])
1013 if string(b[:20]) != pp.Protocol {
1016 CopyExact(&res.peerExtensionBytes, b[20:28])
1017 CopyExact(&res.InfoHash, b[28:48])
1018 CopyExact(&res.peerID, b[48:68])
1019 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
1021 // TODO: Maybe we can just drop peers here if we're not interested. This
1022 // could prevent them trying to reconnect, falsely believing there was
1024 if ih == nil { // We were waiting for the peer to tell us what they wanted.
1025 post(res.InfoHash[:])
1033 // Wraps a raw connection and provides the interface we want for using the
1034 // connection in the message loop.
1035 type deadlineReader struct {
1040 func (me deadlineReader) Read(b []byte) (n int, err error) {
1041 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1042 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1044 err = fmt.Errorf("error setting read deadline: %s", err)
1046 n, err = me.r.Read(b)
1047 // Convert common errors into io.EOF.
1049 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1051 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1061 type readWriter struct {
1066 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1067 var protocol [len(pp.Protocol)]byte
1068 _, err = io.ReadFull(rw, protocol[:])
1073 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1076 if string(protocol[:]) == pp.Protocol {
1080 ret, err = mse.ReceiveHandshake(ret, skeys)
1084 func (cl *Client) receiveSkeys() (ret [][]byte) {
1085 for ih := range cl.torrents {
1086 ret = append(ret, ih[:])
1091 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1093 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1098 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1099 if ih != t.InfoHash {
1105 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1107 skeys := cl.receiveSkeys()
1109 // TODO: Filter unmatching skey errors.
1110 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1112 if err == mse.ErrNoSecretKeyMatch {
1117 ih, ok, err := cl.connBTHandshake(c, nil)
1119 fmt.Errorf("error during bt handshake: %s", err)
1131 // Returns !ok if handshake failed for valid reasons.
1132 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1133 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1134 if err != nil || !ok {
1138 c.PeerExtensionBytes = res.peerExtensionBytes
1139 c.PeerID = res.peerID
1140 c.completedHandshake = time.Now()
1144 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1145 if c.PeerID == cl.peerID {
1146 // Only if we initiated the connection is the remote address a
1147 // listen addr for a doppleganger.
1149 addr := c.conn.RemoteAddr().String()
1150 cl.dopplegangerAddrs[addr] = struct{}{}
1153 return cl.runHandshookConn(c, t)
1156 func (cl *Client) runReceivedConn(c *connection) (err error) {
1157 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1161 t, err := cl.receiveHandshakes(c)
1163 logonce.Stderr.Printf("error receiving handshakes: %s", err)
1171 defer cl.mu.Unlock()
1172 if c.PeerID == cl.peerID {
1175 return cl.runHandshookConn(c, t)
1178 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1179 c.conn.SetWriteDeadline(time.Time{})
1181 deadlineReader{c.conn, c.rw},
1184 if !cl.addConnection(t, c) {
1187 defer cl.dropConnection(t, c)
1189 go c.writeOptimizer(time.Minute)
1190 cl.sendInitialMessages(c, t)
1192 t.initRequestOrdering(c)
1194 err = cl.connectionLoop(t, c)
1196 err = fmt.Errorf("error during connection loop: %s", err)
1201 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1202 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1203 conn.Post(pp.Message{
1205 ExtendedID: pp.HandshakeExtendedID,
1206 ExtendedPayload: func() []byte {
1207 d := map[string]interface{}{
1208 "m": map[string]int{
1212 "v": "go.torrent dev 20140825", // Just the date
1213 // No upload queue is implemented yet.
1214 "reqq": func() int {
1216 // No need to look strange if it costs us nothing.
1222 "e": 1, // Awwww yeah
1224 if torrent.metadataSizeKnown() {
1225 d["metadata_size"] = torrent.metadataSize()
1227 if p := me.incomingPeerPort(); p != 0 {
1230 yourip, err := addrCompactIP(conn.remoteAddr())
1232 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1234 d["yourip"] = yourip
1236 // log.Printf("sending %v", d)
1237 b, err := bencode.Marshal(d)
1245 if torrent.haveAnyPieces() {
1246 conn.Post(pp.Message{
1248 Bitfield: torrent.bitfield(),
1250 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1251 conn.Post(pp.Message{
1255 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1256 conn.Post(pp.Message{
1258 Port: uint16(AddrPort(me.dHT.LocalAddr())),
1263 // Randomizes the piece order for this connection. Every connection will be
1264 // given a different ordering. Having it stored per connection saves having to
1265 // randomize during request filling, and constantly recalculate the ordering
1266 // based on piece priorities.
1267 func (t *torrent) initRequestOrdering(c *connection) {
1268 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1269 panic("double init of request ordering")
1271 c.piecePriorities = mathRand.Perm(t.numPieces())
1272 c.pieceRequestOrder = pieceordering.New()
1273 for i := range iter.N(t.Info.NumPieces()) {
1274 if !c.PeerHasPiece(i) {
1277 if !t.wantPiece(i) {
1280 t.connPendPiece(c, i)
1284 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1287 if c.PeerPieces == nil {
1288 c.PeerPieces = make([]bool, t.numPieces())
1291 for piece >= len(c.PeerPieces) {
1292 c.PeerPieces = append(c.PeerPieces, false)
1295 c.PeerPieces[piece] = true
1297 if t.wantPiece(piece) {
1298 t.connPendPiece(c, piece)
1299 me.replenishConnRequests(t, c)
1303 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1304 me.replenishConnRequests(torrent, conn)
1307 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1310 postedCancels.Add(1)
1315 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1316 if !cn.RequestPending(r) {
1319 delete(cn.Requests, r)
1322 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1327 for index := 0; index < t.metadataPieceCount(); index++ {
1328 if !t.haveMetadataPiece(index) {
1329 pending = append(pending, index)
1332 for _, i := range mathRand.Perm(len(pending)) {
1335 ExtendedID: byte(c.PeerExtensionIDs["ut_metadata"]),
1336 ExtendedPayload: func() []byte {
1337 b, err := bencode.Marshal(map[string]int{
1339 "piece": pending[i],
1350 func (cl *Client) completedMetadata(t *torrent) {
1354 CopyExact(&ih, h.Sum(nil))
1355 if ih != t.InfoHash {
1356 log.Print("bad metadata")
1357 t.invalidateMetadata()
1360 var info metainfo.Info
1361 err := bencode.Unmarshal(t.MetaData, &info)
1363 log.Printf("error unmarshalling metadata: %s", err)
1364 t.invalidateMetadata()
1367 // TODO(anacrolix): If this fails, I think something harsher should be
1369 err = cl.setMetaData(t, &info, t.MetaData)
1371 log.Printf("error setting metadata: %s", err)
1372 t.invalidateMetadata()
1375 log.Printf("%s: got metadata from peers", t)
1378 // Process incoming ut_metadata message.
1379 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1380 var d map[string]int
1381 err = bencode.Unmarshal(payload, &d)
1383 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1386 msgType, ok := d["msg_type"]
1388 err = errors.New("missing msg_type field")
1393 case pp.DataMetadataExtensionMsgType:
1397 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1398 if begin < 0 || begin >= len(payload) {
1399 log.Printf("got bad metadata piece")
1402 t.saveMetadataPiece(piece, payload[begin:])
1403 c.UsefulChunksReceived++
1404 c.lastUsefulChunkReceived = time.Now()
1405 if !t.haveAllMetadataPieces() {
1408 cl.completedMetadata(t)
1409 case pp.RequestMetadataExtensionMsgType:
1410 if !t.haveMetadataPiece(piece) {
1411 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1414 start := (1 << 14) * piece
1415 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1416 case pp.RejectMetadataExtensionMsgType:
1418 err = errors.New("unknown msg_type value")
1423 type peerExchangeMessage struct {
1424 Added CompactPeers `bencode:"added"`
1425 AddedFlags []byte `bencode:"added.f"`
1426 Dropped CompactPeers `bencode:"dropped"`
1429 // Extracts the port as an integer from an address string.
1430 func addrPort(addr net.Addr) int {
1431 return AddrPort(addr)
1434 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1435 cn.peerHasAll = true
1438 for i := 0; i < t.numPieces(); i++ {
1439 cl.peerGotPiece(t, cn, i)
1444 // Processes incoming bittorrent messages. The client lock is held upon entry
1446 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1447 decoder := pp.Decoder{
1448 R: bufio.NewReader(c.rw),
1449 MaxLength: 256 * 1024,
1454 err := decoder.Decode(&msg)
1455 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1457 c.lastMessageReceived = time.Now()
1464 if me.stopped() || err == io.EOF {
1475 for r := range c.Requests {
1476 me.connDeleteRequest(t, c, r)
1478 // We can then reset our interest.
1479 me.replenishConnRequests(t, c)
1481 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1482 me.replenishConnRequests(t, c)
1484 c.PeerChoked = false
1485 me.peerUnchoked(t, c)
1487 c.PeerInterested = true
1488 // TODO: This should be done from a dedicated unchoking routine.
1493 case pp.NotInterested:
1494 c.PeerInterested = false
1497 me.peerGotPiece(t, c, int(msg.Index))
1502 if c.PeerRequests == nil {
1503 c.PeerRequests = make(map[request]struct{}, maxRequests)
1505 request := newRequest(msg.Index, msg.Begin, msg.Length)
1506 // TODO: Requests should be satisfied from a dedicated upload
1508 // c.PeerRequests[request] = struct{}{}
1509 p := make([]byte, msg.Length)
1510 n, err := dataReadAt(t.data, p, int64(t.pieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1512 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1514 if n != int(msg.Length) {
1515 return fmt.Errorf("bad request: %v", msg)
1523 uploadChunksPosted.Add(1)
1525 req := newRequest(msg.Index, msg.Begin, msg.Length)
1526 if !c.PeerCancel(req) {
1527 unexpectedCancels.Add(1)
1530 if c.PeerPieces != nil || c.peerHasAll {
1531 err = errors.New("received unexpected bitfield")
1535 if len(msg.Bitfield) < t.numPieces() {
1536 err = errors.New("received invalid bitfield")
1539 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1541 c.PeerPieces = msg.Bitfield
1542 for index, has := range c.PeerPieces {
1544 me.peerGotPiece(t, c, index)
1548 if c.PeerPieces != nil || c.peerHasAll {
1549 err = errors.New("unexpected have-all")
1554 if c.peerHasAll || c.PeerPieces != nil {
1555 err = errors.New("unexpected have-none")
1558 c.PeerPieces = make([]bool, func() int {
1560 return t.numPieces()
1566 err = me.downloadedChunk(t, c, &msg)
1568 switch msg.ExtendedID {
1569 case pp.HandshakeExtendedID:
1570 // TODO: Create a bencode struct for this.
1571 var d map[string]interface{}
1572 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1574 err = fmt.Errorf("error decoding extended message payload: %s", err)
1577 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1578 if reqq, ok := d["reqq"]; ok {
1579 if i, ok := reqq.(int64); ok {
1580 c.PeerMaxRequests = int(i)
1583 if v, ok := d["v"]; ok {
1584 c.PeerClientName = v.(string)
1588 err = errors.New("handshake missing m item")
1591 mTyped, ok := m.(map[string]interface{})
1593 err = errors.New("handshake m value is not dict")
1596 if c.PeerExtensionIDs == nil {
1597 c.PeerExtensionIDs = make(map[string]int64, len(mTyped))
1599 for name, v := range mTyped {
1602 log.Printf("bad handshake m item extension ID type: %T", v)
1606 delete(c.PeerExtensionIDs, name)
1608 if c.PeerExtensionIDs[name] == 0 {
1609 supportedExtensionMessages.Add(name, 1)
1611 c.PeerExtensionIDs[name] = id
1614 metadata_sizeUntyped, ok := d["metadata_size"]
1616 metadata_size, ok := metadata_sizeUntyped.(int64)
1618 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1620 t.setMetadataSize(metadata_size)
1623 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1624 me.requestPendingMetadata(t, c)
1627 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1629 err = fmt.Errorf("error handling metadata extension message: %s", err)
1632 var pexMsg peerExchangeMessage
1633 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1635 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1640 me.addPeers(t, func() (ret []Peer) {
1641 for i, cp := range pexMsg.Added {
1643 IP: make([]byte, 4),
1645 Source: peerSourcePEX,
1647 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1648 p.SupportsEncryption = true
1650 CopyExact(p.IP, cp.IP[:])
1651 ret = append(ret, p)
1656 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1659 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1662 // That client uses its own extension IDs for outgoing message
1663 // types, which is incorrect.
1664 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1665 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1668 // log.Printf("peer extension map: %#v", c.PeerExtensionIDs)
1674 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1679 pingAddr.Port = int(msg.Port)
1681 _, err = me.dHT.Ping(pingAddr)
1683 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1691 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1692 me.event.Broadcast()
1693 for r := range conn.Requests {
1694 me.connDeleteRequest(torrent, conn, r)
1697 for i0, c := range torrent.Conns {
1701 i1 := len(torrent.Conns) - 1
1703 torrent.Conns[i0] = torrent.Conns[i1]
1705 torrent.Conns = torrent.Conns[:i1]
1706 me.openNewConns(torrent)
1709 panic("connection not found")
1712 func (me *Client) addConnection(t *torrent, c *connection) bool {
1717 case <-t.ceasingNetworking:
1721 if !me.wantConns(t) {
1724 for _, c0 := range t.Conns {
1725 if c.PeerID == c0.PeerID {
1726 // Already connected to a client with that ID.
1727 duplicateClientConns.Add(1)
1731 t.Conns = append(t.Conns, c)
1732 // TODO: This should probably be done by a routine that kills off bad
1733 // connections, and extra connections killed here instead.
1734 if len(t.Conns) > socketsPerTorrent {
1735 wcs := t.worstConnsHeap()
1736 heap.Pop(wcs).(*connection).Close()
1741 func (t *torrent) needData() bool {
1745 for i := range t.Pieces {
1753 // TODO: I'm sure there's something here to do with seeding.
1754 func (t *torrent) badConn(c *connection) bool {
1755 // A 30 second grace for initial messages to go through.
1756 if time.Since(c.completedHandshake) < 30*time.Second {
1760 if !c.supportsExtension("ut_metadata") {
1763 if time.Since(c.completedHandshake) > 2*time.Minute {
1767 return !t.connHasWantedPieces(c)
1770 func (t *torrent) numGoodConns() (num int) {
1771 for _, c := range t.Conns {
1779 func (me *Client) wantConns(t *torrent) bool {
1780 if me.noUpload && !t.needData() {
1783 if t.numGoodConns() >= socketsPerTorrent {
1789 func (me *Client) openNewConns(t *torrent) {
1791 case <-t.ceasingNetworking:
1795 for len(t.Peers) != 0 {
1796 if !me.wantConns(t) {
1799 if len(t.HalfOpen) >= me.halfOpenLimit {
1806 for k, p = range t.Peers {
1810 me.initiateConn(p, t)
1812 t.wantPeers.Broadcast()
1815 func (me *Client) addPeers(t *torrent, peers []Peer) {
1816 for _, p := range peers {
1817 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1820 if me.ipBlockRange(p.IP) != nil {
1828 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1829 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1832 func (cl *Client) saveTorrentFile(t *torrent) error {
1833 path := cl.cachedMetaInfoFilename(t.InfoHash)
1834 os.MkdirAll(filepath.Dir(path), 0777)
1835 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1837 return fmt.Errorf("error opening file: %s", err)
1840 e := bencode.NewEncoder(f)
1841 err = e.Encode(t.MetaInfo())
1843 return fmt.Errorf("error marshalling metainfo: %s", err)
1845 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1847 // For example, a script kiddy makes us load too many files, and we're
1848 // able to save the torrent, but not load it again to check it.
1851 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1852 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1857 func (cl *Client) startTorrent(t *torrent) {
1858 if t.Info == nil || t.data == nil {
1861 // If the client intends to upload, it needs to know what state pieces are
1864 // Queue all pieces for hashing. This is done sequentially to avoid
1865 // spamming goroutines.
1866 for _, p := range t.Pieces {
1867 p.QueuedForHash = true
1870 for i := range t.Pieces {
1871 cl.verifyPiece(t, pp.Integer(i))
1877 // Storage cannot be changed once it's set.
1878 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1879 err = t.setStorage(td)
1880 cl.event.Broadcast()
1888 type TorrentDataOpener func(*metainfo.Info) data.Data
1890 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1891 err = t.setMetadata(md, bytes, &cl.mu)
1895 if !cl.config.DisableMetainfoCache {
1896 if err := cl.saveTorrentFile(t); err != nil {
1897 log.Printf("error saving torrent file for %s: %s", t, err)
1900 cl.event.Broadcast()
1901 if strings.Contains(strings.ToLower(md.Name), "porn") {
1902 cl.dropTorrent(t.InfoHash)
1903 err = errors.New("no porn plx")
1906 close(t.gotMetainfo)
1907 td := cl.torrentDataOpener(md)
1908 err = cl.setStorage(t, td)
1912 // Prepare a Torrent without any attachment to a Client. That means we can
1913 // initialize fields all fields that don't require the Client without locking
1915 func newTorrent(ih InfoHash) (t *torrent, err error) {
1918 Peers: make(map[peersKey]Peer),
1920 closing: make(chan struct{}),
1921 ceasingNetworking: make(chan struct{}),
1923 gotMetainfo: make(chan struct{}),
1925 HalfOpen: make(map[string]struct{}),
1927 t.wantPeers.L = &t.stateMu
1928 t.GotMetainfo = t.gotMetainfo
1933 // For shuffling the tracker tiers.
1934 mathRand.Seed(time.Now().Unix())
1937 // The trackers within each tier must be shuffled before use.
1938 // http://stackoverflow.com/a/12267471/149482
1939 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1940 func shuffleTier(tier []tracker.Client) {
1941 for i := range tier {
1942 j := mathRand.Intn(i + 1)
1943 tier[i], tier[j] = tier[j], tier[i]
1947 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1948 for _, tier := range base {
1949 copy = append(copy, append([]tracker.Client{}, tier...))
1954 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1956 for _, url := range newURLs {
1957 for _, tr := range tier {
1958 if tr.URL() == url {
1962 tr, err := tracker.New(url)
1964 log.Printf("error creating tracker client for %q: %s", url, err)
1967 tier = append(tier, tr)
1972 func (t *torrent) addTrackers(announceList [][]string) {
1973 newTrackers := copyTrackers(t.Trackers)
1974 for tierIndex, tier := range announceList {
1975 if tierIndex < len(newTrackers) {
1976 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1978 newTrackers = append(newTrackers, mergeTier(nil, tier))
1980 shuffleTier(newTrackers[tierIndex])
1982 t.Trackers = newTrackers
1985 // A handle to a live torrent within a Client.
1986 type Torrent struct {
1991 func (t Torrent) NumPieces() int {
1992 return t.numPieces()
1995 func (t Torrent) Drop() {
1997 t.cl.dropTorrent(t.InfoHash)
2001 // Provides access to regions of torrent data that correspond to its files.
2007 fi metainfo.FileInfo
2010 func (f File) FileInfo() metainfo.FileInfo {
2014 func (f File) Path() string {
2018 // A file-like handle to some torrent data resource.
2019 type Handle interface {
2026 // Implements a Handle within a subsection of another Handle.
2027 type sectionHandle struct {
2032 func (me *sectionHandle) Seek(offset int64, whence int) (ret int64, err error) {
2035 } else if whence == 2 {
2037 offset += me.off + me.n
2039 ret, err = me.h.Seek(offset, whence)
2045 func (me *sectionHandle) Close() error {
2049 func (me *sectionHandle) Read(b []byte) (n int, err error) {
2050 max := me.off + me.n - me.cur
2051 if int64(len(b)) > max {
2054 n, err = me.h.Read(b)
2059 if me.cur == me.off+me.n {
2065 func (me *sectionHandle) ReadAt(b []byte, off int64) (n int, err error) {
2070 if int64(len(b)) >= me.n-off {
2073 return me.h.ReadAt(b, me.off+off)
2076 func (f File) Open() (h Handle, err error) {
2077 h = f.t.NewReadHandle()
2078 _, err = h.Seek(f.offset, os.SEEK_SET)
2083 h = §ionHandle{h, f.offset, f.Length(), f.offset}
2087 func (f File) ReadAt(p []byte, off int64) (n int, err error) {
2088 maxLen := f.length - off
2089 if int64(len(p)) > maxLen {
2092 return f.t.ReadAt(p, off+f.offset)
2095 func (f *File) Length() int64 {
2099 type FilePieceState struct {
2104 func (f *File) Progress() (ret []FilePieceState) {
2105 pieceSize := int64(f.t.usualPieceSize())
2106 off := f.offset % pieceSize
2107 remaining := f.length
2108 for i := int(f.offset / pieceSize); ; i++ {
2112 len1 := pieceSize - off
2113 if len1 > remaining {
2116 ret = append(ret, FilePieceState{len1, f.t.pieceStatusChar(i)})
2123 func (f *File) PrioritizeRegion(off, len int64) {
2124 if off < 0 || off >= f.length {
2127 if off+len > f.length {
2128 len = f.length - off
2131 f.t.SetRegionPriority(off, len)
2134 // Returns handles to the files in the torrent. This requires the metainfo is
2136 func (t Torrent) Files() (ret []File) {
2144 for _, fi := range info.UpvertedFiles() {
2145 ret = append(ret, File{
2147 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2157 func (t Torrent) SetRegionPriority(off, len int64) {
2159 defer t.cl.mu.Unlock()
2160 pieceSize := int64(t.usualPieceSize())
2161 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2162 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
2166 func (t Torrent) AddPeers(pp []Peer) error {
2169 defer cl.mu.Unlock()
2170 cl.addPeers(t.torrent, pp)
2174 // Marks the entire torrent for download.
2175 func (t Torrent) DownloadAll() {
2177 defer t.cl.mu.Unlock()
2178 for i := range iter.N(t.numPieces()) {
2179 t.cl.raisePiecePriority(t.torrent, i, piecePriorityNormal)
2181 // Nice to have the first and last pieces sooner for various interactive
2183 t.cl.raisePiecePriority(t.torrent, 0, piecePriorityReadahead)
2184 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, piecePriorityReadahead)
2187 func (me Torrent) ReadAt(p []byte, off int64) (n int, err error) {
2188 return me.cl.torrentReadAt(me.torrent, off, p)
2191 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2192 // metainfo has the correct infohash.
2193 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2194 if cl.config.DisableMetainfoCache {
2197 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2199 if os.IsNotExist(err) {
2205 dec := bencode.NewDecoder(f)
2206 err = dec.Decode(&mi)
2210 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2211 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2217 // Specifies a new torrent for adding to a client. There are helpers for
2218 // magnet URIs and torrent metainfo files.
2219 type TorrentSpec struct {
2222 Info *metainfo.InfoEx
2226 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2227 m, err := ParseMagnetURI(uri)
2231 spec = &TorrentSpec{
2232 Trackers: [][]string{m.Trackers},
2233 DisplayName: m.DisplayName,
2235 CopyExact(&spec.InfoHash, &m.InfoHash)
2239 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2240 spec = &TorrentSpec{
2241 Trackers: mi.AnnounceList,
2244 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2248 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2251 defer cl.mu.Unlock()
2253 t, ok := cl.torrents[spec.InfoHash]
2261 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2262 err = errors.New("banned torrent")
2266 t, err = newTorrent(spec.InfoHash)
2270 if spec.DisplayName != "" {
2271 t.DisplayName = spec.DisplayName
2273 if spec.Info != nil {
2274 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2276 var mi *metainfo.MetaInfo
2277 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2279 log.Printf("error getting cached metainfo: %s", err)
2280 } else if mi != nil {
2281 t.addTrackers(mi.AnnounceList)
2282 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2289 cl.torrents[spec.InfoHash] = t
2292 T.torrent.pruneTimer = time.AfterFunc(0, func() {
2293 cl.pruneConnectionsUnlocked(T.torrent)
2295 t.addTrackers(spec.Trackers)
2296 if !cl.disableTrackers {
2297 go cl.announceTorrentTrackers(T.torrent)
2300 go cl.announceTorrentDHT(T.torrent, true)
2305 // Prunes unused connections. This is required to make space to dial for
2307 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
2309 case <-t.ceasingNetworking:
2316 license := len(t.Conns) - (socketsPerTorrent+1)/2
2317 for _, c := range t.Conns {
2321 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
2324 if time.Now().Sub(c.completedHandshake) < time.Minute {
2331 t.pruneTimer.Reset(pruneInterval)
2334 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2335 t, ok := me.torrents[infoHash]
2337 err = fmt.Errorf("no such torrent")
2344 delete(me.torrents, infoHash)
2348 // Returns true when peers are required, or false if the torrent is closing.
2349 func (cl *Client) waitWantPeers(t *torrent) bool {
2351 defer cl.mu.Unlock()
2353 defer t.stateMu.Unlock()
2356 case <-t.ceasingNetworking:
2360 if len(t.Peers) < torrentPeersLowWater && t.needData() {
2371 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2372 for cl.waitWantPeers(t) {
2373 log.Printf("getting peers for %q from DHT", t)
2374 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2376 log.Printf("error getting peers from dht: %s", err)
2379 allAddrs := make(map[string]struct{})
2383 case v, ok := <-ps.Values:
2387 peersFoundByDHT.Add(int64(len(v.Peers)))
2388 for _, p := range v.Peers {
2389 allAddrs[(&net.UDPAddr{
2392 }).String()] = struct{}{}
2394 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2396 cl.addPeers(t, func() (ret []Peer) {
2397 for _, cp := range v.Peers {
2398 ret = append(ret, Peer{
2401 Source: peerSourceDHT,
2406 numPeers := len(t.Peers)
2408 if numPeers >= torrentPeersHighWater {
2411 case <-t.ceasingNetworking:
2417 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2421 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2422 url_, err := url.Parse(tr.URL())
2426 host, _, err := net.SplitHostPort(url_.Host)
2430 addr, err := net.ResolveIPAddr("ip", host)
2435 if cl.ipBlockList != nil {
2436 if cl.ipBlockRange(addr.IP) != nil {
2444 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2445 blocked, err := cl.trackerBlockedUnlocked(tr)
2447 return fmt.Errorf("error determining if tracker blocked: %s", err)
2450 return fmt.Errorf("tracker blocked: %s", tr)
2452 if err := tr.Connect(); err != nil {
2453 return fmt.Errorf("error connecting: %s", err)
2455 resp, err := tr.Announce(req)
2457 return fmt.Errorf("error announcing: %s", err)
2460 for _, peer := range resp.Peers {
2461 peers = append(peers, Peer{
2467 cl.addPeers(t, peers)
2470 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2471 peersFoundByTracker.Add(int64(len(peers)))
2473 time.Sleep(time.Second * time.Duration(resp.Interval))
2477 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2478 oks := make(chan bool)
2480 for _, tier := range trackers {
2481 for _, tr := range tier {
2483 go func(tr tracker.Client) {
2484 err := cl.announceTorrentSingleTracker(tr, req, t)
2489 for outstanding > 0 {
2499 // Announce torrent to its trackers.
2500 func (cl *Client) announceTorrentTrackers(t *torrent) {
2501 req := tracker.AnnounceRequest{
2502 Event: tracker.Started,
2504 Port: int16(cl.incomingPeerPort()),
2506 InfoHash: t.InfoHash,
2508 if !cl.waitWantPeers(t) {
2512 req.Left = t.bytesLeft()
2513 trackers := t.Trackers
2515 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2516 req.Event = tracker.None
2519 for cl.waitWantPeers(t) {
2521 req.Left = t.bytesLeft()
2522 trackers = t.Trackers
2524 numTrackersTried := 0
2525 for _, tier := range trackers {
2526 for trIndex, tr := range tier {
2528 err := cl.announceTorrentSingleTracker(tr, &req, t)
2530 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2532 // Float the successful announce to the top of the tier. If
2533 // the trackers list has been changed, we'll be modifying an
2534 // old copy so it won't matter.
2536 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2539 req.Event = tracker.None
2540 continue newAnnounce
2543 if numTrackersTried != 0 {
2544 log.Printf("%s: all trackers failed", t)
2546 // TODO: Wait until trackers are added if there are none.
2547 time.Sleep(10 * time.Second)
2551 func (cl *Client) allTorrentsCompleted() bool {
2552 for _, t := range cl.torrents {
2556 if t.numPiecesCompleted() != t.numPieces() {
2563 // Returns true when all torrents are completely downloaded and false if the
2564 // client is stopped before that.
2565 func (me *Client) WaitAll() bool {
2567 defer me.mu.Unlock()
2568 for !me.allTorrentsCompleted() {
2577 func (me *Client) fillRequests(t *torrent, c *connection) {
2582 if len(c.Requests) > c.requestsLowWater {
2586 addRequest := func(req request) (again bool) {
2587 if len(c.Requests) >= 64 {
2590 return c.Request(req)
2592 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2593 pieceIndex := e.Piece()
2594 if !c.PeerHasPiece(pieceIndex) {
2595 panic("piece in request order but peer doesn't have it")
2597 if !t.wantPiece(pieceIndex) {
2598 panic("unwanted piece in connection request order")
2600 piece := t.Pieces[pieceIndex]
2601 for _, cs := range piece.shuffledPendingChunkSpecs() {
2602 r := request{pp.Integer(pieceIndex), cs}
2611 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2615 me.fillRequests(t, c)
2616 if len(c.Requests) == 0 && !c.PeerChoked {
2617 // So we're not choked, but we don't want anything right now. We may
2618 // have completed readahead, and the readahead window has not rolled
2619 // over to the next piece. Better to stay interested in case we're
2620 // going to want data in the near future.
2621 c.SetInterested(!t.haveAllPieces())
2625 // Handle a received chunk from a peer.
2626 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2627 chunksDownloadedCount.Add(1)
2629 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2631 // Request has been satisfied.
2632 me.connDeleteRequest(t, c, req)
2634 defer me.replenishConnRequests(t, c)
2636 piece := t.Pieces[req.Index]
2638 // Do we actually want this chunk?
2639 if _, ok := piece.PendingChunkSpecs[req.chunkSpec]; !ok || piece.Priority == piecePriorityNone {
2640 unusedDownloadedChunksCount.Add(1)
2641 c.UnwantedChunksReceived++
2645 c.UsefulChunksReceived++
2646 c.lastUsefulChunkReceived = time.Now()
2648 // Write the chunk out.
2649 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2651 return fmt.Errorf("error writing chunk: %s", err)
2654 // Record that we have the chunk.
2655 delete(piece.PendingChunkSpecs, req.chunkSpec)
2656 if len(piece.PendingChunkSpecs) == 0 {
2657 for _, c := range t.Conns {
2658 c.pieceRequestOrder.DeletePiece(int(req.Index))
2660 me.queuePieceCheck(t, req.Index)
2663 // Cancel pending requests for this chunk.
2664 for _, c := range t.Conns {
2665 if me.connCancel(t, c, req) {
2666 me.replenishConnRequests(t, c)
2673 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2674 p := t.Pieces[piece]
2675 if p.EverHashed && !correct {
2676 log.Printf("%s: piece %d failed hash", t, piece)
2677 failedPieceHashes.Add(1)
2681 if sd, ok := t.data.(StatefulData); ok {
2682 err := sd.PieceCompleted(int(piece))
2684 log.Printf("error completing piece: %s", err)
2689 me.pieceChanged(t, int(piece))
2692 func (me *Client) pieceChanged(t *torrent, piece int) {
2693 correct := t.pieceComplete(piece)
2694 p := t.Pieces[piece]
2696 p.Priority = piecePriorityNone
2697 p.PendingChunkSpecs = nil
2700 if len(p.PendingChunkSpecs) == 0 {
2701 t.pendAllChunkSpecs(int(piece))
2703 if p.Priority != piecePriorityNone {
2707 for _, conn := range t.Conns {
2709 conn.Post(pp.Message{
2711 Index: pp.Integer(piece),
2713 // TODO: Cancel requests for this piece.
2714 for r := range conn.Requests {
2715 if int(r.Index) == piece {
2719 conn.pieceRequestOrder.DeletePiece(int(piece))
2721 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2722 t.connPendPiece(conn, int(piece))
2723 me.replenishConnRequests(t, conn)
2726 if t.haveAllPieces() && me.noUpload {
2729 me.event.Broadcast()
2732 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2734 defer cl.mu.Unlock()
2735 p := t.Pieces[index]
2736 for p.Hashing || t.data == nil {
2739 p.QueuedForHash = false
2740 if t.isClosed() || t.pieceComplete(int(index)) {
2745 sum := t.hashPiece(index)
2753 cl.pieceHashed(t, index, sum == p.Hash)
2756 // Returns handles to all the torrents loaded in the Client.
2757 func (me *Client) Torrents() (ret []Torrent) {
2759 for _, t := range me.torrents {
2760 ret = append(ret, Torrent{me, t})
2766 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2767 spec, err := TorrentSpecFromMagnetURI(uri)
2771 T, _, err = me.AddTorrentSpec(spec)
2775 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2776 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2780 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2781 mi, err := metainfo.LoadFromFile(filename)
2785 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))