25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/pubsub"
29 "github.com/anacrolix/sync"
30 "github.com/anacrolix/utp"
31 "github.com/bradfitz/iter"
32 "github.com/edsrzf/mmap-go"
34 "github.com/anacrolix/torrent/bencode"
35 "github.com/anacrolix/torrent/data"
36 filePkg "github.com/anacrolix/torrent/data/file"
37 "github.com/anacrolix/torrent/dht"
38 "github.com/anacrolix/torrent/internal/pieceordering"
39 "github.com/anacrolix/torrent/iplist"
40 "github.com/anacrolix/torrent/metainfo"
41 "github.com/anacrolix/torrent/mse"
42 pp "github.com/anacrolix/torrent/peer_protocol"
43 "github.com/anacrolix/torrent/tracker"
47 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
48 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
49 chunksReceived = expvar.NewInt("chunksReceived")
51 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
52 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
53 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
55 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
56 unexpectedCancels = expvar.NewInt("unexpectedCancels")
57 postedCancels = expvar.NewInt("postedCancels")
58 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
60 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
61 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
63 unsuccessfulDials = expvar.NewInt("dialSuccessful")
64 successfulDials = expvar.NewInt("dialUnsuccessful")
66 acceptUTP = expvar.NewInt("acceptUTP")
67 acceptTCP = expvar.NewInt("acceptTCP")
68 acceptReject = expvar.NewInt("acceptReject")
70 peerExtensions = expvar.NewMap("peerExtensions")
71 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
72 // Count of connections to peer with same client ID.
73 connsToSelf = expvar.NewInt("connsToSelf")
74 // Number of completed connections to a client we're already connected with.
75 duplicateClientConns = expvar.NewInt("duplicateClientConns")
76 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
77 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
81 // Justification for set bits follows.
83 // Extension protocol ([5]|=0x10):
84 // http://www.bittorrent.org/beps/bep_0010.html
86 // Fast Extension ([7]|=0x04):
87 // http://bittorrent.org/beps/bep_0006.html.
88 // Disabled until AllowedFast is implemented.
91 // http://www.bittorrent.org/beps/bep_0005.html
92 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
94 socketsPerTorrent = 80
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 // These are our extended message IDs.
105 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
108 // Updated occasionally to when there's been some changes to client
109 // behaviour in case other clients are assuming anything of us. See also
111 extendedHandshakeClientVersion = "go.torrent dev 20150624"
114 // Currently doesn't really queue, but should in the future.
115 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
116 piece := t.Pieces[pieceIndex]
117 if piece.QueuedForHash {
120 piece.QueuedForHash = true
121 t.publishPieceChange(int(pieceIndex))
122 go cl.verifyPiece(t, pieceIndex)
125 // Queue a piece check if one isn't already queued, and the piece has never
126 // been checked before.
127 func (cl *Client) queueFirstHash(t *torrent, piece int) {
129 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
132 cl.queuePieceCheck(t, pp.Integer(piece))
135 // Clients contain zero or more Torrents. A client manages a blocklist, the
136 // TCP/UDP protocol ports, and DHT as desired.
140 listeners []net.Listener
143 ipBlockList iplist.Ranger
144 bannedTorrents map[InfoHash]struct{}
146 pruneTimer *time.Timer
147 extensionBytes peerExtensionBytes
148 // Set of addresses that have our client ID. This intentionally will
149 // include ourselves if we end up trying to connect to our own address
150 // through legitimate channels.
151 dopplegangerAddrs map[string]struct{}
153 torrentDataOpener TorrentDataOpener
159 torrents map[InfoHash]*torrent
162 func (me *Client) IPBlockList() iplist.Ranger {
165 return me.ipBlockList
168 func (me *Client) SetIPBlockList(list iplist.Ranger) {
171 me.ipBlockList = list
173 me.dHT.SetIPBlockList(list)
177 func (me *Client) PeerID() string {
178 return string(me.peerID[:])
181 func (me *Client) ListenAddr() (addr net.Addr) {
182 for _, l := range me.listeners {
189 type hashSorter struct {
193 func (me hashSorter) Len() int {
194 return len(me.Hashes)
197 func (me hashSorter) Less(a, b int) bool {
198 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
201 func (me hashSorter) Swap(a, b int) {
202 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
205 func (cl *Client) sortedTorrents() (ret []*torrent) {
207 for ih := range cl.torrents {
208 hs.Hashes = append(hs.Hashes, ih)
211 for _, ih := range hs.Hashes {
212 ret = append(ret, cl.torrent(ih))
217 // Writes out a human readable status of the client, such as for writing to a
219 func (cl *Client) WriteStatus(_w io.Writer) {
221 defer cl.mu.RUnlock()
222 w := bufio.NewWriter(_w)
224 if addr := cl.ListenAddr(); addr != nil {
225 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
227 fmt.Fprintln(w, "Not listening!")
229 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
231 dhtStats := cl.dHT.Stats()
232 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
233 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
234 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
235 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
236 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
238 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
240 for _, t := range cl.sortedTorrents() {
242 fmt.Fprint(w, "<unknown name>")
244 fmt.Fprint(w, t.Name())
248 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
250 w.WriteString("<missing metainfo>")
258 // A Data that implements this has a streaming interface that should be
259 // preferred over ReadAt. For example, the data is stored in blocks on the
260 // network and have a fixed cost to open.
261 type SectionOpener interface {
262 // Open a ReadCloser at the given offset into torrent data. n is how many
263 // bytes we intend to read.
264 OpenSection(off, n int64) (io.ReadCloser, error)
267 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
269 // if err == io.ErrUnexpectedEOF && n != 0 {
273 // log.Println("data read at", len(b), off)
275 if ra, ok := d.(io.ReaderAt); ok {
276 return ra.ReadAt(b, off)
278 if so, ok := d.(SectionOpener); ok {
280 rc, err = so.OpenSection(off, int64(len(b)))
285 return io.ReadFull(rc, b)
287 if dp, ok := super(d); ok {
291 panic(fmt.Sprintf("can't read from %T", d))
294 // Calculates the number of pieces to set to Readahead priority, after the
295 // Now, and Next pieces.
296 func readaheadPieces(readahead, pieceLength int64) (ret int) {
297 // Expand the readahead to fit any partial pieces. Subtract 1 for the
298 // "next" piece that is assigned.
299 ret = int((readahead+pieceLength-1)/pieceLength - 1)
300 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
301 // piece length is much larger than the readahead.
308 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
309 index := int(off / int64(t.usualPieceSize()))
310 cl.raisePiecePriority(t, index, PiecePriorityNow)
312 if index >= t.numPieces() {
315 cl.raisePiecePriority(t, index, PiecePriorityNext)
316 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
318 if index >= t.numPieces() {
321 cl.raisePiecePriority(t, index, PiecePriorityReadahead)
325 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
327 req, ok := t.offsetRequest(off)
331 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
333 t.urgent = make(map[request]struct{}, (n+int(t.chunkSize)-1)/int(t.chunkSize))
335 t.urgent[req] = struct{}{}
336 cl.event.Broadcast() // Why?
337 index := int(req.Index)
338 cl.queueFirstHash(t, index)
339 cl.pieceChanged(t, index)
341 reqOff := t.requestOffset(req)
342 n1 := req.Length - pp.Integer(off-reqOff)
346 // log.Print(t.urgent)
349 func (cl *Client) configDir() string {
350 if cl.config.ConfigDir == "" {
351 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
353 return cl.config.ConfigDir
356 // The directory where the Client expects to find and store configuration
357 // data. Defaults to $HOME/.config/torrent.
358 func (cl *Client) ConfigDir() string {
359 return cl.configDir()
362 func (t *torrent) connPendPiece(c *connection, piece int) {
363 c.pendPiece(piece, t.Pieces[piece].Priority)
366 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
367 if t.Pieces[piece].Priority < priority {
368 cl.prioritizePiece(t, piece, priority)
372 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
373 if t.havePiece(piece) {
374 priority = PiecePriorityNone
376 if priority != PiecePriorityNone {
377 cl.queueFirstHash(t, piece)
380 if p.Priority != priority {
381 p.Priority = priority
382 cl.pieceChanged(t, piece)
386 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
387 f, err := os.Open(filename)
388 if os.IsNotExist(err) {
396 mm, err := mmap.Map(f, mmap.RDONLY, 0)
400 ret = iplist.NewFromPacked(mm)
404 func (cl *Client) setEnvBlocklist() (err error) {
405 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
406 defaultBlocklist := filename == ""
407 if defaultBlocklist {
408 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
412 if cl.ipBlockList != nil {
415 filename = filepath.Join(cl.configDir(), "blocklist")
417 f, err := os.Open(filename)
419 if defaultBlocklist {
425 cl.ipBlockList, err = iplist.NewFromReader(f)
429 func (cl *Client) initBannedTorrents() error {
430 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
432 if os.IsNotExist(err) {
435 return fmt.Errorf("error opening banned infohashes file: %s", err)
438 scanner := bufio.NewScanner(f)
439 cl.bannedTorrents = make(map[InfoHash]struct{})
441 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
445 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
447 return fmt.Errorf("error reading infohash: %s", err)
453 return errors.New("bad infohash")
457 cl.bannedTorrents[ih] = struct{}{}
459 if err := scanner.Err(); err != nil {
460 return fmt.Errorf("error scanning file: %s", err)
465 // Creates a new client.
466 func NewClient(cfg *Config) (cl *Client, err error) {
477 halfOpenLimit: socketsPerTorrent,
479 torrentDataOpener: func(md *metainfo.Info) data.Data {
480 return filePkg.TorrentData(md, cfg.DataDir)
482 dopplegangerAddrs: make(map[string]struct{}),
484 quit: make(chan struct{}),
485 torrents: make(map[InfoHash]*torrent),
487 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
489 if cfg.TorrentDataOpener != nil {
490 cl.torrentDataOpener = cfg.TorrentDataOpener
493 if cfg.IPBlocklist != nil {
494 cl.ipBlockList = cfg.IPBlocklist
495 } else if !cfg.NoDefaultBlocklist {
496 err = cl.setEnvBlocklist()
502 if err = cl.initBannedTorrents(); err != nil {
503 err = fmt.Errorf("error initing banned torrents: %s", err)
507 if cfg.PeerID != "" {
508 CopyExact(&cl.peerID, cfg.PeerID)
510 o := copy(cl.peerID[:], bep20)
511 _, err = rand.Read(cl.peerID[o:])
513 panic("error generating peer id")
517 // Returns the laddr string to listen on for the next Listen call.
518 listenAddr := func() string {
519 if addr := cl.ListenAddr(); addr != nil {
522 if cfg.ListenAddr == "" {
525 return cfg.ListenAddr
527 if !cl.config.DisableTCP {
529 l, err = net.Listen(func() string {
530 if cl.config.DisableIPv6 {
539 cl.listeners = append(cl.listeners, l)
540 go cl.acceptConnections(l, false)
542 if !cl.config.DisableUTP {
543 cl.utpSock, err = utp.NewSocket(func() string {
544 if cl.config.DisableIPv6 {
553 cl.listeners = append(cl.listeners, cl.utpSock)
554 go cl.acceptConnections(cl.utpSock, true)
557 dhtCfg := cfg.DHTConfig
559 dhtCfg = &dht.ServerConfig{}
561 if dhtCfg.IPBlocklist == nil {
562 dhtCfg.IPBlocklist = cl.ipBlockList
564 if dhtCfg.Addr == "" {
565 dhtCfg.Addr = listenAddr()
567 if dhtCfg.Conn == nil && cl.utpSock != nil {
568 dhtCfg.Conn = cl.utpSock.PacketConn()
570 cl.dHT, err = dht.NewServer(dhtCfg)
579 func (cl *Client) stopped() bool {
588 // Stops the client. All connections to peers are closed and all activity will
590 func (me *Client) Close() {
602 for _, l := range me.listeners {
605 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("blocking non-IPv4 address: %s", ip)
623 r = cl.ipBlockList.Lookup(ip4)
627 func (cl *Client) waitAccept() {
631 for _, t := range cl.torrents {
645 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
648 // We accept all connections immediately, because we don't know what
649 // torrent they're for.
650 conn, err := l.Accept()
669 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
670 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
672 if blockRange != nil || doppleganger {
674 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
678 go cl.incomingConnection(conn, utp)
682 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
684 if tc, ok := nc.(*net.TCPConn); ok {
690 c.Discovery = peerSourceIncoming
692 err := cl.runReceivedConn(c)
698 // Returns a handle to the given torrent, if it's present in the client.
699 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
702 t, ok := cl.torrents[ih]
710 func (me *Client) torrent(ih InfoHash) *torrent {
711 return me.torrents[ih]
714 type dialResult struct {
719 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
720 conn, err := dial(addr, t)
725 conn = nil // Pedantic
727 ch <- dialResult{conn, utp}
729 successfulDials.Add(1)
732 unsuccessfulDials.Add(1)
735 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
736 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
737 if ret < minDialTimeout {
743 // Returns whether an address is known to connect to a client with our own ID.
744 func (me *Client) dopplegangerAddr(addr string) bool {
745 _, ok := me.dopplegangerAddrs[addr]
749 // Start the process of connecting to the given peer for the given torrent if
751 func (me *Client) initiateConn(peer Peer, t *torrent) {
752 if peer.Id == me.peerID {
755 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
756 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
757 duplicateConnsAvoided.Add(1)
760 if r := me.ipBlockRange(peer.IP); r != nil {
761 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
764 t.HalfOpen[addr] = struct{}{}
765 go me.outgoingConnection(t, addr, peer.Source)
768 func (me *Client) dialTimeout(t *torrent) time.Duration {
770 pendingPeers := len(t.Peers)
772 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
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, whichever is first to connect.
788 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
789 // Initiate connections via TCP and UTP simultaneously. Use the first one
792 if !me.config.DisableUTP {
795 if !me.config.DisableTCP {
798 resCh := make(chan dialResult, left)
799 if !me.config.DisableUTP {
800 go doDial(me.dialUTP, resCh, true, addr, t)
802 if !me.config.DisableTCP {
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 // Performs initiator handshakes and returns a connection.
835 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
839 c.encrypted = encrypted
841 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
845 ok, err := me.initiateHandshakes(c, t)
852 // Returns nil connection and nil error if no connection could be established
853 // for valid reasons.
854 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
855 nc, utp := me.dialFirst(addr, t)
859 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
867 if me.config.DisableEncryption {
868 // We already tried without encryption.
871 // Try again without encryption, using whichever protocol type worked last
874 nc, err = me.dialUTP(addr, t)
876 nc, err = me.dialTCP(addr, t)
879 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
882 c, err = me.handshakesConnection(nc, t, false, utp)
889 // Called to dial out and run a connection. The addr we're given is already
890 // considered half-open.
891 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
892 c, err := me.establishOutgoingConn(t, addr)
895 // Don't release lock between here and addConnection, unless it's for
897 me.noLongerHalfOpen(t, addr)
906 err = me.runInitiatedHandshookConn(c, t)
912 // The port number for incoming peer connections. 0 if the client isn't
914 func (cl *Client) incomingPeerPort() int {
915 listenAddr := cl.ListenAddr()
916 if listenAddr == nil {
919 return addrPort(listenAddr)
922 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
923 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
924 func addrCompactIP(addr net.Addr) (string, error) {
925 host, _, err := net.SplitHostPort(addr.String())
929 ip := net.ParseIP(host)
930 if v4 := ip.To4(); v4 != nil {
934 return string(v4), nil
936 return string(ip.To16()), nil
939 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
951 peerExtensionBytes [8]byte
955 func (me *peerExtensionBytes) SupportsExtended() bool {
956 return me[5]&0x10 != 0
959 func (me *peerExtensionBytes) SupportsDHT() bool {
960 return me[7]&0x01 != 0
963 func (me *peerExtensionBytes) SupportsFast() bool {
964 return me[7]&0x04 != 0
967 type handshakeResult struct {
973 // ih is nil if we expect the peer to declare the InfoHash, such as when the
974 // peer initiated the connection. Returns ok if the handshake was successful,
975 // and err if there was an unexpected condition other than the peer simply
976 // abandoning the handshake.
977 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
978 // Bytes to be sent to the peer. Should never block the sender.
979 postCh := make(chan []byte, 4)
980 // A single error value sent when the writer completes.
981 writeDone := make(chan error, 1)
982 // Performs writes to the socket and ensures posts don't block.
983 go handshakeWriter(sock, postCh, writeDone)
986 close(postCh) // Done writing.
993 // Wait until writes complete before returning from handshake.
996 err = fmt.Errorf("error writing: %s", err)
1000 post := func(bb []byte) {
1004 panic("mustn't block while posting")
1008 post([]byte(pp.Protocol))
1010 if ih != nil { // We already know what we want.
1015 _, err = io.ReadFull(sock, b[:68])
1020 if string(b[:20]) != pp.Protocol {
1023 CopyExact(&res.peerExtensionBytes, b[20:28])
1024 CopyExact(&res.InfoHash, b[28:48])
1025 CopyExact(&res.peerID, b[48:68])
1026 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
1028 // TODO: Maybe we can just drop peers here if we're not interested. This
1029 // could prevent them trying to reconnect, falsely believing there was
1031 if ih == nil { // We were waiting for the peer to tell us what they wanted.
1032 post(res.InfoHash[:])
1040 // Wraps a raw connection and provides the interface we want for using the
1041 // connection in the message loop.
1042 type deadlineReader struct {
1047 func (me deadlineReader) Read(b []byte) (n int, err error) {
1048 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1049 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1051 err = fmt.Errorf("error setting read deadline: %s", err)
1053 n, err = me.r.Read(b)
1054 // Convert common errors into io.EOF.
1056 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1058 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1068 type readWriter struct {
1073 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1074 var protocol [len(pp.Protocol)]byte
1075 _, err = io.ReadFull(rw, protocol[:])
1080 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1083 if string(protocol[:]) == pp.Protocol {
1087 ret, err = mse.ReceiveHandshake(ret, skeys)
1091 func (cl *Client) receiveSkeys() (ret [][]byte) {
1092 for ih := range cl.torrents {
1093 ret = append(ret, ih[:])
1098 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1100 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1105 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1106 if ih != t.InfoHash {
1112 // Do encryption and bittorrent handshakes as receiver.
1113 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1115 skeys := cl.receiveSkeys()
1117 if !cl.config.DisableEncryption {
1118 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1120 if err == mse.ErrNoSecretKeyMatch {
1126 ih, ok, err := cl.connBTHandshake(c, nil)
1128 err = fmt.Errorf("error during bt handshake: %s", err)
1140 // Returns !ok if handshake failed for valid reasons.
1141 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1142 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1143 if err != nil || !ok {
1147 c.PeerExtensionBytes = res.peerExtensionBytes
1148 c.PeerID = res.peerID
1149 c.completedHandshake = time.Now()
1153 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1154 if c.PeerID == cl.peerID {
1155 // Only if we initiated the connection is the remote address a
1156 // listen addr for a doppleganger.
1158 addr := c.conn.RemoteAddr().String()
1159 cl.dopplegangerAddrs[addr] = struct{}{}
1162 return cl.runHandshookConn(c, t)
1165 func (cl *Client) runReceivedConn(c *connection) (err error) {
1166 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1170 t, err := cl.receiveHandshakes(c)
1172 err = fmt.Errorf("error receiving handshakes: %s", err)
1179 defer cl.mu.Unlock()
1180 if c.PeerID == cl.peerID {
1183 return cl.runHandshookConn(c, t)
1186 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1187 c.conn.SetWriteDeadline(time.Time{})
1189 deadlineReader{c.conn, c.rw},
1192 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1193 if !cl.addConnection(t, c) {
1196 defer cl.dropConnection(t, c)
1198 go c.writeOptimizer(time.Minute)
1199 cl.sendInitialMessages(c, t)
1201 t.initRequestOrdering(c)
1203 err = cl.connectionLoop(t, c)
1205 err = fmt.Errorf("error during connection loop: %s", err)
1210 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1211 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1212 conn.Post(pp.Message{
1214 ExtendedID: pp.HandshakeExtendedID,
1215 ExtendedPayload: func() []byte {
1216 d := map[string]interface{}{
1217 "m": func() (ret map[string]int) {
1218 ret = make(map[string]int, 2)
1219 ret["ut_metadata"] = metadataExtendedId
1220 if !me.config.DisablePEX {
1221 ret["ut_pex"] = pexExtendedId
1225 "v": extendedHandshakeClientVersion,
1226 // No upload queue is implemented yet.
1229 if !me.config.DisableEncryption {
1232 if torrent.metadataSizeKnown() {
1233 d["metadata_size"] = torrent.metadataSize()
1235 if p := me.incomingPeerPort(); p != 0 {
1238 yourip, err := addrCompactIP(conn.remoteAddr())
1240 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1242 d["yourip"] = yourip
1244 // log.Printf("sending %v", d)
1245 b, err := bencode.Marshal(d)
1253 if torrent.haveAnyPieces() {
1254 conn.Post(pp.Message{
1256 Bitfield: torrent.bitfield(),
1258 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1259 conn.Post(pp.Message{
1263 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1264 conn.Post(pp.Message{
1266 Port: uint16(AddrPort(me.dHT.Addr())),
1271 // Randomizes the piece order for this connection. Every connection will be
1272 // given a different ordering. Having it stored per connection saves having to
1273 // randomize during request filling, and constantly recalculate the ordering
1274 // based on piece priorities.
1275 func (t *torrent) initRequestOrdering(c *connection) {
1276 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1277 panic("double init of request ordering")
1279 c.piecePriorities = mathRand.Perm(t.numPieces())
1280 c.pieceRequestOrder = pieceordering.New()
1281 for i := range iter.N(t.Info.NumPieces()) {
1282 if !c.PeerHasPiece(i) {
1285 if !t.wantPiece(i) {
1288 t.connPendPiece(c, i)
1292 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
1295 if c.PeerPieces == nil {
1296 c.PeerPieces = make([]bool, t.numPieces())
1299 for piece >= len(c.PeerPieces) {
1300 c.PeerPieces = append(c.PeerPieces, false)
1303 if piece >= len(c.PeerPieces) {
1304 return errors.New("peer got out of range piece index")
1306 c.PeerPieces[piece] = true
1308 if t.wantPiece(piece) {
1309 t.connPendPiece(c, piece)
1310 me.replenishConnRequests(t, c)
1315 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1316 me.replenishConnRequests(torrent, conn)
1319 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1322 postedCancels.Add(1)
1327 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1328 if !cn.RequestPending(r) {
1331 delete(cn.Requests, r)
1335 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1339 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1340 // Peer doesn't support this.
1343 // Request metadata pieces that we don't have in a random order.
1345 for index := 0; index < t.metadataPieceCount(); index++ {
1346 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1347 pending = append(pending, index)
1350 for _, i := range mathRand.Perm(len(pending)) {
1351 c.requestMetadataPiece(pending[i])
1355 func (cl *Client) completedMetadata(t *torrent) {
1359 CopyExact(&ih, h.Sum(nil))
1360 if ih != t.InfoHash {
1361 log.Print("bad metadata")
1362 t.invalidateMetadata()
1365 var info metainfo.Info
1366 err := bencode.Unmarshal(t.MetaData, &info)
1368 log.Printf("error unmarshalling metadata: %s", err)
1369 t.invalidateMetadata()
1372 // TODO(anacrolix): If this fails, I think something harsher should be
1374 err = cl.setMetaData(t, &info, t.MetaData)
1376 log.Printf("error setting metadata: %s", err)
1377 t.invalidateMetadata()
1380 if cl.config.Debug {
1381 log.Printf("%s: got metadata from peers", t)
1385 // Process incoming ut_metadata message.
1386 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1387 var d map[string]int
1388 err = bencode.Unmarshal(payload, &d)
1390 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1393 msgType, ok := d["msg_type"]
1395 err = errors.New("missing msg_type field")
1400 case pp.DataMetadataExtensionMsgType:
1404 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1405 if begin < 0 || begin >= len(payload) {
1406 log.Printf("got bad metadata piece")
1409 if !c.requestedMetadataPiece(piece) {
1410 log.Printf("got unexpected metadata piece %d", piece)
1413 c.metadataRequests[piece] = false
1414 t.saveMetadataPiece(piece, payload[begin:])
1415 c.UsefulChunksReceived++
1416 c.lastUsefulChunkReceived = time.Now()
1417 if !t.haveAllMetadataPieces() {
1420 cl.completedMetadata(t)
1421 case pp.RequestMetadataExtensionMsgType:
1422 if !t.haveMetadataPiece(piece) {
1423 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1426 start := (1 << 14) * piece
1427 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1428 case pp.RejectMetadataExtensionMsgType:
1430 err = errors.New("unknown msg_type value")
1435 // Extracts the port as an integer from an address string.
1436 func addrPort(addr net.Addr) int {
1437 return AddrPort(addr)
1440 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1441 cn.peerHasAll = true
1444 for i := 0; i < t.numPieces(); i++ {
1445 cl.peerGotPiece(t, cn, i)
1450 func (me *Client) upload(t *torrent, c *connection) {
1451 if me.config.NoUpload {
1454 if !c.PeerInterested {
1457 seeding := me.seeding(t)
1458 if !seeding && !t.connHasWantedPieces(c) {
1462 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1464 for r := range c.PeerRequests {
1465 err := me.sendChunk(t, c, r)
1467 log.Printf("error sending chunk %+v to peer: %s", r, err)
1469 delete(c.PeerRequests, r)
1477 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1478 // Count the chunk being sent, even if it isn't.
1480 b := make([]byte, r.Length)
1481 tp := t.Pieces[r.Index]
1482 tp.pendingWritesMutex.Lock()
1483 for tp.pendingWrites != 0 {
1484 tp.noPendingWrites.Wait()
1486 tp.pendingWritesMutex.Unlock()
1487 p := t.Info.Piece(int(r.Index))
1488 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1501 uploadChunksPosted.Add(1)
1502 c.lastChunkSent = time.Now()
1506 // Processes incoming bittorrent messages. The client lock is held upon entry
1508 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1509 decoder := pp.Decoder{
1510 R: bufio.NewReader(c.rw),
1511 MaxLength: 256 * 1024,
1516 err := decoder.Decode(&msg)
1517 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1519 c.lastMessageReceived = time.Now()
1526 if me.stopped() || err == io.EOF {
1537 for r := range c.Requests {
1538 me.connDeleteRequest(t, c, r)
1540 // We can then reset our interest.
1541 me.replenishConnRequests(t, c)
1543 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1544 me.replenishConnRequests(t, c)
1546 c.PeerChoked = false
1547 me.peerUnchoked(t, c)
1549 c.PeerInterested = true
1551 case pp.NotInterested:
1552 c.PeerInterested = false
1555 me.peerGotPiece(t, c, int(msg.Index))
1560 if !c.PeerInterested {
1561 err = errors.New("peer sent request but isn't interested")
1564 if c.PeerRequests == nil {
1565 c.PeerRequests = make(map[request]struct{}, maxRequests)
1567 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1570 req := newRequest(msg.Index, msg.Begin, msg.Length)
1571 if !c.PeerCancel(req) {
1572 unexpectedCancels.Add(1)
1575 if c.PeerPieces != nil || c.peerHasAll {
1576 err = errors.New("received unexpected bitfield")
1580 if len(msg.Bitfield) < t.numPieces() {
1581 err = errors.New("received invalid bitfield")
1584 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1586 c.PeerPieces = msg.Bitfield
1587 for index, has := range c.PeerPieces {
1589 me.peerGotPiece(t, c, index)
1593 if c.PeerPieces != nil || c.peerHasAll {
1594 err = errors.New("unexpected have-all")
1599 if c.peerHasAll || c.PeerPieces != nil {
1600 err = errors.New("unexpected have-none")
1603 c.PeerPieces = make([]bool, func() int {
1605 return t.numPieces()
1611 err = me.downloadedChunk(t, c, &msg)
1613 switch msg.ExtendedID {
1614 case pp.HandshakeExtendedID:
1615 // TODO: Create a bencode struct for this.
1616 var d map[string]interface{}
1617 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1619 err = fmt.Errorf("error decoding extended message payload: %s", err)
1622 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1623 if reqq, ok := d["reqq"]; ok {
1624 if i, ok := reqq.(int64); ok {
1625 c.PeerMaxRequests = int(i)
1628 if v, ok := d["v"]; ok {
1629 c.PeerClientName = v.(string)
1633 err = errors.New("handshake missing m item")
1636 mTyped, ok := m.(map[string]interface{})
1638 err = errors.New("handshake m value is not dict")
1641 if c.PeerExtensionIDs == nil {
1642 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1644 for name, v := range mTyped {
1647 log.Printf("bad handshake m item extension ID type: %T", v)
1651 delete(c.PeerExtensionIDs, name)
1653 if c.PeerExtensionIDs[name] == 0 {
1654 supportedExtensionMessages.Add(name, 1)
1656 c.PeerExtensionIDs[name] = byte(id)
1659 metadata_sizeUntyped, ok := d["metadata_size"]
1661 metadata_size, ok := metadata_sizeUntyped.(int64)
1663 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1665 t.setMetadataSize(metadata_size, me)
1668 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1669 me.requestPendingMetadata(t, c)
1671 case metadataExtendedId:
1672 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1674 err = fmt.Errorf("error handling metadata extension message: %s", err)
1677 if me.config.DisablePEX {
1680 var pexMsg peerExchangeMessage
1681 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1683 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1688 me.addPeers(t, func() (ret []Peer) {
1689 for i, cp := range pexMsg.Added {
1691 IP: make([]byte, 4),
1693 Source: peerSourcePEX,
1695 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1696 p.SupportsEncryption = true
1698 CopyExact(p.IP, cp.IP[:])
1699 ret = append(ret, p)
1704 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1707 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1710 // That client uses its own extension IDs for outgoing message
1711 // types, which is incorrect.
1712 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1713 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1721 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1726 pingAddr.Port = int(msg.Port)
1728 _, err = me.dHT.Ping(pingAddr)
1730 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1738 // Returns true if connection is removed from torrent.Conns.
1739 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1740 for i0, _c := range t.Conns {
1744 i1 := len(t.Conns) - 1
1746 t.Conns[i0] = t.Conns[i1]
1748 t.Conns = t.Conns[:i1]
1754 func (me *Client) dropConnection(t *torrent, c *connection) {
1755 me.event.Broadcast()
1757 if me.deleteConnection(t, c) {
1762 // Returns true if the connection is added.
1763 func (me *Client) addConnection(t *torrent, c *connection) bool {
1768 case <-t.ceasingNetworking:
1772 if !me.wantConns(t) {
1775 for _, c0 := range t.Conns {
1776 if c.PeerID == c0.PeerID {
1777 // Already connected to a client with that ID.
1778 duplicateClientConns.Add(1)
1782 if len(t.Conns) >= socketsPerTorrent {
1783 c := t.worstBadConn(me)
1787 if me.config.Debug && missinggo.CryHeard() {
1788 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1791 me.deleteConnection(t, c)
1793 if len(t.Conns) >= socketsPerTorrent {
1796 t.Conns = append(t.Conns, c)
1800 func (t *torrent) needData() bool {
1804 if len(t.urgent) != 0 {
1807 for _, p := range t.Pieces {
1808 if p.Priority != PiecePriorityNone {
1815 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1822 return c.supportsExtension("ut_metadata")
1825 return c.PeerInterested
1827 return t.connHasWantedPieces(c)
1830 func (me *Client) wantConns(t *torrent) bool {
1831 if !me.seeding(t) && !t.needData() {
1834 if len(t.Conns) < socketsPerTorrent {
1837 return t.worstBadConn(me) != nil
1840 func (me *Client) openNewConns(t *torrent) {
1842 case <-t.ceasingNetworking:
1846 for len(t.Peers) != 0 {
1847 if !me.wantConns(t) {
1850 if len(t.HalfOpen) >= me.halfOpenLimit {
1857 for k, p = range t.Peers {
1861 me.initiateConn(p, t)
1863 t.wantPeers.Broadcast()
1866 func (me *Client) addPeers(t *torrent, peers []Peer) {
1867 for _, p := range peers {
1868 if me.dopplegangerAddr(net.JoinHostPort(
1870 strconv.FormatInt(int64(p.Port), 10),
1874 if me.ipBlockRange(p.IP) != nil {
1878 // The spec says to scrub these yourselves. Fine.
1886 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1887 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1890 func (cl *Client) saveTorrentFile(t *torrent) error {
1891 path := cl.cachedMetaInfoFilename(t.InfoHash)
1892 os.MkdirAll(filepath.Dir(path), 0777)
1893 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1895 return fmt.Errorf("error opening file: %s", err)
1898 e := bencode.NewEncoder(f)
1899 err = e.Encode(t.MetaInfo())
1901 return fmt.Errorf("error marshalling metainfo: %s", err)
1903 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1905 // For example, a script kiddy makes us load too many files, and we're
1906 // able to save the torrent, but not load it again to check it.
1909 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1910 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1915 func (cl *Client) startTorrent(t *torrent) {
1916 if t.Info == nil || t.data == nil {
1919 // If the client intends to upload, it needs to know what state pieces are
1921 if !cl.config.NoUpload {
1922 // Queue all pieces for hashing. This is done sequentially to avoid
1923 // spamming goroutines.
1924 for _, p := range t.Pieces {
1925 p.QueuedForHash = true
1928 for i := range t.Pieces {
1929 cl.verifyPiece(t, pp.Integer(i))
1935 // Storage cannot be changed once it's set.
1936 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1937 err = t.setStorage(td)
1938 cl.event.Broadcast()
1946 type TorrentDataOpener func(*metainfo.Info) data.Data
1948 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1949 err = t.setMetadata(md, bytes, &cl.mu)
1953 if !cl.config.DisableMetainfoCache {
1954 if err := cl.saveTorrentFile(t); err != nil {
1955 log.Printf("error saving torrent file for %s: %s", t, err)
1958 cl.event.Broadcast()
1959 close(t.gotMetainfo)
1960 td := cl.torrentDataOpener(md)
1961 err = cl.setStorage(t, td)
1965 // Prepare a Torrent without any attachment to a Client. That means we can
1966 // initialize fields all fields that don't require the Client without locking
1968 func newTorrent(ih InfoHash) (t *torrent, err error) {
1971 chunkSize: defaultChunkSize,
1972 Peers: make(map[peersKey]Peer),
1974 closing: make(chan struct{}),
1975 ceasingNetworking: make(chan struct{}),
1977 gotMetainfo: make(chan struct{}),
1979 HalfOpen: make(map[string]struct{}),
1980 pieceStateChanges: pubsub.NewPubSub(),
1982 t.wantPeers.L = &t.stateMu
1987 // For shuffling the tracker tiers.
1988 mathRand.Seed(time.Now().Unix())
1991 // The trackers within each tier must be shuffled before use.
1992 // http://stackoverflow.com/a/12267471/149482
1993 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1994 func shuffleTier(tier []tracker.Client) {
1995 for i := range tier {
1996 j := mathRand.Intn(i + 1)
1997 tier[i], tier[j] = tier[j], tier[i]
2001 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
2002 for _, tier := range base {
2003 copy = append(copy, append([]tracker.Client{}, tier...))
2008 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
2010 for _, url := range newURLs {
2011 for _, tr := range tier {
2012 if tr.URL() == url {
2016 tr, err := tracker.New(url)
2018 log.Printf("error creating tracker client for %q: %s", url, err)
2021 tier = append(tier, tr)
2026 func (t *torrent) addTrackers(announceList [][]string) {
2027 newTrackers := copyTrackers(t.Trackers)
2028 for tierIndex, tier := range announceList {
2029 if tierIndex < len(newTrackers) {
2030 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
2032 newTrackers = append(newTrackers, mergeTier(nil, tier))
2034 shuffleTier(newTrackers[tierIndex])
2036 t.Trackers = newTrackers
2039 // Don't call this before the info is available.
2040 func (t *torrent) bytesCompleted() int64 {
2044 return t.Info.TotalLength() - t.bytesLeft()
2047 // A file-like handle to some torrent data resource.
2048 type Handle interface {
2055 // Returns handles to the files in the torrent. This requires the metainfo is
2057 func (t Torrent) Files() (ret []File) {
2065 for _, fi := range info.UpvertedFiles() {
2066 ret = append(ret, File{
2068 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2078 // Marks the pieces in the given region for download.
2079 func (t Torrent) SetRegionPriority(off, len int64) {
2081 defer t.cl.mu.Unlock()
2082 pieceSize := int64(t.usualPieceSize())
2083 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2084 t.cl.raisePiecePriority(t.torrent, int(i), PiecePriorityNormal)
2088 func (t Torrent) AddPeers(pp []Peer) error {
2091 defer cl.mu.Unlock()
2092 cl.addPeers(t.torrent, pp)
2096 // Marks the entire torrent for download. Requires the info first, see
2098 func (t Torrent) DownloadAll() {
2100 defer t.cl.mu.Unlock()
2101 for i := range iter.N(t.numPieces()) {
2102 t.cl.raisePiecePriority(t.torrent, i, PiecePriorityNormal)
2104 // Nice to have the first and last pieces sooner for various interactive
2106 t.cl.raisePiecePriority(t.torrent, 0, PiecePriorityReadahead)
2107 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, PiecePriorityReadahead)
2110 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2111 // metainfo has the correct infohash.
2112 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2113 if cl.config.DisableMetainfoCache {
2116 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2118 if os.IsNotExist(err) {
2124 dec := bencode.NewDecoder(f)
2125 err = dec.Decode(&mi)
2129 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2130 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2136 // Specifies a new torrent for adding to a client. There are helpers for
2137 // magnet URIs and torrent metainfo files.
2138 type TorrentSpec struct {
2139 // The tiered tracker URIs.
2142 Info *metainfo.InfoEx
2143 // The name to use if the Name field from the Info isn't available.
2145 // The chunk size to use for outbound requests. Defaults to 16KiB if not
2150 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2151 m, err := ParseMagnetURI(uri)
2155 spec = &TorrentSpec{
2156 Trackers: [][]string{m.Trackers},
2157 DisplayName: m.DisplayName,
2158 InfoHash: m.InfoHash,
2163 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2164 spec = &TorrentSpec{
2165 Trackers: mi.AnnounceList,
2167 DisplayName: mi.Info.Name,
2169 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2173 // Add or merge a torrent spec. If the torrent is already present, the
2174 // trackers will be merged with the existing ones. If the Info isn't yet
2175 // known, it will be set. The display name is replaced if the new spec
2176 // provides one. Returns new if the torrent wasn't already in the client.
2177 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2180 defer cl.mu.Unlock()
2182 t, ok := cl.torrents[spec.InfoHash]
2186 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2187 err = errors.New("banned torrent")
2191 t, err = newTorrent(spec.InfoHash)
2195 if spec.ChunkSize != 0 {
2196 t.chunkSize = pp.Integer(spec.ChunkSize)
2199 if spec.DisplayName != "" {
2200 t.DisplayName = spec.DisplayName
2202 // Try to merge in info we have on the torrent. Any err left will
2203 // terminate the function.
2205 if spec.Info != nil {
2206 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2208 var mi *metainfo.MetaInfo
2209 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2211 log.Printf("error getting cached metainfo: %s", err)
2213 } else if mi != nil {
2214 t.addTrackers(mi.AnnounceList)
2215 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2222 t.addTrackers(spec.Trackers)
2224 cl.torrents[spec.InfoHash] = t
2227 // From this point onwards, we can consider the torrent a part of the
2230 if !cl.config.DisableTrackers {
2231 go cl.announceTorrentTrackers(T.torrent)
2234 go cl.announceTorrentDHT(T.torrent, true)
2240 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2241 t, ok := me.torrents[infoHash]
2243 err = fmt.Errorf("no such torrent")
2250 delete(me.torrents, infoHash)
2254 // Returns true when peers are required, or false if the torrent is closing.
2255 func (cl *Client) waitWantPeers(t *torrent) bool {
2257 defer cl.mu.Unlock()
2259 defer t.stateMu.Unlock()
2262 case <-t.ceasingNetworking:
2266 if len(t.Peers) > torrentPeersLowWater {
2269 if t.needData() || cl.seeding(t) {
2281 // Returns whether the client should make effort to seed the torrent.
2282 func (cl *Client) seeding(t *torrent) bool {
2283 if cl.config.NoUpload {
2286 if !cl.config.Seed {
2295 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2296 for cl.waitWantPeers(t) {
2297 // log.Printf("getting peers for %q from DHT", t)
2298 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2300 log.Printf("error getting peers from dht: %s", err)
2303 // Count all the unique addresses we got during this announce.
2304 allAddrs := make(map[string]struct{})
2308 case v, ok := <-ps.Peers:
2312 addPeers := make([]Peer, 0, len(v.Peers))
2313 for _, cp := range v.Peers {
2315 // Can't do anything with this.
2318 addPeers = append(addPeers, Peer{
2321 Source: peerSourceDHT,
2323 key := (&net.UDPAddr{
2327 allAddrs[key] = struct{}{}
2329 peersFoundByDHT.Add(int64(len(addPeers)))
2331 cl.addPeers(t, addPeers)
2332 numPeers := len(t.Peers)
2334 if numPeers >= torrentPeersHighWater {
2337 case <-t.ceasingNetworking:
2343 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2347 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2348 url_, err := url.Parse(tr.URL())
2352 host, _, err := net.SplitHostPort(url_.Host)
2356 addr, err := net.ResolveIPAddr("ip", host)
2361 if cl.ipBlockList != nil {
2362 if cl.ipBlockRange(addr.IP) != nil {
2370 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2371 blocked, err := cl.trackerBlockedUnlocked(tr)
2373 return fmt.Errorf("error determining if tracker blocked: %s", err)
2376 return fmt.Errorf("tracker blocked: %s", tr)
2378 if err := tr.Connect(); err != nil {
2379 return fmt.Errorf("error connecting: %s", err)
2381 resp, err := tr.Announce(req)
2383 return fmt.Errorf("error announcing: %s", err)
2386 for _, peer := range resp.Peers {
2387 peers = append(peers, Peer{
2393 cl.addPeers(t, peers)
2396 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2397 peersFoundByTracker.Add(int64(len(peers)))
2399 time.Sleep(time.Second * time.Duration(resp.Interval))
2403 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2404 oks := make(chan bool)
2406 for _, tier := range trackers {
2407 for _, tr := range tier {
2409 go func(tr tracker.Client) {
2410 err := cl.announceTorrentSingleTracker(tr, req, t)
2415 for outstanding > 0 {
2425 // Announce torrent to its trackers.
2426 func (cl *Client) announceTorrentTrackers(t *torrent) {
2427 req := tracker.AnnounceRequest{
2428 Event: tracker.Started,
2430 Port: uint16(cl.incomingPeerPort()),
2432 InfoHash: t.InfoHash,
2434 if !cl.waitWantPeers(t) {
2438 req.Left = uint64(t.bytesLeft())
2439 trackers := t.Trackers
2441 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2442 req.Event = tracker.None
2445 for cl.waitWantPeers(t) {
2447 req.Left = uint64(t.bytesLeft())
2448 trackers = t.Trackers
2450 numTrackersTried := 0
2451 for _, tier := range trackers {
2452 for trIndex, tr := range tier {
2454 err := cl.announceTorrentSingleTracker(tr, &req, t)
2455 if err != nil && missinggo.CryHeard() {
2456 log.Printf("%s: error announcing to %s: %s", t, tr, err)
2459 // Float the successful announce to the top of the tier. If
2460 // the trackers list has been changed, we'll be modifying an
2461 // old copy so it won't matter.
2463 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2466 req.Event = tracker.None
2467 continue newAnnounce
2470 if numTrackersTried != 0 {
2471 log.Printf("%s: all trackers failed", t)
2473 // TODO: Wait until trackers are added if there are none.
2474 time.Sleep(10 * time.Second)
2478 func (cl *Client) allTorrentsCompleted() bool {
2479 for _, t := range cl.torrents {
2483 if t.numPiecesCompleted() != t.numPieces() {
2490 // Returns true when all torrents are completely downloaded and false if the
2491 // client is stopped before that.
2492 func (me *Client) WaitAll() bool {
2494 defer me.mu.Unlock()
2495 for !me.allTorrentsCompleted() {
2504 func (me *Client) fillRequests(t *torrent, c *connection) {
2509 if len(c.Requests) > c.requestsLowWater {
2513 addRequest := func(req request) (again bool) {
2514 // TODO: Couldn't this check also be done *after* the request?
2515 if len(c.Requests) >= 64 {
2518 return c.Request(req)
2520 for req := range t.urgent {
2521 if !addRequest(req) {
2525 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2526 pieceIndex := e.Piece()
2527 if !c.PeerHasPiece(pieceIndex) {
2528 panic("piece in request order but peer doesn't have it")
2530 if !t.wantPiece(pieceIndex) {
2531 log.Printf("unwanted piece %d in connection request order\n%s", pieceIndex, c)
2532 c.pieceRequestOrder.DeletePiece(pieceIndex)
2535 piece := t.Pieces[pieceIndex]
2536 for _, cs := range piece.shuffledPendingChunkSpecs(t.pieceLength(pieceIndex), pp.Integer(t.chunkSize)) {
2537 r := request{pp.Integer(pieceIndex), cs}
2546 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2550 me.fillRequests(t, c)
2551 if len(c.Requests) == 0 && !c.PeerChoked {
2552 // So we're not choked, but we don't want anything right now. We may
2553 // have completed readahead, and the readahead window has not rolled
2554 // over to the next piece. Better to stay interested in case we're
2555 // going to want data in the near future.
2556 c.SetInterested(!t.haveAllPieces())
2560 // Handle a received chunk from a peer.
2561 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2562 chunksReceived.Add(1)
2564 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2566 // Request has been satisfied.
2567 if me.connDeleteRequest(t, c, req) {
2568 defer me.replenishConnRequests(t, c)
2570 unexpectedChunksReceived.Add(1)
2573 piece := t.Pieces[req.Index]
2575 // Do we actually want this chunk?
2576 if !t.wantChunk(req) {
2577 unwantedChunksReceived.Add(1)
2578 c.UnwantedChunksReceived++
2582 c.UsefulChunksReceived++
2583 c.lastUsefulChunkReceived = time.Now()
2587 piece.pendingWritesMutex.Lock()
2588 piece.pendingWrites++
2589 piece.pendingWritesMutex.Unlock()
2592 piece.pendingWritesMutex.Lock()
2593 piece.pendingWrites--
2594 if piece.pendingWrites == 0 {
2595 piece.noPendingWrites.Broadcast()
2597 piece.pendingWritesMutex.Unlock()
2599 // Write the chunk out.
2600 tr := perf.NewTimer()
2601 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2603 log.Printf("error writing chunk: %s", err)
2606 tr.Stop("write chunk")
2608 // This could be made dependent on whether any actual data was written.
2609 if c.peerTouchedPieces == nil {
2610 c.peerTouchedPieces = make(map[int]struct{})
2612 c.peerTouchedPieces[int(req.Index)] = struct{}{}
2614 // log.Println("got chunk", req)
2615 piece.Event.Broadcast()
2616 defer t.publishPieceChange(int(req.Index))
2617 // Record that we have the chunk.
2618 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2619 delete(t.urgent, req)
2620 // It's important that the piece is potentially queued before we check if
2621 // the piece is still wanted, because if it is queued, it won't be wanted.
2622 if piece.numPendingChunks() == 0 {
2623 me.queuePieceCheck(t, req.Index)
2625 if !t.wantPiece(int(req.Index)) {
2626 for _, c := range t.Conns {
2627 c.pieceRequestOrder.DeletePiece(int(req.Index))
2631 // Cancel pending requests for this chunk.
2632 for _, c := range t.Conns {
2633 if me.connCancel(t, c, req) {
2634 me.replenishConnRequests(t, c)
2641 // Return the connections that touched a piece, and clear the entry while
2643 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2644 for _, c := range t.Conns {
2645 if _, ok := c.peerTouchedPieces[piece]; ok {
2646 ret = append(ret, c)
2647 delete(c.peerTouchedPieces, piece)
2653 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2654 p := t.Pieces[piece]
2656 // Don't score the first time a piece is hashed, it could be an
2659 pieceHashedCorrect.Add(1)
2661 log.Printf("%s: piece %d failed hash", t, piece)
2662 pieceHashedNotCorrect.Add(1)
2666 touchers := me.reapPieceTouches(t, int(piece))
2668 err := t.data.PieceCompleted(int(piece))
2670 log.Printf("error completing piece: %s", err)
2673 } else if len(touchers) != 0 {
2674 log.Printf("dropping %d conns that touched piece", len(touchers))
2675 for _, c := range touchers {
2676 me.dropConnection(t, c)
2679 me.pieceChanged(t, int(piece))
2682 // TODO: Check this isn't called more than once for each piece being correct.
2683 func (me *Client) pieceChanged(t *torrent, piece int) {
2684 correct := t.pieceComplete(piece)
2685 p := t.Pieces[piece]
2686 defer t.publishPieceChange(piece)
2687 defer p.Event.Broadcast()
2689 p.Priority = PiecePriorityNone
2690 p.PendingChunkSpecs = nil
2691 for req := range t.urgent {
2692 if int(req.Index) == piece {
2693 delete(t.urgent, req)
2697 if p.numPendingChunks() == 0 {
2698 t.pendAllChunkSpecs(int(piece))
2700 if t.wantPiece(piece) {
2704 for _, conn := range t.Conns {
2706 conn.Post(pp.Message{
2708 Index: pp.Integer(piece),
2710 // TODO: Cancel requests for this piece.
2711 for r := range conn.Requests {
2712 if int(r.Index) == piece {
2716 conn.pieceRequestOrder.DeletePiece(int(piece))
2718 } else if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2719 t.connPendPiece(conn, int(piece))
2720 me.replenishConnRequests(t, conn)
2723 me.event.Broadcast()
2726 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2728 defer cl.mu.Unlock()
2729 p := t.Pieces[index]
2730 for p.Hashing || t.data == nil {
2733 p.QueuedForHash = false
2734 if t.isClosed() || t.pieceComplete(int(index)) {
2739 sum := t.hashPiece(index)
2747 cl.pieceHashed(t, index, sum == p.Hash)
2750 // Returns handles to all the torrents loaded in the Client.
2751 func (me *Client) Torrents() (ret []Torrent) {
2753 for _, t := range me.torrents {
2754 ret = append(ret, Torrent{me, t})
2760 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2761 spec, err := TorrentSpecFromMagnetURI(uri)
2765 T, _, err = me.AddTorrentSpec(spec)
2769 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2770 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2774 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2775 mi, err := metainfo.LoadFromFile(filename)
2779 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2783 func (me *Client) DHT() *dht.Server {