26 "github.com/anacrolix/sync"
27 "github.com/anacrolix/utp"
28 "github.com/bradfitz/iter"
30 "github.com/anacrolix/torrent/bencode"
31 "github.com/anacrolix/torrent/data"
32 filePkg "github.com/anacrolix/torrent/data/file"
33 "github.com/anacrolix/torrent/dht"
34 "github.com/anacrolix/torrent/internal/pieceordering"
35 "github.com/anacrolix/torrent/iplist"
36 "github.com/anacrolix/torrent/logonce"
37 "github.com/anacrolix/torrent/metainfo"
38 "github.com/anacrolix/torrent/mse"
39 pp "github.com/anacrolix/torrent/peer_protocol"
40 "github.com/anacrolix/torrent/tracker"
41 . "github.com/anacrolix/torrent/util"
45 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
46 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
47 chunksReceived = expvar.NewInt("chunksReceived")
49 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
50 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
51 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
53 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
54 unexpectedCancels = expvar.NewInt("unexpectedCancels")
55 postedCancels = expvar.NewInt("postedCancels")
56 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
58 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
59 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
61 unsuccessfulDials = expvar.NewInt("dialSuccessful")
62 successfulDials = expvar.NewInt("dialUnsuccessful")
64 acceptUTP = expvar.NewInt("acceptUTP")
65 acceptTCP = expvar.NewInt("acceptTCP")
66 acceptReject = expvar.NewInt("acceptReject")
68 peerExtensions = expvar.NewMap("peerExtensions")
69 // Count of connections to peer with same client ID.
70 connsToSelf = expvar.NewInt("connsToSelf")
71 // Number of completed connections to a client we're already connected with.
72 duplicateClientConns = expvar.NewInt("duplicateClientConns")
73 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
74 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
78 // Justification for set bits follows.
80 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html ([5]|=0x10)
81 // DHT: http://www.bittorrent.org/beps/bep_0005.html ([7]|=1)
83 // http://bittorrent.org/beps/bep_0006.html ([7]|=4)
84 // Disabled until AllowedFast is implemented
85 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
87 socketsPerTorrent = 40
88 torrentPeersHighWater = 200
89 torrentPeersLowWater = 50
91 // Limit how long handshake can take. This is to reduce the lingering
92 // impact of a few bad apples. 4s loses 1% of successful handshakes that
93 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
94 btHandshakeTimeout = 4 * time.Second
95 handshakesTimeout = 20 * time.Second
97 pruneInterval = 10 * time.Second
99 // These are our extended message IDs.
100 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
103 // Updated occasionally to when there's been some changes to client
104 // behaviour in case other clients are assuming anything of us. See also
106 extendedHandshakeClientVersion = "go.torrent dev 20150624"
109 // Currently doesn't really queue, but should in the future.
110 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
111 piece := t.Pieces[pieceIndex]
112 if piece.QueuedForHash {
115 piece.QueuedForHash = true
116 go cl.verifyPiece(t, pieceIndex)
119 // Queue a piece check if one isn't already queued, and the piece has never
120 // been checked before.
121 func (cl *Client) queueFirstHash(t *torrent, piece int) {
123 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
126 cl.queuePieceCheck(t, pp.Integer(piece))
129 // Clients contain zero or more Torrents. A client manages a blocklist, the
130 // TCP/UDP protocol ports, and DHT as desired.
134 listeners []net.Listener
137 ipBlockList *iplist.IPList
138 bannedTorrents map[InfoHash]struct{}
140 pruneTimer *time.Timer
141 extensionBytes peerExtensionBytes
142 // Set of addresses that have our client ID. This intentionally will
143 // include ourselves if we end up trying to connect to our own address
144 // through legitimate channels.
145 dopplegangerAddrs map[string]struct{}
147 torrentDataOpener TorrentDataOpener
153 torrents map[InfoHash]*torrent
156 func (me *Client) IPBlockList() *iplist.IPList {
159 return me.ipBlockList
162 func (me *Client) SetIPBlockList(list *iplist.IPList) {
165 me.ipBlockList = list
167 me.dHT.SetIPBlockList(list)
171 func (me *Client) PeerID() string {
172 return string(me.peerID[:])
175 func (me *Client) ListenAddr() (addr net.Addr) {
176 for _, l := range me.listeners {
183 type hashSorter struct {
187 func (me hashSorter) Len() int {
188 return len(me.Hashes)
191 func (me hashSorter) Less(a, b int) bool {
192 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
195 func (me hashSorter) Swap(a, b int) {
196 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
199 func (cl *Client) sortedTorrents() (ret []*torrent) {
201 for ih := range cl.torrents {
202 hs.Hashes = append(hs.Hashes, ih)
205 for _, ih := range hs.Hashes {
206 ret = append(ret, cl.torrent(ih))
211 // Writes out a human readable status of the client, such as for writing to a
213 func (cl *Client) WriteStatus(_w io.Writer) {
215 defer cl.mu.RUnlock()
216 w := bufio.NewWriter(_w)
218 if addr := cl.ListenAddr(); addr != nil {
219 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
221 fmt.Fprintln(w, "Not listening!")
223 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
225 dhtStats := cl.dHT.Stats()
226 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.Nodes, dhtStats.GoodNodes)
227 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
228 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
229 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
230 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
232 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
234 for _, t := range cl.sortedTorrents() {
236 fmt.Fprint(w, "<unknown name>")
238 fmt.Fprint(w, t.Name())
242 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
244 w.WriteString("<missing metainfo>")
252 // A Data that implements this has a streaming interface that should be
253 // preferred over ReadAt. For example, the data is stored in blocks on the
254 // network and have a fixed cost to open.
255 type SectionOpener interface {
256 // Open a ReadCloser at the given offset into torrent data. n is how many
257 // bytes we intend to read.
258 OpenSection(off, n int64) (io.ReadCloser, error)
261 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
263 // if err == io.ErrUnexpectedEOF && n != 0 {
267 // log.Println("data read at", len(b), off)
269 if ra, ok := d.(io.ReaderAt); ok {
270 return ra.ReadAt(b, off)
272 if so, ok := d.(SectionOpener); ok {
274 rc, err = so.OpenSection(off, int64(len(b)))
279 return io.ReadFull(rc, b)
281 if dp, ok := super(d); ok {
285 panic(fmt.Sprintf("can't read from %T", d))
288 // Calculates the number of pieces to set to Readahead priority, after the
289 // Now, and Next pieces.
290 func readaheadPieces(readahead, pieceLength int64) (ret int) {
291 // Expand the readahead to fit any partial pieces. Subtract 1 for the
292 // "next" piece that is assigned.
293 ret = int((readahead+pieceLength-1)/pieceLength - 1)
294 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
295 // piece length is much larger than the readahead.
302 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
303 index := int(off / int64(t.usualPieceSize()))
304 cl.raisePiecePriority(t, index, PiecePriorityNow)
306 if index >= t.numPieces() {
309 cl.raisePiecePriority(t, index, PiecePriorityNext)
310 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
312 if index >= t.numPieces() {
315 cl.raisePiecePriority(t, index, PiecePriorityReadahead)
319 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
321 req, ok := t.offsetRequest(off)
325 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
327 t.urgent = make(map[request]struct{}, (n+chunkSize-1)/chunkSize)
329 t.urgent[req] = struct{}{}
330 cl.event.Broadcast() // Why?
331 index := int(req.Index)
332 cl.queueFirstHash(t, index)
333 cl.pieceChanged(t, index)
335 reqOff := t.requestOffset(req)
336 n1 := req.Length - pp.Integer(off-reqOff)
340 // log.Print(t.urgent)
343 func (cl *Client) configDir() string {
344 if cl.config.ConfigDir == "" {
345 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
347 return cl.config.ConfigDir
350 // The directory where the Client expects to find and store configuration
351 // data. Defaults to $HOME/.config/torrent.
352 func (cl *Client) ConfigDir() string {
353 return cl.configDir()
356 func (t *torrent) connPendPiece(c *connection, piece int) {
357 c.pendPiece(piece, t.Pieces[piece].Priority)
360 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
361 if t.Pieces[piece].Priority < priority {
362 cl.prioritizePiece(t, piece, priority)
366 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
367 if t.havePiece(piece) {
370 if priority != PiecePriorityNone {
371 cl.queueFirstHash(t, piece)
374 if p.Priority != priority {
375 p.Priority = priority
376 cl.pieceChanged(t, piece)
380 func (cl *Client) setEnvBlocklist() (err error) {
381 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
382 defaultBlocklist := filename == ""
383 if defaultBlocklist {
384 filename = filepath.Join(cl.configDir(), "blocklist")
386 f, err := os.Open(filename)
388 if defaultBlocklist {
394 cl.ipBlockList, err = iplist.NewFromReader(f)
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.
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 == "" {
492 return cfg.ListenAddr
494 if !cl.config.DisableTCP {
496 l, err = net.Listen("tcp", listenAddr())
500 cl.listeners = append(cl.listeners, l)
501 go cl.acceptConnections(l, false)
503 if !cl.config.DisableUTP {
504 cl.utpSock, err = utp.NewSocket(listenAddr())
508 cl.listeners = append(cl.listeners, cl.utpSock)
509 go cl.acceptConnections(cl.utpSock, true)
512 dhtCfg := cfg.DHTConfig
514 dhtCfg = &dht.ServerConfig{
515 IPBlocklist: cl.ipBlockList,
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)
533 func (cl *Client) stopped() bool {
542 // Stops the client. All connections to peers are closed and all activity will
544 func (me *Client) Close() {
548 for _, l := range me.listeners {
552 for _, t := range me.torrents {
557 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
559 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
560 if cl.ipBlockList == nil {
565 log.Printf("blocking non-IPv4 address: %s", ip)
569 r = cl.ipBlockList.Lookup(ip4)
573 func (cl *Client) waitAccept() {
577 for _, t := range cl.torrents {
586 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
589 // We accept all connections immediately, because we don't know what
590 // torrent they're for.
591 conn, err := l.Accept()
610 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
611 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
613 if blockRange != nil || doppleganger {
615 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
619 go cl.incomingConnection(conn, utp)
623 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
625 if tc, ok := nc.(*net.TCPConn); ok {
631 c.Discovery = peerSourceIncoming
633 err := cl.runReceivedConn(c)
639 // Returns a handle to the given torrent, if it's present in the client.
640 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
643 t, ok := cl.torrents[ih]
651 func (me *Client) torrent(ih InfoHash) *torrent {
652 return me.torrents[ih]
655 type dialResult struct {
660 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
661 conn, err := dial(addr, t)
666 conn = nil // Pedantic
668 ch <- dialResult{conn, utp}
670 successfulDials.Add(1)
673 unsuccessfulDials.Add(1)
674 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
677 if netOpErr, ok := err.(*net.OpError); ok {
678 switch netOpErr.Err {
679 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
683 if utp && err.Error() == "timed out waiting for ack" {
687 log.Printf("error dialing %s: %s", addr, err)
692 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
693 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
694 if ret < minDialTimeout {
700 func (me *Client) dopplegangerAddr(addr string) bool {
701 _, ok := me.dopplegangerAddrs[addr]
705 // Start the process of connecting to the given peer for the given torrent if
707 func (me *Client) initiateConn(peer Peer, t *torrent) {
708 if peer.Id == me.peerID {
711 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
712 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
713 duplicateConnsAvoided.Add(1)
716 if r := me.ipBlockRange(peer.IP); r != nil {
717 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
720 t.HalfOpen[addr] = struct{}{}
721 go me.outgoingConnection(t, addr, peer.Source)
724 func (me *Client) dialTimeout(t *torrent) time.Duration {
726 pendingPeers := len(t.Peers)
728 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
731 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
732 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
734 c.(*net.TCPConn).SetLinger(0)
739 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
740 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
743 // Returns a connection over UTP or TCP.
744 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
745 // Initiate connections via TCP and UTP simultaneously. Use the first one
748 if !me.config.DisableUTP {
751 if !me.config.DisableTCP {
754 resCh := make(chan dialResult, left)
755 if !me.config.DisableUTP {
756 go doDial(me.dialUTP, resCh, true, addr, t)
758 if !me.config.DisableTCP {
759 go doDial(me.dialTCP, resCh, false, addr, t)
762 // Wait for a successful connection.
763 for ; left > 0 && res.Conn == nil; left-- {
767 // There are still incompleted dials.
769 for ; left > 0; left-- {
770 conn := (<-resCh).Conn
782 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
783 if _, ok := t.HalfOpen[addr]; !ok {
784 panic("invariant broken")
786 delete(t.HalfOpen, addr)
790 // Returns nil connection and nil error if no connection could be established
791 // for valid reasons.
792 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
793 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
797 c.encrypted = encrypted
799 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
803 ok, err := me.initiateHandshakes(c, t)
809 nc, utp := me.dial(addr, t)
813 c, err = handshakesConnection(nc, !me.config.DisableEncryption, utp)
821 // Try again without encryption, using whichever protocol type worked last
823 if me.config.DisableEncryption {
824 // We already tried without encryption.
828 nc, err = me.dialUTP(addr, t)
830 nc, err = me.dialTCP(addr, t)
833 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
836 c, err = handshakesConnection(nc, false, utp)
843 // Called to dial out and run a connection. The addr we're given is already
844 // considered half-open.
845 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
846 c, err := me.establishOutgoingConn(t, addr)
849 // Don't release lock between here and addConnection, unless it's for
851 me.noLongerHalfOpen(t, addr)
860 err = me.runInitiatedHandshookConn(c, t)
866 // The port number for incoming peer connections. 0 if the client isn't
868 func (cl *Client) incomingPeerPort() int {
869 listenAddr := cl.ListenAddr()
870 if listenAddr == nil {
873 return addrPort(listenAddr)
876 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
877 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
878 func addrCompactIP(addr net.Addr) (string, error) {
879 host, _, err := net.SplitHostPort(addr.String())
883 ip := net.ParseIP(host)
884 if v4 := ip.To4(); v4 != nil {
888 return string(v4), nil
890 return string(ip.To16()), nil
893 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
905 peerExtensionBytes [8]byte
909 func (me *peerExtensionBytes) SupportsExtended() bool {
910 return me[5]&0x10 != 0
913 func (me *peerExtensionBytes) SupportsDHT() bool {
914 return me[7]&0x01 != 0
917 func (me *peerExtensionBytes) SupportsFast() bool {
918 return me[7]&0x04 != 0
921 type handshakeResult struct {
927 // ih is nil if we expect the peer to declare the InfoHash, such as when the
928 // peer initiated the connection. Returns ok if the handshake was successful,
929 // and err if there was an unexpected condition other than the peer simply
930 // abandoning the handshake.
931 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
932 // Bytes to be sent to the peer. Should never block the sender.
933 postCh := make(chan []byte, 4)
934 // A single error value sent when the writer completes.
935 writeDone := make(chan error, 1)
936 // Performs writes to the socket and ensures posts don't block.
937 go handshakeWriter(sock, postCh, writeDone)
940 close(postCh) // Done writing.
947 // Wait until writes complete before returning from handshake.
950 err = fmt.Errorf("error writing: %s", err)
954 post := func(bb []byte) {
958 panic("mustn't block while posting")
962 post([]byte(pp.Protocol))
964 if ih != nil { // We already know what we want.
969 _, err = io.ReadFull(sock, b[:68])
974 if string(b[:20]) != pp.Protocol {
977 CopyExact(&res.peerExtensionBytes, b[20:28])
978 CopyExact(&res.InfoHash, b[28:48])
979 CopyExact(&res.peerID, b[48:68])
980 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
982 // TODO: Maybe we can just drop peers here if we're not interested. This
983 // could prevent them trying to reconnect, falsely believing there was
985 if ih == nil { // We were waiting for the peer to tell us what they wanted.
986 post(res.InfoHash[:])
994 // Wraps a raw connection and provides the interface we want for using the
995 // connection in the message loop.
996 type deadlineReader struct {
1001 func (me deadlineReader) Read(b []byte) (n int, err error) {
1002 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1003 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1005 err = fmt.Errorf("error setting read deadline: %s", err)
1007 n, err = me.r.Read(b)
1008 // Convert common errors into io.EOF.
1010 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1012 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1022 type readWriter struct {
1027 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1028 var protocol [len(pp.Protocol)]byte
1029 _, err = io.ReadFull(rw, protocol[:])
1034 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1037 if string(protocol[:]) == pp.Protocol {
1041 ret, err = mse.ReceiveHandshake(ret, skeys)
1045 func (cl *Client) receiveSkeys() (ret [][]byte) {
1046 for ih := range cl.torrents {
1047 ret = append(ret, ih[:])
1052 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1054 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1059 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1060 if ih != t.InfoHash {
1066 // Do encryption and bittorrent handshakes as receiver.
1067 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1069 skeys := cl.receiveSkeys()
1071 if !cl.config.DisableEncryption {
1072 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1074 if err == mse.ErrNoSecretKeyMatch {
1080 ih, ok, err := cl.connBTHandshake(c, nil)
1082 err = fmt.Errorf("error during bt handshake: %s", err)
1094 // Returns !ok if handshake failed for valid reasons.
1095 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1096 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1097 if err != nil || !ok {
1101 c.PeerExtensionBytes = res.peerExtensionBytes
1102 c.PeerID = res.peerID
1103 c.completedHandshake = time.Now()
1107 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1108 if c.PeerID == cl.peerID {
1109 // Only if we initiated the connection is the remote address a
1110 // listen addr for a doppleganger.
1112 addr := c.conn.RemoteAddr().String()
1113 cl.dopplegangerAddrs[addr] = struct{}{}
1116 return cl.runHandshookConn(c, t)
1119 func (cl *Client) runReceivedConn(c *connection) (err error) {
1120 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1124 t, err := cl.receiveHandshakes(c)
1126 err = fmt.Errorf("error receiving handshakes: %s", err)
1133 defer cl.mu.Unlock()
1134 if c.PeerID == cl.peerID {
1137 return cl.runHandshookConn(c, t)
1140 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1141 c.conn.SetWriteDeadline(time.Time{})
1143 deadlineReader{c.conn, c.rw},
1146 if !cl.addConnection(t, c) {
1149 defer cl.dropConnection(t, c)
1151 go c.writeOptimizer(time.Minute)
1152 cl.sendInitialMessages(c, t)
1154 t.initRequestOrdering(c)
1156 err = cl.connectionLoop(t, c)
1158 err = fmt.Errorf("error during connection loop: %s", err)
1163 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1164 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1165 conn.Post(pp.Message{
1167 ExtendedID: pp.HandshakeExtendedID,
1168 ExtendedPayload: func() []byte {
1169 d := map[string]interface{}{
1170 "m": func() (ret map[string]int) {
1171 ret = make(map[string]int, 2)
1172 ret["ut_metadata"] = metadataExtendedId
1173 if !me.config.DisablePEX {
1174 ret["ut_pex"] = pexExtendedId
1178 "v": extendedHandshakeClientVersion,
1179 // No upload queue is implemented yet.
1182 if !me.config.DisableEncryption {
1185 if torrent.metadataSizeKnown() {
1186 d["metadata_size"] = torrent.metadataSize()
1188 if p := me.incomingPeerPort(); p != 0 {
1191 yourip, err := addrCompactIP(conn.remoteAddr())
1193 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1195 d["yourip"] = yourip
1197 // log.Printf("sending %v", d)
1198 b, err := bencode.Marshal(d)
1206 if torrent.haveAnyPieces() {
1207 conn.Post(pp.Message{
1209 Bitfield: torrent.bitfield(),
1211 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1212 conn.Post(pp.Message{
1216 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1217 conn.Post(pp.Message{
1219 Port: uint16(AddrPort(me.dHT.Addr())),
1224 // Randomizes the piece order for this connection. Every connection will be
1225 // given a different ordering. Having it stored per connection saves having to
1226 // randomize during request filling, and constantly recalculate the ordering
1227 // based on piece priorities.
1228 func (t *torrent) initRequestOrdering(c *connection) {
1229 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1230 panic("double init of request ordering")
1232 c.piecePriorities = mathRand.Perm(t.numPieces())
1233 c.pieceRequestOrder = pieceordering.New()
1234 for i := range iter.N(t.Info.NumPieces()) {
1235 if !c.PeerHasPiece(i) {
1238 if !t.wantPiece(i) {
1241 t.connPendPiece(c, i)
1245 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1248 if c.PeerPieces == nil {
1249 c.PeerPieces = make([]bool, t.numPieces())
1252 for piece >= len(c.PeerPieces) {
1253 c.PeerPieces = append(c.PeerPieces, false)
1256 c.PeerPieces[piece] = true
1258 if t.wantPiece(piece) {
1259 t.connPendPiece(c, piece)
1260 me.replenishConnRequests(t, c)
1264 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1265 me.replenishConnRequests(torrent, conn)
1268 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1271 postedCancels.Add(1)
1276 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1277 if !cn.RequestPending(r) {
1280 delete(cn.Requests, r)
1284 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1288 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1289 // Peer doesn't support this.
1292 // Request metadata pieces that we don't have in a random order.
1294 for index := 0; index < t.metadataPieceCount(); index++ {
1295 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1296 pending = append(pending, index)
1299 for _, i := range mathRand.Perm(len(pending)) {
1300 c.requestMetadataPiece(pending[i])
1304 func (cl *Client) completedMetadata(t *torrent) {
1308 CopyExact(&ih, h.Sum(nil))
1309 if ih != t.InfoHash {
1310 log.Print("bad metadata")
1311 t.invalidateMetadata()
1314 var info metainfo.Info
1315 err := bencode.Unmarshal(t.MetaData, &info)
1317 log.Printf("error unmarshalling metadata: %s", err)
1318 t.invalidateMetadata()
1321 // TODO(anacrolix): If this fails, I think something harsher should be
1323 err = cl.setMetaData(t, &info, t.MetaData)
1325 log.Printf("error setting metadata: %s", err)
1326 t.invalidateMetadata()
1329 log.Printf("%s: got metadata from peers", t)
1332 // Process incoming ut_metadata message.
1333 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1334 var d map[string]int
1335 err = bencode.Unmarshal(payload, &d)
1337 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1340 msgType, ok := d["msg_type"]
1342 err = errors.New("missing msg_type field")
1347 case pp.DataMetadataExtensionMsgType:
1351 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1352 if begin < 0 || begin >= len(payload) {
1353 log.Printf("got bad metadata piece")
1356 if !c.requestedMetadataPiece(piece) {
1357 log.Printf("got unexpected metadata piece %d", piece)
1360 c.metadataRequests[piece] = false
1361 t.saveMetadataPiece(piece, payload[begin:])
1362 c.UsefulChunksReceived++
1363 c.lastUsefulChunkReceived = time.Now()
1364 if !t.haveAllMetadataPieces() {
1367 cl.completedMetadata(t)
1368 case pp.RequestMetadataExtensionMsgType:
1369 if !t.haveMetadataPiece(piece) {
1370 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1373 start := (1 << 14) * piece
1374 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1375 case pp.RejectMetadataExtensionMsgType:
1377 err = errors.New("unknown msg_type value")
1382 type peerExchangeMessage struct {
1383 Added CompactPeers `bencode:"added"`
1384 AddedFlags []byte `bencode:"added.f"`
1385 Dropped CompactPeers `bencode:"dropped"`
1388 // Extracts the port as an integer from an address string.
1389 func addrPort(addr net.Addr) int {
1390 return AddrPort(addr)
1393 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1394 cn.peerHasAll = true
1397 for i := 0; i < t.numPieces(); i++ {
1398 cl.peerGotPiece(t, cn, i)
1403 func (me *Client) upload(t *torrent, c *connection) {
1404 if me.config.NoUpload {
1407 if !c.PeerInterested {
1410 if !me.seeding(t) && !t.connHasWantedPieces(c) {
1414 for c.chunksSent < c.UsefulChunksReceived+6 {
1416 for r := range c.PeerRequests {
1417 err := me.sendChunk(t, c, r)
1419 log.Printf("error sending chunk to peer: %s", err)
1421 delete(c.PeerRequests, r)
1429 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1430 b := make([]byte, r.Length)
1431 p := t.Info.Piece(int(r.Index))
1432 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1445 uploadChunksPosted.Add(1)
1447 c.lastChunkSent = time.Now()
1451 // Processes incoming bittorrent messages. The client lock is held upon entry
1453 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1454 decoder := pp.Decoder{
1455 R: bufio.NewReader(c.rw),
1456 MaxLength: 256 * 1024,
1461 err := decoder.Decode(&msg)
1462 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1464 c.lastMessageReceived = time.Now()
1471 if me.stopped() || err == io.EOF {
1482 for r := range c.Requests {
1483 me.connDeleteRequest(t, c, r)
1485 // We can then reset our interest.
1486 me.replenishConnRequests(t, c)
1488 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1489 me.replenishConnRequests(t, c)
1491 c.PeerChoked = false
1492 me.peerUnchoked(t, c)
1494 c.PeerInterested = true
1496 case pp.NotInterested:
1497 c.PeerInterested = false
1500 me.peerGotPiece(t, c, int(msg.Index))
1505 if !c.PeerInterested {
1506 err = errors.New("peer sent request but isn't interested")
1509 if c.PeerRequests == nil {
1510 c.PeerRequests = make(map[request]struct{}, maxRequests)
1512 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1515 req := newRequest(msg.Index, msg.Begin, msg.Length)
1516 if !c.PeerCancel(req) {
1517 unexpectedCancels.Add(1)
1520 if c.PeerPieces != nil || c.peerHasAll {
1521 err = errors.New("received unexpected bitfield")
1525 if len(msg.Bitfield) < t.numPieces() {
1526 err = errors.New("received invalid bitfield")
1529 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1531 c.PeerPieces = msg.Bitfield
1532 for index, has := range c.PeerPieces {
1534 me.peerGotPiece(t, c, index)
1538 if c.PeerPieces != nil || c.peerHasAll {
1539 err = errors.New("unexpected have-all")
1544 if c.peerHasAll || c.PeerPieces != nil {
1545 err = errors.New("unexpected have-none")
1548 c.PeerPieces = make([]bool, func() int {
1550 return t.numPieces()
1556 err = me.downloadedChunk(t, c, &msg)
1558 switch msg.ExtendedID {
1559 case pp.HandshakeExtendedID:
1560 // TODO: Create a bencode struct for this.
1561 var d map[string]interface{}
1562 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1564 err = fmt.Errorf("error decoding extended message payload: %s", err)
1567 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1568 if reqq, ok := d["reqq"]; ok {
1569 if i, ok := reqq.(int64); ok {
1570 c.PeerMaxRequests = int(i)
1573 if v, ok := d["v"]; ok {
1574 c.PeerClientName = v.(string)
1578 err = errors.New("handshake missing m item")
1581 mTyped, ok := m.(map[string]interface{})
1583 err = errors.New("handshake m value is not dict")
1586 if c.PeerExtensionIDs == nil {
1587 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1589 for name, v := range mTyped {
1592 log.Printf("bad handshake m item extension ID type: %T", v)
1596 delete(c.PeerExtensionIDs, name)
1598 if c.PeerExtensionIDs[name] == 0 {
1599 supportedExtensionMessages.Add(name, 1)
1601 c.PeerExtensionIDs[name] = byte(id)
1604 metadata_sizeUntyped, ok := d["metadata_size"]
1606 metadata_size, ok := metadata_sizeUntyped.(int64)
1608 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1610 t.setMetadataSize(metadata_size, me)
1613 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1614 me.requestPendingMetadata(t, c)
1616 case metadataExtendedId:
1617 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1619 err = fmt.Errorf("error handling metadata extension message: %s", err)
1622 if me.config.DisablePEX {
1625 var pexMsg peerExchangeMessage
1626 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1628 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1633 me.addPeers(t, func() (ret []Peer) {
1634 for i, cp := range pexMsg.Added {
1636 IP: make([]byte, 4),
1638 Source: peerSourcePEX,
1640 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1641 p.SupportsEncryption = true
1643 CopyExact(p.IP, cp.IP[:])
1644 ret = append(ret, p)
1649 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1652 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1655 // That client uses its own extension IDs for outgoing message
1656 // types, which is incorrect.
1657 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1658 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1666 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1671 pingAddr.Port = int(msg.Port)
1673 _, err = me.dHT.Ping(pingAddr)
1675 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1683 // Returns true if connection is removed from torrent.Conns.
1684 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1685 for i0, _c := range t.Conns {
1689 i1 := len(t.Conns) - 1
1691 t.Conns[i0] = t.Conns[i1]
1693 t.Conns = t.Conns[:i1]
1699 func (me *Client) dropConnection(t *torrent, c *connection) {
1700 me.event.Broadcast()
1702 if me.deleteConnection(t, c) {
1707 // Returns true if the connection is added.
1708 func (me *Client) addConnection(t *torrent, c *connection) bool {
1713 case <-t.ceasingNetworking:
1717 if !me.wantConns(t) {
1720 for _, c0 := range t.Conns {
1721 if c.PeerID == c0.PeerID {
1722 // Already connected to a client with that ID.
1723 duplicateClientConns.Add(1)
1727 if len(t.Conns) >= socketsPerTorrent {
1728 c := t.worstBadConn(me)
1732 log.Printf("%s: dropping connection to make room for new one: %s", t, c)
1734 me.deleteConnection(t, c)
1736 if len(t.Conns) >= socketsPerTorrent {
1739 t.Conns = append(t.Conns, c)
1743 func (t *torrent) needData() bool {
1747 for i := range t.Pieces {
1755 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1762 return c.supportsExtension("ut_metadata")
1765 return c.PeerInterested
1767 return t.connHasWantedPieces(c)
1770 func (me *Client) wantConns(t *torrent) bool {
1771 if !me.seeding(t) && !t.needData() {
1774 if len(t.Conns) < socketsPerTorrent {
1777 return t.worstBadConn(me) != nil
1780 func (me *Client) openNewConns(t *torrent) {
1782 case <-t.ceasingNetworking:
1786 for len(t.Peers) != 0 {
1787 if !me.wantConns(t) {
1790 if len(t.HalfOpen) >= me.halfOpenLimit {
1797 for k, p = range t.Peers {
1801 me.initiateConn(p, t)
1803 t.wantPeers.Broadcast()
1806 func (me *Client) addPeers(t *torrent, peers []Peer) {
1807 for _, p := range peers {
1808 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1811 if me.ipBlockRange(p.IP) != nil {
1815 log.Printf("got bad peer: %v", p)
1823 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1824 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1827 func (cl *Client) saveTorrentFile(t *torrent) error {
1828 path := cl.cachedMetaInfoFilename(t.InfoHash)
1829 os.MkdirAll(filepath.Dir(path), 0777)
1830 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1832 return fmt.Errorf("error opening file: %s", err)
1835 e := bencode.NewEncoder(f)
1836 err = e.Encode(t.MetaInfo())
1838 return fmt.Errorf("error marshalling metainfo: %s", err)
1840 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1842 // For example, a script kiddy makes us load too many files, and we're
1843 // able to save the torrent, but not load it again to check it.
1846 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1847 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1852 func (cl *Client) startTorrent(t *torrent) {
1853 if t.Info == nil || t.data == nil {
1856 // If the client intends to upload, it needs to know what state pieces are
1858 if !cl.config.NoUpload {
1859 // Queue all pieces for hashing. This is done sequentially to avoid
1860 // spamming goroutines.
1861 for _, p := range t.Pieces {
1862 p.QueuedForHash = true
1865 for i := range t.Pieces {
1866 cl.verifyPiece(t, pp.Integer(i))
1872 // Storage cannot be changed once it's set.
1873 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1874 err = t.setStorage(td)
1875 cl.event.Broadcast()
1879 for index := range iter.N(t.numPieces()) {
1880 cl.pieceChanged(t, index)
1886 type TorrentDataOpener func(*metainfo.Info) data.Data
1888 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1889 err = t.setMetadata(md, bytes, &cl.mu)
1893 if !cl.config.DisableMetainfoCache {
1894 if err := cl.saveTorrentFile(t); err != nil {
1895 log.Printf("error saving torrent file for %s: %s", t, err)
1898 cl.event.Broadcast()
1899 close(t.gotMetainfo)
1900 td := cl.torrentDataOpener(md)
1901 err = cl.setStorage(t, td)
1905 // Prepare a Torrent without any attachment to a Client. That means we can
1906 // initialize fields all fields that don't require the Client without locking
1908 func newTorrent(ih InfoHash) (t *torrent, err error) {
1911 Peers: make(map[peersKey]Peer),
1913 closing: make(chan struct{}),
1914 ceasingNetworking: make(chan struct{}),
1916 gotMetainfo: make(chan struct{}),
1918 HalfOpen: make(map[string]struct{}),
1920 t.wantPeers.L = &t.stateMu
1925 // For shuffling the tracker tiers.
1926 mathRand.Seed(time.Now().Unix())
1929 // The trackers within each tier must be shuffled before use.
1930 // http://stackoverflow.com/a/12267471/149482
1931 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1932 func shuffleTier(tier []tracker.Client) {
1933 for i := range tier {
1934 j := mathRand.Intn(i + 1)
1935 tier[i], tier[j] = tier[j], tier[i]
1939 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1940 for _, tier := range base {
1941 copy = append(copy, append([]tracker.Client{}, tier...))
1946 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1948 for _, url := range newURLs {
1949 for _, tr := range tier {
1950 if tr.URL() == url {
1954 tr, err := tracker.New(url)
1956 log.Printf("error creating tracker client for %q: %s", url, err)
1959 tier = append(tier, tr)
1964 func (t *torrent) addTrackers(announceList [][]string) {
1965 newTrackers := copyTrackers(t.Trackers)
1966 for tierIndex, tier := range announceList {
1967 if tierIndex < len(newTrackers) {
1968 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1970 newTrackers = append(newTrackers, mergeTier(nil, tier))
1972 shuffleTier(newTrackers[tierIndex])
1974 t.Trackers = newTrackers
1977 // Don't call this before the info is available.
1978 func (t *torrent) BytesCompleted() int64 {
1982 return t.Info.TotalLength() - t.bytesLeft()
1985 // A file-like handle to some torrent data resource.
1986 type Handle interface {
1993 // Returns handles to the files in the torrent. This requires the metainfo is
1995 func (t Torrent) Files() (ret []File) {
2003 for _, fi := range info.UpvertedFiles() {
2004 ret = append(ret, File{
2006 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2016 // Marks the pieces in the given region for download.
2017 func (t Torrent) SetRegionPriority(off, len int64) {
2019 defer t.cl.mu.Unlock()
2020 pieceSize := int64(t.usualPieceSize())
2021 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2022 t.cl.raisePiecePriority(t.torrent, int(i), PiecePriorityNormal)
2026 func (t Torrent) AddPeers(pp []Peer) error {
2029 defer cl.mu.Unlock()
2030 cl.addPeers(t.torrent, pp)
2034 // Marks the entire torrent for download. Requires the info first, see
2036 func (t Torrent) DownloadAll() {
2038 defer t.cl.mu.Unlock()
2039 for i := range iter.N(t.numPieces()) {
2040 t.cl.raisePiecePriority(t.torrent, i, PiecePriorityNormal)
2042 // Nice to have the first and last pieces sooner for various interactive
2044 t.cl.raisePiecePriority(t.torrent, 0, PiecePriorityReadahead)
2045 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, PiecePriorityReadahead)
2048 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2049 // metainfo has the correct infohash.
2050 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2051 if cl.config.DisableMetainfoCache {
2054 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2056 if os.IsNotExist(err) {
2062 dec := bencode.NewDecoder(f)
2063 err = dec.Decode(&mi)
2067 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2068 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2074 // Specifies a new torrent for adding to a client. There are helpers for
2075 // magnet URIs and torrent metainfo files.
2076 type TorrentSpec struct {
2079 Info *metainfo.InfoEx
2083 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2084 m, err := ParseMagnetURI(uri)
2088 spec = &TorrentSpec{
2089 Trackers: [][]string{m.Trackers},
2090 DisplayName: m.DisplayName,
2091 InfoHash: m.InfoHash,
2096 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2097 spec = &TorrentSpec{
2098 Trackers: mi.AnnounceList,
2100 DisplayName: mi.Info.Name,
2102 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2106 // Add or merge a torrent spec. If the torrent is already present, the
2107 // trackers will be merged with the existing ones. If the Info isn't yet
2108 // known, it will be set. The display name is replaced if the new spec
2109 // provides one. Returns new if the torrent wasn't already in the client.
2110 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2113 defer cl.mu.Unlock()
2115 t, ok := cl.torrents[spec.InfoHash]
2119 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2120 err = errors.New("banned torrent")
2124 t, err = newTorrent(spec.InfoHash)
2129 if spec.DisplayName != "" {
2130 t.DisplayName = spec.DisplayName
2132 // Try to merge in info we have on the torrent. Any err left will
2133 // terminate the function.
2135 if spec.Info != nil {
2136 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2138 var mi *metainfo.MetaInfo
2139 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2141 log.Printf("error getting cached metainfo: %s", err)
2143 } else if mi != nil {
2144 t.addTrackers(mi.AnnounceList)
2145 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2152 t.addTrackers(spec.Trackers)
2154 cl.torrents[spec.InfoHash] = t
2157 // From this point onwards, we can consider the torrent a part of the
2160 if !cl.config.DisableTrackers {
2161 go cl.announceTorrentTrackers(T.torrent)
2164 go cl.announceTorrentDHT(T.torrent, true)
2170 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2171 t, ok := me.torrents[infoHash]
2173 err = fmt.Errorf("no such torrent")
2180 delete(me.torrents, infoHash)
2184 // Returns true when peers are required, or false if the torrent is closing.
2185 func (cl *Client) waitWantPeers(t *torrent) bool {
2187 defer cl.mu.Unlock()
2189 defer t.stateMu.Unlock()
2192 case <-t.ceasingNetworking:
2196 if len(t.Peers) > torrentPeersLowWater {
2199 if t.needData() || cl.seeding(t) {
2211 // Returns whether the client should make effort to seed the torrent.
2212 func (cl *Client) seeding(t *torrent) bool {
2213 if cl.config.NoUpload {
2216 if !cl.config.Seed {
2225 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2226 for cl.waitWantPeers(t) {
2227 log.Printf("getting peers for %q from DHT", t)
2228 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2230 log.Printf("error getting peers from dht: %s", err)
2233 allAddrs := make(map[string]struct{})
2237 case v, ok := <-ps.Peers:
2241 peersFoundByDHT.Add(int64(len(v.Peers)))
2242 for _, p := range v.Peers {
2243 allAddrs[(&net.UDPAddr{
2246 }).String()] = struct{}{}
2248 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2250 cl.addPeers(t, func() (ret []Peer) {
2251 for _, cp := range v.Peers {
2252 ret = append(ret, Peer{
2255 Source: peerSourceDHT,
2260 numPeers := len(t.Peers)
2262 if numPeers >= torrentPeersHighWater {
2265 case <-t.ceasingNetworking:
2271 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2275 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2276 url_, err := url.Parse(tr.URL())
2280 host, _, err := net.SplitHostPort(url_.Host)
2284 addr, err := net.ResolveIPAddr("ip", host)
2289 if cl.ipBlockList != nil {
2290 if cl.ipBlockRange(addr.IP) != nil {
2298 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2299 blocked, err := cl.trackerBlockedUnlocked(tr)
2301 return fmt.Errorf("error determining if tracker blocked: %s", err)
2304 return fmt.Errorf("tracker blocked: %s", tr)
2306 if err := tr.Connect(); err != nil {
2307 return fmt.Errorf("error connecting: %s", err)
2309 resp, err := tr.Announce(req)
2311 return fmt.Errorf("error announcing: %s", err)
2314 for _, peer := range resp.Peers {
2315 peers = append(peers, Peer{
2321 cl.addPeers(t, peers)
2324 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2325 peersFoundByTracker.Add(int64(len(peers)))
2327 time.Sleep(time.Second * time.Duration(resp.Interval))
2331 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2332 oks := make(chan bool)
2334 for _, tier := range trackers {
2335 for _, tr := range tier {
2337 go func(tr tracker.Client) {
2338 err := cl.announceTorrentSingleTracker(tr, req, t)
2343 for outstanding > 0 {
2353 // Announce torrent to its trackers.
2354 func (cl *Client) announceTorrentTrackers(t *torrent) {
2355 req := tracker.AnnounceRequest{
2356 Event: tracker.Started,
2358 Port: uint16(cl.incomingPeerPort()),
2360 InfoHash: t.InfoHash,
2362 if !cl.waitWantPeers(t) {
2366 req.Left = uint64(t.bytesLeft())
2367 trackers := t.Trackers
2369 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2370 req.Event = tracker.None
2373 for cl.waitWantPeers(t) {
2375 req.Left = uint64(t.bytesLeft())
2376 trackers = t.Trackers
2378 numTrackersTried := 0
2379 for _, tier := range trackers {
2380 for trIndex, tr := range tier {
2382 err := cl.announceTorrentSingleTracker(tr, &req, t)
2384 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2387 // Float the successful announce to the top of the tier. If
2388 // the trackers list has been changed, we'll be modifying an
2389 // old copy so it won't matter.
2391 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2394 req.Event = tracker.None
2395 continue newAnnounce
2398 if numTrackersTried != 0 {
2399 log.Printf("%s: all trackers failed", t)
2401 // TODO: Wait until trackers are added if there are none.
2402 time.Sleep(10 * time.Second)
2406 func (cl *Client) allTorrentsCompleted() bool {
2407 for _, t := range cl.torrents {
2411 if t.numPiecesCompleted() != t.numPieces() {
2418 // Returns true when all torrents are completely downloaded and false if the
2419 // client is stopped before that.
2420 func (me *Client) WaitAll() bool {
2422 defer me.mu.Unlock()
2423 for !me.allTorrentsCompleted() {
2432 func (me *Client) fillRequests(t *torrent, c *connection) {
2437 if len(c.Requests) > c.requestsLowWater {
2441 addRequest := func(req request) (again bool) {
2442 // TODO: Couldn't this check also be done *after* the request?
2443 if len(c.Requests) >= 64 {
2446 return c.Request(req)
2448 for req := range t.urgent {
2449 if !addRequest(req) {
2453 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2454 pieceIndex := e.Piece()
2455 if !c.PeerHasPiece(pieceIndex) {
2456 panic("piece in request order but peer doesn't have it")
2458 if !t.wantPiece(pieceIndex) {
2459 panic("unwanted piece in connection request order")
2461 piece := t.Pieces[pieceIndex]
2462 for _, cs := range piece.shuffledPendingChunkSpecs(t.pieceLength(pieceIndex)) {
2463 r := request{pp.Integer(pieceIndex), cs}
2472 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2476 me.fillRequests(t, c)
2477 if len(c.Requests) == 0 && !c.PeerChoked {
2478 // So we're not choked, but we don't want anything right now. We may
2479 // have completed readahead, and the readahead window has not rolled
2480 // over to the next piece. Better to stay interested in case we're
2481 // going to want data in the near future.
2482 c.SetInterested(!t.haveAllPieces())
2486 // Handle a received chunk from a peer.
2487 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2488 chunksReceived.Add(1)
2490 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2492 // Request has been satisfied.
2493 if me.connDeleteRequest(t, c, req) {
2494 defer me.replenishConnRequests(t, c)
2496 unexpectedChunksReceived.Add(1)
2499 piece := t.Pieces[req.Index]
2501 // Do we actually want this chunk?
2502 if !t.wantChunk(req) {
2503 unwantedChunksReceived.Add(1)
2504 c.UnwantedChunksReceived++
2508 c.UsefulChunksReceived++
2509 c.lastUsefulChunkReceived = time.Now()
2513 // Write the chunk out.
2514 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2516 log.Printf("error writing chunk: %s", err)
2520 // log.Println("got chunk", req)
2521 piece.Event.Broadcast()
2522 // Record that we have the chunk.
2523 piece.unpendChunkIndex(chunkIndex(req.chunkSpec))
2524 delete(t.urgent, req)
2525 if piece.numPendingChunks() == 0 {
2526 for _, c := range t.Conns {
2527 c.pieceRequestOrder.DeletePiece(int(req.Index))
2529 me.queuePieceCheck(t, req.Index)
2532 // Cancel pending requests for this chunk.
2533 for _, c := range t.Conns {
2534 if me.connCancel(t, c, req) {
2535 me.replenishConnRequests(t, c)
2542 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2543 p := t.Pieces[piece]
2546 pieceHashedCorrect.Add(1)
2548 log.Printf("%s: piece %d failed hash", t, piece)
2549 pieceHashedNotCorrect.Add(1)
2554 err := t.data.PieceCompleted(int(piece))
2556 log.Printf("error completing piece: %s", err)
2560 me.pieceChanged(t, int(piece))
2563 // TODO: Check this isn't called more than once for each piece being correct.
2564 func (me *Client) pieceChanged(t *torrent, piece int) {
2565 correct := t.pieceComplete(piece)
2566 p := t.Pieces[piece]
2567 defer p.Event.Broadcast()
2569 p.Priority = PiecePriorityNone
2570 p.PendingChunkSpecs = nil
2571 for req := range t.urgent {
2572 if int(req.Index) == piece {
2573 delete(t.urgent, req)
2577 if p.numPendingChunks() == 0 {
2578 t.pendAllChunkSpecs(int(piece))
2580 if t.wantPiece(piece) {
2584 for _, conn := range t.Conns {
2586 conn.Post(pp.Message{
2588 Index: pp.Integer(piece),
2590 // TODO: Cancel requests for this piece.
2591 for r := range conn.Requests {
2592 if int(r.Index) == piece {
2596 conn.pieceRequestOrder.DeletePiece(int(piece))
2598 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2599 t.connPendPiece(conn, int(piece))
2600 me.replenishConnRequests(t, conn)
2603 me.event.Broadcast()
2606 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2608 defer cl.mu.Unlock()
2609 p := t.Pieces[index]
2610 for p.Hashing || t.data == nil {
2613 p.QueuedForHash = false
2614 if t.isClosed() || t.pieceComplete(int(index)) {
2619 sum := t.hashPiece(index)
2627 cl.pieceHashed(t, index, sum == p.Hash)
2630 // Returns handles to all the torrents loaded in the Client.
2631 func (me *Client) Torrents() (ret []Torrent) {
2633 for _, t := range me.torrents {
2634 ret = append(ret, Torrent{me, t})
2640 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2641 spec, err := TorrentSpecFromMagnetURI(uri)
2645 T, _, err = me.AddTorrentSpec(spec)
2649 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2650 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2654 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2655 mi, err := metainfo.LoadFromFile(filename)
2659 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))