2 Package torrent implements a torrent client.
6 c, _ := torrent.NewClient(&torrent.Config{})
8 t, _ := c.AddMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU")
11 log.Print("ermahgerd, torrent downloaded")
41 "github.com/anacrolix/torrent/bencode"
42 "github.com/anacrolix/torrent/metainfo"
43 "github.com/anacrolix/sync"
44 "github.com/anacrolix/utp"
45 "github.com/bradfitz/iter"
47 "github.com/anacrolix/torrent/data"
48 filePkg "github.com/anacrolix/torrent/data/file"
49 "github.com/anacrolix/torrent/dht"
50 "github.com/anacrolix/torrent/internal/pieceordering"
51 "github.com/anacrolix/torrent/iplist"
52 "github.com/anacrolix/torrent/logonce"
53 "github.com/anacrolix/torrent/mse"
54 pp "github.com/anacrolix/torrent/peer_protocol"
55 "github.com/anacrolix/torrent/tracker"
56 . "github.com/anacrolix/torrent/util"
60 unusedDownloadedChunksCount = expvar.NewInt("unusedDownloadedChunksCount")
61 chunksDownloadedCount = expvar.NewInt("chunksDownloadedCount")
62 peersFoundByDHT = expvar.NewInt("peersFoundByDHT")
63 peersFoundByPEX = expvar.NewInt("peersFoundByPEX")
64 peersFoundByTracker = expvar.NewInt("peersFoundByTracker")
65 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
66 unexpectedCancels = expvar.NewInt("unexpectedCancels")
67 postedCancels = expvar.NewInt("postedCancels")
68 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
69 failedPieceHashes = expvar.NewInt("failedPieceHashes")
70 unsuccessfulDials = expvar.NewInt("unsuccessfulDials")
71 successfulDials = expvar.NewInt("successfulDials")
72 acceptedConns = expvar.NewInt("acceptedConns")
73 inboundConnsBlocked = expvar.NewInt("inboundConnsBlocked")
74 peerExtensions = expvar.NewMap("peerExtensions")
75 // Count of connections to peer with same client ID.
76 connsToSelf = expvar.NewInt("connsToSelf")
77 // Number of completed connections to a client we're already connected with.
78 duplicateClientConns = expvar.NewInt("duplicateClientConns")
79 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
80 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
84 // Justification for set bits follows.
86 // Extension protocol: http://www.bittorrent.org/beps/bep_0010.html ([5]|=0x10)
87 // DHT: http://www.bittorrent.org/beps/bep_0005.html ([7]|=1)
89 // http://bittorrent.org/beps/bep_0006.html ([7]|=4)
90 // Disabled until AllowedFast is implemented
91 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
93 socketsPerTorrent = 40
94 torrentPeersHighWater = 200
95 torrentPeersLowWater = 50
97 // Limit how long handshake can take. This is to reduce the lingering
98 // impact of a few bad apples. 4s loses 1% of successful handshakes that
99 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
100 btHandshakeTimeout = 4 * time.Second
101 handshakesTimeout = 20 * time.Second
103 pruneInterval = 10 * time.Second
105 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
108 extendedHandshakeClientVersion = "go.torrent dev 20140825"
111 // Currently doesn't really queue, but should in the future.
112 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex pp.Integer) {
113 piece := t.Pieces[pieceIndex]
114 if piece.QueuedForHash {
117 piece.QueuedForHash = true
118 go cl.verifyPiece(t, pieceIndex)
121 // Queue a piece check if one isn't already queued, and the piece has never
122 // been checked before.
123 func (cl *Client) queueFirstHash(t *torrent, piece int) {
125 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
128 cl.queuePieceCheck(t, pp.Integer(piece))
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 {
177 if addr != nil && l.Addr().String() != addr.String() {
178 panic("listeners exist on different addresses")
185 type hashSorter struct {
189 func (me hashSorter) Len() int {
190 return len(me.Hashes)
193 func (me hashSorter) Less(a, b int) bool {
194 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
197 func (me hashSorter) Swap(a, b int) {
198 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
201 func (cl *Client) sortedTorrents() (ret []*torrent) {
203 for ih := range cl.torrents {
204 hs.Hashes = append(hs.Hashes, ih)
207 for _, ih := range hs.Hashes {
208 ret = append(ret, cl.torrent(ih))
213 // Writes out a human readable status of the client, such as for writing to a
215 func (cl *Client) WriteStatus(_w io.Writer) {
217 defer cl.mu.RUnlock()
218 w := bufio.NewWriter(_w)
220 if addr := cl.ListenAddr(); addr != nil {
221 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
223 fmt.Fprintln(w, "Not listening!")
225 fmt.Fprintf(w, "Peer ID: %q\n", cl.peerID)
227 dhtStats := cl.dHT.Stats()
228 fmt.Fprintf(w, "DHT nodes: %d (%d good)\n", dhtStats.Nodes, dhtStats.GoodNodes)
229 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
230 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
231 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
232 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
234 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
236 for _, t := range cl.sortedTorrents() {
238 fmt.Fprint(w, "<unknown name>")
240 fmt.Fprint(w, t.Name())
244 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
246 w.WriteString("<missing metainfo>")
254 // A Data that implements this has a streaming interface that should be
255 // preferred over ReadAt. For example, the data is stored in blocks on the
256 // network and have a fixed cost to open.
257 type SectionOpener interface {
258 // Open a ReadCloser at the given offset into torrent data. n is how many
259 // bytes we intend to read.
260 OpenSection(off, n int64) (io.ReadCloser, error)
263 func dataReadAt(d data.Data, b []byte, off int64) (n int, err error) {
265 // if err == io.ErrUnexpectedEOF && n != 0 {
269 // log.Println("data read at", len(b), off)
271 if ra, ok := d.(io.ReaderAt); ok {
272 return ra.ReadAt(b, off)
274 if so, ok := d.(SectionOpener); ok {
276 rc, err = so.OpenSection(off, int64(len(b)))
281 return io.ReadFull(rc, b)
283 if dp, ok := super(d); ok {
287 panic(fmt.Sprintf("can't read from %T", d))
290 // Calculates the number of pieces to set to Readahead priority, after the
291 // Now, and Next pieces.
292 func readaheadPieces(readahead, pieceLength int64) int {
293 return int((readahead+pieceLength-1)/pieceLength - 1)
296 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
297 index := int(off / int64(t.usualPieceSize()))
298 cl.raisePiecePriority(t, index, piecePriorityNow)
300 if index >= t.numPieces() {
303 cl.raisePiecePriority(t, index, piecePriorityNext)
304 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
306 if index >= t.numPieces() {
309 cl.raisePiecePriority(t, index, piecePriorityReadahead)
313 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
315 req, ok := t.offsetRequest(off)
319 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
321 t.urgent = make(map[request]struct{}, (n+chunkSize-1)/chunkSize)
323 t.urgent[req] = struct{}{}
324 cl.event.Broadcast() // Why?
325 index := int(req.Index)
326 cl.queueFirstHash(t, index)
327 cl.pieceChanged(t, index)
329 reqOff := t.requestOffset(req)
330 n1 := req.Length - pp.Integer(off-reqOff)
334 // log.Print(t.urgent)
337 func (cl *Client) configDir() string {
338 if cl.config.ConfigDir == "" {
339 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
341 return cl.config.ConfigDir
344 func (cl *Client) ConfigDir() string {
345 return cl.configDir()
348 func (t *torrent) connPendPiece(c *connection, piece int) {
349 c.pendPiece(piece, t.Pieces[piece].Priority)
352 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
353 if t.Pieces[piece].Priority < priority {
355 cl.prioritizePiece(t, piece, priority)
359 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
360 if t.havePiece(piece) {
363 cl.queueFirstHash(t, piece)
364 t.Pieces[piece].Priority = priority
365 cl.pieceChanged(t, piece)
368 func (cl *Client) setEnvBlocklist() (err error) {
369 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
370 defaultBlocklist := filename == ""
371 if defaultBlocklist {
372 filename = filepath.Join(cl.configDir(), "blocklist")
374 f, err := os.Open(filename)
376 if defaultBlocklist {
382 var ranges []iplist.Range
383 uniqStrs := make(map[string]string)
384 scanner := bufio.NewScanner(f)
387 r, ok, lineErr := iplist.ParseBlocklistP2PLine(scanner.Bytes())
389 err = fmt.Errorf("error reading torrent blocklist line %d: %s", lineNum, lineErr)
396 if s, ok := uniqStrs[r.Description]; ok {
399 uniqStrs[r.Description] = r.Description
401 ranges = append(ranges, r)
405 err = fmt.Errorf("error reading torrent blocklist: %s", err)
408 cl.ipBlockList = iplist.New(ranges)
412 func (cl *Client) initBannedTorrents() error {
413 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
415 if os.IsNotExist(err) {
418 return fmt.Errorf("error opening banned infohashes file: %s", err)
421 scanner := bufio.NewScanner(f)
422 cl.bannedTorrents = make(map[InfoHash]struct{})
424 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
428 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
430 return fmt.Errorf("error reading infohash: %s", err)
436 return errors.New("bad infohash")
440 cl.bannedTorrents[ih] = struct{}{}
442 if err := scanner.Err(); err != nil {
443 return fmt.Errorf("error scanning file: %s", err)
448 // Creates a new client. Clients contain zero or more Torrents.
449 func NewClient(cfg *Config) (cl *Client, err error) {
460 halfOpenLimit: socketsPerTorrent,
462 torrentDataOpener: func(md *metainfo.Info) data.Data {
463 return filePkg.TorrentData(md, cfg.DataDir)
465 dopplegangerAddrs: make(map[string]struct{}),
467 quit: make(chan struct{}),
468 torrents: make(map[InfoHash]*torrent),
470 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
472 if cfg.TorrentDataOpener != nil {
473 cl.torrentDataOpener = cfg.TorrentDataOpener
476 if !cfg.NoDefaultBlocklist {
477 err = cl.setEnvBlocklist()
483 if err = cl.initBannedTorrents(); err != nil {
484 err = fmt.Errorf("error initing banned torrents: %s", err)
488 if cfg.PeerID != "" {
489 CopyExact(&cl.peerID, cfg.PeerID)
491 o := copy(cl.peerID[:], bep20)
492 _, err = rand.Read(cl.peerID[o:])
494 panic("error generating peer id")
498 // Returns the laddr string to listen on for the next Listen call.
499 listenAddr := func() string {
500 if addr := cl.ListenAddr(); addr != nil {
503 if cfg.ListenAddr == "" {
504 // IPv6 isn't well supported with blocklists, or with trackers and
506 return "0.0.0.0:50007"
508 return cfg.ListenAddr
510 if !cl.config.DisableTCP {
512 l, err = net.Listen("tcp", listenAddr())
516 cl.listeners = append(cl.listeners, l)
517 go cl.acceptConnections(l, false)
519 if !cl.config.DisableUTP {
520 cl.utpSock, err = utp.NewSocket(listenAddr())
524 cl.listeners = append(cl.listeners, cl.utpSock)
525 go cl.acceptConnections(cl.utpSock, true)
528 dhtCfg := cfg.DHTConfig
530 dhtCfg = &dht.ServerConfig{}
532 if dhtCfg.Addr == "" {
533 dhtCfg.Addr = listenAddr()
535 if dhtCfg.Conn == nil && cl.utpSock != nil {
536 dhtCfg.Conn = cl.utpSock.PacketConn()
538 cl.dHT, err = dht.NewServer(dhtCfg)
542 if cl.ipBlockList != nil {
543 cl.dHT.SetIPBlockList(cl.ipBlockList)
550 func (cl *Client) stopped() bool {
559 // Stops the client. All connections to peers are closed and all activity will
561 func (me *Client) Close() {
565 for _, l := range me.listeners {
569 for _, t := range me.torrents {
574 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
576 func (cl *Client) ipBlockRange(ip net.IP) (r *iplist.Range) {
577 if cl.ipBlockList == nil {
582 log.Printf("blocking non-IPv4 address: %s", ip)
586 r = cl.ipBlockList.Lookup(ip4)
590 func (cl *Client) waitAccept() {
594 for _, t := range cl.torrents {
603 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
606 // We accept all connections immediately, because we don't know what
607 // torrent they're for.
608 conn, err := l.Accept()
623 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
624 blockRange := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
626 if blockRange != nil || doppleganger {
627 inboundConnsBlocked.Add(1)
628 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
632 go cl.incomingConnection(conn, utp)
636 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
638 if tc, ok := nc.(*net.TCPConn); ok {
644 c.Discovery = peerSourceIncoming
646 err := cl.runReceivedConn(c)
652 // Returns a handle to the given torrent, if it's present in the client.
653 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
656 t, ok := cl.torrents[ih]
664 func (me *Client) torrent(ih InfoHash) *torrent {
665 return me.torrents[ih]
668 type dialResult struct {
673 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
674 conn, err := dial(addr, t)
679 conn = nil // Pedantic
681 ch <- dialResult{conn, utp}
683 successfulDials.Add(1)
686 unsuccessfulDials.Add(1)
687 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
690 if netOpErr, ok := err.(*net.OpError); ok {
691 switch netOpErr.Err {
692 case syscall.ECONNREFUSED, syscall.EHOSTUNREACH:
697 log.Printf("error dialing %s: %s", addr, err)
702 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
703 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
704 if ret < minDialTimeout {
710 func (me *Client) dopplegangerAddr(addr string) bool {
711 _, ok := me.dopplegangerAddrs[addr]
715 // Start the process of connecting to the given peer for the given torrent if
717 func (me *Client) initiateConn(peer Peer, t *torrent) {
718 if peer.Id == me.peerID {
721 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
722 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
723 duplicateConnsAvoided.Add(1)
726 if r := me.ipBlockRange(peer.IP); r != nil {
727 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
730 t.HalfOpen[addr] = struct{}{}
731 go me.outgoingConnection(t, addr, peer.Source)
734 func (me *Client) dialTimeout(t *torrent) time.Duration {
736 pendingPeers := len(t.Peers)
738 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
741 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
742 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
744 c.(*net.TCPConn).SetLinger(0)
749 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
750 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
753 // Returns a connection over UTP or TCP.
754 func (me *Client) dial(addr string, t *torrent) (conn net.Conn, utp bool) {
755 // Initiate connections via TCP and UTP simultaneously. Use the first one
758 if !me.config.DisableUTP {
761 if !me.config.DisableTCP {
764 resCh := make(chan dialResult, left)
765 if !me.config.DisableUTP {
766 go doDial(me.dialUTP, resCh, true, addr, t)
768 if !me.config.DisableTCP {
769 go doDial(me.dialTCP, resCh, false, addr, t)
772 // Wait for a successful connection.
773 for ; left > 0 && res.Conn == nil; left-- {
777 // There are still incompleted dials.
779 for ; left > 0; left-- {
780 conn := (<-resCh).Conn
792 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
793 if _, ok := t.HalfOpen[addr]; !ok {
794 panic("invariant broken")
796 delete(t.HalfOpen, addr)
800 // Returns nil connection and nil error if no connection could be established
801 // for valid reasons.
802 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
803 handshakesConnection := func(nc net.Conn, encrypted, utp bool) (c *connection, err error) {
807 c.encrypted = encrypted
809 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
813 ok, err := me.initiateHandshakes(c, t)
819 nc, utp := me.dial(addr, t)
823 c, err = handshakesConnection(nc, !me.config.DisableEncryption, utp)
832 nc, err = me.dialUTP(addr, t)
834 nc, err = me.dialTCP(addr, t)
837 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
840 c, err = handshakesConnection(nc, false, utp)
847 // Called to dial out and run a connection. The addr we're given is already
848 // considered half-open.
849 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
850 c, err := me.establishOutgoingConn(t, addr)
853 // Don't release lock between here and addConnection, unless it's for
855 me.noLongerHalfOpen(t, addr)
864 err = me.runInitiatedHandshookConn(c, t)
870 // The port number for incoming peer connections. 0 if the client isn't
872 func (cl *Client) incomingPeerPort() int {
873 listenAddr := cl.ListenAddr()
874 if listenAddr == nil {
877 return addrPort(listenAddr)
880 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
881 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
882 func addrCompactIP(addr net.Addr) (string, error) {
883 host, _, err := net.SplitHostPort(addr.String())
887 ip := net.ParseIP(host)
888 if v4 := ip.To4(); v4 != nil {
892 return string(v4), nil
894 return string(ip.To16()), nil
897 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
909 peerExtensionBytes [8]byte
913 func (me *peerExtensionBytes) SupportsExtended() bool {
914 return me[5]&0x10 != 0
917 func (me *peerExtensionBytes) SupportsDHT() bool {
918 return me[7]&0x01 != 0
921 func (me *peerExtensionBytes) SupportsFast() bool {
922 return me[7]&0x04 != 0
925 type handshakeResult struct {
931 // ih is nil if we expect the peer to declare the InfoHash, such as when the
932 // peer initiated the connection. Returns ok if the handshake was successful,
933 // and err if there was an unexpected condition other than the peer simply
934 // abandoning the handshake.
935 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
936 // Bytes to be sent to the peer. Should never block the sender.
937 postCh := make(chan []byte, 4)
938 // A single error value sent when the writer completes.
939 writeDone := make(chan error, 1)
940 // Performs writes to the socket and ensures posts don't block.
941 go handshakeWriter(sock, postCh, writeDone)
944 close(postCh) // Done writing.
951 // Wait until writes complete before returning from handshake.
954 err = fmt.Errorf("error writing: %s", err)
958 post := func(bb []byte) {
962 panic("mustn't block while posting")
966 post([]byte(pp.Protocol))
968 if ih != nil { // We already know what we want.
973 _, err = io.ReadFull(sock, b[:68])
978 if string(b[:20]) != pp.Protocol {
981 CopyExact(&res.peerExtensionBytes, b[20:28])
982 CopyExact(&res.InfoHash, b[28:48])
983 CopyExact(&res.peerID, b[48:68])
984 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
986 // TODO: Maybe we can just drop peers here if we're not interested. This
987 // could prevent them trying to reconnect, falsely believing there was
989 if ih == nil { // We were waiting for the peer to tell us what they wanted.
990 post(res.InfoHash[:])
998 // Wraps a raw connection and provides the interface we want for using the
999 // connection in the message loop.
1000 type deadlineReader struct {
1005 func (me deadlineReader) Read(b []byte) (n int, err error) {
1006 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1007 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1009 err = fmt.Errorf("error setting read deadline: %s", err)
1011 n, err = me.r.Read(b)
1012 // Convert common errors into io.EOF.
1014 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1016 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1026 type readWriter struct {
1031 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1032 var protocol [len(pp.Protocol)]byte
1033 _, err = io.ReadFull(rw, protocol[:])
1038 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1041 if string(protocol[:]) == pp.Protocol {
1045 ret, err = mse.ReceiveHandshake(ret, skeys)
1049 func (cl *Client) receiveSkeys() (ret [][]byte) {
1050 for ih := range cl.torrents {
1051 ret = append(ret, ih[:])
1056 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1058 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1063 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1064 if ih != t.InfoHash {
1070 // Do encryption and bittorrent handshakes as receiver.
1071 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1073 skeys := cl.receiveSkeys()
1075 if !cl.config.DisableEncryption {
1076 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1078 if err == mse.ErrNoSecretKeyMatch {
1084 ih, ok, err := cl.connBTHandshake(c, nil)
1086 fmt.Errorf("error during bt handshake: %s", err)
1098 // Returns !ok if handshake failed for valid reasons.
1099 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1100 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1101 if err != nil || !ok {
1105 c.PeerExtensionBytes = res.peerExtensionBytes
1106 c.PeerID = res.peerID
1107 c.completedHandshake = time.Now()
1111 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1112 if c.PeerID == cl.peerID {
1113 // Only if we initiated the connection is the remote address a
1114 // listen addr for a doppleganger.
1116 addr := c.conn.RemoteAddr().String()
1117 cl.dopplegangerAddrs[addr] = struct{}{}
1120 return cl.runHandshookConn(c, t)
1123 func (cl *Client) runReceivedConn(c *connection) (err error) {
1124 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1128 t, err := cl.receiveHandshakes(c)
1130 err = fmt.Errorf("error receiving handshakes: %s", err)
1137 defer cl.mu.Unlock()
1138 if c.PeerID == cl.peerID {
1141 return cl.runHandshookConn(c, t)
1144 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1145 c.conn.SetWriteDeadline(time.Time{})
1147 deadlineReader{c.conn, c.rw},
1150 if !cl.addConnection(t, c) {
1153 defer cl.dropConnection(t, c)
1155 go c.writeOptimizer(time.Minute)
1156 cl.sendInitialMessages(c, t)
1158 t.initRequestOrdering(c)
1160 err = cl.connectionLoop(t, c)
1162 err = fmt.Errorf("error during connection loop: %s", err)
1167 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1168 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1169 conn.Post(pp.Message{
1171 ExtendedID: pp.HandshakeExtendedID,
1172 ExtendedPayload: func() []byte {
1173 d := map[string]interface{}{
1174 "m": func() (ret map[string]int) {
1175 ret = make(map[string]int, 2)
1176 ret["ut_metadata"] = metadataExtendedId
1177 if !me.config.DisablePEX {
1178 ret["ut_pex"] = pexExtendedId
1182 "v": extendedHandshakeClientVersion,
1183 // No upload queue is implemented yet.
1184 "reqq": func() int {
1185 if me.config.NoUpload {
1186 // No need to look strange if it costs us nothing.
1193 if !me.config.DisableEncryption {
1196 if torrent.metadataSizeKnown() {
1197 d["metadata_size"] = torrent.metadataSize()
1199 if p := me.incomingPeerPort(); p != 0 {
1202 yourip, err := addrCompactIP(conn.remoteAddr())
1204 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1206 d["yourip"] = yourip
1208 // log.Printf("sending %v", d)
1209 b, err := bencode.Marshal(d)
1217 if torrent.haveAnyPieces() {
1218 conn.Post(pp.Message{
1220 Bitfield: torrent.bitfield(),
1222 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1223 conn.Post(pp.Message{
1227 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1228 conn.Post(pp.Message{
1230 Port: uint16(AddrPort(me.dHT.Addr())),
1235 // Randomizes the piece order for this connection. Every connection will be
1236 // given a different ordering. Having it stored per connection saves having to
1237 // randomize during request filling, and constantly recalculate the ordering
1238 // based on piece priorities.
1239 func (t *torrent) initRequestOrdering(c *connection) {
1240 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1241 panic("double init of request ordering")
1243 c.piecePriorities = mathRand.Perm(t.numPieces())
1244 c.pieceRequestOrder = pieceordering.New()
1245 for i := range iter.N(t.Info.NumPieces()) {
1246 if !c.PeerHasPiece(i) {
1249 if !t.wantPiece(i) {
1252 t.connPendPiece(c, i)
1256 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) {
1259 if c.PeerPieces == nil {
1260 c.PeerPieces = make([]bool, t.numPieces())
1263 for piece >= len(c.PeerPieces) {
1264 c.PeerPieces = append(c.PeerPieces, false)
1267 c.PeerPieces[piece] = true
1269 if t.wantPiece(piece) {
1270 t.connPendPiece(c, piece)
1271 me.replenishConnRequests(t, c)
1275 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1276 me.replenishConnRequests(torrent, conn)
1279 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1282 postedCancels.Add(1)
1287 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) {
1288 if !cn.RequestPending(r) {
1291 delete(cn.Requests, r)
1294 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1298 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1299 // Peer doesn't support this.
1302 // Request metadata pieces that we don't have in a random order.
1304 for index := 0; index < t.metadataPieceCount(); index++ {
1305 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1306 pending = append(pending, index)
1309 for _, i := range mathRand.Perm(len(pending)) {
1310 c.requestMetadataPiece(pending[i])
1314 func (cl *Client) completedMetadata(t *torrent) {
1318 CopyExact(&ih, h.Sum(nil))
1319 if ih != t.InfoHash {
1320 log.Print("bad metadata")
1321 t.invalidateMetadata()
1324 var info metainfo.Info
1325 err := bencode.Unmarshal(t.MetaData, &info)
1327 log.Printf("error unmarshalling metadata: %s", err)
1328 t.invalidateMetadata()
1331 // TODO(anacrolix): If this fails, I think something harsher should be
1333 err = cl.setMetaData(t, &info, t.MetaData)
1335 log.Printf("error setting metadata: %s", err)
1336 t.invalidateMetadata()
1339 log.Printf("%s: got metadata from peers", t)
1342 // Process incoming ut_metadata message.
1343 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1344 var d map[string]int
1345 err = bencode.Unmarshal(payload, &d)
1347 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1350 msgType, ok := d["msg_type"]
1352 err = errors.New("missing msg_type field")
1357 case pp.DataMetadataExtensionMsgType:
1361 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1362 if begin < 0 || begin >= len(payload) {
1363 log.Printf("got bad metadata piece")
1366 if !c.requestedMetadataPiece(piece) {
1367 log.Printf("got unexpected metadata piece %d", piece)
1370 c.metadataRequests[piece] = false
1371 t.saveMetadataPiece(piece, payload[begin:])
1372 c.UsefulChunksReceived++
1373 c.lastUsefulChunkReceived = time.Now()
1374 if !t.haveAllMetadataPieces() {
1377 cl.completedMetadata(t)
1378 case pp.RequestMetadataExtensionMsgType:
1379 if !t.haveMetadataPiece(piece) {
1380 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1383 start := (1 << 14) * piece
1384 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1385 case pp.RejectMetadataExtensionMsgType:
1387 err = errors.New("unknown msg_type value")
1392 type peerExchangeMessage struct {
1393 Added CompactPeers `bencode:"added"`
1394 AddedFlags []byte `bencode:"added.f"`
1395 Dropped CompactPeers `bencode:"dropped"`
1398 // Extracts the port as an integer from an address string.
1399 func addrPort(addr net.Addr) int {
1400 return AddrPort(addr)
1403 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1404 cn.peerHasAll = true
1407 for i := 0; i < t.numPieces(); i++ {
1408 cl.peerGotPiece(t, cn, i)
1413 // Processes incoming bittorrent messages. The client lock is held upon entry
1415 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1416 decoder := pp.Decoder{
1417 R: bufio.NewReader(c.rw),
1418 MaxLength: 256 * 1024,
1423 err := decoder.Decode(&msg)
1424 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1426 c.lastMessageReceived = time.Now()
1433 if me.stopped() || err == io.EOF {
1444 for r := range c.Requests {
1445 me.connDeleteRequest(t, c, r)
1447 // We can then reset our interest.
1448 me.replenishConnRequests(t, c)
1450 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1451 me.replenishConnRequests(t, c)
1453 c.PeerChoked = false
1454 me.peerUnchoked(t, c)
1456 c.PeerInterested = true
1457 // TODO: This should be done from a dedicated unchoking routine.
1458 if me.config.NoUpload {
1462 case pp.NotInterested:
1463 c.PeerInterested = false
1466 me.peerGotPiece(t, c, int(msg.Index))
1468 if me.config.NoUpload {
1471 if c.PeerRequests == nil {
1472 c.PeerRequests = make(map[request]struct{}, maxRequests)
1474 request := newRequest(msg.Index, msg.Begin, msg.Length)
1475 // TODO: Requests should be satisfied from a dedicated upload
1477 // c.PeerRequests[request] = struct{}{}
1478 p := make([]byte, msg.Length)
1479 n, err := dataReadAt(t.data, p, int64(t.pieceLength(0))*int64(msg.Index)+int64(msg.Begin))
1481 return fmt.Errorf("reading t data to serve request %q: %s", request, err)
1483 if n != int(msg.Length) {
1484 return fmt.Errorf("bad request: %v", msg)
1492 uploadChunksPosted.Add(1)
1494 req := newRequest(msg.Index, msg.Begin, msg.Length)
1495 if !c.PeerCancel(req) {
1496 unexpectedCancels.Add(1)
1499 if c.PeerPieces != nil || c.peerHasAll {
1500 err = errors.New("received unexpected bitfield")
1504 if len(msg.Bitfield) < t.numPieces() {
1505 err = errors.New("received invalid bitfield")
1508 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1510 c.PeerPieces = msg.Bitfield
1511 for index, has := range c.PeerPieces {
1513 me.peerGotPiece(t, c, index)
1517 if c.PeerPieces != nil || c.peerHasAll {
1518 err = errors.New("unexpected have-all")
1523 if c.peerHasAll || c.PeerPieces != nil {
1524 err = errors.New("unexpected have-none")
1527 c.PeerPieces = make([]bool, func() int {
1529 return t.numPieces()
1535 err = me.downloadedChunk(t, c, &msg)
1537 switch msg.ExtendedID {
1538 case pp.HandshakeExtendedID:
1539 // TODO: Create a bencode struct for this.
1540 var d map[string]interface{}
1541 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1543 err = fmt.Errorf("error decoding extended message payload: %s", err)
1546 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1547 if reqq, ok := d["reqq"]; ok {
1548 if i, ok := reqq.(int64); ok {
1549 c.PeerMaxRequests = int(i)
1552 if v, ok := d["v"]; ok {
1553 c.PeerClientName = v.(string)
1557 err = errors.New("handshake missing m item")
1560 mTyped, ok := m.(map[string]interface{})
1562 err = errors.New("handshake m value is not dict")
1565 if c.PeerExtensionIDs == nil {
1566 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1568 for name, v := range mTyped {
1571 log.Printf("bad handshake m item extension ID type: %T", v)
1575 delete(c.PeerExtensionIDs, name)
1577 if c.PeerExtensionIDs[name] == 0 {
1578 supportedExtensionMessages.Add(name, 1)
1580 c.PeerExtensionIDs[name] = byte(id)
1583 metadata_sizeUntyped, ok := d["metadata_size"]
1585 metadata_size, ok := metadata_sizeUntyped.(int64)
1587 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1589 t.setMetadataSize(metadata_size, me)
1592 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1593 me.requestPendingMetadata(t, c)
1595 case metadataExtendedId:
1596 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1598 err = fmt.Errorf("error handling metadata extension message: %s", err)
1601 if me.config.DisablePEX {
1604 var pexMsg peerExchangeMessage
1605 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1607 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1612 me.addPeers(t, func() (ret []Peer) {
1613 for i, cp := range pexMsg.Added {
1615 IP: make([]byte, 4),
1617 Source: peerSourcePEX,
1619 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1620 p.SupportsEncryption = true
1622 CopyExact(p.IP, cp.IP[:])
1623 ret = append(ret, p)
1628 peersFoundByPEX.Add(int64(len(pexMsg.Added)))
1631 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1634 // That client uses its own extension IDs for outgoing message
1635 // types, which is incorrect.
1636 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1637 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1645 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1650 pingAddr.Port = int(msg.Port)
1652 _, err = me.dHT.Ping(pingAddr)
1654 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1662 func (me *Client) dropConnection(torrent *torrent, conn *connection) {
1663 me.event.Broadcast()
1664 for r := range conn.Requests {
1665 me.connDeleteRequest(torrent, conn, r)
1668 for i0, c := range torrent.Conns {
1672 i1 := len(torrent.Conns) - 1
1674 torrent.Conns[i0] = torrent.Conns[i1]
1676 torrent.Conns = torrent.Conns[:i1]
1677 me.openNewConns(torrent)
1680 panic("connection not found")
1683 func (me *Client) addConnection(t *torrent, c *connection) bool {
1688 case <-t.ceasingNetworking:
1692 if !me.wantConns(t) {
1695 for _, c0 := range t.Conns {
1696 if c.PeerID == c0.PeerID {
1697 // Already connected to a client with that ID.
1698 duplicateClientConns.Add(1)
1702 t.Conns = append(t.Conns, c)
1703 // TODO: This should probably be done by a routine that kills off bad
1704 // connections, and extra connections killed here instead.
1705 if len(t.Conns) > socketsPerTorrent {
1706 wcs := t.worstConnsHeap()
1707 heap.Pop(wcs).(*connection).Close()
1712 func (t *torrent) needData() bool {
1716 for i := range t.Pieces {
1724 // TODO: I'm sure there's something here to do with seeding.
1725 func (t *torrent) badConn(c *connection) bool {
1726 // A 30 second grace for initial messages to go through.
1727 if time.Since(c.completedHandshake) < 30*time.Second {
1731 if !c.supportsExtension("ut_metadata") {
1734 if time.Since(c.completedHandshake) > 2*time.Minute {
1738 return !t.connHasWantedPieces(c)
1741 func (t *torrent) numGoodConns() (num int) {
1742 for _, c := range t.Conns {
1750 func (me *Client) wantConns(t *torrent) bool {
1751 if me.config.NoUpload && !t.needData() {
1754 if t.numGoodConns() >= socketsPerTorrent {
1760 func (me *Client) openNewConns(t *torrent) {
1762 case <-t.ceasingNetworking:
1766 for len(t.Peers) != 0 {
1767 if !me.wantConns(t) {
1770 if len(t.HalfOpen) >= me.halfOpenLimit {
1777 for k, p = range t.Peers {
1781 me.initiateConn(p, t)
1783 t.wantPeers.Broadcast()
1786 func (me *Client) addPeers(t *torrent, peers []Peer) {
1787 for _, p := range peers {
1788 if me.dopplegangerAddr(net.JoinHostPort(p.IP.String(), strconv.FormatInt(int64(p.Port), 10))) {
1791 if me.ipBlockRange(p.IP) != nil {
1799 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1800 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1803 func (cl *Client) saveTorrentFile(t *torrent) error {
1804 path := cl.cachedMetaInfoFilename(t.InfoHash)
1805 os.MkdirAll(filepath.Dir(path), 0777)
1806 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1808 return fmt.Errorf("error opening file: %s", err)
1811 e := bencode.NewEncoder(f)
1812 err = e.Encode(t.MetaInfo())
1814 return fmt.Errorf("error marshalling metainfo: %s", err)
1816 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1818 // For example, a script kiddy makes us load too many files, and we're
1819 // able to save the torrent, but not load it again to check it.
1822 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1823 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1828 func (cl *Client) startTorrent(t *torrent) {
1829 if t.Info == nil || t.data == nil {
1832 // If the client intends to upload, it needs to know what state pieces are
1834 if !cl.config.NoUpload {
1835 // Queue all pieces for hashing. This is done sequentially to avoid
1836 // spamming goroutines.
1837 for _, p := range t.Pieces {
1838 p.QueuedForHash = true
1841 for i := range t.Pieces {
1842 cl.verifyPiece(t, pp.Integer(i))
1848 // Storage cannot be changed once it's set.
1849 func (cl *Client) setStorage(t *torrent, td data.Data) (err error) {
1850 err = t.setStorage(td)
1851 cl.event.Broadcast()
1855 for index := range iter.N(t.numPieces()) {
1856 cl.pieceChanged(t, index)
1862 type TorrentDataOpener func(*metainfo.Info) data.Data
1864 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1865 err = t.setMetadata(md, bytes, &cl.mu)
1869 if !cl.config.DisableMetainfoCache {
1870 if err := cl.saveTorrentFile(t); err != nil {
1871 log.Printf("error saving torrent file for %s: %s", t, err)
1874 cl.event.Broadcast()
1875 close(t.gotMetainfo)
1876 td := cl.torrentDataOpener(md)
1877 err = cl.setStorage(t, td)
1881 // Prepare a Torrent without any attachment to a Client. That means we can
1882 // initialize fields all fields that don't require the Client without locking
1884 func newTorrent(ih InfoHash) (t *torrent, err error) {
1887 Peers: make(map[peersKey]Peer),
1889 closing: make(chan struct{}),
1890 ceasingNetworking: make(chan struct{}),
1892 gotMetainfo: make(chan struct{}),
1894 HalfOpen: make(map[string]struct{}),
1896 t.wantPeers.L = &t.stateMu
1897 t.GotMetainfo = t.gotMetainfo
1902 // For shuffling the tracker tiers.
1903 mathRand.Seed(time.Now().Unix())
1906 // The trackers within each tier must be shuffled before use.
1907 // http://stackoverflow.com/a/12267471/149482
1908 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1909 func shuffleTier(tier []tracker.Client) {
1910 for i := range tier {
1911 j := mathRand.Intn(i + 1)
1912 tier[i], tier[j] = tier[j], tier[i]
1916 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1917 for _, tier := range base {
1918 copy = append(copy, append([]tracker.Client{}, tier...))
1923 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1925 for _, url := range newURLs {
1926 for _, tr := range tier {
1927 if tr.URL() == url {
1931 tr, err := tracker.New(url)
1933 log.Printf("error creating tracker client for %q: %s", url, err)
1936 tier = append(tier, tr)
1941 func (t *torrent) addTrackers(announceList [][]string) {
1942 newTrackers := copyTrackers(t.Trackers)
1943 for tierIndex, tier := range announceList {
1944 if tierIndex < len(newTrackers) {
1945 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1947 newTrackers = append(newTrackers, mergeTier(nil, tier))
1949 shuffleTier(newTrackers[tierIndex])
1951 t.Trackers = newTrackers
1954 // Don't call this before the info is available.
1955 func (t *torrent) BytesCompleted() int64 {
1959 return t.Info.TotalLength() - t.bytesLeft()
1962 func (t Torrent) NumPieces() int {
1963 return t.numPieces()
1966 func (t Torrent) Drop() {
1968 t.cl.dropTorrent(t.InfoHash)
1972 // A file-like handle to some torrent data resource.
1973 type Handle interface {
1980 // Returns handles to the files in the torrent. This requires the metainfo is
1982 func (t Torrent) Files() (ret []File) {
1990 for _, fi := range info.UpvertedFiles() {
1991 ret = append(ret, File{
1993 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
2003 func (t Torrent) SetRegionPriority(off, len int64) {
2005 defer t.cl.mu.Unlock()
2006 pieceSize := int64(t.usualPieceSize())
2007 for i := off / pieceSize; i*pieceSize < off+len; i++ {
2008 t.cl.prioritizePiece(t.torrent, int(i), piecePriorityNormal)
2012 func (t Torrent) AddPeers(pp []Peer) error {
2015 defer cl.mu.Unlock()
2016 cl.addPeers(t.torrent, pp)
2020 // Marks the entire torrent for download.
2021 func (t Torrent) DownloadAll() {
2023 defer t.cl.mu.Unlock()
2024 for i := range iter.N(t.numPieces()) {
2025 t.cl.raisePiecePriority(t.torrent, i, piecePriorityNormal)
2027 // Nice to have the first and last pieces sooner for various interactive
2029 t.cl.raisePiecePriority(t.torrent, 0, piecePriorityReadahead)
2030 t.cl.raisePiecePriority(t.torrent, t.numPieces()-1, piecePriorityReadahead)
2033 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
2034 // metainfo has the correct infohash.
2035 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
2036 if cl.config.DisableMetainfoCache {
2039 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
2041 if os.IsNotExist(err) {
2047 dec := bencode.NewDecoder(f)
2048 err = dec.Decode(&mi)
2052 if !bytes.Equal(mi.Info.Hash, ih[:]) {
2053 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
2059 // Specifies a new torrent for adding to a client. There are helpers for
2060 // magnet URIs and torrent metainfo files.
2061 type TorrentSpec struct {
2064 Info *metainfo.InfoEx
2068 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2069 m, err := ParseMagnetURI(uri)
2073 spec = &TorrentSpec{
2074 Trackers: [][]string{m.Trackers},
2075 DisplayName: m.DisplayName,
2076 InfoHash: m.InfoHash,
2081 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2082 spec = &TorrentSpec{
2083 Trackers: mi.AnnounceList,
2085 DisplayName: mi.Info.Name,
2087 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2091 // Add or merge a torrent spec. If the torrent is already present, the
2092 // trackers will be merged with the existing ones. If the Info isn't yet
2093 // known, it will be set. The display name is replaced if the new spec
2094 // provides one. Returns new if the torrent wasn't already in the client.
2095 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2098 defer cl.mu.Unlock()
2100 t, ok := cl.torrents[spec.InfoHash]
2104 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2105 err = errors.New("banned torrent")
2109 t, err = newTorrent(spec.InfoHash)
2114 if spec.DisplayName != "" {
2115 t.DisplayName = spec.DisplayName
2117 // Try to merge in info we have on the torrent. Any err left will
2118 // terminate the function.
2120 if spec.Info != nil {
2121 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2123 var mi *metainfo.MetaInfo
2124 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2126 log.Printf("error getting cached metainfo: %s", err)
2128 } else if mi != nil {
2129 t.addTrackers(mi.AnnounceList)
2130 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2137 t.addTrackers(spec.Trackers)
2139 cl.torrents[spec.InfoHash] = t
2142 // From this point onwards, we can consider the torrent a part of the
2145 t.pruneTimer = time.AfterFunc(0, func() {
2146 cl.pruneConnectionsUnlocked(T.torrent)
2148 if !cl.config.DisableTrackers {
2149 go cl.announceTorrentTrackers(T.torrent)
2152 go cl.announceTorrentDHT(T.torrent, true)
2158 // Prunes unused connections. This is required to make space to dial for
2160 func (cl *Client) pruneConnectionsUnlocked(t *torrent) {
2162 case <-t.ceasingNetworking:
2169 license := len(t.Conns) - (socketsPerTorrent+1)/2
2170 for _, c := range t.Conns {
2174 if time.Now().Sub(c.lastUsefulChunkReceived) < time.Minute {
2177 if time.Now().Sub(c.completedHandshake) < time.Minute {
2184 t.pruneTimer.Reset(pruneInterval)
2187 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2188 t, ok := me.torrents[infoHash]
2190 err = fmt.Errorf("no such torrent")
2197 delete(me.torrents, infoHash)
2201 // Returns true when peers are required, or false if the torrent is closing.
2202 func (cl *Client) waitWantPeers(t *torrent) bool {
2204 defer cl.mu.Unlock()
2206 defer t.stateMu.Unlock()
2209 case <-t.ceasingNetworking:
2213 if len(t.Peers) < torrentPeersLowWater && t.needData() {
2224 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2225 for cl.waitWantPeers(t) {
2226 log.Printf("getting peers for %q from DHT", t)
2227 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2229 log.Printf("error getting peers from dht: %s", err)
2232 allAddrs := make(map[string]struct{})
2236 case v, ok := <-ps.Peers:
2240 peersFoundByDHT.Add(int64(len(v.Peers)))
2241 for _, p := range v.Peers {
2242 allAddrs[(&net.UDPAddr{
2245 }).String()] = struct{}{}
2247 // log.Printf("%s: %d new peers from DHT", t, len(v.Peers))
2249 cl.addPeers(t, func() (ret []Peer) {
2250 for _, cp := range v.Peers {
2251 ret = append(ret, Peer{
2254 Source: peerSourceDHT,
2259 numPeers := len(t.Peers)
2261 if numPeers >= torrentPeersHighWater {
2264 case <-t.ceasingNetworking:
2270 log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2274 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2275 url_, err := url.Parse(tr.URL())
2279 host, _, err := net.SplitHostPort(url_.Host)
2283 addr, err := net.ResolveIPAddr("ip", host)
2288 if cl.ipBlockList != nil {
2289 if cl.ipBlockRange(addr.IP) != nil {
2297 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2298 blocked, err := cl.trackerBlockedUnlocked(tr)
2300 return fmt.Errorf("error determining if tracker blocked: %s", err)
2303 return fmt.Errorf("tracker blocked: %s", tr)
2305 if err := tr.Connect(); err != nil {
2306 return fmt.Errorf("error connecting: %s", err)
2308 resp, err := tr.Announce(req)
2310 return fmt.Errorf("error announcing: %s", err)
2313 for _, peer := range resp.Peers {
2314 peers = append(peers, Peer{
2320 cl.addPeers(t, peers)
2323 log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2324 peersFoundByTracker.Add(int64(len(peers)))
2326 time.Sleep(time.Second * time.Duration(resp.Interval))
2330 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2331 oks := make(chan bool)
2333 for _, tier := range trackers {
2334 for _, tr := range tier {
2336 go func(tr tracker.Client) {
2337 err := cl.announceTorrentSingleTracker(tr, req, t)
2342 for outstanding > 0 {
2352 // Announce torrent to its trackers.
2353 func (cl *Client) announceTorrentTrackers(t *torrent) {
2354 req := tracker.AnnounceRequest{
2355 Event: tracker.Started,
2357 Port: uint16(cl.incomingPeerPort()),
2359 InfoHash: t.InfoHash,
2361 if !cl.waitWantPeers(t) {
2365 req.Left = uint64(t.bytesLeft())
2366 trackers := t.Trackers
2368 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2369 req.Event = tracker.None
2372 for cl.waitWantPeers(t) {
2374 req.Left = uint64(t.bytesLeft())
2375 trackers = t.Trackers
2377 numTrackersTried := 0
2378 for _, tier := range trackers {
2379 for trIndex, tr := range tier {
2381 err := cl.announceTorrentSingleTracker(tr, &req, t)
2383 logonce.Stderr.Printf("%s: error announcing to %s: %s", t, tr, err)
2386 // Float the successful announce to the top of the tier. If
2387 // the trackers list has been changed, we'll be modifying an
2388 // old copy so it won't matter.
2390 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2393 req.Event = tracker.None
2394 continue newAnnounce
2397 if numTrackersTried != 0 {
2398 log.Printf("%s: all trackers failed", t)
2400 // TODO: Wait until trackers are added if there are none.
2401 time.Sleep(10 * time.Second)
2405 func (cl *Client) allTorrentsCompleted() bool {
2406 for _, t := range cl.torrents {
2410 if t.numPiecesCompleted() != t.numPieces() {
2417 // Returns true when all torrents are completely downloaded and false if the
2418 // client is stopped before that.
2419 func (me *Client) WaitAll() bool {
2421 defer me.mu.Unlock()
2422 for !me.allTorrentsCompleted() {
2431 func (me *Client) fillRequests(t *torrent, c *connection) {
2436 if len(c.Requests) > c.requestsLowWater {
2440 addRequest := func(req request) (again bool) {
2441 // TODO: Couldn't this check also be done *after* the request?
2442 if len(c.Requests) >= 64 {
2445 return c.Request(req)
2447 for req := range t.urgent {
2448 if !addRequest(req) {
2452 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2453 pieceIndex := e.Piece()
2454 if !c.PeerHasPiece(pieceIndex) {
2455 panic("piece in request order but peer doesn't have it")
2457 if !t.wantPiece(pieceIndex) {
2458 panic("unwanted piece in connection request order")
2460 piece := t.Pieces[pieceIndex]
2461 for _, cs := range piece.shuffledPendingChunkSpecs() {
2462 r := request{pp.Integer(pieceIndex), cs}
2471 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2475 me.fillRequests(t, c)
2476 if len(c.Requests) == 0 && !c.PeerChoked {
2477 // So we're not choked, but we don't want anything right now. We may
2478 // have completed readahead, and the readahead window has not rolled
2479 // over to the next piece. Better to stay interested in case we're
2480 // going to want data in the near future.
2481 c.SetInterested(!t.haveAllPieces())
2485 // Handle a received chunk from a peer.
2486 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2487 chunksDownloadedCount.Add(1)
2489 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2491 // Request has been satisfied.
2492 me.connDeleteRequest(t, c, req)
2494 defer me.replenishConnRequests(t, c)
2496 piece := t.Pieces[req.Index]
2498 // Do we actually want this chunk?
2499 if !t.wantChunk(req) {
2500 unusedDownloadedChunksCount.Add(1)
2501 c.UnwantedChunksReceived++
2505 c.UsefulChunksReceived++
2506 c.lastUsefulChunkReceived = time.Now()
2508 // Write the chunk out.
2509 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2511 return fmt.Errorf("error writing chunk: %s", err)
2514 // log.Println("got chunk", req)
2515 piece.Event.Broadcast()
2516 // Record that we have the chunk.
2517 delete(piece.PendingChunkSpecs, req.chunkSpec)
2518 delete(t.urgent, req)
2519 if len(piece.PendingChunkSpecs) == 0 {
2520 for _, c := range t.Conns {
2521 c.pieceRequestOrder.DeletePiece(int(req.Index))
2523 me.queuePieceCheck(t, req.Index)
2526 // Cancel pending requests for this chunk.
2527 for _, c := range t.Conns {
2528 if me.connCancel(t, c, req) {
2529 me.replenishConnRequests(t, c)
2536 func (me *Client) pieceHashed(t *torrent, piece pp.Integer, correct bool) {
2537 p := t.Pieces[piece]
2538 if p.EverHashed && !correct {
2539 log.Printf("%s: piece %d failed hash", t, piece)
2540 failedPieceHashes.Add(1)
2544 if sd, ok := t.data.(StatefulData); ok {
2545 err := sd.PieceCompleted(int(piece))
2547 log.Printf("error completing piece: %s", err)
2552 me.pieceChanged(t, int(piece))
2555 // TODO: Check this isn't called more than once for each piece being correct.
2556 func (me *Client) pieceChanged(t *torrent, piece int) {
2557 correct := t.pieceComplete(piece)
2558 p := t.Pieces[piece]
2560 p.Priority = piecePriorityNone
2561 p.PendingChunkSpecs = nil
2562 for req := range t.urgent {
2563 if int(req.Index) == piece {
2564 delete(t.urgent, req)
2569 if len(p.PendingChunkSpecs) == 0 {
2570 t.pendAllChunkSpecs(int(piece))
2572 if t.wantPiece(piece) {
2576 for _, conn := range t.Conns {
2578 conn.Post(pp.Message{
2580 Index: pp.Integer(piece),
2582 // TODO: Cancel requests for this piece.
2583 for r := range conn.Requests {
2584 if int(r.Index) == piece {
2588 conn.pieceRequestOrder.DeletePiece(int(piece))
2590 if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2591 t.connPendPiece(conn, int(piece))
2592 me.replenishConnRequests(t, conn)
2595 if t.haveAllPieces() && me.config.NoUpload {
2598 me.event.Broadcast()
2601 func (cl *Client) verifyPiece(t *torrent, index pp.Integer) {
2603 defer cl.mu.Unlock()
2604 p := t.Pieces[index]
2605 for p.Hashing || t.data == nil {
2608 p.QueuedForHash = false
2609 if t.isClosed() || t.pieceComplete(int(index)) {
2614 sum := t.hashPiece(index)
2622 cl.pieceHashed(t, index, sum == p.Hash)
2625 // Returns handles to all the torrents loaded in the Client.
2626 func (me *Client) Torrents() (ret []Torrent) {
2628 for _, t := range me.torrents {
2629 ret = append(ret, Torrent{me, t})
2635 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2636 spec, err := TorrentSpecFromMagnetURI(uri)
2640 T, _, err = me.AddTorrentSpec(spec)
2644 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2645 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2649 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2650 mi, err := metainfo.LoadFromFile(filename)
2654 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))