25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/sync"
29 "github.com/anacrolix/utp"
30 "github.com/bradfitz/iter"
32 "github.com/anacrolix/torrent/bencode"
33 "github.com/anacrolix/torrent/data"
34 filePkg "github.com/anacrolix/torrent/data/file"
35 "github.com/anacrolix/torrent/dht"
36 "github.com/anacrolix/torrent/internal/pieceordering"
37 "github.com/anacrolix/torrent/iplist"
38 "github.com/anacrolix/torrent/logonce"
39 "github.com/anacrolix/torrent/metainfo"
40 "github.com/anacrolix/torrent/mse"
41 pp "github.com/anacrolix/torrent/peer_protocol"
42 "github.com/anacrolix/torrent/tracker"
43 . "github.com/anacrolix/torrent/util"
47 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
48 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
49 chunksReceived = expvar.NewInt("chunksReceived")
51 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
52 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
53 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
55 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
56 unexpectedCancels = expvar.NewInt("unexpectedCancels")
57 postedCancels = expvar.NewInt("postedCancels")
58 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
60 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
61 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
63 unsuccessfulDials = expvar.NewInt("dialSuccessful")
64 successfulDials = expvar.NewInt("dialUnsuccessful")
66 acceptUTP = expvar.NewInt("acceptUTP")
67 acceptTCP = expvar.NewInt("acceptTCP")
68 acceptReject = expvar.NewInt("acceptReject")
70 peerExtensions = expvar.NewMap("peerExtensions")
71 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
72 // Count of connections to peer with same client ID.
73 connsToSelf = expvar.NewInt("connsToSelf")
74 // Number of completed connections to a client we're already connected with.
75 duplicateClientConns = expvar.NewInt("duplicateClientConns")
76 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
77 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
81 // Justification for set bits follows.
83 // Extension protocol ([5]|=0x10):
84 // http://www.bittorrent.org/beps/bep_0010.html
86 // Fast Extension ([7]|=0x04):
87 // http://bittorrent.org/beps/bep_0006.html.
88 // Disabled until AllowedFast is implemented.
91 // http://www.bittorrent.org/beps/bep_0005.html
92 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
94 socketsPerTorrent = 80
95 torrentPeersHighWater = 200
96 torrentPeersLowWater = 50
98 // Limit how long handshake can take. This is to reduce the lingering
99 // impact of a few bad apples. 4s loses 1% of successful handshakes that
100 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
101 btHandshakeTimeout = 4 * time.Second
102 handshakesTimeout = 20 * time.Second
104 // These are our extended message IDs.
105 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
108 // Updated occasionally to when there's been some changes to client
109 // behaviour in case other clients are assuming anything of us. See also
111 extendedHandshakeClientVersion = "go.torrent dev 20150624"
114 // Currently doesn't really queue, but should in the future.
115 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
116 piece := t.Pieces[pieceIndex]
117 if piece.QueuedForHash {
120 piece.QueuedForHash = true
121 go cl.verifyPiece(t, pieceIndex)
124 // Queue a piece check if one isn't already queued, and the piece has never
125 // been checked before.
126 func (cl *Client) queueFirstHash(t *torrent, piece int) {
128 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
131 cl.queuePieceCheck(t, pp.Integer(piece))
134 // Clients contain zero or more Torrents. A client manages a blocklist, the
135 // TCP/UDP protocol ports, and DHT as desired.
139 listeners []net.Listener
142 ipBlockList *iplist.IPList
143 bannedTorrents map[InfoHash]struct{}
145 pruneTimer *time.Timer
146 extensionBytes peerExtensionBytes
147 // Set of addresses that have our client ID. This intentionally will
148 // include ourselves if we end up trying to connect to our own address
149 // through legitimate channels.
150 dopplegangerAddrs map[string]struct{}
152 torrentDataOpener TorrentDataOpener
158 torrents map[InfoHash]*torrent
161 func (me *Client) IPBlockList() *iplist.IPList {
164 return me.ipBlockList
167 func (me *Client) SetIPBlockList(list *iplist.IPList) {
170 me.ipBlockList = list
172 me.dHT.SetIPBlockList(list)
176 func (me *Client) PeerID() string {
177 return string(me.peerID[:])
180 func (me *Client) ListenAddr() (addr net.Addr) {
181 for _, l := range me.listeners {
188 type hashSorter struct {
192 func (me hashSorter) Len() int {
193 return len(me.Hashes)
196 func (me hashSorter) Less(a, b int) bool {
197 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
200 func (me hashSorter) Swap(a, b int) {
201 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
204 func (cl *Client) sortedTorrents() (ret []*torrent) {
206 for ih := range cl.torrents {
207 hs.Hashes = append(hs.Hashes, ih)
210 for _, ih := range hs.Hashes {
211 ret = append(ret, cl.torrent(ih))
216 // Writes out a human readable status of the client, such as for writing to a
218 func (cl *Client) WriteStatus(_w io.Writer) {
220 defer cl.mu.RUnlock()
221 w := bufio.NewWriter(_w)
223 if addr := cl.ListenAddr(); addr != nil {
224 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
226 fmt.Fprintln(w, "Not listening!")
228 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
230 dhtStats := cl.dHT.Stats()
231 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
232 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
233 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
234 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
235 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
237 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
239 for _, t := range cl.sortedTorrents() {
241 fmt.Fprint(w, "<unknown name>")
243 fmt.Fprint(w, t.Name())
247 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
249 w.WriteString("<missing metainfo>")
257 // A Data that implements this has a streaming interface that should be
258 // preferred over ReadAt. For example, the data is stored in blocks on the
259 // network and have a fixed cost to open.
260 type SectionOpener interface {
261 // Open a ReadCloser at the given offset into torrent data. n is how many
262 // bytes we intend to read.
263 OpenSection(off, n int64) (io.ReadCloser, error)
266 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
268 // if err == io.ErrUnexpectedEOF && n != 0 {
272 // log.Println("data read at", len(b), off)
274 if ra, ok := d.(io.ReaderAt); ok {
275 return ra.ReadAt(b, off)
277 if so, ok := d.(SectionOpener); ok {
279 rc, err = so.OpenSection(off, int64(len(b)))
284 return io.ReadFull(rc, b)
286 if dp, ok := super(d); ok {
290 panic(fmt.Sprintf("can't read from %T", d))
293 // Calculates the number of pieces to set to Readahead priority, after the
294 // Now, and Next pieces.
295 func readaheadPieces(readahead, pieceLength int64) (ret int) {
296 // Expand the readahead to fit any partial pieces. Subtract 1 for the
297 // "next" piece that is assigned.
298 ret = int((readahead+pieceLength-1)/pieceLength - 1)
299 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
300 // piece length is much larger than the readahead.
307 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
308 index := int(off / int64(t.usualPieceSize()))
309 cl.raisePiecePriority(t, index, PiecePriorityNow)
311 if index >= t.numPieces() {
314 cl.raisePiecePriority(t, index, PiecePriorityNext)
315 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
317 if index >= t.numPieces() {
320 cl.raisePiecePriority(t, index, PiecePriorityReadahead)
324 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
326 req, ok := t.offsetRequest(off)
330 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
332 t.urgent = make(map[request]struct{}, (n+int(t.chunkSize)-1)/int(t.chunkSize))
334 t.urgent[req] = struct{}{}
335 cl.event.Broadcast() // Why?
336 index := int(req.Index)
337 cl.queueFirstHash(t, index)
338 cl.pieceChanged(t, index)
340 reqOff := t.requestOffset(req)
341 n1 := req.Length - pp.Integer(off-reqOff)
345 // log.Print(t.urgent)
348 func (cl *Client) configDir() string {
349 if cl.config.ConfigDir == "" {
350 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
352 return cl.config.ConfigDir
355 // The directory where the Client expects to find and store configuration
356 // data. Defaults to $HOME/.config/torrent.
357 func (cl *Client) ConfigDir() string {
358 return cl.configDir()
361 func (t *torrent) connPendPiece(c *connection, piece int) {
362 c.pendPiece(piece, t.Pieces[piece].Priority)
365 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
366 if t.Pieces[piece].Priority < priority {
367 cl.prioritizePiece(t, piece, priority)
371 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
372 if t.havePiece(piece) {
373 priority = PiecePriorityNone
375 if priority != PiecePriorityNone {
376 cl.queueFirstHash(t, piece)
379 if p.Priority != priority {
380 p.Priority = priority
381 cl.pieceChanged(t, piece)
385 func (cl *Client) setEnvBlocklist() (err error) {
386 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
387 defaultBlocklist := filename == ""
388 if defaultBlocklist {
389 filename = filepath.Join(cl.configDir(), "blocklist")
391 f, err := os.Open(filename)
393 if defaultBlocklist {
399 cl.ipBlockList, err = iplist.NewFromReader(f)
403 func (cl *Client) initBannedTorrents() error {
404 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
406 if os.IsNotExist(err) {
409 return fmt.Errorf("error opening banned infohashes file: %s", err)
412 scanner := bufio.NewScanner(f)
413 cl.bannedTorrents = make(map[InfoHash]struct{})
415 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
419 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
421 return fmt.Errorf("error reading infohash: %s", err)
427 return errors.New("bad infohash")
431 cl.bannedTorrents[ih] = struct{}{}
433 if err := scanner.Err(); err != nil {
434 return fmt.Errorf("error scanning file: %s", err)
439 // Creates a new client.
440 func NewClient(cfg *Config) (cl *Client, err error) {
451 halfOpenLimit: socketsPerTorrent,
453 torrentDataOpener: func(md *metainfo.Info) data.Data {
454 return filePkg.TorrentData(md, cfg.DataDir)
456 dopplegangerAddrs: make(map[string]struct{}),
458 quit: make(chan struct{}),
459 torrents: make(map[InfoHash]*torrent),
461 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
463 if cfg.TorrentDataOpener != nil {
464 cl.torrentDataOpener = cfg.TorrentDataOpener
467 if cfg.IPBlocklist != nil {
468 cl.ipBlockList = cfg.IPBlocklist
469 } else if !cfg.NoDefaultBlocklist {
470 err = cl.setEnvBlocklist()
476 if err = cl.initBannedTorrents(); err != nil {
477 err = fmt.Errorf("error initing banned torrents: %s", err)
481 if cfg.PeerID != "" {
482 CopyExact(&cl.peerID, cfg.PeerID)
484 o := copy(cl.peerID[:], bep20)
485 _, err = rand.Read(cl.peerID[o:])
487 panic("error generating peer id")
491 // Returns the laddr string to listen on for the next Listen call.
492 listenAddr := func() string {
493 if addr := cl.ListenAddr(); addr != nil {
496 if cfg.ListenAddr == "" {
499 return cfg.ListenAddr
501 if !cl.config.DisableTCP {
503 l, err = net.Listen(func() string {
504 if cl.config.DisableIPv6 {
513 cl.listeners = append(cl.listeners, l)
514 go cl.acceptConnections(l, false)
516 if !cl.config.DisableUTP {
517 cl.utpSock, err = utp.NewSocket(func() string {
518 if cl.config.DisableIPv6 {
527 cl.listeners = append(cl.listeners, cl.utpSock)
528 go cl.acceptConnections(cl.utpSock, true)
531 dhtCfg := cfg.DHTConfig
533 dhtCfg = &dht.ServerConfig{}
535 if dhtCfg.IPBlocklist == nil {
536 dhtCfg.IPBlocklist = cl.ipBlockList
538 if dhtCfg.Addr == "" {
539 dhtCfg.Addr = listenAddr()
541 if dhtCfg.Conn == nil && cl.utpSock != nil {
542 dhtCfg.Conn = cl.utpSock.PacketConn()
544 cl.dHT, err = dht.NewServer(dhtCfg)
553 func (cl *Client) stopped() bool {
562 // Stops the client. All connections to peers are closed and all activity will
564 func (me *Client) Close() {
576 for _, l := range me.listeners {
579 for _, t := range me.torrents {
585 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
587 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
588 if cl.ipBlockList == nil {
593 log.Printf("blocking non-IPv4 address: %s", ip)
597 r = cl.ipBlockList.Lookup(ip4)
601 func (cl *Client) waitAccept() {
605 for _, t := range cl.torrents {
619 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
622 // We accept all connections immediately, because we don't know what
623 // torrent they're for.
624 conn, err := l.Accept()
643 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
644 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
646 if blockRange != nil || doppleganger {
648 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
652 go cl.incomingConnection(conn, utp)
656 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
658 if tc, ok := nc.(*net.TCPConn); ok {
664 c.Discovery = peerSourceIncoming
666 err := cl.runReceivedConn(c)
672 // Returns a handle to the given torrent, if it's present in the client.
673 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
676 t, ok := cl.torrents[ih]
684 func (me *Client) torrent(ih InfoHash) *torrent {
685 return me.torrents[ih]
688 type dialResult struct {
693 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
694 conn, err := dial(addr, t)
699 conn = nil // Pedantic
701 ch <- dialResult{conn, utp}
703 successfulDials.Add(1)
706 unsuccessfulDials.Add(1)
709 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
710 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
711 if ret < minDialTimeout {
717 func (me *Client) dopplegangerAddr(addr string) bool {
718 _, ok := me.dopplegangerAddrs[addr]
722 // Start the process of connecting to the given peer for the given torrent if
724 func (me *Client) initiateConn(peer Peer, t *torrent) {
725 if peer.Id == me.peerID {
728 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
729 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
730 duplicateConnsAvoided.Add(1)
733 if r := me.ipBlockRange(peer.IP); r != nil {
734 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
737 t.HalfOpen[addr] = struct{}{}
738 go me.outgoingConnection(t, addr, peer.Source)
741 func (me *Client) dialTimeout(t *torrent) time.Duration {
743 pendingPeers := len(t.Peers)
745 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
748 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
749 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
751 c.(*net.TCPConn).SetLinger(0)
756 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
757 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
760 // Returns a connection over UTP or TCP, whichever is first to connect.
761 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
762 // Initiate connections via TCP and UTP simultaneously. Use the first one
765 if !me.config.DisableUTP {
768 if !me.config.DisableTCP {
771 resCh := make(chan dialResult, left)
772 if !me.config.DisableUTP {
773 go doDial(me.dialUTP, resCh, true, addr, t)
775 if !me.config.DisableTCP {
776 go doDial(me.dialTCP, resCh, false, addr, t)
779 // Wait for a successful connection.
780 for ; left > 0 && res.Conn == nil; left-- {
784 // There are still incompleted dials.
786 for ; left > 0; left-- {
787 conn := (<-resCh).Conn
799 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
800 if _, ok := t.HalfOpen[addr]; !ok {
801 panic("invariant broken")
803 delete(t.HalfOpen, addr)
807 // Performs initiator handshakes and returns a connection.
808 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
812 c.encrypted = encrypted
814 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
818 ok, err := me.initiateHandshakes(c, t)
825 // Returns nil connection and nil error if no connection could be established
826 // for valid reasons.
827 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
828 nc, utp := me.dialFirst(addr, t)
832 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
840 if me.config.DisableEncryption {
841 // We already tried without encryption.
844 // Try again without encryption, using whichever protocol type worked last
847 nc, err = me.dialUTP(addr, t)
849 nc, err = me.dialTCP(addr, t)
852 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
855 c, err = me.handshakesConnection(nc, t, false, utp)
862 // Called to dial out and run a connection. The addr we're given is already
863 // considered half-open.
864 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
865 c, err := me.establishOutgoingConn(t, addr)
868 // Don't release lock between here and addConnection, unless it's for
870 me.noLongerHalfOpen(t, addr)
879 err = me.runInitiatedHandshookConn(c, t)
885 // The port number for incoming peer connections. 0 if the client isn't
887 func (cl *Client) incomingPeerPort() int {
888 listenAddr := cl.ListenAddr()
889 if listenAddr == nil {
892 return addrPort(listenAddr)
895 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
896 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
897 func addrCompactIP(addr net.Addr) (string, error) {
898 host, _, err := net.SplitHostPort(addr.String())
902 ip := net.ParseIP(host)
903 if v4 := ip.To4(); v4 != nil {
907 return string(v4), nil
909 return string(ip.To16()), nil
912 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
924 peerExtensionBytes [8]byte
928 func (me *peerExtensionBytes) SupportsExtended() bool {
929 return me[5]&0x10 != 0
932 func (me *peerExtensionBytes) SupportsDHT() bool {
933 return me[7]&0x01 != 0
936 func (me *peerExtensionBytes) SupportsFast() bool {
937 return me[7]&0x04 != 0
940 type handshakeResult struct {
946 // ih is nil if we expect the peer to declare the InfoHash, such as when the
947 // peer initiated the connection. Returns ok if the handshake was successful,
948 // and err if there was an unexpected condition other than the peer simply
949 // abandoning the handshake.
950 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
951 // Bytes to be sent to the peer. Should never block the sender.
952 postCh := make(chan []byte, 4)
953 // A single error value sent when the writer completes.
954 writeDone := make(chan error, 1)
955 // Performs writes to the socket and ensures posts don't block.
956 go handshakeWriter(sock, postCh, writeDone)
959 close(postCh) // Done writing.
966 // Wait until writes complete before returning from handshake.
969 err = fmt.Errorf("error writing: %s", err)
973 post := func(bb []byte) {
977 panic("mustn't block while posting")
981 post([]byte(pp.Protocol))
983 if ih != nil { // We already know what we want.
988 _, err = io.ReadFull(sock, b[:68])
993 if string(b[:20]) != pp.Protocol {
996 CopyExact(&res.peerExtensionBytes, b[20:28])
997 CopyExact(&res.InfoHash, b[28:48])
998 CopyExact(&res.peerID, b[48:68])
999 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
1001 // TODO: Maybe we can just drop peers here if we're not interested. This
1002 // could prevent them trying to reconnect, falsely believing there was
1004 if ih == nil { // We were waiting for the peer to tell us what they wanted.
1005 post(res.InfoHash[:])
1013 // Wraps a raw connection and provides the interface we want for using the
1014 // connection in the message loop.
1015 type deadlineReader struct {
1020 func (me deadlineReader) Read(b []byte) (n int, err error) {
1021 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1022 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1024 err = fmt.Errorf("error setting read deadline: %s", err)
1026 n, err = me.r.Read(b)
1027 // Convert common errors into io.EOF.
1029 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1031 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1041 type readWriter struct {
1046 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1047 var protocol [len(pp.Protocol)]byte
1048 _, err = io.ReadFull(rw, protocol[:])
1053 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1056 if string(protocol[:]) == pp.Protocol {
1060 ret, err = mse.ReceiveHandshake(ret, skeys)
1064 func (cl *Client) receiveSkeys() (ret [][]byte) {
1065 for ih := range cl.torrents {
1066 ret = append(ret, ih[:])
1071 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1073 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1078 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1079 if ih != t.InfoHash {
1085 // Do encryption and bittorrent handshakes as receiver.
1086 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1088 skeys := cl.receiveSkeys()
1090 if !cl.config.DisableEncryption {
1091 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1093 if err == mse.ErrNoSecretKeyMatch {
1099 ih, ok, err := cl.connBTHandshake(c, nil)
1101 err = fmt.Errorf("error during bt handshake: %s", err)
1113 // Returns !ok if handshake failed for valid reasons.
1114 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1115 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1116 if err != nil || !ok {
1120 c.PeerExtensionBytes = res.peerExtensionBytes
1121 c.PeerID = res.peerID
1122 c.completedHandshake = time.Now()
1126 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1127 if c.PeerID == cl.peerID {
1128 // Only if we initiated the connection is the remote address a
1129 // listen addr for a doppleganger.
1131 addr := c.conn.RemoteAddr().String()
1132 cl.dopplegangerAddrs[addr] = struct{}{}
1135 return cl.runHandshookConn(c, t)
1138 func (cl *Client) runReceivedConn(c *connection) (err error) {
1139 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1143 t, err := cl.receiveHandshakes(c)
1145 err = fmt.Errorf("error receiving handshakes: %s", err)
1152 defer cl.mu.Unlock()
1153 if c.PeerID == cl.peerID {
1156 return cl.runHandshookConn(c, t)
1159 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1160 c.conn.SetWriteDeadline(time.Time{})
1162 deadlineReader{c.conn, c.rw},
1165 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1166 if !cl.addConnection(t, c) {
1169 defer cl.dropConnection(t, c)
1171 go c.writeOptimizer(time.Minute)
1172 cl.sendInitialMessages(c, t)
1174 t.initRequestOrdering(c)
1176 err = cl.connectionLoop(t, c)
1178 err = fmt.Errorf("error during connection loop: %s", err)
1183 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1184 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1185 conn.Post(pp.Message{
1187 ExtendedID: pp.HandshakeExtendedID,
1188 ExtendedPayload: func() []byte {
1189 d := map[string]interface{}{
1190 "m": func() (ret map[string]int) {
1191 ret = make(map[string]int, 2)
1192 ret["ut_metadata"] = metadataExtendedId
1193 if !me.config.DisablePEX {
1194 ret["ut_pex"] = pexExtendedId
1198 "v": extendedHandshakeClientVersion,
1199 // No upload queue is implemented yet.
1202 if !me.config.DisableEncryption {
1205 if torrent.metadataSizeKnown() {
1206 d["metadata_size"] = torrent.metadataSize()
1208 if p := me.incomingPeerPort(); p != 0 {
1211 yourip, err := addrCompactIP(conn.remoteAddr())
1213 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1215 d["yourip"] = yourip
1217 // log.Printf("sending %v", d)
1218 b, err := bencode.Marshal(d)
1226 if torrent.haveAnyPieces() {
1227 conn.Post(pp.Message{
1229 Bitfield: torrent.bitfield(),
1231 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1232 conn.Post(pp.Message{
1236 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1237 conn.Post(pp.Message{
1239 Port: uint16(AddrPort(me.dHT.Addr())),
1244 // Randomizes the piece order for this connection. Every connection will be
1245 // given a different ordering. Having it stored per connection saves having to
1246 // randomize during request filling, and constantly recalculate the ordering
1247 // based on piece priorities.
1248 func (t *torrent) initRequestOrdering(c *connection) {
1249 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1250 panic("double init of request ordering")
1252 c.piecePriorities = mathRand.Perm(t.numPieces())
1253 c.pieceRequestOrder = pieceordering.New()
1254 for i := range iter.N(t.Info.NumPieces()) {
1255 if !c.PeerHasPiece(i) {
1258 if !t.wantPiece(i) {
1261 t.connPendPiece(c, i)
1265 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
1268 if c.PeerPieces == nil {
1269 c.PeerPieces = make([]bool, t.numPieces())
1272 for piece >= len(c.PeerPieces) {
1273 c.PeerPieces = append(c.PeerPieces, false)
1276 if piece >= len(c.PeerPieces) {
1277 return errors.New("peer got out of range piece index")
1279 c.PeerPieces[piece] = true
1281 if t.wantPiece(piece) {
1282 t.connPendPiece(c, piece)
1283 me.replenishConnRequests(t, c)
1288 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1289 me.replenishConnRequests(torrent, conn)
1292 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1295 postedCancels.Add(1)
1300 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1301 if !cn.RequestPending(r) {
1304 delete(cn.Requests, r)
1308 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1312 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1313 // Peer doesn't support this.
1316 // Request metadata pieces that we don't have in a random order.
1318 for index := 0; index < t.metadataPieceCount(); index++ {
1319 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1320 pending = append(pending, index)
1323 for _, i := range mathRand.Perm(len(pending)) {
1324 c.requestMetadataPiece(pending[i])
1328 func (cl *Client) completedMetadata(t *torrent) {
1332 CopyExact(&ih, h.Sum(nil))
1333 if ih != t.InfoHash {
1334 log.Print("bad metadata")
1335 t.invalidateMetadata()
1338 var info metainfo.Info
1339 err := bencode.Unmarshal(t.MetaData, &info)
1341 log.Printf("error unmarshalling metadata: %s", err)
1342 t.invalidateMetadata()
1345 // TODO(anacrolix): If this fails, I think something harsher should be
1347 err = cl.setMetaData(t, &info, t.MetaData)
1349 log.Printf("error setting metadata: %s", err)
1350 t.invalidateMetadata()
1353 log.Printf("%s: got metadata from peers", t)
1356 // Process incoming ut_metadata message.
1357 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1358 var d map[string]int
1359 err = bencode.Unmarshal(payload, &d)
1361 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1364 msgType, ok := d["msg_type"]
1366 err = errors.New("missing msg_type field")
1371 case pp.DataMetadataExtensionMsgType:
1375 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1376 if begin < 0 || begin >= len(payload) {
1377 log.Printf("got bad metadata piece")
1380 if !c.requestedMetadataPiece(piece) {
1381 log.Printf("got unexpected metadata piece %d", piece)
1384 c.metadataRequests[piece] = false
1385 t.saveMetadataPiece(piece, payload[begin:])
1386 c.UsefulChunksReceived++
1387 c.lastUsefulChunkReceived = time.Now()
1388 if !t.haveAllMetadataPieces() {
1391 cl.completedMetadata(t)
1392 case pp.RequestMetadataExtensionMsgType:
1393 if !t.haveMetadataPiece(piece) {
1394 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1397 start := (1 << 14) * piece
1398 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1399 case pp.RejectMetadataExtensionMsgType:
1401 err = errors.New("unknown msg_type value")
1406 type peerExchangeMessage struct {
1407 Added CompactPeers `bencode:"added"`
1408 AddedFlags []byte `bencode:"added.f"`
1409 Dropped CompactPeers `bencode:"dropped"`
1412 // Extracts the port as an integer from an address string.
1413 func addrPort(addr net.Addr) int {
1414 return AddrPort(addr)
1417 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1418 cn.peerHasAll = true
1421 for i := 0; i < t.numPieces(); i++ {
1422 cl.peerGotPiece(t, cn, i)
1427 func (me *Client) upload(t *torrent, c *connection) {
1428 if me.config.NoUpload {
1431 if !c.PeerInterested {
1434 seeding := me.seeding(t)
1435 if !seeding && !t.connHasWantedPieces(c) {
1439 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1441 for r := range c.PeerRequests {
1442 err := me.sendChunk(t, c, r)
1444 log.Printf("error sending chunk to peer: %s", err)
1446 delete(c.PeerRequests, r)
1454 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1455 b := make([]byte, r.Length)
1456 tp := t.Pieces[r.Index]
1457 tp.pendingWritesMutex.Lock()
1458 for tp.pendingWrites != 0 {
1459 tp.noPendingWrites.Wait()
1461 tp.pendingWritesMutex.Unlock()
1462 p := t.Info.Piece(int(r.Index))
1463 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1476 uploadChunksPosted.Add(1)
1478 c.lastChunkSent = time.Now()
1482 // Processes incoming bittorrent messages. The client lock is held upon entry
1484 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1485 decoder := pp.Decoder{
1486 R: bufio.NewReader(c.rw),
1487 MaxLength: 256 * 1024,
1492 err := decoder.Decode(&msg)
1493 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1495 c.lastMessageReceived = time.Now()
1502 if me.stopped() || err == io.EOF {
1513 for r := range c.Requests {
1514 me.connDeleteRequest(t, c, r)
1516 // We can then reset our interest.
1517 me.replenishConnRequests(t, c)
1519 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1520 me.replenishConnRequests(t, c)
1522 c.PeerChoked = false
1523 me.peerUnchoked(t, c)
1525 c.PeerInterested = true
1527 case pp.NotInterested:
1528 c.PeerInterested = false
1531 me.peerGotPiece(t, c, int(msg.Index))
1536 if !c.PeerInterested {
1537 err = errors.New("peer sent request but isn't interested")
1540 if c.PeerRequests == nil {
1541 c.PeerRequests = make(map[request]struct{}, maxRequests)
1543 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1546 req := newRequest(msg.Index, msg.Begin, msg.Length)
1547 if !c.PeerCancel(req) {
1548 unexpectedCancels.Add(1)
1551 if c.PeerPieces != nil || c.peerHasAll {
1552 err = errors.New("received unexpected bitfield")
1556 if len(msg.Bitfield) < t.numPieces() {
1557 err = errors.New("received invalid bitfield")
1560 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1562 c.PeerPieces = msg.Bitfield
1563 for index, has := range c.PeerPieces {
1565 me.peerGotPiece(t, c, index)
1569 if c.PeerPieces != nil || c.peerHasAll {
1570 err = errors.New("unexpected have-all")
1575 if c.peerHasAll || c.PeerPieces != nil {
1576 err = errors.New("unexpected have-none")
1579 c.PeerPieces = make([]bool, func() int {
1581 return t.numPieces()
1587 err = me.downloadedChunk(t, c, &msg)
1589 switch msg.ExtendedID {
1590 case pp.HandshakeExtendedID:
1591 // TODO: Create a bencode struct for this.
1592 var d map[string]interface{}
1593 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1595 err = fmt.Errorf("error decoding extended message payload: %s", err)
1598 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1599 if reqq, ok := d["reqq"]; ok {
1600 if i, ok := reqq.(int64); ok {
1601 c.PeerMaxRequests = int(i)
1604 if v, ok := d["v"]; ok {
1605 c.PeerClientName = v.(string)
1609 err = errors.New("handshake missing m item")
1612 mTyped, ok := m.(map[string]interface{})
1614 err = errors.New("handshake m value is not dict")
1617 if c.PeerExtensionIDs == nil {
1618 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1620 for name, v := range mTyped {
1623 log.Printf("bad handshake m item extension ID type: %T", v)
1627 delete(c.PeerExtensionIDs, name)
1629 if c.PeerExtensionIDs[name] == 0 {
1630 supportedExtensionMessages.Add(name, 1)
1632 c.PeerExtensionIDs[name] = byte(id)
1635 metadata_sizeUntyped, ok := d["metadata_size"]
1637 metadata_size, ok := metadata_sizeUntyped.(int64)
1639 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1641 t.setMetadataSize(metadata_size, me)
1644 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1645 me.requestPendingMetadata(t, c)
1647 case metadataExtendedId:
1648 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1650 err = fmt.Errorf("error handling metadata extension message: %s", err)
1653 if me.config.DisablePEX {
1656 var pexMsg peerExchangeMessage
1657 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1659 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1664 me.addPeers(t, func() (ret []Peer) {
1665 for i, cp := range pexMsg.Added {
1667 log.Printf("peer gave zero port peer over PEX\n\t%s", c)
1671 IP: make([]byte, 4),
1673 Source: peerSourcePEX,
1675 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1676 p.SupportsEncryption = true
1678 CopyExact(p.IP, cp.IP[:])
1679 ret = append(ret, p)
1684 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1687 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1690 // That client uses its own extension IDs for outgoing message
1691 // types, which is incorrect.
1692 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1693 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1701 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1706 pingAddr.Port = int(msg.Port)
1708 _, err = me.dHT.Ping(pingAddr)
1710 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1718 // Returns true if connection is removed from torrent.Conns.
1719 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1720 for i0, _c := range t.Conns {
1724 i1 := len(t.Conns) - 1
1726 t.Conns[i0] = t.Conns[i1]
1728 t.Conns = t.Conns[:i1]
1734 func (me *Client) dropConnection(t *torrent, c *connection) {
1735 me.event.Broadcast()
1737 if me.deleteConnection(t, c) {
1742 // Returns true if the connection is added.
1743 func (me *Client) addConnection(t *torrent, c *connection) bool {
1748 case <-t.ceasingNetworking:
1752 if !me.wantConns(t) {
1755 for _, c0 := range t.Conns {
1756 if c.PeerID == c0.PeerID {
1757 // Already connected to a client with that ID.
1758 duplicateClientConns.Add(1)
1762 if len(t.Conns) >= socketsPerTorrent {
1763 c := t.worstBadConn(me)
1767 if missinggo.CryHeard() {
1768 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1771 me.deleteConnection(t, c)
1773 if len(t.Conns) >= socketsPerTorrent {
1776 t.Conns = append(t.Conns, c)
1780 func (t *torrent) needData() bool {
1784 if len(t.urgent) != 0 {
1787 for _, p := range t.Pieces {
1788 if p.Priority != PiecePriorityNone {
1795 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1802 return c.supportsExtension("ut_metadata")
1805 return c.PeerInterested
1807 return t.connHasWantedPieces(c)
1810 func (me *Client) wantConns(t *torrent) bool {
1811 if !me.seeding(t) && !t.needData() {
1814 if len(t.Conns) < socketsPerTorrent {
1817 return t.worstBadConn(me) != nil
1820 func (me *Client) openNewConns(t *torrent) {
1822 case <-t.ceasingNetworking:
1826 for len(t.Peers) != 0 {
1827 if !me.wantConns(t) {
1830 if len(t.HalfOpen) >= me.halfOpenLimit {
1837 for k, p = range t.Peers {
1841 me.initiateConn(p, t)
1843 t.wantPeers.Broadcast()
1846 func (me *Client) addPeers(t *torrent, peers []Peer) {
1847 for _, p := range peers {
1848 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1851 if me.ipBlockRange(p.IP) != nil {
1855 log.Printf("got bad peer: %v", p)
1863 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1864 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1867 func (cl *Client) saveTorrentFile(t *torrent) error {
1868 path := cl.cachedMetaInfoFilename(t.InfoHash)
1869 os.MkdirAll(filepath.Dir(path), 0777)
1870 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1872 return fmt.Errorf("error opening file: %s", err)
1875 e := bencode.NewEncoder(f)
1876 err = e.Encode(t.MetaInfo())
1878 return fmt.Errorf("error marshalling metainfo: %s", err)
1880 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1882 // For example, a script kiddy makes us load too many files, and we're
1883 // able to save the torrent, but not load it again to check it.
1886 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1887 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1892 func (cl *Client) startTorrent(t *torrent) {
1893 if t.Info == nil || t.data == nil {
1896 // If the client intends to upload, it needs to know what state pieces are
1898 if !cl.config.NoUpload {
1899 // Queue all pieces for hashing. This is done sequentially to avoid
1900 // spamming goroutines.
1901 for _, p := range t.Pieces {
1902 p.QueuedForHash = true
1905 for i := range t.Pieces {
1906 cl.verifyPiece(t, pp.Integer(i))
1912 // Storage cannot be changed once it's set.
1913 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1914 err = t.setStorage(td)
1915 cl.event.Broadcast()
1923 type TorrentDataOpener func(*metainfo.Info) data.Data
1925 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1926 err = t.setMetadata(md, bytes, &cl.mu)
1930 if !cl.config.DisableMetainfoCache {
1931 if err := cl.saveTorrentFile(t); err != nil {
1932 log.Printf("error saving torrent file for %s: %s", t, err)
1935 cl.event.Broadcast()
1936 close(t.gotMetainfo)
1937 td := cl.torrentDataOpener(md)
1938 err = cl.setStorage(t, td)
1942 // Prepare a Torrent without any attachment to a Client. That means we can
1943 // initialize fields all fields that don't require the Client without locking
1945 func newTorrent(ih InfoHash) (t *torrent, err error) {
1948 chunkSize: defaultChunkSize,
1949 Peers: make(map[peersKey]Peer),
1951 closing: make(chan struct{}),
1952 ceasingNetworking: make(chan struct{}),
1954 gotMetainfo: make(chan struct{}),
1956 HalfOpen: make(map[string]struct{}),
1958 t.wantPeers.L = &t.stateMu
1963 // For shuffling the tracker tiers.
1964 mathRand.Seed(time.Now().Unix())
1967 // The trackers within each tier must be shuffled before use.
1968 // http://stackoverflow.com/a/12267471/149482
1969 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1970 func shuffleTier(tier []tracker.Client) {
1971 for i := range tier {
1972 j := mathRand.Intn(i + 1)
1973 tier[i], tier[j] = tier[j], tier[i]
1977 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1978 for _, tier := range base {
1979 copy = append(copy, append([]tracker.Client{}, tier...))
1984 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1986 for _, url := range newURLs {
1987 for _, tr := range tier {
1988 if tr.URL() == url {
1992 tr, err := tracker.New(url)
1994 log.Printf("error creating tracker client for %q: %s", url, err)
1997 tier = append(tier, tr)
2002 func (t *torrent) addTrackers(announceList [][]string) {
2003 newTrackers := copyTrackers(t.Trackers)
2004 for tierIndex, tier := range announceList {
2005 if tierIndex < len(newTrackers) {
2006 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
2008 newTrackers = append(newTrackers, mergeTier(nil, tier))
2010 shuffleTier(newTrackers[tierIndex])
2012 t.Trackers = newTrackers
2015 // Don't call this before the info is available.
2016 func (t *torrent) bytesCompleted() int64 {
2020 return t.Info.TotalLength() - t.bytesLeft()
2023 // A file-like handle to some torrent data resource.
2024 type Handle interface {
2031 // Returns handles to the files in the torrent. This requires the metainfo is
2033 func (t Torrent) Files() (ret []File) {
2041 for _, fi := range info.UpvertedFiles() {
2042 ret = append(ret, File{
2044 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2054 // Marks the pieces in the given region for download.
2055 func (t Torrent) SetRegionPriority(off, len int64) {
2057 defer t.cl.mu.Unlock()
2058 pieceSize := int64(t.usualPieceSize())
2059 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2060 t.cl.raisePiecePriority(t.torrent, int(i), PiecePriorityNormal)
2064 func (t Torrent) AddPeers(pp []Peer) error {
2067 defer cl.mu.Unlock()
2068 cl.addPeers(t.torrent, pp)
2072 // Marks the entire torrent for download. Requires the info first, see
2074 func (t Torrent) DownloadAll() {
2076 defer t.cl.mu.Unlock()
2077 for i := range iter.N(t.numPieces()) {
2078 t.cl.raisePiecePriority(t.torrent, i, PiecePriorityNormal)
2080 // Nice to have the first and last pieces sooner for various interactive
2082 t.cl.raisePiecePriority(t.torrent, 0, PiecePriorityReadahead)
2083 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, PiecePriorityReadahead)
2086 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2087 // metainfo has the correct infohash.
2088 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2089 if cl.config.DisableMetainfoCache {
2092 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2094 if os.IsNotExist(err) {
2100 dec := bencode.NewDecoder(f)
2101 err = dec.Decode(&mi)
2105 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2106 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2112 // Specifies a new torrent for adding to a client. There are helpers for
2113 // magnet URIs and torrent metainfo files.
2114 type TorrentSpec struct {
2115 // The tiered tracker URIs.
2118 Info *metainfo.InfoEx
2119 // The name to use if the Name field from the Info isn't available.
2121 // The chunk size to use for outbound requests. Defaults to 16KiB if not
2126 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2127 m, err := ParseMagnetURI(uri)
2131 spec = &TorrentSpec{
2132 Trackers: [][]string{m.Trackers},
2133 DisplayName: m.DisplayName,
2134 InfoHash: m.InfoHash,
2139 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2140 spec = &TorrentSpec{
2141 Trackers: mi.AnnounceList,
2143 DisplayName: mi.Info.Name,
2145 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2149 // Add or merge a torrent spec. If the torrent is already present, the
2150 // trackers will be merged with the existing ones. If the Info isn't yet
2151 // known, it will be set. The display name is replaced if the new spec
2152 // provides one. Returns new if the torrent wasn't already in the client.
2153 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2156 defer cl.mu.Unlock()
2158 t, ok := cl.torrents[spec.InfoHash]
2162 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2163 err = errors.New("banned torrent")
2167 t, err = newTorrent(spec.InfoHash)
2171 if spec.ChunkSize != 0 {
2172 t.chunkSize = pp.Integer(spec.ChunkSize)
2175 if spec.DisplayName != "" {
2176 t.DisplayName = spec.DisplayName
2178 // Try to merge in info we have on the torrent. Any err left will
2179 // terminate the function.
2181 if spec.Info != nil {
2182 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2184 var mi *metainfo.MetaInfo
2185 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2187 log.Printf("error getting cached metainfo: %s", err)
2189 } else if mi != nil {
2190 t.addTrackers(mi.AnnounceList)
2191 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2198 t.addTrackers(spec.Trackers)
2200 cl.torrents[spec.InfoHash] = t
2203 // From this point onwards, we can consider the torrent a part of the
2206 if !cl.config.DisableTrackers {
2207 go cl.announceTorrentTrackers(T.torrent)
2210 go cl.announceTorrentDHT(T.torrent, true)
2216 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2217 t, ok := me.torrents[infoHash]
2219 err = fmt.Errorf("no such torrent")
2226 delete(me.torrents, infoHash)
2230 // Returns true when peers are required, or false if the torrent is closing.
2231 func (cl *Client) waitWantPeers(t *torrent) bool {
2233 defer cl.mu.Unlock()
2235 defer t.stateMu.Unlock()
2238 case <-t.ceasingNetworking:
2242 if len(t.Peers) > torrentPeersLowWater {
2245 if t.needData() || cl.seeding(t) {
2257 // Returns whether the client should make effort to seed the torrent.
2258 func (cl *Client) seeding(t *torrent) bool {
2259 if cl.config.NoUpload {
2262 if !cl.config.Seed {
2271 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2272 for cl.waitWantPeers(t) {
2273 // log.Printf("getting peers for %q from DHT", t)
2274 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2276 log.Printf("error getting peers from dht: %s", err)
2279 // Count all the unique addresses we got during this announce.
2280 allAddrs := make(map[string]struct{})
2284 case v, ok := <-ps.Peers:
2288 addPeers := make([]Peer, 0, len(v.Peers))
2289 for _, cp := range v.Peers {
2291 // Can't do anything with this.
2294 addPeers = append(addPeers, Peer{
2297 Source: peerSourceDHT,
2299 key := (&net.UDPAddr{
2303 allAddrs[key] = struct{}{}
2305 peersFoundByDHT.Add(int64(len(addPeers)))
2307 cl.addPeers(t, addPeers)
2308 numPeers := len(t.Peers)
2310 if numPeers >= torrentPeersHighWater {
2313 case <-t.ceasingNetworking:
2319 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2323 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2324 url_, err := url.Parse(tr.URL())
2328 host, _, err := net.SplitHostPort(url_.Host)
2332 addr, err := net.ResolveIPAddr("ip", host)
2337 if cl.ipBlockList != nil {
2338 if cl.ipBlockRange(addr.IP) != nil {
2346 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2347 blocked, err := cl.trackerBlockedUnlocked(tr)
2349 return fmt.Errorf("error determining if tracker blocked: %s", err)
2352 return fmt.Errorf("tracker blocked: %s", tr)
2354 if err := tr.Connect(); err != nil {
2355 return fmt.Errorf("error connecting: %s", err)
2357 resp, err := tr.Announce(req)
2359 return fmt.Errorf("error announcing: %s", err)
2362 for _, peer := range resp.Peers {
2365 log.Printf("tracker %s gave peer %s", tr, peer)
2369 peers = append(peers, Peer{
2375 cl.addPeers(t, peers)
2378 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2379 peersFoundByTracker.Add(int64(len(peers)))
2381 time.Sleep(time.Second * time.Duration(resp.Interval))
2385 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2386 oks := make(chan bool)
2388 for _, tier := range trackers {
2389 for _, tr := range tier {
2391 go func(tr tracker.Client) {
2392 err := cl.announceTorrentSingleTracker(tr, req, t)
2397 for outstanding > 0 {
2407 // Announce torrent to its trackers.
2408 func (cl *Client) announceTorrentTrackers(t *torrent) {
2409 req := tracker.AnnounceRequest{
2410 Event: tracker.Started,
2412 Port: uint16(cl.incomingPeerPort()),
2414 InfoHash: t.InfoHash,
2416 if !cl.waitWantPeers(t) {
2420 req.Left = uint64(t.bytesLeft())
2421 trackers := t.Trackers
2423 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2424 req.Event = tracker.None
2427 for cl.waitWantPeers(t) {
2429 req.Left = uint64(t.bytesLeft())
2430 trackers = t.Trackers
2432 numTrackersTried := 0
2433 for _, tier := range trackers {
2434 for trIndex, tr := range tier {
2436 err := cl.announceTorrentSingleTracker(tr, &req, t)
2438 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2441 // Float the successful announce to the top of the tier. If
2442 // the trackers list has been changed, we'll be modifying an
2443 // old copy so it won't matter.
2445 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2448 req.Event = tracker.None
2449 continue newAnnounce
2452 if numTrackersTried != 0 {
2453 log.Printf("%s: all trackers failed", t)
2455 // TODO: Wait until trackers are added if there are none.
2456 time.Sleep(10 * time.Second)
2460 func (cl *Client) allTorrentsCompleted() bool {
2461 for _, t := range cl.torrents {
2465 if t.numPiecesCompleted() != t.numPieces() {
2472 // Returns true when all torrents are completely downloaded and false if the
2473 // client is stopped before that.
2474 func (me *Client) WaitAll() bool {
2476 defer me.mu.Unlock()
2477 for !me.allTorrentsCompleted() {
2486 func (me *Client) fillRequests(t *torrent, c *connection) {
2491 if len(c.Requests) > c.requestsLowWater {
2495 addRequest := func(req request) (again bool) {
2496 // TODO: Couldn't this check also be done *after* the request?
2497 if len(c.Requests) >= 64 {
2500 return c.Request(req)
2502 for req := range t.urgent {
2503 if !addRequest(req) {
2507 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2508 pieceIndex := e.Piece()
2509 if !c.PeerHasPiece(pieceIndex) {
2510 panic("piece in request order but peer doesn't have it")
2512 if !t.wantPiece(pieceIndex) {
2513 log.Printf("unwanted piece %d in connection request order\n%s", pieceIndex, c)
2514 c.pieceRequestOrder.DeletePiece(pieceIndex)
2517 piece := t.Pieces[pieceIndex]
2518 for _, cs := range piece.shuffledPendingChunkSpecs(t.pieceLength(pieceIndex), pp.Integer(t.chunkSize)) {
2519 r := request{pp.Integer(pieceIndex), cs}
2528 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2532 me.fillRequests(t, c)
2533 if len(c.Requests) == 0 && !c.PeerChoked {
2534 // So we're not choked, but we don't want anything right now. We may
2535 // have completed readahead, and the readahead window has not rolled
2536 // over to the next piece. Better to stay interested in case we're
2537 // going to want data in the near future.
2538 c.SetInterested(!t.haveAllPieces())
2542 // Handle a received chunk from a peer.
2543 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2544 chunksReceived.Add(1)
2546 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2548 // Request has been satisfied.
2549 if me.connDeleteRequest(t, c, req) {
2550 defer me.replenishConnRequests(t, c)
2552 unexpectedChunksReceived.Add(1)
2555 piece := t.Pieces[req.Index]
2557 // Do we actually want this chunk?
2558 if !t.wantChunk(req) {
2559 unwantedChunksReceived.Add(1)
2560 c.UnwantedChunksReceived++
2564 c.UsefulChunksReceived++
2565 c.lastUsefulChunkReceived = time.Now()
2569 piece.pendingWritesMutex.Lock()
2570 piece.pendingWrites++
2571 piece.pendingWritesMutex.Unlock()
2574 piece.pendingWritesMutex.Lock()
2575 piece.pendingWrites--
2576 if piece.pendingWrites == 0 {
2577 piece.noPendingWrites.Broadcast()
2579 piece.pendingWritesMutex.Unlock()
2581 // Write the chunk out.
2582 tr := perf.NewTimer()
2583 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2585 log.Printf("error writing chunk: %s", err)
2588 tr.Stop("write chunk")
2590 if c.peerTouchedPieces == nil {
2591 c.peerTouchedPieces = make(map[int]struct{})
2593 c.peerTouchedPieces[int(req.Index)] = struct{}{}
2595 // log.Println("got chunk", req)
2596 piece.Event.Broadcast()
2597 // Record that we have the chunk.
2598 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2599 delete(t.urgent, req)
2600 // It's important that the piece is potentially queued before we check if
2601 // the piece is still wanted, because if it is queued, it won't be wanted.
2602 if piece.numPendingChunks() == 0 {
2603 me.queuePieceCheck(t, req.Index)
2605 if !t.wantPiece(int(req.Index)) {
2606 for _, c := range t.Conns {
2607 c.pieceRequestOrder.DeletePiece(int(req.Index))
2611 // Cancel pending requests for this chunk.
2612 for _, c := range t.Conns {
2613 if me.connCancel(t, c, req) {
2614 me.replenishConnRequests(t, c)
2621 // Return the connections that touched a piece, and clear the entry while
2623 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2624 for _, c := range t.Conns {
2625 if _, ok := c.peerTouchedPieces[piece]; ok {
2626 ret = append(ret, c)
2627 delete(c.peerTouchedPieces, piece)
2633 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2634 p := t.Pieces[piece]
2636 // Don't score the first time a piece is hashed, it could be an
2639 pieceHashedCorrect.Add(1)
2641 log.Printf("%s: piece %d failed hash", t, piece)
2642 pieceHashedNotCorrect.Add(1)
2646 touchers := me.reapPieceTouches(t, int(piece))
2648 err := t.data.PieceCompleted(int(piece))
2650 log.Printf("error completing piece: %s", err)
2653 } else if len(touchers) != 0 {
2654 log.Printf("dropping %d conns that touched piece", len(touchers))
2655 for _, c := range touchers {
2656 me.dropConnection(t, c)
2659 me.pieceChanged(t, int(piece))
2662 // TODO: Check this isn't called more than once for each piece being correct.
2663 func (me *Client) pieceChanged(t *torrent, piece int) {
2664 correct := t.pieceComplete(piece)
2665 p := t.Pieces[piece]
2666 defer p.Event.Broadcast()
2668 p.Priority = PiecePriorityNone
2669 p.PendingChunkSpecs = nil
2670 for req := range t.urgent {
2671 if int(req.Index) == piece {
2672 delete(t.urgent, req)
2676 if p.numPendingChunks() == 0 {
2677 t.pendAllChunkSpecs(int(piece))
2679 if t.wantPiece(piece) {
2683 for _, conn := range t.Conns {
2685 conn.Post(pp.Message{
2687 Index: pp.Integer(piece),
2689 // TODO: Cancel requests for this piece.
2690 for r := range conn.Requests {
2691 if int(r.Index) == piece {
2695 conn.pieceRequestOrder.DeletePiece(int(piece))
2697 } else if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2698 t.connPendPiece(conn, int(piece))
2699 me.replenishConnRequests(t, conn)
2702 me.event.Broadcast()
2705 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2707 defer cl.mu.Unlock()
2708 p := t.Pieces[index]
2709 for p.Hashing || t.data == nil {
2712 p.QueuedForHash = false
2713 if t.isClosed() || t.pieceComplete(int(index)) {
2718 sum := t.hashPiece(index)
2726 cl.pieceHashed(t, index, sum == p.Hash)
2729 // Returns handles to all the torrents loaded in the Client.
2730 func (me *Client) Torrents() (ret []Torrent) {
2732 for _, t := range me.torrents {
2733 ret = append(ret, Torrent{me, t})
2739 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2740 spec, err := TorrentSpecFromMagnetURI(uri)
2744 T, _, err = me.AddTorrentSpec(spec)
2748 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2749 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2753 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2754 mi, err := metainfo.LoadFromFile(filename)
2758 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2762 func (me *Client) DHT() *dht.Server {