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 = 80
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+int(t.chunkSize)-1)/int(t.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) {
368 priority = PiecePriorityNone
370 if priority != PiecePriorityNone {
371 cl.queueFirstHash(t, piece)
374 if p.Hashing || p.QueuedForHash {
377 if p.Priority != priority {
378 p.Priority = priority
379 cl.pieceChanged(t, piece)
383 func (cl *Client) setEnvBlocklist() (err error) {
384 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
385 defaultBlocklist := filename == ""
386 if defaultBlocklist {
387 filename = filepath.Join(cl.configDir(), "blocklist")
389 f, err := os.Open(filename)
391 if defaultBlocklist {
397 cl.ipBlockList, err = iplist.NewFromReader(f)
401 func (cl *Client) initBannedTorrents() error {
402 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
404 if os.IsNotExist(err) {
407 return fmt.Errorf("error opening banned infohashes file: %s", err)
410 scanner := bufio.NewScanner(f)
411 cl.bannedTorrents = make(map[InfoHash]struct{})
413 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
417 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
419 return fmt.Errorf("error reading infohash: %s", err)
425 return errors.New("bad infohash")
429 cl.bannedTorrents[ih] = struct{}{}
431 if err := scanner.Err(); err != nil {
432 return fmt.Errorf("error scanning file: %s", err)
437 // Creates a new client.
438 func NewClient(cfg *Config) (cl *Client, err error) {
449 halfOpenLimit: socketsPerTorrent,
451 torrentDataOpener: func(md *metainfo.Info) data.Data {
452 return filePkg.TorrentData(md, cfg.DataDir)
454 dopplegangerAddrs: make(map[string]struct{}),
456 quit: make(chan struct{}),
457 torrents: make(map[InfoHash]*torrent),
459 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
461 if cfg.TorrentDataOpener != nil {
462 cl.torrentDataOpener = cfg.TorrentDataOpener
465 if !cfg.NoDefaultBlocklist {
466 err = cl.setEnvBlocklist()
472 if err = cl.initBannedTorrents(); err != nil {
473 err = fmt.Errorf("error initing banned torrents: %s", err)
477 if cfg.PeerID != "" {
478 CopyExact(&cl.peerID, cfg.PeerID)
480 o := copy(cl.peerID[:], bep20)
481 _, err = rand.Read(cl.peerID[o:])
483 panic("error generating peer id")
487 // Returns the laddr string to listen on for the next Listen call.
488 listenAddr := func() string {
489 if addr := cl.ListenAddr(); addr != nil {
492 if cfg.ListenAddr == "" {
495 return cfg.ListenAddr
497 if !cl.config.DisableTCP {
499 l, err = net.Listen("tcp", listenAddr())
503 cl.listeners = append(cl.listeners, l)
504 go cl.acceptConnections(l, false)
506 if !cl.config.DisableUTP {
507 cl.utpSock, err = utp.NewSocket(listenAddr())
511 cl.listeners = append(cl.listeners, cl.utpSock)
512 go cl.acceptConnections(cl.utpSock, true)
515 dhtCfg := cfg.DHTConfig
517 dhtCfg = &dht.ServerConfig{
518 IPBlocklist: cl.ipBlockList,
521 if dhtCfg.Addr == "" {
522 dhtCfg.Addr = listenAddr()
524 if dhtCfg.Conn == nil && cl.utpSock != nil {
525 dhtCfg.Conn = cl.utpSock.PacketConn()
527 cl.dHT, err = dht.NewServer(dhtCfg)
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()
613 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
614 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
616 if blockRange != nil || doppleganger {
618 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
622 go cl.incomingConnection(conn, utp)
626 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
628 if tc, ok := nc.(*net.TCPConn); ok {
634 c.Discovery = peerSourceIncoming
636 err := cl.runReceivedConn(c)
642 // Returns a handle to the given torrent, if it's present in the client.
643 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
646 t, ok := cl.torrents[ih]
654 func (me *Client) torrent(ih InfoHash) *torrent {
655 return me.torrents[ih]
658 type dialResult struct {
663 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
664 conn, err := dial(addr, t)
669 conn = nil // Pedantic
671 ch <- dialResult{conn, utp}
673 successfulDials.Add(1)
676 unsuccessfulDials.Add(1)
677 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
680 if netOpErr, ok := err.(*net.OpError); ok {
681 switch netOpErr.Err {
682 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
686 if utp && err.Error() == "timed out waiting for ack" {
690 log.Printf("error dialing %s: %s", addr, err)
695 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
696 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
697 if ret < minDialTimeout {
703 func (me *Client) dopplegangerAddr(addr string) bool {
704 _, ok := me.dopplegangerAddrs[addr]
708 // Start the process of connecting to the given peer for the given torrent if
710 func (me *Client) initiateConn(peer Peer, t *torrent) {
711 if peer.Id == me.peerID {
714 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
715 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
716 duplicateConnsAvoided.Add(1)
719 if r := me.ipBlockRange(peer.IP); r != nil {
720 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
723 t.HalfOpen[addr] = struct{}{}
724 go me.outgoingConnection(t, addr, peer.Source)
727 func (me *Client) dialTimeout(t *torrent) time.Duration {
729 pendingPeers := len(t.Peers)
731 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
734 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
735 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
737 c.(*net.TCPConn).SetLinger(0)
742 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
743 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
746 // Returns a connection over UTP or TCP.
747 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
748 // Initiate connections via TCP and UTP simultaneously. Use the first one
751 if !me.config.DisableUTP {
754 if !me.config.DisableTCP {
757 resCh := make(chan dialResult, left)
758 if !me.config.DisableUTP {
759 go doDial(me.dialUTP, resCh, true, addr, t)
761 if !me.config.DisableTCP {
762 go doDial(me.dialTCP, resCh, false, addr, t)
765 // Wait for a successful connection.
766 for ; left > 0 && res.Conn == nil; left-- {
770 // There are still incompleted dials.
772 for ; left > 0; left-- {
773 conn := (<-resCh).Conn
785 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
786 if _, ok := t.HalfOpen[addr]; !ok {
787 panic("invariant broken")
789 delete(t.HalfOpen, addr)
793 // Returns nil connection and nil error if no connection could be established
794 // for valid reasons.
795 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
796 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
800 c.encrypted = encrypted
802 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
806 ok, err := me.initiateHandshakes(c, t)
812 nc, utp := me.dial(addr, t)
816 c, err = handshakesConnection(nc, !me.config.DisableEncryption, utp)
824 // Try again without encryption, using whichever protocol type worked last
826 if me.config.DisableEncryption {
827 // We already tried without encryption.
831 nc, err = me.dialUTP(addr, t)
833 nc, err = me.dialTCP(addr, t)
836 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
839 c, err = handshakesConnection(nc, false, utp)
846 // Called to dial out and run a connection. The addr we're given is already
847 // considered half-open.
848 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
849 c, err := me.establishOutgoingConn(t, addr)
852 // Don't release lock between here and addConnection, unless it's for
854 me.noLongerHalfOpen(t, addr)
863 err = me.runInitiatedHandshookConn(c, t)
869 // The port number for incoming peer connections. 0 if the client isn't
871 func (cl *Client) incomingPeerPort() int {
872 listenAddr := cl.ListenAddr()
873 if listenAddr == nil {
876 return addrPort(listenAddr)
879 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
880 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
881 func addrCompactIP(addr net.Addr) (string, error) {
882 host, _, err := net.SplitHostPort(addr.String())
886 ip := net.ParseIP(host)
887 if v4 := ip.To4(); v4 != nil {
891 return string(v4), nil
893 return string(ip.To16()), nil
896 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
908 peerExtensionBytes [8]byte
912 func (me *peerExtensionBytes) SupportsExtended() bool {
913 return me[5]&0x10 != 0
916 func (me *peerExtensionBytes) SupportsDHT() bool {
917 return me[7]&0x01 != 0
920 func (me *peerExtensionBytes) SupportsFast() bool {
921 return me[7]&0x04 != 0
924 type handshakeResult struct {
930 // ih is nil if we expect the peer to declare the InfoHash, such as when the
931 // peer initiated the connection. Returns ok if the handshake was successful,
932 // and err if there was an unexpected condition other than the peer simply
933 // abandoning the handshake.
934 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
935 // Bytes to be sent to the peer. Should never block the sender.
936 postCh := make(chan []byte, 4)
937 // A single error value sent when the writer completes.
938 writeDone := make(chan error, 1)
939 // Performs writes to the socket and ensures posts don't block.
940 go handshakeWriter(sock, postCh, writeDone)
943 close(postCh) // Done writing.
950 // Wait until writes complete before returning from handshake.
953 err = fmt.Errorf("error writing: %s", err)
957 post := func(bb []byte) {
961 panic("mustn't block while posting")
965 post([]byte(pp.Protocol))
967 if ih != nil { // We already know what we want.
972 _, err = io.ReadFull(sock, b[:68])
977 if string(b[:20]) != pp.Protocol {
980 CopyExact(&res.peerExtensionBytes, b[20:28])
981 CopyExact(&res.InfoHash, b[28:48])
982 CopyExact(&res.peerID, b[48:68])
983 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
985 // TODO: Maybe we can just drop peers here if we're not interested. This
986 // could prevent them trying to reconnect, falsely believing there was
988 if ih == nil { // We were waiting for the peer to tell us what they wanted.
989 post(res.InfoHash[:])
997 // Wraps a raw connection and provides the interface we want for using the
998 // connection in the message loop.
999 type deadlineReader struct {
1004 func (me deadlineReader) Read(b []byte) (n int, err error) {
1005 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1006 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1008 err = fmt.Errorf("error setting read deadline: %s", err)
1010 n, err = me.r.Read(b)
1011 // Convert common errors into io.EOF.
1013 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1015 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1025 type readWriter struct {
1030 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1031 var protocol [len(pp.Protocol)]byte
1032 _, err = io.ReadFull(rw, protocol[:])
1037 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1040 if string(protocol[:]) == pp.Protocol {
1044 ret, err = mse.ReceiveHandshake(ret, skeys)
1048 func (cl *Client) receiveSkeys() (ret [][]byte) {
1049 for ih := range cl.torrents {
1050 ret = append(ret, ih[:])
1055 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1057 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1062 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1063 if ih != t.InfoHash {
1069 // Do encryption and bittorrent handshakes as receiver.
1070 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1072 skeys := cl.receiveSkeys()
1074 if !cl.config.DisableEncryption {
1075 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1077 if err == mse.ErrNoSecretKeyMatch {
1083 ih, ok, err := cl.connBTHandshake(c, nil)
1085 err = fmt.Errorf("error during bt handshake: %s", err)
1097 // Returns !ok if handshake failed for valid reasons.
1098 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1099 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1100 if err != nil || !ok {
1104 c.PeerExtensionBytes = res.peerExtensionBytes
1105 c.PeerID = res.peerID
1106 c.completedHandshake = time.Now()
1110 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1111 if c.PeerID == cl.peerID {
1112 // Only if we initiated the connection is the remote address a
1113 // listen addr for a doppleganger.
1115 addr := c.conn.RemoteAddr().String()
1116 cl.dopplegangerAddrs[addr] = struct{}{}
1119 return cl.runHandshookConn(c, t)
1122 func (cl *Client) runReceivedConn(c *connection) (err error) {
1123 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1127 t, err := cl.receiveHandshakes(c)
1129 err = fmt.Errorf("error receiving handshakes: %s", err)
1136 defer cl.mu.Unlock()
1137 if c.PeerID == cl.peerID {
1140 return cl.runHandshookConn(c, t)
1143 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1144 c.conn.SetWriteDeadline(time.Time{})
1146 deadlineReader{c.conn, c.rw},
1149 if !cl.addConnection(t, c) {
1152 defer cl.dropConnection(t, c)
1154 go c.writeOptimizer(time.Minute)
1155 cl.sendInitialMessages(c, t)
1157 t.initRequestOrdering(c)
1159 err = cl.connectionLoop(t, c)
1161 err = fmt.Errorf("error during connection loop: %s", err)
1166 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1167 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1168 conn.Post(pp.Message{
1170 ExtendedID: pp.HandshakeExtendedID,
1171 ExtendedPayload: func() []byte {
1172 d := map[string]interface{}{
1173 "m": func() (ret map[string]int) {
1174 ret = make(map[string]int, 2)
1175 ret["ut_metadata"] = metadataExtendedId
1176 if !me.config.DisablePEX {
1177 ret["ut_pex"] = pexExtendedId
1181 "v": extendedHandshakeClientVersion,
1182 // No upload queue is implemented yet.
1185 if !me.config.DisableEncryption {
1188 if torrent.metadataSizeKnown() {
1189 d["metadata_size"] = torrent.metadataSize()
1191 if p := me.incomingPeerPort(); p != 0 {
1194 yourip, err := addrCompactIP(conn.remoteAddr())
1196 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1198 d["yourip"] = yourip
1200 // log.Printf("sending %v", d)
1201 b, err := bencode.Marshal(d)
1209 if torrent.haveAnyPieces() {
1210 conn.Post(pp.Message{
1212 Bitfield: torrent.bitfield(),
1214 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1215 conn.Post(pp.Message{
1219 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1220 conn.Post(pp.Message{
1222 Port: uint16(AddrPort(me.dHT.Addr())),
1227 // Randomizes the piece order for this connection. Every connection will be
1228 // given a different ordering. Having it stored per connection saves having to
1229 // randomize during request filling, and constantly recalculate the ordering
1230 // based on piece priorities.
1231 func (t *torrent) initRequestOrdering(c *connection) {
1232 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1233 panic("double init of request ordering")
1235 c.piecePriorities = mathRand.Perm(t.numPieces())
1236 c.pieceRequestOrder = pieceordering.New()
1237 for i := range iter.N(t.Info.NumPieces()) {
1238 if !c.PeerHasPiece(i) {
1241 if !t.wantPiece(i) {
1244 t.connPendPiece(c, i)
1248 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1251 if c.PeerPieces == nil {
1252 c.PeerPieces = make([]bool, t.numPieces())
1255 for piece >= len(c.PeerPieces) {
1256 c.PeerPieces = append(c.PeerPieces, false)
1259 c.PeerPieces[piece] = true
1261 if t.wantPiece(piece) {
1262 t.connPendPiece(c, piece)
1263 me.replenishConnRequests(t, c)
1267 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1268 me.replenishConnRequests(torrent, conn)
1271 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1274 postedCancels.Add(1)
1279 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1280 if !cn.RequestPending(r) {
1283 delete(cn.Requests, r)
1287 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1291 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1292 // Peer doesn't support this.
1295 // Request metadata pieces that we don't have in a random order.
1297 for index := 0; index < t.metadataPieceCount(); index++ {
1298 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1299 pending = append(pending, index)
1302 for _, i := range mathRand.Perm(len(pending)) {
1303 c.requestMetadataPiece(pending[i])
1307 func (cl *Client) completedMetadata(t *torrent) {
1311 CopyExact(&ih, h.Sum(nil))
1312 if ih != t.InfoHash {
1313 log.Print("bad metadata")
1314 t.invalidateMetadata()
1317 var info metainfo.Info
1318 err := bencode.Unmarshal(t.MetaData, &info)
1320 log.Printf("error unmarshalling metadata: %s", err)
1321 t.invalidateMetadata()
1324 // TODO(anacrolix): If this fails, I think something harsher should be
1326 err = cl.setMetaData(t, &info, t.MetaData)
1328 log.Printf("error setting metadata: %s", err)
1329 t.invalidateMetadata()
1332 log.Printf("%s: got metadata from peers", t)
1335 // Process incoming ut_metadata message.
1336 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1337 var d map[string]int
1338 err = bencode.Unmarshal(payload, &d)
1340 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1343 msgType, ok := d["msg_type"]
1345 err = errors.New("missing msg_type field")
1350 case pp.DataMetadataExtensionMsgType:
1354 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1355 if begin < 0 || begin >= len(payload) {
1356 log.Printf("got bad metadata piece")
1359 if !c.requestedMetadataPiece(piece) {
1360 log.Printf("got unexpected metadata piece %d", piece)
1363 c.metadataRequests[piece] = false
1364 t.saveMetadataPiece(piece, payload[begin:])
1365 c.UsefulChunksReceived++
1366 c.lastUsefulChunkReceived = time.Now()
1367 if !t.haveAllMetadataPieces() {
1370 cl.completedMetadata(t)
1371 case pp.RequestMetadataExtensionMsgType:
1372 if !t.haveMetadataPiece(piece) {
1373 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1376 start := (1 << 14) * piece
1377 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1378 case pp.RejectMetadataExtensionMsgType:
1380 err = errors.New("unknown msg_type value")
1385 type peerExchangeMessage struct {
1386 Added CompactPeers `bencode:"added"`
1387 AddedFlags []byte `bencode:"added.f"`
1388 Dropped CompactPeers `bencode:"dropped"`
1391 // Extracts the port as an integer from an address string.
1392 func addrPort(addr net.Addr) int {
1393 return AddrPort(addr)
1396 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1397 cn.peerHasAll = true
1400 for i := 0; i < t.numPieces(); i++ {
1401 cl.peerGotPiece(t, cn, i)
1406 func (me *Client) upload(t *torrent, c *connection) {
1407 if me.config.NoUpload {
1410 if !c.PeerInterested {
1413 seeding := me.seeding(t)
1414 if !seeding && !t.connHasWantedPieces(c) {
1418 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1420 for r := range c.PeerRequests {
1421 err := me.sendChunk(t, c, r)
1423 log.Printf("error sending chunk to peer: %s", err)
1425 delete(c.PeerRequests, r)
1433 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1434 b := make([]byte, r.Length)
1435 t.Pieces[r.Index].pendingWrites.Wait()
1436 p := t.Info.Piece(int(r.Index))
1437 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1450 uploadChunksPosted.Add(1)
1452 c.lastChunkSent = time.Now()
1456 // Processes incoming bittorrent messages. The client lock is held upon entry
1458 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1459 decoder := pp.Decoder{
1460 R: bufio.NewReader(c.rw),
1461 MaxLength: 256 * 1024,
1466 err := decoder.Decode(&msg)
1467 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1469 c.lastMessageReceived = time.Now()
1476 if me.stopped() || err == io.EOF {
1487 for r := range c.Requests {
1488 me.connDeleteRequest(t, c, r)
1490 // We can then reset our interest.
1491 me.replenishConnRequests(t, c)
1493 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1494 me.replenishConnRequests(t, c)
1496 c.PeerChoked = false
1497 me.peerUnchoked(t, c)
1499 c.PeerInterested = true
1501 case pp.NotInterested:
1502 c.PeerInterested = false
1505 me.peerGotPiece(t, c, int(msg.Index))
1510 if !c.PeerInterested {
1511 err = errors.New("peer sent request but isn't interested")
1514 if c.PeerRequests == nil {
1515 c.PeerRequests = make(map[request]struct{}, maxRequests)
1517 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1520 req := newRequest(msg.Index, msg.Begin, msg.Length)
1521 if !c.PeerCancel(req) {
1522 unexpectedCancels.Add(1)
1525 if c.PeerPieces != nil || c.peerHasAll {
1526 err = errors.New("received unexpected bitfield")
1530 if len(msg.Bitfield) < t.numPieces() {
1531 err = errors.New("received invalid bitfield")
1534 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1536 c.PeerPieces = msg.Bitfield
1537 for index, has := range c.PeerPieces {
1539 me.peerGotPiece(t, c, index)
1543 if c.PeerPieces != nil || c.peerHasAll {
1544 err = errors.New("unexpected have-all")
1549 if c.peerHasAll || c.PeerPieces != nil {
1550 err = errors.New("unexpected have-none")
1553 c.PeerPieces = make([]bool, func() int {
1555 return t.numPieces()
1561 err = me.downloadedChunk(t, c, &msg)
1563 switch msg.ExtendedID {
1564 case pp.HandshakeExtendedID:
1565 // TODO: Create a bencode struct for this.
1566 var d map[string]interface{}
1567 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1569 err = fmt.Errorf("error decoding extended message payload: %s", err)
1572 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1573 if reqq, ok := d["reqq"]; ok {
1574 if i, ok := reqq.(int64); ok {
1575 c.PeerMaxRequests = int(i)
1578 if v, ok := d["v"]; ok {
1579 c.PeerClientName = v.(string)
1583 err = errors.New("handshake missing m item")
1586 mTyped, ok := m.(map[string]interface{})
1588 err = errors.New("handshake m value is not dict")
1591 if c.PeerExtensionIDs == nil {
1592 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1594 for name, v := range mTyped {
1597 log.Printf("bad handshake m item extension ID type: %T", v)
1601 delete(c.PeerExtensionIDs, name)
1603 if c.PeerExtensionIDs[name] == 0 {
1604 supportedExtensionMessages.Add(name, 1)
1606 c.PeerExtensionIDs[name] = byte(id)
1609 metadata_sizeUntyped, ok := d["metadata_size"]
1611 metadata_size, ok := metadata_sizeUntyped.(int64)
1613 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1615 t.setMetadataSize(metadata_size, me)
1618 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1619 me.requestPendingMetadata(t, c)
1621 case metadataExtendedId:
1622 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1624 err = fmt.Errorf("error handling metadata extension message: %s", err)
1627 if me.config.DisablePEX {
1630 var pexMsg peerExchangeMessage
1631 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1633 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1638 me.addPeers(t, func() (ret []Peer) {
1639 for i, cp := range pexMsg.Added {
1641 IP: make([]byte, 4),
1643 Source: peerSourcePEX,
1645 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1646 p.SupportsEncryption = true
1648 CopyExact(p.IP, cp.IP[:])
1649 ret = append(ret, p)
1654 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1657 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1660 // That client uses its own extension IDs for outgoing message
1661 // types, which is incorrect.
1662 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1663 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1671 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1676 pingAddr.Port = int(msg.Port)
1678 _, err = me.dHT.Ping(pingAddr)
1680 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1688 // Returns true if connection is removed from torrent.Conns.
1689 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1690 for i0, _c := range t.Conns {
1694 i1 := len(t.Conns) - 1
1696 t.Conns[i0] = t.Conns[i1]
1698 t.Conns = t.Conns[:i1]
1704 func (me *Client) dropConnection(t *torrent, c *connection) {
1705 me.event.Broadcast()
1707 if me.deleteConnection(t, c) {
1712 // Returns true if the connection is added.
1713 func (me *Client) addConnection(t *torrent, c *connection) bool {
1718 case <-t.ceasingNetworking:
1722 if !me.wantConns(t) {
1725 for _, c0 := range t.Conns {
1726 if c.PeerID == c0.PeerID {
1727 // Already connected to a client with that ID.
1728 duplicateClientConns.Add(1)
1732 if len(t.Conns) >= socketsPerTorrent {
1733 c := t.worstBadConn(me)
1737 log.Printf("%s: dropping connection to make room for new one: %s", t, c)
1739 me.deleteConnection(t, c)
1741 if len(t.Conns) >= socketsPerTorrent {
1744 t.Conns = append(t.Conns, c)
1748 func (t *torrent) needData() bool {
1752 for i := range t.Pieces {
1760 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1767 return c.supportsExtension("ut_metadata")
1770 return c.PeerInterested
1772 return t.connHasWantedPieces(c)
1775 func (me *Client) wantConns(t *torrent) bool {
1776 if !me.seeding(t) && !t.needData() {
1779 if len(t.Conns) < socketsPerTorrent {
1782 return t.worstBadConn(me) != nil
1785 func (me *Client) openNewConns(t *torrent) {
1787 case <-t.ceasingNetworking:
1791 for len(t.Peers) != 0 {
1792 if !me.wantConns(t) {
1795 if len(t.HalfOpen) >= me.halfOpenLimit {
1802 for k, p = range t.Peers {
1806 me.initiateConn(p, t)
1808 t.wantPeers.Broadcast()
1811 func (me *Client) addPeers(t *torrent, peers []Peer) {
1812 for _, p := range peers {
1813 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1816 if me.ipBlockRange(p.IP) != nil {
1820 log.Printf("got bad peer: %v", p)
1828 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1829 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1832 func (cl *Client) saveTorrentFile(t *torrent) error {
1833 path := cl.cachedMetaInfoFilename(t.InfoHash)
1834 os.MkdirAll(filepath.Dir(path), 0777)
1835 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1837 return fmt.Errorf("error opening file: %s", err)
1840 e := bencode.NewEncoder(f)
1841 err = e.Encode(t.MetaInfo())
1843 return fmt.Errorf("error marshalling metainfo: %s", err)
1845 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1847 // For example, a script kiddy makes us load too many files, and we're
1848 // able to save the torrent, but not load it again to check it.
1851 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1852 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1857 func (cl *Client) startTorrent(t *torrent) {
1858 if t.Info == nil || t.data == nil {
1861 // If the client intends to upload, it needs to know what state pieces are
1863 if !cl.config.NoUpload {
1864 // Queue all pieces for hashing. This is done sequentially to avoid
1865 // spamming goroutines.
1866 for _, p := range t.Pieces {
1867 p.QueuedForHash = true
1870 for i := range t.Pieces {
1871 cl.verifyPiece(t, pp.Integer(i))
1877 // Storage cannot be changed once it's set.
1878 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1879 err = t.setStorage(td)
1880 cl.event.Broadcast()
1884 for index := range iter.N(t.numPieces()) {
1885 cl.pieceChanged(t, index)
1891 type TorrentDataOpener func(*metainfo.Info) data.Data
1893 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1894 err = t.setMetadata(md, bytes, &cl.mu)
1898 if !cl.config.DisableMetainfoCache {
1899 if err := cl.saveTorrentFile(t); err != nil {
1900 log.Printf("error saving torrent file for %s: %s", t, err)
1903 cl.event.Broadcast()
1904 close(t.gotMetainfo)
1905 td := cl.torrentDataOpener(md)
1906 err = cl.setStorage(t, td)
1910 // Prepare a Torrent without any attachment to a Client. That means we can
1911 // initialize fields all fields that don't require the Client without locking
1913 func newTorrent(ih InfoHash) (t *torrent, err error) {
1916 chunkSize: defaultChunkSize,
1917 Peers: make(map[peersKey]Peer),
1919 closing: make(chan struct{}),
1920 ceasingNetworking: make(chan struct{}),
1922 gotMetainfo: make(chan struct{}),
1924 HalfOpen: make(map[string]struct{}),
1926 t.wantPeers.L = &t.stateMu
1931 // For shuffling the tracker tiers.
1932 mathRand.Seed(time.Now().Unix())
1935 // The trackers within each tier must be shuffled before use.
1936 // http://stackoverflow.com/a/12267471/149482
1937 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1938 func shuffleTier(tier []tracker.Client) {
1939 for i := range tier {
1940 j := mathRand.Intn(i + 1)
1941 tier[i], tier[j] = tier[j], tier[i]
1945 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1946 for _, tier := range base {
1947 copy = append(copy, append([]tracker.Client{}, tier...))
1952 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1954 for _, url := range newURLs {
1955 for _, tr := range tier {
1956 if tr.URL() == url {
1960 tr, err := tracker.New(url)
1962 log.Printf("error creating tracker client for %q: %s", url, err)
1965 tier = append(tier, tr)
1970 func (t *torrent) addTrackers(announceList [][]string) {
1971 newTrackers := copyTrackers(t.Trackers)
1972 for tierIndex, tier := range announceList {
1973 if tierIndex < len(newTrackers) {
1974 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1976 newTrackers = append(newTrackers, mergeTier(nil, tier))
1978 shuffleTier(newTrackers[tierIndex])
1980 t.Trackers = newTrackers
1983 // Don't call this before the info is available.
1984 func (t *torrent) BytesCompleted() int64 {
1988 return t.Info.TotalLength() - t.bytesLeft()
1991 // A file-like handle to some torrent data resource.
1992 type Handle interface {
1999 // Returns handles to the files in the torrent. This requires the metainfo is
2001 func (t Torrent) Files() (ret []File) {
2009 for _, fi := range info.UpvertedFiles() {
2010 ret = append(ret, File{
2012 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2022 // Marks the pieces in the given region for download.
2023 func (t Torrent) SetRegionPriority(off, len int64) {
2025 defer t.cl.mu.Unlock()
2026 pieceSize := int64(t.usualPieceSize())
2027 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2028 t.cl.raisePiecePriority(t.torrent, int(i), PiecePriorityNormal)
2032 func (t Torrent) AddPeers(pp []Peer) error {
2035 defer cl.mu.Unlock()
2036 cl.addPeers(t.torrent, pp)
2040 // Marks the entire torrent for download. Requires the info first, see
2042 func (t Torrent) DownloadAll() {
2044 defer t.cl.mu.Unlock()
2045 for i := range iter.N(t.numPieces()) {
2046 t.cl.raisePiecePriority(t.torrent, i, PiecePriorityNormal)
2048 // Nice to have the first and last pieces sooner for various interactive
2050 t.cl.raisePiecePriority(t.torrent, 0, PiecePriorityReadahead)
2051 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, PiecePriorityReadahead)
2054 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2055 // metainfo has the correct infohash.
2056 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2057 if cl.config.DisableMetainfoCache {
2060 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2062 if os.IsNotExist(err) {
2068 dec := bencode.NewDecoder(f)
2069 err = dec.Decode(&mi)
2073 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2074 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2080 // Specifies a new torrent for adding to a client. There are helpers for
2081 // magnet URIs and torrent metainfo files.
2082 type TorrentSpec struct {
2083 // The tiered tracker URIs.
2086 Info *metainfo.InfoEx
2087 // The name to use if the Name field from the Info isn't available.
2089 // The chunk size to use for outbound requests. Defaults to 16KiB if not
2094 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2095 m, err := ParseMagnetURI(uri)
2099 spec = &TorrentSpec{
2100 Trackers: [][]string{m.Trackers},
2101 DisplayName: m.DisplayName,
2102 InfoHash: m.InfoHash,
2107 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2108 spec = &TorrentSpec{
2109 Trackers: mi.AnnounceList,
2111 DisplayName: mi.Info.Name,
2113 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2117 // Add or merge a torrent spec. If the torrent is already present, the
2118 // trackers will be merged with the existing ones. If the Info isn't yet
2119 // known, it will be set. The display name is replaced if the new spec
2120 // provides one. Returns new if the torrent wasn't already in the client.
2121 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2124 defer cl.mu.Unlock()
2126 t, ok := cl.torrents[spec.InfoHash]
2130 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2131 err = errors.New("banned torrent")
2135 t, err = newTorrent(spec.InfoHash)
2139 if spec.ChunkSize != 0 {
2140 t.chunkSize = pp.Integer(spec.ChunkSize)
2143 if spec.DisplayName != "" {
2144 t.DisplayName = spec.DisplayName
2146 // Try to merge in info we have on the torrent. Any err left will
2147 // terminate the function.
2149 if spec.Info != nil {
2150 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2152 var mi *metainfo.MetaInfo
2153 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2155 log.Printf("error getting cached metainfo: %s", err)
2157 } else if mi != nil {
2158 t.addTrackers(mi.AnnounceList)
2159 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2166 t.addTrackers(spec.Trackers)
2168 cl.torrents[spec.InfoHash] = t
2171 // From this point onwards, we can consider the torrent a part of the
2174 if !cl.config.DisableTrackers {
2175 go cl.announceTorrentTrackers(T.torrent)
2178 go cl.announceTorrentDHT(T.torrent, true)
2184 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2185 t, ok := me.torrents[infoHash]
2187 err = fmt.Errorf("no such torrent")
2194 delete(me.torrents, infoHash)
2198 // Returns true when peers are required, or false if the torrent is closing.
2199 func (cl *Client) waitWantPeers(t *torrent) bool {
2201 defer cl.mu.Unlock()
2203 defer t.stateMu.Unlock()
2206 case <-t.ceasingNetworking:
2210 if len(t.Peers) > torrentPeersLowWater {
2213 if t.needData() || cl.seeding(t) {
2225 // Returns whether the client should make effort to seed the torrent.
2226 func (cl *Client) seeding(t *torrent) bool {
2227 if cl.config.NoUpload {
2230 if !cl.config.Seed {
2239 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2240 for cl.waitWantPeers(t) {
2241 log.Printf("getting peers for %q from DHT", t)
2242 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2244 log.Printf("error getting peers from dht: %s", err)
2247 allAddrs := make(map[string]struct{})
2251 case v, ok := <-ps.Peers:
2255 peersFoundByDHT.Add(int64(len(v.Peers)))
2256 for _, p := range v.Peers {
2257 allAddrs[(&net.UDPAddr{
2260 }).String()] = struct{}{}
2262 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2264 cl.addPeers(t, func() (ret []Peer) {
2265 for _, cp := range v.Peers {
2266 ret = append(ret, Peer{
2269 Source: peerSourceDHT,
2274 numPeers := len(t.Peers)
2276 if numPeers >= torrentPeersHighWater {
2279 case <-t.ceasingNetworking:
2285 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2289 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2290 url_, err := url.Parse(tr.URL())
2294 host, _, err := net.SplitHostPort(url_.Host)
2298 addr, err := net.ResolveIPAddr("ip", host)
2303 if cl.ipBlockList != nil {
2304 if cl.ipBlockRange(addr.IP) != nil {
2312 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2313 blocked, err := cl.trackerBlockedUnlocked(tr)
2315 return fmt.Errorf("error determining if tracker blocked: %s", err)
2318 return fmt.Errorf("tracker blocked: %s", tr)
2320 if err := tr.Connect(); err != nil {
2321 return fmt.Errorf("error connecting: %s", err)
2323 resp, err := tr.Announce(req)
2325 return fmt.Errorf("error announcing: %s", err)
2328 for _, peer := range resp.Peers {
2329 peers = append(peers, Peer{
2335 cl.addPeers(t, peers)
2338 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2339 peersFoundByTracker.Add(int64(len(peers)))
2341 time.Sleep(time.Second * time.Duration(resp.Interval))
2345 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2346 oks := make(chan bool)
2348 for _, tier := range trackers {
2349 for _, tr := range tier {
2351 go func(tr tracker.Client) {
2352 err := cl.announceTorrentSingleTracker(tr, req, t)
2357 for outstanding > 0 {
2367 // Announce torrent to its trackers.
2368 func (cl *Client) announceTorrentTrackers(t *torrent) {
2369 req := tracker.AnnounceRequest{
2370 Event: tracker.Started,
2372 Port: uint16(cl.incomingPeerPort()),
2374 InfoHash: t.InfoHash,
2376 if !cl.waitWantPeers(t) {
2380 req.Left = uint64(t.bytesLeft())
2381 trackers := t.Trackers
2383 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2384 req.Event = tracker.None
2387 for cl.waitWantPeers(t) {
2389 req.Left = uint64(t.bytesLeft())
2390 trackers = t.Trackers
2392 numTrackersTried := 0
2393 for _, tier := range trackers {
2394 for trIndex, tr := range tier {
2396 err := cl.announceTorrentSingleTracker(tr, &req, t)
2398 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2401 // Float the successful announce to the top of the tier. If
2402 // the trackers list has been changed, we'll be modifying an
2403 // old copy so it won't matter.
2405 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2408 req.Event = tracker.None
2409 continue newAnnounce
2412 if numTrackersTried != 0 {
2413 log.Printf("%s: all trackers failed", t)
2415 // TODO: Wait until trackers are added if there are none.
2416 time.Sleep(10 * time.Second)
2420 func (cl *Client) allTorrentsCompleted() bool {
2421 for _, t := range cl.torrents {
2425 if t.numPiecesCompleted() != t.numPieces() {
2432 // Returns true when all torrents are completely downloaded and false if the
2433 // client is stopped before that.
2434 func (me *Client) WaitAll() bool {
2436 defer me.mu.Unlock()
2437 for !me.allTorrentsCompleted() {
2446 func (me *Client) fillRequests(t *torrent, c *connection) {
2451 if len(c.Requests) > c.requestsLowWater {
2455 addRequest := func(req request) (again bool) {
2456 // TODO: Couldn't this check also be done *after* the request?
2457 if len(c.Requests) >= 64 {
2460 return c.Request(req)
2462 for req := range t.urgent {
2463 if !addRequest(req) {
2467 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2468 pieceIndex := e.Piece()
2469 if !c.PeerHasPiece(pieceIndex) {
2470 panic("piece in request order but peer doesn't have it")
2472 if !t.wantPiece(pieceIndex) {
2473 panic("unwanted piece in connection request order")
2475 piece := t.Pieces[pieceIndex]
2476 for _, cs := range piece.shuffledPendingChunkSpecs(t.pieceLength(pieceIndex), pp.Integer(t.chunkSize)) {
2477 r := request{pp.Integer(pieceIndex), cs}
2486 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2490 me.fillRequests(t, c)
2491 if len(c.Requests) == 0 && !c.PeerChoked {
2492 // So we're not choked, but we don't want anything right now. We may
2493 // have completed readahead, and the readahead window has not rolled
2494 // over to the next piece. Better to stay interested in case we're
2495 // going to want data in the near future.
2496 c.SetInterested(!t.haveAllPieces())
2500 // Handle a received chunk from a peer.
2501 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2502 chunksReceived.Add(1)
2504 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2506 // Request has been satisfied.
2507 if me.connDeleteRequest(t, c, req) {
2508 defer me.replenishConnRequests(t, c)
2510 unexpectedChunksReceived.Add(1)
2513 piece := t.Pieces[req.Index]
2515 // Do we actually want this chunk?
2516 if !t.wantChunk(req) {
2517 unwantedChunksReceived.Add(1)
2518 c.UnwantedChunksReceived++
2522 c.UsefulChunksReceived++
2523 c.lastUsefulChunkReceived = time.Now()
2527 piece.pendingWrites.Add(1)
2529 defer piece.pendingWrites.Done()
2530 // Write the chunk out.
2531 tr := perf.NewTimer()
2532 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2534 log.Printf("error writing chunk: %s", err)
2537 tr.Stop("write chunk")
2540 // log.Println("got chunk", req)
2541 piece.Event.Broadcast()
2542 // Record that we have the chunk.
2543 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2544 delete(t.urgent, req)
2545 if piece.numPendingChunks() == 0 {
2546 for _, c := range t.Conns {
2547 c.pieceRequestOrder.DeletePiece(int(req.Index))
2549 me.queuePieceCheck(t, req.Index)
2552 // Cancel pending requests for this chunk.
2553 for _, c := range t.Conns {
2554 if me.connCancel(t, c, req) {
2555 me.replenishConnRequests(t, c)
2562 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2563 p := t.Pieces[piece]
2566 pieceHashedCorrect.Add(1)
2568 log.Printf("%s: piece %d failed hash", t, piece)
2569 pieceHashedNotCorrect.Add(1)
2574 err := t.data.PieceCompleted(int(piece))
2576 log.Printf("error completing piece: %s", err)
2580 me.pieceChanged(t, int(piece))
2583 // TODO: Check this isn't called more than once for each piece being correct.
2584 func (me *Client) pieceChanged(t *torrent, piece int) {
2585 correct := t.pieceComplete(piece)
2586 p := t.Pieces[piece]
2587 defer p.Event.Broadcast()
2589 p.Priority = PiecePriorityNone
2590 p.PendingChunkSpecs = nil
2591 for req := range t.urgent {
2592 if int(req.Index) == piece {
2593 delete(t.urgent, req)
2597 if p.numPendingChunks() == 0 {
2598 t.pendAllChunkSpecs(int(piece))
2600 if t.wantPiece(piece) {
2604 for _, conn := range t.Conns {
2606 conn.Post(pp.Message{
2608 Index: pp.Integer(piece),
2610 // TODO: Cancel requests for this piece.
2611 for r := range conn.Requests {
2612 if int(r.Index) == piece {
2616 conn.pieceRequestOrder.DeletePiece(int(piece))
2618 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2619 t.connPendPiece(conn, int(piece))
2620 me.replenishConnRequests(t, conn)
2623 me.event.Broadcast()
2626 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2628 defer cl.mu.Unlock()
2629 p := t.Pieces[index]
2630 for p.Hashing || t.data == nil {
2633 p.QueuedForHash = false
2634 if t.isClosed() || t.pieceComplete(int(index)) {
2639 sum := t.hashPiece(index)
2647 cl.pieceHashed(t, index, sum == p.Hash)
2650 // Returns handles to all the torrents loaded in the Client.
2651 func (me *Client) Torrents() (ret []Torrent) {
2653 for _, t := range me.torrents {
2654 ret = append(ret, Torrent{me, t})
2660 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2661 spec, err := TorrentSpecFromMagnetURI(uri)
2665 T, _, err = me.AddTorrentSpec(spec)
2669 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2670 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2674 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2675 mi, err := metainfo.LoadFromFile(filename)
2679 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))