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 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
47 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
48 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
49 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
50 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
51 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
52 unexpectedCancels = expvar.NewInt("unexpectedCancels")
53 postedCancels = expvar.NewInt("postedCancels")
54 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
55 failedPieceHashes = expvar.NewInt("failedPieceHashes")
56 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
57 successfulDials = expvar.NewInt("successfulDials")
58 acceptedConns = expvar.NewInt("acceptedConns")
59 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
60 peerExtensions = expvar.NewMap("peerExtensions")
61 // Count of connections to peer with same client ID.
62 connsToSelf = expvar.NewInt("connsToSelf")
63 // Number of completed connections to a client we're already connected with.
64 duplicateClientConns = expvar.NewInt("duplicateClientConns")
65 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
66 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
70 // Justification for set bits follows.
72 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html ([5]|=0x10)
73 // DHT: http://www.bittorrent.org/beps/bep_0005.html ([7]|=1)
75 // http://bittorrent.org/beps/bep_0006.html ([7]|=4)
76 // Disabled until AllowedFast is implemented
77 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
79 socketsPerTorrent = 40
80 torrentPeersHighWater = 200
81 torrentPeersLowWater = 50
83 // Limit how long handshake can take. This is to reduce the lingering
84 // impact of a few bad apples. 4s loses 1% of successful handshakes that
85 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
86 btHandshakeTimeout = 4 * time.Second
87 handshakesTimeout = 20 * time.Second
89 pruneInterval = 10 * time.Second
91 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
94 extendedHandshakeClientVersion = "go.torrent dev 20140825"
97 // Currently doesn't really queue, but should in the future.
98 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
99 piece := t.Pieces[pieceIndex]
100 if piece.QueuedForHash {
103 piece.QueuedForHash = true
104 go cl.verifyPiece(t, pieceIndex)
107 // Queue a piece check if one isn't already queued, and the piece has never
108 // been checked before.
109 func (cl *Client) queueFirstHash(t *torrent, piece int) {
111 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
114 cl.queuePieceCheck(t, pp.Integer(piece))
120 listeners []net.Listener
123 ipBlockList *iplist.IPList
124 bannedTorrents map[InfoHash]struct{}
126 pruneTimer *time.Timer
127 extensionBytes peerExtensionBytes
128 // Set of addresses that have our client ID. This intentionally will
129 // include ourselves if we end up trying to connect to our own address
130 // through legitimate channels.
131 dopplegangerAddrs map[string]struct{}
133 torrentDataOpener TorrentDataOpener
139 torrents map[InfoHash]*torrent
142 func (me *Client) IPBlockList() *iplist.IPList {
145 return me.ipBlockList
148 func (me *Client) SetIPBlockList(list *iplist.IPList) {
151 me.ipBlockList = list
153 me.dHT.SetIPBlockList(list)
157 func (me *Client) PeerID() string {
158 return string(me.peerID[:])
161 func (me *Client) ListenAddr() (addr net.Addr) {
162 for _, l := range me.listeners {
163 if addr != nil && l.Addr().String() != addr.String() {
164 panic("listeners exist on different addresses")
171 type hashSorter struct {
175 func (me hashSorter) Len() int {
176 return len(me.Hashes)
179 func (me hashSorter) Less(a, b int) bool {
180 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
183 func (me hashSorter) Swap(a, b int) {
184 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
187 func (cl *Client) sortedTorrents() (ret []*torrent) {
189 for ih := range cl.torrents {
190 hs.Hashes = append(hs.Hashes, ih)
193 for _, ih := range hs.Hashes {
194 ret = append(ret, cl.torrent(ih))
199 // Writes out a human readable status of the client, such as for writing to a
201 func (cl *Client) WriteStatus(_w io.Writer) {
203 defer cl.mu.RUnlock()
204 w := bufio.NewWriter(_w)
206 if addr := cl.ListenAddr(); addr != nil {
207 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
209 fmt.Fprintln(w, "Not listening!")
211 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
213 dhtStats := cl.dHT.Stats()
214 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.Nodes, dhtStats.GoodNodes)
215 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
216 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
217 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
218 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
220 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
222 for _, t := range cl.sortedTorrents() {
224 fmt.Fprint(w, "<unknown name>")
226 fmt.Fprint(w, t.Name())
230 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
232 w.WriteString("<missing metainfo>")
240 // A Data that implements this has a streaming interface that should be
241 // preferred over ReadAt. For example, the data is stored in blocks on the
242 // network and have a fixed cost to open.
243 type SectionOpener interface {
244 // Open a ReadCloser at the given offset into torrent data. n is how many
245 // bytes we intend to read.
246 OpenSection(off, n int64) (io.ReadCloser, error)
249 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
251 // if err == io.ErrUnexpectedEOF && n != 0 {
255 // log.Println("data read at", len(b), off)
257 if ra, ok := d.(io.ReaderAt); ok {
258 return ra.ReadAt(b, off)
260 if so, ok := d.(SectionOpener); ok {
262 rc, err = so.OpenSection(off, int64(len(b)))
267 return io.ReadFull(rc, b)
269 if dp, ok := super(d); ok {
273 panic(fmt.Sprintf("can't read from %T", d))
276 // Calculates the number of pieces to set to Readahead priority, after the
277 // Now, and Next pieces.
278 func readaheadPieces(readahead, pieceLength int64) int {
279 return int((readahead+pieceLength-1)/pieceLength - 1)
282 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
283 index := int(off / int64(t.usualPieceSize()))
284 cl.raisePiecePriority(t, index, piecePriorityNow)
286 if index >= t.numPieces() {
289 cl.raisePiecePriority(t, index, piecePriorityNext)
290 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
292 if index >= t.numPieces() {
295 cl.raisePiecePriority(t, index, piecePriorityReadahead)
299 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
301 req, ok := t.offsetRequest(off)
305 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
307 t.urgent = make(map[request]struct{}, (n+chunkSize-1)/chunkSize)
309 t.urgent[req] = struct{}{}
310 cl.event.Broadcast() // Why?
311 index := int(req.Index)
312 cl.queueFirstHash(t, index)
313 cl.pieceChanged(t, index)
315 reqOff := t.requestOffset(req)
316 n1 := req.Length - pp.Integer(off-reqOff)
320 // log.Print(t.urgent)
323 func (cl *Client) configDir() string {
324 if cl.config.ConfigDir == "" {
325 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
327 return cl.config.ConfigDir
330 func (cl *Client) ConfigDir() string {
331 return cl.configDir()
334 func (t *torrent) connPendPiece(c *connection, piece int) {
335 c.pendPiece(piece, t.Pieces[piece].Priority)
338 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
339 if t.Pieces[piece].Priority < priority {
341 cl.prioritizePiece(t, piece, priority)
345 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
346 if t.havePiece(piece) {
349 cl.queueFirstHash(t, piece)
350 t.Pieces[piece].Priority = priority
351 cl.pieceChanged(t, piece)
354 func (cl *Client) setEnvBlocklist() (err error) {
355 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
356 defaultBlocklist := filename == ""
357 if defaultBlocklist {
358 filename = filepath.Join(cl.configDir(), "blocklist")
360 f, err := os.Open(filename)
362 if defaultBlocklist {
368 var ranges []iplist.Range
369 uniqStrs := make(map[string]string)
370 scanner := bufio.NewScanner(f)
373 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
375 err = fmt.Errorf("error reading torrent blocklist line %d: %s", lineNum, lineErr)
382 if s, ok := uniqStrs[r.Description]; ok {
385 uniqStrs[r.Description] = r.Description
387 ranges = append(ranges, r)
391 err = fmt.Errorf("error reading torrent blocklist: %s", err)
394 cl.ipBlockList = iplist.New(ranges)
398 func (cl *Client) initBannedTorrents() error {
399 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
401 if os.IsNotExist(err) {
404 return fmt.Errorf("error opening banned infohashes file: %s", err)
407 scanner := bufio.NewScanner(f)
408 cl.bannedTorrents = make(map[InfoHash]struct{})
410 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
414 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
416 return fmt.Errorf("error reading infohash: %s", err)
422 return errors.New("bad infohash")
426 cl.bannedTorrents[ih] = struct{}{}
428 if err := scanner.Err(); err != nil {
429 return fmt.Errorf("error scanning file: %s", err)
434 // Creates a new client. Clients contain zero or more Torrents.
435 func NewClient(cfg *Config) (cl *Client, err error) {
446 halfOpenLimit: socketsPerTorrent,
448 torrentDataOpener: func(md *metainfo.Info) data.Data {
449 return filePkg.TorrentData(md, cfg.DataDir)
451 dopplegangerAddrs: make(map[string]struct{}),
453 quit: make(chan struct{}),
454 torrents: make(map[InfoHash]*torrent),
456 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
458 if cfg.TorrentDataOpener != nil {
459 cl.torrentDataOpener = cfg.TorrentDataOpener
462 if !cfg.NoDefaultBlocklist {
463 err = cl.setEnvBlocklist()
469 if err = cl.initBannedTorrents(); err != nil {
470 err = fmt.Errorf("error initing banned torrents: %s", err)
474 if cfg.PeerID != "" {
475 CopyExact(&cl.peerID, cfg.PeerID)
477 o := copy(cl.peerID[:], bep20)
478 _, err = rand.Read(cl.peerID[o:])
480 panic("error generating peer id")
484 // Returns the laddr string to listen on for the next Listen call.
485 listenAddr := func() string {
486 if addr := cl.ListenAddr(); addr != nil {
489 if cfg.ListenAddr == "" {
490 // IPv6 isn't well supported with blocklists, or with trackers and
492 return "0.0.0.0:50007"
494 return cfg.ListenAddr
496 if !cl.config.DisableTCP {
498 l, err = net.Listen("tcp", listenAddr())
502 cl.listeners = append(cl.listeners, l)
503 go cl.acceptConnections(l, false)
505 if !cl.config.DisableUTP {
506 cl.utpSock, err = utp.NewSocket(listenAddr())
510 cl.listeners = append(cl.listeners, cl.utpSock)
511 go cl.acceptConnections(cl.utpSock, true)
514 dhtCfg := cfg.DHTConfig
516 dhtCfg = &dht.ServerConfig{}
518 if dhtCfg.Addr == "" {
519 dhtCfg.Addr = listenAddr()
521 if dhtCfg.Conn == nil && cl.utpSock != nil {
522 dhtCfg.Conn = cl.utpSock.PacketConn()
524 cl.dHT, err = dht.NewServer(dhtCfg)
528 if cl.ipBlockList != nil {
529 cl.dHT.SetIPBlockList(cl.ipBlockList)
536 func (cl *Client) stopped() bool {
545 // Stops the client. All connections to peers are closed and all activity will
547 func (me *Client) Close() {
551 for _, l := range me.listeners {
555 for _, t := range me.torrents {
560 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
562 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
563 if cl.ipBlockList == nil {
568 log.Printf("blocking non-IPv4 address: %s", ip)
572 r = cl.ipBlockList.Lookup(ip4)
576 func (cl *Client) waitAccept() {
580 for _, t := range cl.torrents {
589 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
592 // We accept all connections immediately, because we don't know what
593 // torrent they're for.
594 conn, err := l.Accept()
609 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
610 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
612 if blockRange != nil || doppleganger {
613 inboundConnsBlocked.Add(1)
614 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
618 go cl.incomingConnection(conn, utp)
622 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
624 if tc, ok := nc.(*net.TCPConn); ok {
630 c.Discovery = peerSourceIncoming
632 err := cl.runReceivedConn(c)
638 // Returns a handle to the given torrent, if it's present in the client.
639 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
642 t, ok := cl.torrents[ih]
646 T = Torrent{cl, t, t.gotMetainfo}
650 func (me *Client) torrent(ih InfoHash) *torrent {
651 return me.torrents[ih]
654 type dialResult struct {
659 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
660 conn, err := dial(addr, t)
665 conn = nil // Pedantic
667 ch <- dialResult{conn, utp}
669 successfulDials.Add(1)
672 unsuccessfulDials.Add(1)
673 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
676 if netOpErr, ok := err.(*net.OpError); ok {
677 switch netOpErr.Err {
678 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
683 log.Printf("error dialing %s: %s", addr, err)
688 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
689 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
690 if ret < minDialTimeout {
696 func (me *Client) dopplegangerAddr(addr string) bool {
697 _, ok := me.dopplegangerAddrs[addr]
701 // Start the process of connecting to the given peer for the given torrent if
703 func (me *Client) initiateConn(peer Peer, t *torrent) {
704 if peer.Id == me.peerID {
707 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
708 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
709 duplicateConnsAvoided.Add(1)
712 if r := me.ipBlockRange(peer.IP); r != nil {
713 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
716 t.HalfOpen[addr] = struct{}{}
717 go me.outgoingConnection(t, addr, peer.Source)
720 func (me *Client) dialTimeout(t *torrent) time.Duration {
722 pendingPeers := len(t.Peers)
724 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
727 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
728 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
730 c.(*net.TCPConn).SetLinger(0)
735 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
736 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
739 // Returns a connection over UTP or TCP.
740 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
741 // Initiate connections via TCP and UTP simultaneously. Use the first one
744 if !me.config.DisableUTP {
747 if !me.config.DisableTCP {
750 resCh := make(chan dialResult, left)
751 if !me.config.DisableUTP {
752 go doDial(me.dialUTP, resCh, true, addr, t)
754 if !me.config.DisableTCP {
755 go doDial(me.dialTCP, resCh, false, addr, t)
758 // Wait for a successful connection.
759 for ; left > 0 && res.Conn == nil; left-- {
763 // There are still incompleted dials.
765 for ; left > 0; left-- {
766 conn := (<-resCh).Conn
778 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
779 if _, ok := t.HalfOpen[addr]; !ok {
780 panic("invariant broken")
782 delete(t.HalfOpen, addr)
786 // Returns nil connection and nil error if no connection could be established
787 // for valid reasons.
788 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
789 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
793 c.encrypted = encrypted
795 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
799 ok, err := me.initiateHandshakes(c, t)
805 nc, utp := me.dial(addr, t)
809 c, err = handshakesConnection(nc, !me.config.DisableEncryption, utp)
818 nc, err = me.dialUTP(addr, t)
820 nc, err = me.dialTCP(addr, t)
823 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
826 c, err = handshakesConnection(nc, false, utp)
833 // Called to dial out and run a connection. The addr we're given is already
834 // considered half-open.
835 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
836 c, err := me.establishOutgoingConn(t, addr)
839 // Don't release lock between here and addConnection, unless it's for
841 me.noLongerHalfOpen(t, addr)
850 err = me.runInitiatedHandshookConn(c, t)
856 // The port number for incoming peer connections. 0 if the client isn't
858 func (cl *Client) incomingPeerPort() int {
859 listenAddr := cl.ListenAddr()
860 if listenAddr == nil {
863 return addrPort(listenAddr)
866 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
867 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
868 func addrCompactIP(addr net.Addr) (string, error) {
869 host, _, err := net.SplitHostPort(addr.String())
873 ip := net.ParseIP(host)
874 if v4 := ip.To4(); v4 != nil {
878 return string(v4), nil
880 return string(ip.To16()), nil
883 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
895 peerExtensionBytes [8]byte
899 func (me *peerExtensionBytes) SupportsExtended() bool {
900 return me[5]&0x10 != 0
903 func (me *peerExtensionBytes) SupportsDHT() bool {
904 return me[7]&0x01 != 0
907 func (me *peerExtensionBytes) SupportsFast() bool {
908 return me[7]&0x04 != 0
911 type handshakeResult struct {
917 // ih is nil if we expect the peer to declare the InfoHash, such as when the
918 // peer initiated the connection. Returns ok if the handshake was successful,
919 // and err if there was an unexpected condition other than the peer simply
920 // abandoning the handshake.
921 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
922 // Bytes to be sent to the peer. Should never block the sender.
923 postCh := make(chan []byte, 4)
924 // A single error value sent when the writer completes.
925 writeDone := make(chan error, 1)
926 // Performs writes to the socket and ensures posts don't block.
927 go handshakeWriter(sock, postCh, writeDone)
930 close(postCh) // Done writing.
937 // Wait until writes complete before returning from handshake.
940 err = fmt.Errorf("error writing: %s", err)
944 post := func(bb []byte) {
948 panic("mustn't block while posting")
952 post([]byte(pp.Protocol))
954 if ih != nil { // We already know what we want.
959 _, err = io.ReadFull(sock, b[:68])
964 if string(b[:20]) != pp.Protocol {
967 CopyExact(&res.peerExtensionBytes, b[20:28])
968 CopyExact(&res.InfoHash, b[28:48])
969 CopyExact(&res.peerID, b[48:68])
970 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
972 // TODO: Maybe we can just drop peers here if we're not interested. This
973 // could prevent them trying to reconnect, falsely believing there was
975 if ih == nil { // We were waiting for the peer to tell us what they wanted.
976 post(res.InfoHash[:])
984 // Wraps a raw connection and provides the interface we want for using the
985 // connection in the message loop.
986 type deadlineReader struct {
991 func (me deadlineReader) Read(b []byte) (n int, err error) {
992 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
993 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
995 err = fmt.Errorf("error setting read deadline: %s", err)
997 n, err = me.r.Read(b)
998 // Convert common errors into io.EOF.
1000 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1002 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1012 type readWriter struct {
1017 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1018 var protocol [len(pp.Protocol)]byte
1019 _, err = io.ReadFull(rw, protocol[:])
1024 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1027 if string(protocol[:]) == pp.Protocol {
1031 ret, err = mse.ReceiveHandshake(ret, skeys)
1035 func (cl *Client) receiveSkeys() (ret [][]byte) {
1036 for ih := range cl.torrents {
1037 ret = append(ret, ih[:])
1042 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1044 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1049 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1050 if ih != t.InfoHash {
1056 // Do encryption and bittorrent handshakes as receiver.
1057 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1059 skeys := cl.receiveSkeys()
1061 if !cl.config.DisableEncryption {
1062 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1064 if err == mse.ErrNoSecretKeyMatch {
1070 ih, ok, err := cl.connBTHandshake(c, nil)
1072 fmt.Errorf("error during bt handshake: %s", err)
1084 // Returns !ok if handshake failed for valid reasons.
1085 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1086 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1087 if err != nil || !ok {
1091 c.PeerExtensionBytes = res.peerExtensionBytes
1092 c.PeerID = res.peerID
1093 c.completedHandshake = time.Now()
1097 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1098 if c.PeerID == cl.peerID {
1099 // Only if we initiated the connection is the remote address a
1100 // listen addr for a doppleganger.
1102 addr := c.conn.RemoteAddr().String()
1103 cl.dopplegangerAddrs[addr] = struct{}{}
1106 return cl.runHandshookConn(c, t)
1109 func (cl *Client) runReceivedConn(c *connection) (err error) {
1110 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1114 t, err := cl.receiveHandshakes(c)
1116 err = fmt.Errorf("error receiving handshakes: %s", err)
1123 defer cl.mu.Unlock()
1124 if c.PeerID == cl.peerID {
1127 return cl.runHandshookConn(c, t)
1130 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1131 c.conn.SetWriteDeadline(time.Time{})
1133 deadlineReader{c.conn, c.rw},
1136 if !cl.addConnection(t, c) {
1139 defer cl.dropConnection(t, c)
1141 go c.writeOptimizer(time.Minute)
1142 cl.sendInitialMessages(c, t)
1144 t.initRequestOrdering(c)
1146 err = cl.connectionLoop(t, c)
1148 err = fmt.Errorf("error during connection loop: %s", err)
1153 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1154 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1155 conn.Post(pp.Message{
1157 ExtendedID: pp.HandshakeExtendedID,
1158 ExtendedPayload: func() []byte {
1159 d := map[string]interface{}{
1160 "m": func() (ret map[string]int) {
1161 ret = make(map[string]int, 2)
1162 ret["ut_metadata"] = metadataExtendedId
1163 if !me.config.DisablePEX {
1164 ret["ut_pex"] = pexExtendedId
1168 "v": extendedHandshakeClientVersion,
1169 // No upload queue is implemented yet.
1170 "reqq": func() int {
1171 if me.config.NoUpload {
1172 // No need to look strange if it costs us nothing.
1179 if !me.config.DisableEncryption {
1182 if torrent.metadataSizeKnown() {
1183 d["metadata_size"] = torrent.metadataSize()
1185 if p := me.incomingPeerPort(); p != 0 {
1188 yourip, err := addrCompactIP(conn.remoteAddr())
1190 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1192 d["yourip"] = yourip
1194 // log.Printf("sending %v", d)
1195 b, err := bencode.Marshal(d)
1203 if torrent.haveAnyPieces() {
1204 conn.Post(pp.Message{
1206 Bitfield: torrent.bitfield(),
1208 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1209 conn.Post(pp.Message{
1213 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1214 conn.Post(pp.Message{
1216 Port: uint16(AddrPort(me.dHT.Addr())),
1221 // Randomizes the piece order for this connection. Every connection will be
1222 // given a different ordering. Having it stored per connection saves having to
1223 // randomize during request filling, and constantly recalculate the ordering
1224 // based on piece priorities.
1225 func (t *torrent) initRequestOrdering(c *connection) {
1226 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1227 panic("double init of request ordering")
1229 c.piecePriorities = mathRand.Perm(t.numPieces())
1230 c.pieceRequestOrder = pieceordering.New()
1231 for i := range iter.N(t.Info.NumPieces()) {
1232 if !c.PeerHasPiece(i) {
1235 if !t.wantPiece(i) {
1238 t.connPendPiece(c, i)
1242 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1245 if c.PeerPieces == nil {
1246 c.PeerPieces = make([]bool, t.numPieces())
1249 for piece >= len(c.PeerPieces) {
1250 c.PeerPieces = append(c.PeerPieces, false)
1253 c.PeerPieces[piece] = true
1255 if t.wantPiece(piece) {
1256 t.connPendPiece(c, piece)
1257 me.replenishConnRequests(t, c)
1261 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1262 me.replenishConnRequests(torrent, conn)
1265 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1268 postedCancels.Add(1)
1273 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1274 if !cn.RequestPending(r) {
1277 delete(cn.Requests, r)
1280 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1284 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1285 // Peer doesn't support this.
1288 // Request metadata pieces that we don't have in a random order.
1290 for index := 0; index < t.metadataPieceCount(); index++ {
1291 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1292 pending = append(pending, index)
1295 for _, i := range mathRand.Perm(len(pending)) {
1296 c.requestMetadataPiece(pending[i])
1300 func (cl *Client) completedMetadata(t *torrent) {
1304 CopyExact(&ih, h.Sum(nil))
1305 if ih != t.InfoHash {
1306 log.Print("bad metadata")
1307 t.invalidateMetadata()
1310 var info metainfo.Info
1311 err := bencode.Unmarshal(t.MetaData, &info)
1313 log.Printf("error unmarshalling metadata: %s", err)
1314 t.invalidateMetadata()
1317 // TODO(anacrolix): If this fails, I think something harsher should be
1319 err = cl.setMetaData(t, &info, t.MetaData)
1321 log.Printf("error setting metadata: %s", err)
1322 t.invalidateMetadata()
1325 log.Printf("%s: got metadata from peers", t)
1328 // Process incoming ut_metadata message.
1329 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1330 var d map[string]int
1331 err = bencode.Unmarshal(payload, &d)
1333 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1336 msgType, ok := d["msg_type"]
1338 err = errors.New("missing msg_type field")
1343 case pp.DataMetadataExtensionMsgType:
1347 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1348 if begin < 0 || begin >= len(payload) {
1349 log.Printf("got bad metadata piece")
1352 if !c.requestedMetadataPiece(piece) {
1353 log.Printf("got unexpected metadata piece %d", piece)
1356 c.metadataRequests[piece] = false
1357 t.saveMetadataPiece(piece, payload[begin:])
1358 c.UsefulChunksReceived++
1359 c.lastUsefulChunkReceived = time.Now()
1360 if !t.haveAllMetadataPieces() {
1363 cl.completedMetadata(t)
1364 case pp.RequestMetadataExtensionMsgType:
1365 if !t.haveMetadataPiece(piece) {
1366 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1369 start := (1 << 14) * piece
1370 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1371 case pp.RejectMetadataExtensionMsgType:
1373 err = errors.New("unknown msg_type value")
1378 type peerExchangeMessage struct {
1379 Added CompactPeers `bencode:"added"`
1380 AddedFlags []byte `bencode:"added.f"`
1381 Dropped CompactPeers `bencode:"dropped"`
1384 // Extracts the port as an integer from an address string.
1385 func addrPort(addr net.Addr) int {
1386 return AddrPort(addr)
1389 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1390 cn.peerHasAll = true
1393 for i := 0; i < t.numPieces(); i++ {
1394 cl.peerGotPiece(t, cn, i)
1399 // Processes incoming bittorrent messages. The client lock is held upon entry
1401 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1402 decoder := pp.Decoder{
1403 R: bufio.NewReader(c.rw),
1404 MaxLength: 256 * 1024,
1409 err := decoder.Decode(&msg)
1410 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1412 c.lastMessageReceived = time.Now()
1419 if me.stopped() || err == io.EOF {
1430 for r := range c.Requests {
1431 me.connDeleteRequest(t, c, r)
1433 // We can then reset our interest.
1434 me.replenishConnRequests(t, c)
1436 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1437 me.replenishConnRequests(t, c)
1439 c.PeerChoked = false
1440 me.peerUnchoked(t, c)
1442 c.PeerInterested = true
1443 // TODO: This should be done from a dedicated unchoking routine.
1444 if me.config.NoUpload {
1448 case pp.NotInterested:
1449 c.PeerInterested = false
1452 me.peerGotPiece(t, c, int(msg.Index))
1454 if me.config.NoUpload {
1457 if c.PeerRequests == nil {
1458 c.PeerRequests = make(map[request]struct{}, maxRequests)
1460 request := newRequest(msg.Index, msg.Begin, msg.Length)
1461 // TODO: Requests should be satisfied from a dedicated upload
1463 // c.PeerRequests[request] = struct{}{}
1464 p := make([]byte, msg.Length)
1465 n, err := dataReadAt(t.data, p, int64(t.pieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1467 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1469 if n != int(msg.Length) {
1470 return fmt.Errorf("bad request: %v", msg)
1478 uploadChunksPosted.Add(1)
1480 req := newRequest(msg.Index, msg.Begin, msg.Length)
1481 if !c.PeerCancel(req) {
1482 unexpectedCancels.Add(1)
1485 if c.PeerPieces != nil || c.peerHasAll {
1486 err = errors.New("received unexpected bitfield")
1490 if len(msg.Bitfield) < t.numPieces() {
1491 err = errors.New("received invalid bitfield")
1494 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1496 c.PeerPieces = msg.Bitfield
1497 for index, has := range c.PeerPieces {
1499 me.peerGotPiece(t, c, index)
1503 if c.PeerPieces != nil || c.peerHasAll {
1504 err = errors.New("unexpected have-all")
1509 if c.peerHasAll || c.PeerPieces != nil {
1510 err = errors.New("unexpected have-none")
1513 c.PeerPieces = make([]bool, func() int {
1515 return t.numPieces()
1521 err = me.downloadedChunk(t, c, &msg)
1523 switch msg.ExtendedID {
1524 case pp.HandshakeExtendedID:
1525 // TODO: Create a bencode struct for this.
1526 var d map[string]interface{}
1527 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1529 err = fmt.Errorf("error decoding extended message payload: %s", err)
1532 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1533 if reqq, ok := d["reqq"]; ok {
1534 if i, ok := reqq.(int64); ok {
1535 c.PeerMaxRequests = int(i)
1538 if v, ok := d["v"]; ok {
1539 c.PeerClientName = v.(string)
1543 err = errors.New("handshake missing m item")
1546 mTyped, ok := m.(map[string]interface{})
1548 err = errors.New("handshake m value is not dict")
1551 if c.PeerExtensionIDs == nil {
1552 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1554 for name, v := range mTyped {
1557 log.Printf("bad handshake m item extension ID type: %T", v)
1561 delete(c.PeerExtensionIDs, name)
1563 if c.PeerExtensionIDs[name] == 0 {
1564 supportedExtensionMessages.Add(name, 1)
1566 c.PeerExtensionIDs[name] = byte(id)
1569 metadata_sizeUntyped, ok := d["metadata_size"]
1571 metadata_size, ok := metadata_sizeUntyped.(int64)
1573 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1575 t.setMetadataSize(metadata_size, me)
1578 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1579 me.requestPendingMetadata(t, c)
1581 case metadataExtendedId:
1582 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1584 err = fmt.Errorf("error handling metadata extension message: %s", err)
1587 if me.config.DisablePEX {
1590 var pexMsg peerExchangeMessage
1591 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1593 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1598 me.addPeers(t, func() (ret []Peer) {
1599 for i, cp := range pexMsg.Added {
1601 IP: make([]byte, 4),
1603 Source: peerSourcePEX,
1605 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1606 p.SupportsEncryption = true
1608 CopyExact(p.IP, cp.IP[:])
1609 ret = append(ret, p)
1614 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1617 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1620 // That client uses its own extension IDs for outgoing message
1621 // types, which is incorrect.
1622 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1623 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1631 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1636 pingAddr.Port = int(msg.Port)
1638 _, err = me.dHT.Ping(pingAddr)
1640 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1648 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1649 me.event.Broadcast()
1650 for r := range conn.Requests {
1651 me.connDeleteRequest(torrent, conn, r)
1654 for i0, c := range torrent.Conns {
1658 i1 := len(torrent.Conns) - 1
1660 torrent.Conns[i0] = torrent.Conns[i1]
1662 torrent.Conns = torrent.Conns[:i1]
1663 me.openNewConns(torrent)
1666 panic("connection not found")
1669 func (me *Client) addConnection(t *torrent, c *connection) bool {
1674 case <-t.ceasingNetworking:
1678 if !me.wantConns(t) {
1681 for _, c0 := range t.Conns {
1682 if c.PeerID == c0.PeerID {
1683 // Already connected to a client with that ID.
1684 duplicateClientConns.Add(1)
1688 t.Conns = append(t.Conns, c)
1689 // TODO: This should probably be done by a routine that kills off bad
1690 // connections, and extra connections killed here instead.
1691 if len(t.Conns) > socketsPerTorrent {
1692 wcs := t.worstConnsHeap()
1693 heap.Pop(wcs).(*connection).Close()
1698 func (t *torrent) needData() bool {
1702 for i := range t.Pieces {
1710 // TODO: I'm sure there's something here to do with seeding.
1711 func (t *torrent) badConn(c *connection) bool {
1712 // A 30 second grace for initial messages to go through.
1713 if time.Since(c.completedHandshake) < 30*time.Second {
1717 if !c.supportsExtension("ut_metadata") {
1720 if time.Since(c.completedHandshake) > 2*time.Minute {
1724 return !t.connHasWantedPieces(c)
1727 func (t *torrent) numGoodConns() (num int) {
1728 for _, c := range t.Conns {
1736 func (me *Client) wantConns(t *torrent) bool {
1737 if me.config.NoUpload && !t.needData() {
1740 if t.numGoodConns() >= socketsPerTorrent {
1746 func (me *Client) openNewConns(t *torrent) {
1748 case <-t.ceasingNetworking:
1752 for len(t.Peers) != 0 {
1753 if !me.wantConns(t) {
1756 if len(t.HalfOpen) >= me.halfOpenLimit {
1763 for k, p = range t.Peers {
1767 me.initiateConn(p, t)
1769 t.wantPeers.Broadcast()
1772 func (me *Client) addPeers(t *torrent, peers []Peer) {
1773 for _, p := range peers {
1774 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1777 if me.ipBlockRange(p.IP) != nil {
1785 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1786 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1789 func (cl *Client) saveTorrentFile(t *torrent) error {
1790 path := cl.cachedMetaInfoFilename(t.InfoHash)
1791 os.MkdirAll(filepath.Dir(path), 0777)
1792 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1794 return fmt.Errorf("error opening file: %s", err)
1797 e := bencode.NewEncoder(f)
1798 err = e.Encode(t.MetaInfo())
1800 return fmt.Errorf("error marshalling metainfo: %s", err)
1802 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1804 // For example, a script kiddy makes us load too many files, and we're
1805 // able to save the torrent, but not load it again to check it.
1808 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1809 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1814 func (cl *Client) startTorrent(t *torrent) {
1815 if t.Info == nil || t.data == nil {
1818 // If the client intends to upload, it needs to know what state pieces are
1820 if !cl.config.NoUpload {
1821 // Queue all pieces for hashing. This is done sequentially to avoid
1822 // spamming goroutines.
1823 for _, p := range t.Pieces {
1824 p.QueuedForHash = true
1827 for i := range t.Pieces {
1828 cl.verifyPiece(t, pp.Integer(i))
1834 // Storage cannot be changed once it's set.
1835 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1836 err = t.setStorage(td)
1837 cl.event.Broadcast()
1841 for index := range iter.N(t.numPieces()) {
1842 cl.pieceChanged(t, index)
1848 type TorrentDataOpener func(*metainfo.Info) data.Data
1850 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1851 err = t.setMetadata(md, bytes, &cl.mu)
1855 if !cl.config.DisableMetainfoCache {
1856 if err := cl.saveTorrentFile(t); err != nil {
1857 log.Printf("error saving torrent file for %s: %s", t, err)
1860 cl.event.Broadcast()
1861 close(t.gotMetainfo)
1862 td := cl.torrentDataOpener(md)
1863 err = cl.setStorage(t, td)
1867 // Prepare a Torrent without any attachment to a Client. That means we can
1868 // initialize fields all fields that don't require the Client without locking
1870 func newTorrent(ih InfoHash) (t *torrent, err error) {
1873 Peers: make(map[peersKey]Peer),
1875 closing: make(chan struct{}),
1876 ceasingNetworking: make(chan struct{}),
1878 gotMetainfo: make(chan struct{}),
1880 HalfOpen: make(map[string]struct{}),
1882 t.wantPeers.L = &t.stateMu
1887 // For shuffling the tracker tiers.
1888 mathRand.Seed(time.Now().Unix())
1891 // The trackers within each tier must be shuffled before use.
1892 // http://stackoverflow.com/a/12267471/149482
1893 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1894 func shuffleTier(tier []tracker.Client) {
1895 for i := range tier {
1896 j := mathRand.Intn(i + 1)
1897 tier[i], tier[j] = tier[j], tier[i]
1901 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1902 for _, tier := range base {
1903 copy = append(copy, append([]tracker.Client{}, tier...))
1908 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1910 for _, url := range newURLs {
1911 for _, tr := range tier {
1912 if tr.URL() == url {
1916 tr, err := tracker.New(url)
1918 log.Printf("error creating tracker client for %q: %s", url, err)
1921 tier = append(tier, tr)
1926 func (t *torrent) addTrackers(announceList [][]string) {
1927 newTrackers := copyTrackers(t.Trackers)
1928 for tierIndex, tier := range announceList {
1929 if tierIndex < len(newTrackers) {
1930 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1932 newTrackers = append(newTrackers, mergeTier(nil, tier))
1934 shuffleTier(newTrackers[tierIndex])
1936 t.Trackers = newTrackers
1939 // Don't call this before the info is available.
1940 func (t *torrent) BytesCompleted() int64 {
1944 return t.Info.TotalLength() - t.bytesLeft()
1947 func (t Torrent) NumPieces() int {
1948 return t.numPieces()
1951 func (t Torrent) Drop() {
1953 t.cl.dropTorrent(t.InfoHash)
1957 // A file-like handle to some torrent data resource.
1958 type Handle interface {
1965 // Returns handles to the files in the torrent. This requires the metainfo is
1967 func (t Torrent) Files() (ret []File) {
1975 for _, fi := range info.UpvertedFiles() {
1976 ret = append(ret, File{
1978 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1988 func (t Torrent) SetRegionPriority(off, len int64) {
1990 defer t.cl.mu.Unlock()
1991 pieceSize := int64(t.usualPieceSize())
1992 for i := off / pieceSize; i*pieceSize < off+len; i++ {
1993 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
1997 func (t Torrent) AddPeers(pp []Peer) error {
2000 defer cl.mu.Unlock()
2001 cl.addPeers(t.torrent, pp)
2005 // Marks the entire torrent for download. Requires the info first, see
2007 func (t Torrent) DownloadAll() {
2009 defer t.cl.mu.Unlock()
2010 for i := range iter.N(t.numPieces()) {
2011 t.cl.raisePiecePriority(t.torrent, i, piecePriorityNormal)
2013 // Nice to have the first and last pieces sooner for various interactive
2015 t.cl.raisePiecePriority(t.torrent, 0, piecePriorityReadahead)
2016 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, piecePriorityReadahead)
2019 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2020 // metainfo has the correct infohash.
2021 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2022 if cl.config.DisableMetainfoCache {
2025 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2027 if os.IsNotExist(err) {
2033 dec := bencode.NewDecoder(f)
2034 err = dec.Decode(&mi)
2038 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2039 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2045 // Specifies a new torrent for adding to a client. There are helpers for
2046 // magnet URIs and torrent metainfo files.
2047 type TorrentSpec struct {
2050 Info *metainfo.InfoEx
2054 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2055 m, err := ParseMagnetURI(uri)
2059 spec = &TorrentSpec{
2060 Trackers: [][]string{m.Trackers},
2061 DisplayName: m.DisplayName,
2062 InfoHash: m.InfoHash,
2067 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2068 spec = &TorrentSpec{
2069 Trackers: mi.AnnounceList,
2071 DisplayName: mi.Info.Name,
2073 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2077 // Add or merge a torrent spec. If the torrent is already present, the
2078 // trackers will be merged with the existing ones. If the Info isn't yet
2079 // known, it will be set. The display name is replaced if the new spec
2080 // provides one. Returns new if the torrent wasn't already in the client.
2081 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2084 defer cl.mu.Unlock()
2086 t, ok := cl.torrents[spec.InfoHash]
2090 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2091 err = errors.New("banned torrent")
2095 t, err = newTorrent(spec.InfoHash)
2100 if spec.DisplayName != "" {
2101 t.DisplayName = spec.DisplayName
2103 // Try to merge in info we have on the torrent. Any err left will
2104 // terminate the function.
2106 if spec.Info != nil {
2107 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2109 var mi *metainfo.MetaInfo
2110 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2112 log.Printf("error getting cached metainfo: %s", err)
2114 } else if mi != nil {
2115 t.addTrackers(mi.AnnounceList)
2116 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2123 t.addTrackers(spec.Trackers)
2125 cl.torrents[spec.InfoHash] = t
2128 // From this point onwards, we can consider the torrent a part of the
2131 t.pruneTimer = time.AfterFunc(0, func() {
2132 cl.pruneConnectionsUnlocked(T.torrent)
2134 if !cl.config.DisableTrackers {
2135 go cl.announceTorrentTrackers(T.torrent)
2138 go cl.announceTorrentDHT(T.torrent, true)
2144 // Prunes unused connections. This is required to make space to dial for
2146 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
2148 case <-t.ceasingNetworking:
2155 license := len(t.Conns) - (socketsPerTorrent+1)/2
2156 for _, c := range t.Conns {
2160 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
2163 if time.Now().Sub(c.completedHandshake) < time.Minute {
2170 t.pruneTimer.Reset(pruneInterval)
2173 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2174 t, ok := me.torrents[infoHash]
2176 err = fmt.Errorf("no such torrent")
2183 delete(me.torrents, infoHash)
2187 // Returns true when peers are required, or false if the torrent is closing.
2188 func (cl *Client) waitWantPeers(t *torrent) bool {
2190 defer cl.mu.Unlock()
2192 defer t.stateMu.Unlock()
2195 case <-t.ceasingNetworking:
2199 if len(t.Peers) < torrentPeersLowWater && t.needData() {
2210 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2211 for cl.waitWantPeers(t) {
2212 log.Printf("getting peers for %q from DHT", t)
2213 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2215 log.Printf("error getting peers from dht: %s", err)
2218 allAddrs := make(map[string]struct{})
2222 case v, ok := <-ps.Peers:
2226 peersFoundByDHT.Add(int64(len(v.Peers)))
2227 for _, p := range v.Peers {
2228 allAddrs[(&net.UDPAddr{
2231 }).String()] = struct{}{}
2233 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2235 cl.addPeers(t, func() (ret []Peer) {
2236 for _, cp := range v.Peers {
2237 ret = append(ret, Peer{
2240 Source: peerSourceDHT,
2245 numPeers := len(t.Peers)
2247 if numPeers >= torrentPeersHighWater {
2250 case <-t.ceasingNetworking:
2256 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2260 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2261 url_, err := url.Parse(tr.URL())
2265 host, _, err := net.SplitHostPort(url_.Host)
2269 addr, err := net.ResolveIPAddr("ip", host)
2274 if cl.ipBlockList != nil {
2275 if cl.ipBlockRange(addr.IP) != nil {
2283 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2284 blocked, err := cl.trackerBlockedUnlocked(tr)
2286 return fmt.Errorf("error determining if tracker blocked: %s", err)
2289 return fmt.Errorf("tracker blocked: %s", tr)
2291 if err := tr.Connect(); err != nil {
2292 return fmt.Errorf("error connecting: %s", err)
2294 resp, err := tr.Announce(req)
2296 return fmt.Errorf("error announcing: %s", err)
2299 for _, peer := range resp.Peers {
2300 peers = append(peers, Peer{
2306 cl.addPeers(t, peers)
2309 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2310 peersFoundByTracker.Add(int64(len(peers)))
2312 time.Sleep(time.Second * time.Duration(resp.Interval))
2316 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2317 oks := make(chan bool)
2319 for _, tier := range trackers {
2320 for _, tr := range tier {
2322 go func(tr tracker.Client) {
2323 err := cl.announceTorrentSingleTracker(tr, req, t)
2328 for outstanding > 0 {
2338 // Announce torrent to its trackers.
2339 func (cl *Client) announceTorrentTrackers(t *torrent) {
2340 req := tracker.AnnounceRequest{
2341 Event: tracker.Started,
2343 Port: uint16(cl.incomingPeerPort()),
2345 InfoHash: t.InfoHash,
2347 if !cl.waitWantPeers(t) {
2351 req.Left = uint64(t.bytesLeft())
2352 trackers := t.Trackers
2354 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2355 req.Event = tracker.None
2358 for cl.waitWantPeers(t) {
2360 req.Left = uint64(t.bytesLeft())
2361 trackers = t.Trackers
2363 numTrackersTried := 0
2364 for _, tier := range trackers {
2365 for trIndex, tr := range tier {
2367 err := cl.announceTorrentSingleTracker(tr, &req, t)
2369 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2372 // Float the successful announce to the top of the tier. If
2373 // the trackers list has been changed, we'll be modifying an
2374 // old copy so it won't matter.
2376 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2379 req.Event = tracker.None
2380 continue newAnnounce
2383 if numTrackersTried != 0 {
2384 log.Printf("%s: all trackers failed", t)
2386 // TODO: Wait until trackers are added if there are none.
2387 time.Sleep(10 * time.Second)
2391 func (cl *Client) allTorrentsCompleted() bool {
2392 for _, t := range cl.torrents {
2396 if t.numPiecesCompleted() != t.numPieces() {
2403 // Returns true when all torrents are completely downloaded and false if the
2404 // client is stopped before that.
2405 func (me *Client) WaitAll() bool {
2407 defer me.mu.Unlock()
2408 for !me.allTorrentsCompleted() {
2417 func (me *Client) fillRequests(t *torrent, c *connection) {
2422 if len(c.Requests) > c.requestsLowWater {
2426 addRequest := func(req request) (again bool) {
2427 // TODO: Couldn't this check also be done *after* the request?
2428 if len(c.Requests) >= 64 {
2431 return c.Request(req)
2433 for req := range t.urgent {
2434 if !addRequest(req) {
2438 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2439 pieceIndex := e.Piece()
2440 if !c.PeerHasPiece(pieceIndex) {
2441 panic("piece in request order but peer doesn't have it")
2443 if !t.wantPiece(pieceIndex) {
2444 panic("unwanted piece in connection request order")
2446 piece := t.Pieces[pieceIndex]
2447 for _, cs := range piece.shuffledPendingChunkSpecs() {
2448 r := request{pp.Integer(pieceIndex), cs}
2457 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2461 me.fillRequests(t, c)
2462 if len(c.Requests) == 0 && !c.PeerChoked {
2463 // So we're not choked, but we don't want anything right now. We may
2464 // have completed readahead, and the readahead window has not rolled
2465 // over to the next piece. Better to stay interested in case we're
2466 // going to want data in the near future.
2467 c.SetInterested(!t.haveAllPieces())
2471 // Handle a received chunk from a peer.
2472 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2473 chunksDownloadedCount.Add(1)
2475 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2477 // Request has been satisfied.
2478 me.connDeleteRequest(t, c, req)
2480 defer me.replenishConnRequests(t, c)
2482 piece := t.Pieces[req.Index]
2484 // Do we actually want this chunk?
2485 if !t.wantChunk(req) {
2486 unusedDownloadedChunksCount.Add(1)
2487 c.UnwantedChunksReceived++
2491 c.UsefulChunksReceived++
2492 c.lastUsefulChunkReceived = time.Now()
2494 // Write the chunk out.
2495 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2497 return fmt.Errorf("error writing chunk: %s", err)
2500 // log.Println("got chunk", req)
2501 piece.Event.Broadcast()
2502 // Record that we have the chunk.
2503 delete(piece.PendingChunkSpecs, req.chunkSpec)
2504 delete(t.urgent, req)
2505 if len(piece.PendingChunkSpecs) == 0 {
2506 for _, c := range t.Conns {
2507 c.pieceRequestOrder.DeletePiece(int(req.Index))
2509 me.queuePieceCheck(t, req.Index)
2512 // Cancel pending requests for this chunk.
2513 for _, c := range t.Conns {
2514 if me.connCancel(t, c, req) {
2515 me.replenishConnRequests(t, c)
2522 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2523 p := t.Pieces[piece]
2524 if p.EverHashed && !correct {
2525 log.Printf("%s: piece %d failed hash", t, piece)
2526 failedPieceHashes.Add(1)
2530 if sd, ok := t.data.(StatefulData); ok {
2531 err := sd.PieceCompleted(int(piece))
2533 log.Printf("error completing piece: %s", err)
2538 me.pieceChanged(t, int(piece))
2541 // TODO: Check this isn't called more than once for each piece being correct.
2542 func (me *Client) pieceChanged(t *torrent, piece int) {
2543 correct := t.pieceComplete(piece)
2544 p := t.Pieces[piece]
2546 p.Priority = piecePriorityNone
2547 p.PendingChunkSpecs = nil
2548 for req := range t.urgent {
2549 if int(req.Index) == piece {
2550 delete(t.urgent, req)
2555 if len(p.PendingChunkSpecs) == 0 {
2556 t.pendAllChunkSpecs(int(piece))
2558 if t.wantPiece(piece) {
2562 for _, conn := range t.Conns {
2564 conn.Post(pp.Message{
2566 Index: pp.Integer(piece),
2568 // TODO: Cancel requests for this piece.
2569 for r := range conn.Requests {
2570 if int(r.Index) == piece {
2574 conn.pieceRequestOrder.DeletePiece(int(piece))
2576 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2577 t.connPendPiece(conn, int(piece))
2578 me.replenishConnRequests(t, conn)
2581 if t.haveAllPieces() && me.config.NoUpload {
2584 me.event.Broadcast()
2587 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2589 defer cl.mu.Unlock()
2590 p := t.Pieces[index]
2591 for p.Hashing || t.data == nil {
2594 p.QueuedForHash = false
2595 if t.isClosed() || t.pieceComplete(int(index)) {
2600 sum := t.hashPiece(index)
2608 cl.pieceHashed(t, index, sum == p.Hash)
2611 // Returns handles to all the torrents loaded in the Client.
2612 func (me *Client) Torrents() (ret []Torrent) {
2614 for _, t := range me.torrents {
2615 ret = append(ret, Torrent{me, t, t.gotMetainfo})
2621 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2622 spec, err := TorrentSpecFromMagnetURI(uri)
2626 T, _, err = me.AddTorrentSpec(spec)
2630 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2631 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2635 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2636 mi, err := metainfo.LoadFromFile(filename)
2640 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))