27 "github.com/anacrolix/sync"
28 "github.com/anacrolix/utp"
29 "github.com/bradfitz/iter"
31 "github.com/anacrolix/torrent/bencode"
32 "github.com/anacrolix/torrent/data"
33 filePkg "github.com/anacrolix/torrent/data/file"
34 "github.com/anacrolix/torrent/dht"
35 "github.com/anacrolix/torrent/internal/pieceordering"
36 "github.com/anacrolix/torrent/iplist"
37 "github.com/anacrolix/torrent/logonce"
38 "github.com/anacrolix/torrent/metainfo"
39 "github.com/anacrolix/torrent/mse"
40 pp "github.com/anacrolix/torrent/peer_protocol"
41 "github.com/anacrolix/torrent/tracker"
42 . "github.com/anacrolix/torrent/util"
46 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
47 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
48 chunksReceived = expvar.NewInt("chunksReceived")
49 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
50 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
51 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
52 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
53 unexpectedCancels = expvar.NewInt("unexpectedCancels")
54 postedCancels = expvar.NewInt("postedCancels")
55 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
56 failedPieceHashes = expvar.NewInt("failedPieceHashes")
57 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
58 successfulDials = expvar.NewInt("successfulDials")
59 acceptedConns = expvar.NewInt("acceptedConns")
60 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
61 peerExtensions = expvar.NewMap("peerExtensions")
62 // Count of connections to peer with same client ID.
63 connsToSelf = expvar.NewInt("connsToSelf")
64 // Number of completed connections to a client we're already connected with.
65 duplicateClientConns = expvar.NewInt("duplicateClientConns")
66 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
67 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
71 // Justification for set bits follows.
73 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html ([5]|=0x10)
74 // DHT: http://www.bittorrent.org/beps/bep_0005.html ([7]|=1)
76 // http://bittorrent.org/beps/bep_0006.html ([7]|=4)
77 // Disabled until AllowedFast is implemented
78 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
80 socketsPerTorrent = 40
81 torrentPeersHighWater = 200
82 torrentPeersLowWater = 50
84 // Limit how long handshake can take. This is to reduce the lingering
85 // impact of a few bad apples. 4s loses 1% of successful handshakes that
86 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
87 btHandshakeTimeout = 4 * time.Second
88 handshakesTimeout = 20 * time.Second
90 pruneInterval = 10 * time.Second
92 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
95 extendedHandshakeClientVersion = "go.torrent dev 20140825"
98 // Currently doesn't really queue, but should in the future.
99 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
100 piece := t.Pieces[pieceIndex]
101 if piece.QueuedForHash {
104 piece.QueuedForHash = true
105 go cl.verifyPiece(t, pieceIndex)
108 // Queue a piece check if one isn't already queued, and the piece has never
109 // been checked before.
110 func (cl *Client) queueFirstHash(t *torrent, piece int) {
112 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
115 cl.queuePieceCheck(t, pp.Integer(piece))
118 // Clients contain zero or more Torrents. A client manages a blocklist, the
119 // TCP/UDP protocol ports, and DHT as desired.
123 listeners []net.Listener
126 ipBlockList *iplist.IPList
127 bannedTorrents map[InfoHash]struct{}
129 pruneTimer *time.Timer
130 extensionBytes peerExtensionBytes
131 // Set of addresses that have our client ID. This intentionally will
132 // include ourselves if we end up trying to connect to our own address
133 // through legitimate channels.
134 dopplegangerAddrs map[string]struct{}
136 torrentDataOpener TorrentDataOpener
142 torrents map[InfoHash]*torrent
145 func (me *Client) IPBlockList() *iplist.IPList {
148 return me.ipBlockList
151 func (me *Client) SetIPBlockList(list *iplist.IPList) {
154 me.ipBlockList = list
156 me.dHT.SetIPBlockList(list)
160 func (me *Client) PeerID() string {
161 return string(me.peerID[:])
164 func (me *Client) ListenAddr() (addr net.Addr) {
165 for _, l := range me.listeners {
172 type hashSorter struct {
176 func (me hashSorter) Len() int {
177 return len(me.Hashes)
180 func (me hashSorter) Less(a, b int) bool {
181 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
184 func (me hashSorter) Swap(a, b int) {
185 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
188 func (cl *Client) sortedTorrents() (ret []*torrent) {
190 for ih := range cl.torrents {
191 hs.Hashes = append(hs.Hashes, ih)
194 for _, ih := range hs.Hashes {
195 ret = append(ret, cl.torrent(ih))
200 // Writes out a human readable status of the client, such as for writing to a
202 func (cl *Client) WriteStatus(_w io.Writer) {
204 defer cl.mu.RUnlock()
205 w := bufio.NewWriter(_w)
207 if addr := cl.ListenAddr(); addr != nil {
208 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
210 fmt.Fprintln(w, "Not listening!")
212 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
214 dhtStats := cl.dHT.Stats()
215 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.Nodes, dhtStats.GoodNodes)
216 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
217 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
218 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
219 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
221 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
223 for _, t := range cl.sortedTorrents() {
225 fmt.Fprint(w, "<unknown name>")
227 fmt.Fprint(w, t.Name())
231 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
233 w.WriteString("<missing metainfo>")
241 // A Data that implements this has a streaming interface that should be
242 // preferred over ReadAt. For example, the data is stored in blocks on the
243 // network and have a fixed cost to open.
244 type SectionOpener interface {
245 // Open a ReadCloser at the given offset into torrent data. n is how many
246 // bytes we intend to read.
247 OpenSection(off, n int64) (io.ReadCloser, error)
250 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
252 // if err == io.ErrUnexpectedEOF && n != 0 {
256 // log.Println("data read at", len(b), off)
258 if ra, ok := d.(io.ReaderAt); ok {
259 return ra.ReadAt(b, off)
261 if so, ok := d.(SectionOpener); ok {
263 rc, err = so.OpenSection(off, int64(len(b)))
268 return io.ReadFull(rc, b)
270 if dp, ok := super(d); ok {
274 panic(fmt.Sprintf("can't read from %T", d))
277 // Calculates the number of pieces to set to Readahead priority, after the
278 // Now, and Next pieces.
279 func readaheadPieces(readahead, pieceLength int64) (ret int) {
280 // Expand the readahead to fit any partial pieces. Subtract 1 for the
281 // "next" piece that is assigned.
282 ret = int((readahead+pieceLength-1)/pieceLength - 1)
283 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
284 // piece length is much larger than the readahead.
291 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
292 index := int(off / int64(t.usualPieceSize()))
293 cl.raisePiecePriority(t, index, PiecePriorityNow)
295 if index >= t.numPieces() {
298 cl.raisePiecePriority(t, index, PiecePriorityNext)
299 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
301 if index >= t.numPieces() {
304 cl.raisePiecePriority(t, index, PiecePriorityReadahead)
308 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
310 req, ok := t.offsetRequest(off)
314 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
316 t.urgent = make(map[request]struct{}, (n+chunkSize-1)/chunkSize)
318 t.urgent[req] = struct{}{}
319 cl.event.Broadcast() // Why?
320 index := int(req.Index)
321 cl.queueFirstHash(t, index)
322 cl.pieceChanged(t, index)
324 reqOff := t.requestOffset(req)
325 n1 := req.Length - pp.Integer(off-reqOff)
329 // log.Print(t.urgent)
332 func (cl *Client) configDir() string {
333 if cl.config.ConfigDir == "" {
334 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
336 return cl.config.ConfigDir
339 // The directory where the Client expects to find and store configuration
340 // data. Defaults to $HOME/.config/torrent.
341 func (cl *Client) ConfigDir() string {
342 return cl.configDir()
345 func (t *torrent) connPendPiece(c *connection, piece int) {
346 c.pendPiece(piece, t.Pieces[piece].Priority)
349 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
350 if t.Pieces[piece].Priority < priority {
351 cl.prioritizePiece(t, piece, priority)
355 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
356 if t.havePiece(piece) {
359 if priority != PiecePriorityNone {
360 cl.queueFirstHash(t, piece)
363 if p.Priority != priority {
364 p.Priority = priority
365 cl.pieceChanged(t, piece)
369 func (cl *Client) setEnvBlocklist() (err error) {
370 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
371 defaultBlocklist := filename == ""
372 if defaultBlocklist {
373 filename = filepath.Join(cl.configDir(), "blocklist")
375 f, err := os.Open(filename)
377 if defaultBlocklist {
383 cl.ipBlockList, err = iplist.NewFromReader(f)
387 func (cl *Client) initBannedTorrents() error {
388 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
390 if os.IsNotExist(err) {
393 return fmt.Errorf("error opening banned infohashes file: %s", err)
396 scanner := bufio.NewScanner(f)
397 cl.bannedTorrents = make(map[InfoHash]struct{})
399 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
403 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
405 return fmt.Errorf("error reading infohash: %s", err)
411 return errors.New("bad infohash")
415 cl.bannedTorrents[ih] = struct{}{}
417 if err := scanner.Err(); err != nil {
418 return fmt.Errorf("error scanning file: %s", err)
423 // Creates a new client.
424 func NewClient(cfg *Config) (cl *Client, err error) {
435 halfOpenLimit: socketsPerTorrent,
437 torrentDataOpener: func(md *metainfo.Info) data.Data {
438 return filePkg.TorrentData(md, cfg.DataDir)
440 dopplegangerAddrs: make(map[string]struct{}),
442 quit: make(chan struct{}),
443 torrents: make(map[InfoHash]*torrent),
445 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
447 if cfg.TorrentDataOpener != nil {
448 cl.torrentDataOpener = cfg.TorrentDataOpener
451 if !cfg.NoDefaultBlocklist {
452 err = cl.setEnvBlocklist()
458 if err = cl.initBannedTorrents(); err != nil {
459 err = fmt.Errorf("error initing banned torrents: %s", err)
463 if cfg.PeerID != "" {
464 CopyExact(&cl.peerID, cfg.PeerID)
466 o := copy(cl.peerID[:], bep20)
467 _, err = rand.Read(cl.peerID[o:])
469 panic("error generating peer id")
473 // Returns the laddr string to listen on for the next Listen call.
474 listenAddr := func() string {
475 if addr := cl.ListenAddr(); addr != nil {
478 if cfg.ListenAddr == "" {
481 return cfg.ListenAddr
483 if !cl.config.DisableTCP {
485 l, err = net.Listen("tcp", listenAddr())
489 cl.listeners = append(cl.listeners, l)
490 go cl.acceptConnections(l, false)
492 if !cl.config.DisableUTP {
493 cl.utpSock, err = utp.NewSocket(listenAddr())
497 cl.listeners = append(cl.listeners, cl.utpSock)
498 go cl.acceptConnections(cl.utpSock, true)
501 dhtCfg := cfg.DHTConfig
503 dhtCfg = &dht.ServerConfig{
504 IPBlocklist: cl.ipBlockList,
507 if dhtCfg.Addr == "" {
508 dhtCfg.Addr = listenAddr()
510 if dhtCfg.Conn == nil && cl.utpSock != nil {
511 dhtCfg.Conn = cl.utpSock.PacketConn()
513 cl.dHT, err = dht.NewServer(dhtCfg)
522 func (cl *Client) stopped() bool {
531 // Stops the client. All connections to peers are closed and all activity will
533 func (me *Client) Close() {
537 for _, l := range me.listeners {
541 for _, t := range me.torrents {
546 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
548 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
549 if cl.ipBlockList == nil {
554 log.Printf("blocking non-IPv4 address: %s", ip)
558 r = cl.ipBlockList.Lookup(ip4)
562 func (cl *Client) waitAccept() {
566 for _, t := range cl.torrents {
575 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
578 // We accept all connections immediately, because we don't know what
579 // torrent they're for.
580 conn, err := l.Accept()
595 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
596 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
598 if blockRange != nil || doppleganger {
599 inboundConnsBlocked.Add(1)
600 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
604 go cl.incomingConnection(conn, utp)
608 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
610 if tc, ok := nc.(*net.TCPConn); ok {
616 c.Discovery = peerSourceIncoming
618 err := cl.runReceivedConn(c)
624 // Returns a handle to the given torrent, if it's present in the client.
625 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
628 t, ok := cl.torrents[ih]
636 func (me *Client) torrent(ih InfoHash) *torrent {
637 return me.torrents[ih]
640 type dialResult struct {
645 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
646 conn, err := dial(addr, t)
651 conn = nil // Pedantic
653 ch <- dialResult{conn, utp}
655 successfulDials.Add(1)
658 unsuccessfulDials.Add(1)
659 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
662 if netOpErr, ok := err.(*net.OpError); ok {
663 switch netOpErr.Err {
664 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
668 if utp && err.Error() == "timed out waiting for ack" {
672 log.Printf("error dialing %s: %s", addr, err)
677 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
678 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
679 if ret < minDialTimeout {
685 func (me *Client) dopplegangerAddr(addr string) bool {
686 _, ok := me.dopplegangerAddrs[addr]
690 // Start the process of connecting to the given peer for the given torrent if
692 func (me *Client) initiateConn(peer Peer, t *torrent) {
693 if peer.Id == me.peerID {
696 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
697 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
698 duplicateConnsAvoided.Add(1)
701 if r := me.ipBlockRange(peer.IP); r != nil {
702 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
705 t.HalfOpen[addr] = struct{}{}
706 go me.outgoingConnection(t, addr, peer.Source)
709 func (me *Client) dialTimeout(t *torrent) time.Duration {
711 pendingPeers := len(t.Peers)
713 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
716 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
717 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
719 c.(*net.TCPConn).SetLinger(0)
724 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
725 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
728 // Returns a connection over UTP or TCP.
729 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
730 // Initiate connections via TCP and UTP simultaneously. Use the first one
733 if !me.config.DisableUTP {
736 if !me.config.DisableTCP {
739 resCh := make(chan dialResult, left)
740 if !me.config.DisableUTP {
741 go doDial(me.dialUTP, resCh, true, addr, t)
743 if !me.config.DisableTCP {
744 go doDial(me.dialTCP, resCh, false, addr, t)
747 // Wait for a successful connection.
748 for ; left > 0 && res.Conn == nil; left-- {
752 // There are still incompleted dials.
754 for ; left > 0; left-- {
755 conn := (<-resCh).Conn
767 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
768 if _, ok := t.HalfOpen[addr]; !ok {
769 panic("invariant broken")
771 delete(t.HalfOpen, addr)
775 // Returns nil connection and nil error if no connection could be established
776 // for valid reasons.
777 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
778 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
782 c.encrypted = encrypted
784 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
788 ok, err := me.initiateHandshakes(c, t)
794 nc, utp := me.dial(addr, t)
798 c, err = handshakesConnection(nc, !me.config.DisableEncryption, utp)
806 // Try again without encryption, using whichever protocol type worked last
808 if me.config.DisableEncryption {
809 // We already tried without encryption.
813 nc, err = me.dialUTP(addr, t)
815 nc, err = me.dialTCP(addr, t)
818 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
821 c, err = handshakesConnection(nc, false, utp)
828 // Called to dial out and run a connection. The addr we're given is already
829 // considered half-open.
830 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
831 c, err := me.establishOutgoingConn(t, addr)
834 // Don't release lock between here and addConnection, unless it's for
836 me.noLongerHalfOpen(t, addr)
845 err = me.runInitiatedHandshookConn(c, t)
851 // The port number for incoming peer connections. 0 if the client isn't
853 func (cl *Client) incomingPeerPort() int {
854 listenAddr := cl.ListenAddr()
855 if listenAddr == nil {
858 return addrPort(listenAddr)
861 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
862 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
863 func addrCompactIP(addr net.Addr) (string, error) {
864 host, _, err := net.SplitHostPort(addr.String())
868 ip := net.ParseIP(host)
869 if v4 := ip.To4(); v4 != nil {
873 return string(v4), nil
875 return string(ip.To16()), nil
878 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
890 peerExtensionBytes [8]byte
894 func (me *peerExtensionBytes) SupportsExtended() bool {
895 return me[5]&0x10 != 0
898 func (me *peerExtensionBytes) SupportsDHT() bool {
899 return me[7]&0x01 != 0
902 func (me *peerExtensionBytes) SupportsFast() bool {
903 return me[7]&0x04 != 0
906 type handshakeResult struct {
912 // ih is nil if we expect the peer to declare the InfoHash, such as when the
913 // peer initiated the connection. Returns ok if the handshake was successful,
914 // and err if there was an unexpected condition other than the peer simply
915 // abandoning the handshake.
916 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
917 // Bytes to be sent to the peer. Should never block the sender.
918 postCh := make(chan []byte, 4)
919 // A single error value sent when the writer completes.
920 writeDone := make(chan error, 1)
921 // Performs writes to the socket and ensures posts don't block.
922 go handshakeWriter(sock, postCh, writeDone)
925 close(postCh) // Done writing.
932 // Wait until writes complete before returning from handshake.
935 err = fmt.Errorf("error writing: %s", err)
939 post := func(bb []byte) {
943 panic("mustn't block while posting")
947 post([]byte(pp.Protocol))
949 if ih != nil { // We already know what we want.
954 _, err = io.ReadFull(sock, b[:68])
959 if string(b[:20]) != pp.Protocol {
962 CopyExact(&res.peerExtensionBytes, b[20:28])
963 CopyExact(&res.InfoHash, b[28:48])
964 CopyExact(&res.peerID, b[48:68])
965 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
967 // TODO: Maybe we can just drop peers here if we're not interested. This
968 // could prevent them trying to reconnect, falsely believing there was
970 if ih == nil { // We were waiting for the peer to tell us what they wanted.
971 post(res.InfoHash[:])
979 // Wraps a raw connection and provides the interface we want for using the
980 // connection in the message loop.
981 type deadlineReader struct {
986 func (me deadlineReader) Read(b []byte) (n int, err error) {
987 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
988 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
990 err = fmt.Errorf("error setting read deadline: %s", err)
992 n, err = me.r.Read(b)
993 // Convert common errors into io.EOF.
995 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
997 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1007 type readWriter struct {
1012 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1013 var protocol [len(pp.Protocol)]byte
1014 _, err = io.ReadFull(rw, protocol[:])
1019 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1022 if string(protocol[:]) == pp.Protocol {
1026 ret, err = mse.ReceiveHandshake(ret, skeys)
1030 func (cl *Client) receiveSkeys() (ret [][]byte) {
1031 for ih := range cl.torrents {
1032 ret = append(ret, ih[:])
1037 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1039 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1044 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1045 if ih != t.InfoHash {
1051 // Do encryption and bittorrent handshakes as receiver.
1052 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1054 skeys := cl.receiveSkeys()
1056 if !cl.config.DisableEncryption {
1057 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1059 if err == mse.ErrNoSecretKeyMatch {
1065 ih, ok, err := cl.connBTHandshake(c, nil)
1067 err = fmt.Errorf("error during bt handshake: %s", err)
1079 // Returns !ok if handshake failed for valid reasons.
1080 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1081 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1082 if err != nil || !ok {
1086 c.PeerExtensionBytes = res.peerExtensionBytes
1087 c.PeerID = res.peerID
1088 c.completedHandshake = time.Now()
1092 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1093 if c.PeerID == cl.peerID {
1094 // Only if we initiated the connection is the remote address a
1095 // listen addr for a doppleganger.
1097 addr := c.conn.RemoteAddr().String()
1098 cl.dopplegangerAddrs[addr] = struct{}{}
1101 return cl.runHandshookConn(c, t)
1104 func (cl *Client) runReceivedConn(c *connection) (err error) {
1105 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1109 t, err := cl.receiveHandshakes(c)
1111 err = fmt.Errorf("error receiving handshakes: %s", err)
1118 defer cl.mu.Unlock()
1119 if c.PeerID == cl.peerID {
1122 return cl.runHandshookConn(c, t)
1125 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1126 c.conn.SetWriteDeadline(time.Time{})
1128 deadlineReader{c.conn, c.rw},
1131 if !cl.addConnection(t, c) {
1134 defer cl.dropConnection(t, c)
1136 go c.writeOptimizer(time.Minute)
1137 cl.sendInitialMessages(c, t)
1139 t.initRequestOrdering(c)
1141 err = cl.connectionLoop(t, c)
1143 err = fmt.Errorf("error during connection loop: %s", err)
1148 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1149 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1150 conn.Post(pp.Message{
1152 ExtendedID: pp.HandshakeExtendedID,
1153 ExtendedPayload: func() []byte {
1154 d := map[string]interface{}{
1155 "m": func() (ret map[string]int) {
1156 ret = make(map[string]int, 2)
1157 ret["ut_metadata"] = metadataExtendedId
1158 if !me.config.DisablePEX {
1159 ret["ut_pex"] = pexExtendedId
1163 "v": extendedHandshakeClientVersion,
1164 // No upload queue is implemented yet.
1167 if !me.config.DisableEncryption {
1170 if torrent.metadataSizeKnown() {
1171 d["metadata_size"] = torrent.metadataSize()
1173 if p := me.incomingPeerPort(); p != 0 {
1176 yourip, err := addrCompactIP(conn.remoteAddr())
1178 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1180 d["yourip"] = yourip
1182 // log.Printf("sending %v", d)
1183 b, err := bencode.Marshal(d)
1191 if torrent.haveAnyPieces() {
1192 conn.Post(pp.Message{
1194 Bitfield: torrent.bitfield(),
1196 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1197 conn.Post(pp.Message{
1201 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1202 conn.Post(pp.Message{
1204 Port: uint16(AddrPort(me.dHT.Addr())),
1209 // Randomizes the piece order for this connection. Every connection will be
1210 // given a different ordering. Having it stored per connection saves having to
1211 // randomize during request filling, and constantly recalculate the ordering
1212 // based on piece priorities.
1213 func (t *torrent) initRequestOrdering(c *connection) {
1214 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1215 panic("double init of request ordering")
1217 c.piecePriorities = mathRand.Perm(t.numPieces())
1218 c.pieceRequestOrder = pieceordering.New()
1219 for i := range iter.N(t.Info.NumPieces()) {
1220 if !c.PeerHasPiece(i) {
1223 if !t.wantPiece(i) {
1226 t.connPendPiece(c, i)
1230 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1233 if c.PeerPieces == nil {
1234 c.PeerPieces = make([]bool, t.numPieces())
1237 for piece >= len(c.PeerPieces) {
1238 c.PeerPieces = append(c.PeerPieces, false)
1241 c.PeerPieces[piece] = true
1243 if t.wantPiece(piece) {
1244 t.connPendPiece(c, piece)
1245 me.replenishConnRequests(t, c)
1249 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1250 me.replenishConnRequests(torrent, conn)
1253 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1256 postedCancels.Add(1)
1261 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1262 if !cn.RequestPending(r) {
1265 delete(cn.Requests, r)
1269 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1273 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1274 // Peer doesn't support this.
1277 // Request metadata pieces that we don't have in a random order.
1279 for index := 0; index < t.metadataPieceCount(); index++ {
1280 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1281 pending = append(pending, index)
1284 for _, i := range mathRand.Perm(len(pending)) {
1285 c.requestMetadataPiece(pending[i])
1289 func (cl *Client) completedMetadata(t *torrent) {
1293 CopyExact(&ih, h.Sum(nil))
1294 if ih != t.InfoHash {
1295 log.Print("bad metadata")
1296 t.invalidateMetadata()
1299 var info metainfo.Info
1300 err := bencode.Unmarshal(t.MetaData, &info)
1302 log.Printf("error unmarshalling metadata: %s", err)
1303 t.invalidateMetadata()
1306 // TODO(anacrolix): If this fails, I think something harsher should be
1308 err = cl.setMetaData(t, &info, t.MetaData)
1310 log.Printf("error setting metadata: %s", err)
1311 t.invalidateMetadata()
1314 log.Printf("%s: got metadata from peers", t)
1317 // Process incoming ut_metadata message.
1318 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1319 var d map[string]int
1320 err = bencode.Unmarshal(payload, &d)
1322 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1325 msgType, ok := d["msg_type"]
1327 err = errors.New("missing msg_type field")
1332 case pp.DataMetadataExtensionMsgType:
1336 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1337 if begin < 0 || begin >= len(payload) {
1338 log.Printf("got bad metadata piece")
1341 if !c.requestedMetadataPiece(piece) {
1342 log.Printf("got unexpected metadata piece %d", piece)
1345 c.metadataRequests[piece] = false
1346 t.saveMetadataPiece(piece, payload[begin:])
1347 c.UsefulChunksReceived++
1348 c.lastUsefulChunkReceived = time.Now()
1349 if !t.haveAllMetadataPieces() {
1352 cl.completedMetadata(t)
1353 case pp.RequestMetadataExtensionMsgType:
1354 if !t.haveMetadataPiece(piece) {
1355 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1358 start := (1 << 14) * piece
1359 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1360 case pp.RejectMetadataExtensionMsgType:
1362 err = errors.New("unknown msg_type value")
1367 type peerExchangeMessage struct {
1368 Added CompactPeers `bencode:"added"`
1369 AddedFlags []byte `bencode:"added.f"`
1370 Dropped CompactPeers `bencode:"dropped"`
1373 // Extracts the port as an integer from an address string.
1374 func addrPort(addr net.Addr) int {
1375 return AddrPort(addr)
1378 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1379 cn.peerHasAll = true
1382 for i := 0; i < t.numPieces(); i++ {
1383 cl.peerGotPiece(t, cn, i)
1388 func (me *Client) upload(t *torrent, c *connection) {
1389 if me.config.NoUpload {
1392 if !c.PeerInterested {
1395 if !me.seeding(t) && !t.connHasWantedPieces(c) {
1399 for c.chunksSent < c.UsefulChunksReceived+6 {
1401 for r := range c.PeerRequests {
1402 err := me.sendChunk(t, c, r)
1404 log.Printf("error sending chunk to peer: %s", err)
1406 delete(c.PeerRequests, r)
1414 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1415 b := make([]byte, r.Length)
1416 p := t.Info.Piece(int(r.Index))
1417 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1430 uploadChunksPosted.Add(1)
1432 c.lastChunkSent = time.Now()
1436 // Processes incoming bittorrent messages. The client lock is held upon entry
1438 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1439 decoder := pp.Decoder{
1440 R: bufio.NewReader(c.rw),
1441 MaxLength: 256 * 1024,
1446 err := decoder.Decode(&msg)
1447 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1449 c.lastMessageReceived = time.Now()
1456 if me.stopped() || err == io.EOF {
1467 for r := range c.Requests {
1468 me.connDeleteRequest(t, c, r)
1470 // We can then reset our interest.
1471 me.replenishConnRequests(t, c)
1473 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1474 me.replenishConnRequests(t, c)
1476 c.PeerChoked = false
1477 me.peerUnchoked(t, c)
1479 c.PeerInterested = true
1481 case pp.NotInterested:
1482 c.PeerInterested = false
1485 me.peerGotPiece(t, c, int(msg.Index))
1490 if !c.PeerInterested {
1491 err = errors.New("peer sent request but isn't interested")
1494 if c.PeerRequests == nil {
1495 c.PeerRequests = make(map[request]struct{}, maxRequests)
1497 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1500 req := newRequest(msg.Index, msg.Begin, msg.Length)
1501 if !c.PeerCancel(req) {
1502 unexpectedCancels.Add(1)
1505 if c.PeerPieces != nil || c.peerHasAll {
1506 err = errors.New("received unexpected bitfield")
1510 if len(msg.Bitfield) < t.numPieces() {
1511 err = errors.New("received invalid bitfield")
1514 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1516 c.PeerPieces = msg.Bitfield
1517 for index, has := range c.PeerPieces {
1519 me.peerGotPiece(t, c, index)
1523 if c.PeerPieces != nil || c.peerHasAll {
1524 err = errors.New("unexpected have-all")
1529 if c.peerHasAll || c.PeerPieces != nil {
1530 err = errors.New("unexpected have-none")
1533 c.PeerPieces = make([]bool, func() int {
1535 return t.numPieces()
1541 err = me.downloadedChunk(t, c, &msg)
1543 switch msg.ExtendedID {
1544 case pp.HandshakeExtendedID:
1545 // TODO: Create a bencode struct for this.
1546 var d map[string]interface{}
1547 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1549 err = fmt.Errorf("error decoding extended message payload: %s", err)
1552 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1553 if reqq, ok := d["reqq"]; ok {
1554 if i, ok := reqq.(int64); ok {
1555 c.PeerMaxRequests = int(i)
1558 if v, ok := d["v"]; ok {
1559 c.PeerClientName = v.(string)
1563 err = errors.New("handshake missing m item")
1566 mTyped, ok := m.(map[string]interface{})
1568 err = errors.New("handshake m value is not dict")
1571 if c.PeerExtensionIDs == nil {
1572 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1574 for name, v := range mTyped {
1577 log.Printf("bad handshake m item extension ID type: %T", v)
1581 delete(c.PeerExtensionIDs, name)
1583 if c.PeerExtensionIDs[name] == 0 {
1584 supportedExtensionMessages.Add(name, 1)
1586 c.PeerExtensionIDs[name] = byte(id)
1589 metadata_sizeUntyped, ok := d["metadata_size"]
1591 metadata_size, ok := metadata_sizeUntyped.(int64)
1593 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1595 t.setMetadataSize(metadata_size, me)
1598 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1599 me.requestPendingMetadata(t, c)
1601 case metadataExtendedId:
1602 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1604 err = fmt.Errorf("error handling metadata extension message: %s", err)
1607 if me.config.DisablePEX {
1610 var pexMsg peerExchangeMessage
1611 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1613 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1618 me.addPeers(t, func() (ret []Peer) {
1619 for i, cp := range pexMsg.Added {
1621 IP: make([]byte, 4),
1623 Source: peerSourcePEX,
1625 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1626 p.SupportsEncryption = true
1628 CopyExact(p.IP, cp.IP[:])
1629 ret = append(ret, p)
1634 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1637 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1640 // That client uses its own extension IDs for outgoing message
1641 // types, which is incorrect.
1642 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1643 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1651 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1656 pingAddr.Port = int(msg.Port)
1658 _, err = me.dHT.Ping(pingAddr)
1660 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1668 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1669 me.event.Broadcast()
1670 for r := range conn.Requests {
1671 me.connDeleteRequest(torrent, conn, r)
1674 for i0, c := range torrent.Conns {
1678 i1 := len(torrent.Conns) - 1
1680 torrent.Conns[i0] = torrent.Conns[i1]
1682 torrent.Conns = torrent.Conns[:i1]
1683 me.openNewConns(torrent)
1686 panic("connection not found")
1689 func (me *Client) addConnection(t *torrent, c *connection) bool {
1694 case <-t.ceasingNetworking:
1698 if !me.wantConns(t) {
1701 for _, c0 := range t.Conns {
1702 if c.PeerID == c0.PeerID {
1703 // Already connected to a client with that ID.
1704 duplicateClientConns.Add(1)
1708 t.Conns = append(t.Conns, c)
1709 // TODO: This should probably be done by a routine that kills off bad
1710 // connections, and extra connections killed here instead.
1711 if len(t.Conns) > socketsPerTorrent {
1712 wcs := t.worstConnsHeap(me)
1713 heap.Pop(wcs).(*connection).Close()
1718 func (t *torrent) needData() bool {
1722 for i := range t.Pieces {
1730 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1731 // A 30 second grace for initial messages to go through.
1732 if time.Since(c.completedHandshake) < 30*time.Second {
1736 if !c.supportsExtension("ut_metadata") {
1739 if time.Since(c.completedHandshake) < 2*time.Minute {
1745 return c.PeerInterested
1747 return t.connHasWantedPieces(c)
1750 func (t *torrent) numGoodConns(cl *Client) (num int) {
1751 for _, c := range t.Conns {
1752 if cl.usefulConn(t, c) {
1759 func (me *Client) wantConns(t *torrent) bool {
1760 if !me.seeding(t) && !t.needData() {
1763 if t.numGoodConns(me) >= socketsPerTorrent {
1769 func (me *Client) openNewConns(t *torrent) {
1771 case <-t.ceasingNetworking:
1775 for len(t.Peers) != 0 {
1776 if !me.wantConns(t) {
1779 if len(t.HalfOpen) >= me.halfOpenLimit {
1786 for k, p = range t.Peers {
1790 me.initiateConn(p, t)
1792 t.wantPeers.Broadcast()
1795 func (me *Client) addPeers(t *torrent, peers []Peer) {
1796 for _, p := range peers {
1797 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1800 if me.ipBlockRange(p.IP) != nil {
1804 log.Printf("got bad peer: %v", p)
1812 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1813 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1816 func (cl *Client) saveTorrentFile(t *torrent) error {
1817 path := cl.cachedMetaInfoFilename(t.InfoHash)
1818 os.MkdirAll(filepath.Dir(path), 0777)
1819 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1821 return fmt.Errorf("error opening file: %s", err)
1824 e := bencode.NewEncoder(f)
1825 err = e.Encode(t.MetaInfo())
1827 return fmt.Errorf("error marshalling metainfo: %s", err)
1829 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1831 // For example, a script kiddy makes us load too many files, and we're
1832 // able to save the torrent, but not load it again to check it.
1835 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1836 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1841 func (cl *Client) startTorrent(t *torrent) {
1842 if t.Info == nil || t.data == nil {
1845 // If the client intends to upload, it needs to know what state pieces are
1847 if !cl.config.NoUpload {
1848 // Queue all pieces for hashing. This is done sequentially to avoid
1849 // spamming goroutines.
1850 for _, p := range t.Pieces {
1851 p.QueuedForHash = true
1854 for i := range t.Pieces {
1855 cl.verifyPiece(t, pp.Integer(i))
1861 // Storage cannot be changed once it's set.
1862 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1863 err = t.setStorage(td)
1864 cl.event.Broadcast()
1868 for index := range iter.N(t.numPieces()) {
1869 cl.pieceChanged(t, index)
1875 type TorrentDataOpener func(*metainfo.Info) data.Data
1877 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1878 err = t.setMetadata(md, bytes, &cl.mu)
1882 if !cl.config.DisableMetainfoCache {
1883 if err := cl.saveTorrentFile(t); err != nil {
1884 log.Printf("error saving torrent file for %s: %s", t, err)
1887 cl.event.Broadcast()
1888 close(t.gotMetainfo)
1889 td := cl.torrentDataOpener(md)
1890 err = cl.setStorage(t, td)
1894 // Prepare a Torrent without any attachment to a Client. That means we can
1895 // initialize fields all fields that don't require the Client without locking
1897 func newTorrent(ih InfoHash) (t *torrent, err error) {
1900 Peers: make(map[peersKey]Peer),
1902 closing: make(chan struct{}),
1903 ceasingNetworking: make(chan struct{}),
1905 gotMetainfo: make(chan struct{}),
1907 HalfOpen: make(map[string]struct{}),
1909 t.wantPeers.L = &t.stateMu
1914 // For shuffling the tracker tiers.
1915 mathRand.Seed(time.Now().Unix())
1918 // The trackers within each tier must be shuffled before use.
1919 // http://stackoverflow.com/a/12267471/149482
1920 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1921 func shuffleTier(tier []tracker.Client) {
1922 for i := range tier {
1923 j := mathRand.Intn(i + 1)
1924 tier[i], tier[j] = tier[j], tier[i]
1928 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1929 for _, tier := range base {
1930 copy = append(copy, append([]tracker.Client{}, tier...))
1935 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1937 for _, url := range newURLs {
1938 for _, tr := range tier {
1939 if tr.URL() == url {
1943 tr, err := tracker.New(url)
1945 log.Printf("error creating tracker client for %q: %s", url, err)
1948 tier = append(tier, tr)
1953 func (t *torrent) addTrackers(announceList [][]string) {
1954 newTrackers := copyTrackers(t.Trackers)
1955 for tierIndex, tier := range announceList {
1956 if tierIndex < len(newTrackers) {
1957 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1959 newTrackers = append(newTrackers, mergeTier(nil, tier))
1961 shuffleTier(newTrackers[tierIndex])
1963 t.Trackers = newTrackers
1966 // Don't call this before the info is available.
1967 func (t *torrent) BytesCompleted() int64 {
1971 return t.Info.TotalLength() - t.bytesLeft()
1974 // A file-like handle to some torrent data resource.
1975 type Handle interface {
1982 // Returns handles to the files in the torrent. This requires the metainfo is
1984 func (t Torrent) Files() (ret []File) {
1992 for _, fi := range info.UpvertedFiles() {
1993 ret = append(ret, File{
1995 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2005 // Marks the pieces in the given region for download.
2006 func (t Torrent) SetRegionPriority(off, len int64) {
2008 defer t.cl.mu.Unlock()
2009 pieceSize := int64(t.usualPieceSize())
2010 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2011 t.cl.raisePiecePriority(t.torrent, int(i), PiecePriorityNormal)
2015 func (t Torrent) AddPeers(pp []Peer) error {
2018 defer cl.mu.Unlock()
2019 cl.addPeers(t.torrent, pp)
2023 // Marks the entire torrent for download. Requires the info first, see
2025 func (t Torrent) DownloadAll() {
2027 defer t.cl.mu.Unlock()
2028 for i := range iter.N(t.numPieces()) {
2029 t.cl.raisePiecePriority(t.torrent, i, PiecePriorityNormal)
2031 // Nice to have the first and last pieces sooner for various interactive
2033 t.cl.raisePiecePriority(t.torrent, 0, PiecePriorityReadahead)
2034 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, PiecePriorityReadahead)
2037 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2038 // metainfo has the correct infohash.
2039 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2040 if cl.config.DisableMetainfoCache {
2043 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2045 if os.IsNotExist(err) {
2051 dec := bencode.NewDecoder(f)
2052 err = dec.Decode(&mi)
2056 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2057 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2063 // Specifies a new torrent for adding to a client. There are helpers for
2064 // magnet URIs and torrent metainfo files.
2065 type TorrentSpec struct {
2068 Info *metainfo.InfoEx
2072 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2073 m, err := ParseMagnetURI(uri)
2077 spec = &TorrentSpec{
2078 Trackers: [][]string{m.Trackers},
2079 DisplayName: m.DisplayName,
2080 InfoHash: m.InfoHash,
2085 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2086 spec = &TorrentSpec{
2087 Trackers: mi.AnnounceList,
2089 DisplayName: mi.Info.Name,
2091 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2095 // Add or merge a torrent spec. If the torrent is already present, the
2096 // trackers will be merged with the existing ones. If the Info isn't yet
2097 // known, it will be set. The display name is replaced if the new spec
2098 // provides one. Returns new if the torrent wasn't already in the client.
2099 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2102 defer cl.mu.Unlock()
2104 t, ok := cl.torrents[spec.InfoHash]
2108 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2109 err = errors.New("banned torrent")
2113 t, err = newTorrent(spec.InfoHash)
2118 if spec.DisplayName != "" {
2119 t.DisplayName = spec.DisplayName
2121 // Try to merge in info we have on the torrent. Any err left will
2122 // terminate the function.
2124 if spec.Info != nil {
2125 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2127 var mi *metainfo.MetaInfo
2128 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2130 log.Printf("error getting cached metainfo: %s", err)
2132 } else if mi != nil {
2133 t.addTrackers(mi.AnnounceList)
2134 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2141 t.addTrackers(spec.Trackers)
2143 cl.torrents[spec.InfoHash] = t
2146 // From this point onwards, we can consider the torrent a part of the
2149 t.pruneTimer = time.AfterFunc(0, func() {
2150 cl.pruneConnectionsUnlocked(T.torrent)
2152 if !cl.config.DisableTrackers {
2153 go cl.announceTorrentTrackers(T.torrent)
2156 go cl.announceTorrentDHT(T.torrent, true)
2162 // Prunes unused connections. This is required to make space to dial for
2164 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
2166 case <-t.ceasingNetworking:
2173 license := len(t.Conns) - (socketsPerTorrent+1)/2
2174 for _, c := range t.Conns {
2178 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
2181 if time.Now().Sub(c.completedHandshake) < time.Minute {
2188 t.pruneTimer.Reset(pruneInterval)
2191 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2192 t, ok := me.torrents[infoHash]
2194 err = fmt.Errorf("no such torrent")
2201 delete(me.torrents, infoHash)
2205 // Returns true when peers are required, or false if the torrent is closing.
2206 func (cl *Client) waitWantPeers(t *torrent) bool {
2208 defer cl.mu.Unlock()
2210 defer t.stateMu.Unlock()
2213 case <-t.ceasingNetworking:
2217 if len(t.Peers) > torrentPeersLowWater {
2220 if t.needData() || cl.seeding(t) {
2232 // Returns whether the client should make effort to seed the torrent.
2233 func (cl *Client) seeding(t *torrent) bool {
2234 if cl.config.NoUpload {
2237 if !cl.config.Seed {
2246 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2247 for cl.waitWantPeers(t) {
2248 log.Printf("getting peers for %q from DHT", t)
2249 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2251 log.Printf("error getting peers from dht: %s", err)
2254 allAddrs := make(map[string]struct{})
2258 case v, ok := <-ps.Peers:
2262 peersFoundByDHT.Add(int64(len(v.Peers)))
2263 for _, p := range v.Peers {
2264 allAddrs[(&net.UDPAddr{
2267 }).String()] = struct{}{}
2269 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2271 cl.addPeers(t, func() (ret []Peer) {
2272 for _, cp := range v.Peers {
2273 ret = append(ret, Peer{
2276 Source: peerSourceDHT,
2281 numPeers := len(t.Peers)
2283 if numPeers >= torrentPeersHighWater {
2286 case <-t.ceasingNetworking:
2292 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2296 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2297 url_, err := url.Parse(tr.URL())
2301 host, _, err := net.SplitHostPort(url_.Host)
2305 addr, err := net.ResolveIPAddr("ip", host)
2310 if cl.ipBlockList != nil {
2311 if cl.ipBlockRange(addr.IP) != nil {
2319 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2320 blocked, err := cl.trackerBlockedUnlocked(tr)
2322 return fmt.Errorf("error determining if tracker blocked: %s", err)
2325 return fmt.Errorf("tracker blocked: %s", tr)
2327 if err := tr.Connect(); err != nil {
2328 return fmt.Errorf("error connecting: %s", err)
2330 resp, err := tr.Announce(req)
2332 return fmt.Errorf("error announcing: %s", err)
2335 for _, peer := range resp.Peers {
2336 peers = append(peers, Peer{
2342 cl.addPeers(t, peers)
2345 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2346 peersFoundByTracker.Add(int64(len(peers)))
2348 time.Sleep(time.Second * time.Duration(resp.Interval))
2352 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2353 oks := make(chan bool)
2355 for _, tier := range trackers {
2356 for _, tr := range tier {
2358 go func(tr tracker.Client) {
2359 err := cl.announceTorrentSingleTracker(tr, req, t)
2364 for outstanding > 0 {
2374 // Announce torrent to its trackers.
2375 func (cl *Client) announceTorrentTrackers(t *torrent) {
2376 req := tracker.AnnounceRequest{
2377 Event: tracker.Started,
2379 Port: uint16(cl.incomingPeerPort()),
2381 InfoHash: t.InfoHash,
2383 if !cl.waitWantPeers(t) {
2387 req.Left = uint64(t.bytesLeft())
2388 trackers := t.Trackers
2390 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2391 req.Event = tracker.None
2394 for cl.waitWantPeers(t) {
2396 req.Left = uint64(t.bytesLeft())
2397 trackers = t.Trackers
2399 numTrackersTried := 0
2400 for _, tier := range trackers {
2401 for trIndex, tr := range tier {
2403 err := cl.announceTorrentSingleTracker(tr, &req, t)
2405 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2408 // Float the successful announce to the top of the tier. If
2409 // the trackers list has been changed, we'll be modifying an
2410 // old copy so it won't matter.
2412 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2415 req.Event = tracker.None
2416 continue newAnnounce
2419 if numTrackersTried != 0 {
2420 log.Printf("%s: all trackers failed", t)
2422 // TODO: Wait until trackers are added if there are none.
2423 time.Sleep(10 * time.Second)
2427 func (cl *Client) allTorrentsCompleted() bool {
2428 for _, t := range cl.torrents {
2432 if t.numPiecesCompleted() != t.numPieces() {
2439 // Returns true when all torrents are completely downloaded and false if the
2440 // client is stopped before that.
2441 func (me *Client) WaitAll() bool {
2443 defer me.mu.Unlock()
2444 for !me.allTorrentsCompleted() {
2453 func (me *Client) fillRequests(t *torrent, c *connection) {
2458 if len(c.Requests) > c.requestsLowWater {
2462 addRequest := func(req request) (again bool) {
2463 // TODO: Couldn't this check also be done *after* the request?
2464 if len(c.Requests) >= 64 {
2467 return c.Request(req)
2469 for req := range t.urgent {
2470 if !addRequest(req) {
2474 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2475 pieceIndex := e.Piece()
2476 if !c.PeerHasPiece(pieceIndex) {
2477 panic("piece in request order but peer doesn't have it")
2479 if !t.wantPiece(pieceIndex) {
2480 panic("unwanted piece in connection request order")
2482 piece := t.Pieces[pieceIndex]
2483 for _, cs := range piece.shuffledPendingChunkSpecs(t.pieceLength(pieceIndex)) {
2484 r := request{pp.Integer(pieceIndex), cs}
2493 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2497 me.fillRequests(t, c)
2498 if len(c.Requests) == 0 && !c.PeerChoked {
2499 // So we're not choked, but we don't want anything right now. We may
2500 // have completed readahead, and the readahead window has not rolled
2501 // over to the next piece. Better to stay interested in case we're
2502 // going to want data in the near future.
2503 c.SetInterested(!t.haveAllPieces())
2507 // Handle a received chunk from a peer.
2508 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2509 chunksReceived.Add(1)
2511 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2513 // Request has been satisfied.
2514 if me.connDeleteRequest(t, c, req) {
2515 defer me.replenishConnRequests(t, c)
2517 unexpectedChunksReceived.Add(1)
2520 piece := t.Pieces[req.Index]
2522 // Do we actually want this chunk?
2523 if !t.wantChunk(req) {
2524 unwantedChunksReceived.Add(1)
2525 c.UnwantedChunksReceived++
2529 c.UsefulChunksReceived++
2530 c.lastUsefulChunkReceived = time.Now()
2534 // Write the chunk out.
2535 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2537 log.Printf("error writing chunk: %s", err)
2541 // log.Println("got chunk", req)
2542 piece.Event.Broadcast()
2543 // Record that we have the chunk.
2544 piece.unpendChunkIndex(chunkIndex(req.chunkSpec))
2545 delete(t.urgent, req)
2546 if piece.numPendingChunks() == 0 {
2547 for _, c := range t.Conns {
2548 c.pieceRequestOrder.DeletePiece(int(req.Index))
2550 me.queuePieceCheck(t, req.Index)
2553 // Cancel pending requests for this chunk.
2554 for _, c := range t.Conns {
2555 if me.connCancel(t, c, req) {
2556 me.replenishConnRequests(t, c)
2563 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2564 p := t.Pieces[piece]
2565 if p.EverHashed && !correct {
2566 log.Printf("%s: piece %d failed hash", t, piece)
2567 failedPieceHashes.Add(1)
2571 err := t.data.PieceCompleted(int(piece))
2573 log.Printf("error completing piece: %s", err)
2577 me.pieceChanged(t, int(piece))
2580 // TODO: Check this isn't called more than once for each piece being correct.
2581 func (me *Client) pieceChanged(t *torrent, piece int) {
2582 correct := t.pieceComplete(piece)
2583 p := t.Pieces[piece]
2584 defer p.Event.Broadcast()
2586 p.Priority = PiecePriorityNone
2587 p.PendingChunkSpecs = nil
2588 for req := range t.urgent {
2589 if int(req.Index) == piece {
2590 delete(t.urgent, req)
2594 if p.numPendingChunks() == 0 {
2595 t.pendAllChunkSpecs(int(piece))
2597 if t.wantPiece(piece) {
2601 for _, conn := range t.Conns {
2603 conn.Post(pp.Message{
2605 Index: pp.Integer(piece),
2607 // TODO: Cancel requests for this piece.
2608 for r := range conn.Requests {
2609 if int(r.Index) == piece {
2613 conn.pieceRequestOrder.DeletePiece(int(piece))
2615 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2616 t.connPendPiece(conn, int(piece))
2617 me.replenishConnRequests(t, conn)
2620 me.event.Broadcast()
2623 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2625 defer cl.mu.Unlock()
2626 p := t.Pieces[index]
2627 for p.Hashing || t.data == nil {
2630 p.QueuedForHash = false
2631 if t.isClosed() || t.pieceComplete(int(index)) {
2636 sum := t.hashPiece(index)
2644 cl.pieceHashed(t, index, sum == p.Hash)
2647 // Returns handles to all the torrents loaded in the Client.
2648 func (me *Client) Torrents() (ret []Torrent) {
2650 for _, t := range me.torrents {
2651 ret = append(ret, Torrent{me, t})
2657 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2658 spec, err := TorrentSpecFromMagnetURI(uri)
2662 T, _, err = me.AddTorrentSpec(spec)
2666 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2667 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2671 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2672 mi, err := metainfo.LoadFromFile(filename)
2676 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))