25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/pubsub"
29 "github.com/anacrolix/sync"
30 "github.com/anacrolix/utp"
31 "github.com/bradfitz/iter"
32 "github.com/edsrzf/mmap-go"
34 "github.com/anacrolix/torrent/bencode"
35 filePkg "github.com/anacrolix/torrent/data/file"
36 "github.com/anacrolix/torrent/dht"
37 "github.com/anacrolix/torrent/internal/pieceordering"
38 "github.com/anacrolix/torrent/iplist"
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"
46 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
47 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
48 chunksReceived = expvar.NewInt("chunksReceived")
50 peersAddedBySource = expvar.NewMap("peersAddedBySource")
52 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
53 unexpectedCancels = expvar.NewInt("unexpectedCancels")
54 postedCancels = expvar.NewInt("postedCancels")
55 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
57 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
58 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
60 unsuccessfulDials = expvar.NewInt("dialSuccessful")
61 successfulDials = expvar.NewInt("dialUnsuccessful")
63 acceptUTP = expvar.NewInt("acceptUTP")
64 acceptTCP = expvar.NewInt("acceptTCP")
65 acceptReject = expvar.NewInt("acceptReject")
67 peerExtensions = expvar.NewMap("peerExtensions")
68 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
69 // Count of connections to peer with same client ID.
70 connsToSelf = expvar.NewInt("connsToSelf")
71 // Number of completed connections to a client we're already connected with.
72 duplicateClientConns = expvar.NewInt("duplicateClientConns")
73 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
74 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
78 // Justification for set bits follows.
80 // Extension protocol ([5]|=0x10):
81 // http://www.bittorrent.org/beps/bep_0010.html
83 // Fast Extension ([7]|=0x04):
84 // http://bittorrent.org/beps/bep_0006.html.
85 // Disabled until AllowedFast is implemented.
88 // http://www.bittorrent.org/beps/bep_0005.html
89 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
91 socketsPerTorrent = 80
92 torrentPeersHighWater = 200
93 torrentPeersLowWater = 50
95 // Limit how long handshake can take. This is to reduce the lingering
96 // impact of a few bad apples. 4s loses 1% of successful handshakes that
97 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
98 btHandshakeTimeout = 4 * time.Second
99 handshakesTimeout = 20 * time.Second
101 // These are our extended message IDs.
102 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
105 // Updated occasionally to when there's been some changes to client
106 // behaviour in case other clients are assuming anything of us. See also
108 extendedHandshakeClientVersion = "go.torrent dev 20150624"
111 // Currently doesn't really queue, but should in the future.
112 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
113 piece := &t.Pieces[pieceIndex]
114 if piece.QueuedForHash {
117 piece.QueuedForHash = true
118 t.publishPieceChange(int(pieceIndex))
119 go cl.verifyPiece(t, int(pieceIndex))
122 // Queue a piece check if one isn't already queued, and the piece has never
123 // been checked before.
124 func (cl *Client) queueFirstHash(t *torrent, piece int) {
125 p := &t.Pieces[piece]
126 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
129 cl.queuePieceCheck(t, piece)
132 // Clients contain zero or more Torrents. A client manages a blocklist, the
133 // TCP/UDP protocol ports, and DHT as desired.
137 listeners []net.Listener
140 ipBlockList iplist.Ranger
141 bannedTorrents map[InfoHash]struct{}
143 pruneTimer *time.Timer
144 extensionBytes peerExtensionBytes
145 // Set of addresses that have our client ID. This intentionally will
146 // include ourselves if we end up trying to connect to our own address
147 // through legitimate channels.
148 dopplegangerAddrs map[string]struct{}
150 torrentDataOpener TorrentDataOpener
156 torrents map[InfoHash]*torrent
159 func (me *Client) IPBlockList() iplist.Ranger {
162 return me.ipBlockList
165 func (me *Client) SetIPBlockList(list iplist.Ranger) {
168 me.ipBlockList = list
170 me.dHT.SetIPBlockList(list)
174 func (me *Client) PeerID() string {
175 return string(me.peerID[:])
178 func (me *Client) ListenAddr() (addr net.Addr) {
179 for _, l := range me.listeners {
186 type hashSorter struct {
190 func (me hashSorter) Len() int {
191 return len(me.Hashes)
194 func (me hashSorter) Less(a, b int) bool {
195 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
198 func (me hashSorter) Swap(a, b int) {
199 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
202 func (cl *Client) sortedTorrents() (ret []*torrent) {
204 for ih := range cl.torrents {
205 hs.Hashes = append(hs.Hashes, ih)
208 for _, ih := range hs.Hashes {
209 ret = append(ret, cl.torrent(ih))
214 // Writes out a human readable status of the client, such as for writing to a
216 func (cl *Client) WriteStatus(_w io.Writer) {
218 defer cl.mu.RUnlock()
219 w := bufio.NewWriter(_w)
221 if addr := cl.ListenAddr(); addr != nil {
222 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
224 fmt.Fprintln(w, "Not listening!")
226 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
228 dhtStats := cl.dHT.Stats()
229 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
230 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
231 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
232 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
233 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
235 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
237 for _, t := range cl.sortedTorrents() {
239 fmt.Fprint(w, "<unknown name>")
241 fmt.Fprint(w, t.Name())
245 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.Length())), t.Length())
247 w.WriteString("<missing metainfo>")
255 func dataReadAt(d Data, b []byte, off int64) (n int, err error) {
257 // if err == io.ErrUnexpectedEOF && n != 0 {
261 // log.Println("data read at", len(b), off)
262 return d.ReadAt(b, off)
265 // Calculates the number of pieces to set to Readahead priority, after the
266 // Now, and Next pieces.
267 func readaheadPieces(readahead, pieceLength int64) (ret int) {
268 // Expand the readahead to fit any partial pieces. Subtract 1 for the
269 // "next" piece that is assigned.
270 ret = int((readahead+pieceLength-1)/pieceLength - 1)
271 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
272 // piece length is much larger than the readahead.
279 func (cl *Client) readRaisePiecePriorities(t *torrent, off, readaheadBytes int64) {
280 index := int(off / int64(t.usualPieceSize()))
281 cl.raisePiecePriority(t, index, PiecePriorityNow)
283 if index >= t.numPieces() {
286 cl.raisePiecePriority(t, index, PiecePriorityNext)
287 for range iter.N(readaheadPieces(readaheadBytes, t.Info.PieceLength)) {
289 if index >= t.numPieces() {
292 cl.raisePiecePriority(t, index, PiecePriorityReadahead)
296 func (cl *Client) addUrgentRequests(t *torrent, off int64, n int) {
298 req, ok := t.offsetRequest(off)
302 if _, ok := t.urgent[req]; !ok && !t.haveChunk(req) {
304 t.urgent = make(map[request]struct{}, (n+int(t.chunkSize)-1)/int(t.chunkSize))
306 t.urgent[req] = struct{}{}
307 cl.event.Broadcast() // Why?
308 index := int(req.Index)
309 cl.queueFirstHash(t, index)
310 cl.pieceChanged(t, index)
312 reqOff := t.requestOffset(req)
313 n1 := req.Length - pp.Integer(off-reqOff)
317 // log.Print(t.urgent)
320 func (cl *Client) configDir() string {
321 if cl.config.ConfigDir == "" {
322 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
324 return cl.config.ConfigDir
327 // The directory where the Client expects to find and store configuration
328 // data. Defaults to $HOME/.config/torrent.
329 func (cl *Client) ConfigDir() string {
330 return cl.configDir()
333 func (t *torrent) connPendPiece(c *connection, piece int) {
334 c.pendPiece(piece, t.Pieces[piece].Priority, t)
337 func (cl *Client) raisePiecePriority(t *torrent, piece int, priority piecePriority) {
338 if t.Pieces[piece].Priority < priority {
339 cl.prioritizePiece(t, piece, priority)
343 func (cl *Client) prioritizePiece(t *torrent, piece int, priority piecePriority) {
344 if t.havePiece(piece) {
345 priority = PiecePriorityNone
347 if priority != PiecePriorityNone {
348 cl.queueFirstHash(t, piece)
350 p := &t.Pieces[piece]
351 if p.Priority != priority {
352 p.Priority = priority
353 cl.pieceChanged(t, piece)
357 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
358 f, err := os.Open(filename)
359 if os.IsNotExist(err) {
367 mm, err := mmap.Map(f, mmap.RDONLY, 0)
371 ret = iplist.NewFromPacked(mm)
375 func (cl *Client) setEnvBlocklist() (err error) {
376 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
377 defaultBlocklist := filename == ""
378 if defaultBlocklist {
379 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
383 if cl.ipBlockList != nil {
386 filename = filepath.Join(cl.configDir(), "blocklist")
388 f, err := os.Open(filename)
390 if defaultBlocklist {
396 cl.ipBlockList, err = iplist.NewFromReader(f)
400 func (cl *Client) initBannedTorrents() error {
401 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
403 if os.IsNotExist(err) {
406 return fmt.Errorf("error opening banned infohashes file: %s", err)
409 scanner := bufio.NewScanner(f)
410 cl.bannedTorrents = make(map[InfoHash]struct{})
412 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
416 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
418 return fmt.Errorf("error reading infohash: %s", err)
424 return errors.New("bad infohash")
428 cl.bannedTorrents[ih] = struct{}{}
430 if err := scanner.Err(); err != nil {
431 return fmt.Errorf("error scanning file: %s", err)
436 // Creates a new client.
437 func NewClient(cfg *Config) (cl *Client, err error) {
448 halfOpenLimit: socketsPerTorrent,
450 torrentDataOpener: func(md *metainfo.Info) Data {
451 return filePkg.TorrentData(md, cfg.DataDir)
453 dopplegangerAddrs: make(map[string]struct{}),
455 quit: make(chan struct{}),
456 torrents: make(map[InfoHash]*torrent),
458 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
460 if cfg.TorrentDataOpener != nil {
461 cl.torrentDataOpener = cfg.TorrentDataOpener
464 if cfg.IPBlocklist != nil {
465 cl.ipBlockList = cfg.IPBlocklist
466 } else if !cfg.NoDefaultBlocklist {
467 err = cl.setEnvBlocklist()
473 if err = cl.initBannedTorrents(); err != nil {
474 err = fmt.Errorf("error initing banned torrents: %s", err)
478 if cfg.PeerID != "" {
479 CopyExact(&cl.peerID, cfg.PeerID)
481 o := copy(cl.peerID[:], bep20)
482 _, err = rand.Read(cl.peerID[o:])
484 panic("error generating peer id")
488 // Returns the laddr string to listen on for the next Listen call.
489 listenAddr := func() string {
490 if addr := cl.ListenAddr(); addr != nil {
493 if cfg.ListenAddr == "" {
496 return cfg.ListenAddr
498 if !cl.config.DisableTCP {
500 l, err = net.Listen(func() string {
501 if cl.config.DisableIPv6 {
510 cl.listeners = append(cl.listeners, l)
511 go cl.acceptConnections(l, false)
513 if !cl.config.DisableUTP {
514 cl.utpSock, err = utp.NewSocket(func() string {
515 if cl.config.DisableIPv6 {
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.IPBlocklist == nil {
533 dhtCfg.IPBlocklist = cl.ipBlockList
535 if dhtCfg.Addr == "" {
536 dhtCfg.Addr = listenAddr()
538 if dhtCfg.Conn == nil && cl.utpSock != nil {
539 dhtCfg.Conn = cl.utpSock
541 cl.dHT, err = dht.NewServer(dhtCfg)
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() {
573 for _, l := range me.listeners {
576 for _, t := range me.torrents {
582 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
584 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
585 if cl.ipBlockList == nil {
589 // If blocklists are enabled, then block non-IPv4 addresses, because
590 // blocklists do not yet support IPv6.
592 if missinggo.CryHeard() {
593 log.Printf("blocking non-IPv4 address: %s", ip)
599 return cl.ipBlockList.Lookup(ip4)
602 func (cl *Client) waitAccept() {
606 for _, t := range cl.torrents {
620 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
623 // We accept all connections immediately, because we don't know what
624 // torrent they're for.
625 conn, err := l.Accept()
644 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
645 _, blocked := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
647 if blocked || doppleganger {
649 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
653 go cl.incomingConnection(conn, utp)
657 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
659 if tc, ok := nc.(*net.TCPConn); ok {
665 c.Discovery = peerSourceIncoming
667 err := cl.runReceivedConn(c)
673 // Returns a handle to the given torrent, if it's present in the client.
674 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
677 t, ok := cl.torrents[ih]
681 T = clientTorrent{cl, t}
685 func (me *Client) torrent(ih InfoHash) *torrent {
686 return me.torrents[ih]
689 type dialResult struct {
694 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
695 conn, err := dial(addr, t)
700 conn = nil // Pedantic
702 ch <- dialResult{conn, utp}
704 successfulDials.Add(1)
707 unsuccessfulDials.Add(1)
710 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
711 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
712 if ret < minDialTimeout {
718 // Returns whether an address is known to connect to a client with our own ID.
719 func (me *Client) dopplegangerAddr(addr string) bool {
720 _, ok := me.dopplegangerAddrs[addr]
724 // Start the process of connecting to the given peer for the given torrent if
726 func (me *Client) initiateConn(peer Peer, t *torrent) {
727 if peer.Id == me.peerID {
730 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
731 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
732 duplicateConnsAvoided.Add(1)
735 if r, ok := me.ipBlockRange(peer.IP); ok {
736 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
739 t.HalfOpen[addr] = struct{}{}
740 go me.outgoingConnection(t, addr, peer.Source)
743 func (me *Client) dialTimeout(t *torrent) time.Duration {
745 pendingPeers := len(t.Peers)
747 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
750 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
751 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
753 c.(*net.TCPConn).SetLinger(0)
758 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
759 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
762 // Returns a connection over UTP or TCP, whichever is first to connect.
763 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
764 // Initiate connections via TCP and UTP simultaneously. Use the first one
767 if !me.config.DisableUTP {
770 if !me.config.DisableTCP {
773 resCh := make(chan dialResult, left)
774 if !me.config.DisableUTP {
775 go doDial(me.dialUTP, resCh, true, addr, t)
777 if !me.config.DisableTCP {
778 go doDial(me.dialTCP, resCh, false, addr, t)
781 // Wait for a successful connection.
782 for ; left > 0 && res.Conn == nil; left-- {
786 // There are still incompleted dials.
788 for ; left > 0; left-- {
789 conn := (<-resCh).Conn
801 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
802 if _, ok := t.HalfOpen[addr]; !ok {
803 panic("invariant broken")
805 delete(t.HalfOpen, addr)
809 // Performs initiator handshakes and returns a connection.
810 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
814 c.encrypted = encrypted
816 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
820 ok, err := me.initiateHandshakes(c, t)
827 // Returns nil connection and nil error if no connection could be established
828 // for valid reasons.
829 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
830 nc, utp := me.dialFirst(addr, t)
834 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
842 if me.config.DisableEncryption {
843 // We already tried without encryption.
846 // Try again without encryption, using whichever protocol type worked last
849 nc, err = me.dialUTP(addr, t)
851 nc, err = me.dialTCP(addr, t)
854 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
857 c, err = me.handshakesConnection(nc, t, false, utp)
864 // Called to dial out and run a connection. The addr we're given is already
865 // considered half-open.
866 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
867 c, err := me.establishOutgoingConn(t, addr)
870 // Don't release lock between here and addConnection, unless it's for
872 me.noLongerHalfOpen(t, addr)
881 err = me.runInitiatedHandshookConn(c, t)
887 // The port number for incoming peer connections. 0 if the client isn't
889 func (cl *Client) incomingPeerPort() int {
890 listenAddr := cl.ListenAddr()
891 if listenAddr == nil {
894 return addrPort(listenAddr)
897 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
898 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
899 func addrCompactIP(addr net.Addr) (string, error) {
900 host, _, err := net.SplitHostPort(addr.String())
904 ip := net.ParseIP(host)
905 if v4 := ip.To4(); v4 != nil {
909 return string(v4), nil
911 return string(ip.To16()), nil
914 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
926 peerExtensionBytes [8]byte
930 func (me *peerExtensionBytes) SupportsExtended() bool {
931 return me[5]&0x10 != 0
934 func (me *peerExtensionBytes) SupportsDHT() bool {
935 return me[7]&0x01 != 0
938 func (me *peerExtensionBytes) SupportsFast() bool {
939 return me[7]&0x04 != 0
942 type handshakeResult struct {
948 // ih is nil if we expect the peer to declare the InfoHash, such as when the
949 // peer initiated the connection. Returns ok if the handshake was successful,
950 // and err if there was an unexpected condition other than the peer simply
951 // abandoning the handshake.
952 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
953 // Bytes to be sent to the peer. Should never block the sender.
954 postCh := make(chan []byte, 4)
955 // A single error value sent when the writer completes.
956 writeDone := make(chan error, 1)
957 // Performs writes to the socket and ensures posts don't block.
958 go handshakeWriter(sock, postCh, writeDone)
961 close(postCh) // Done writing.
968 // Wait until writes complete before returning from handshake.
971 err = fmt.Errorf("error writing: %s", err)
975 post := func(bb []byte) {
979 panic("mustn't block while posting")
983 post([]byte(pp.Protocol))
985 if ih != nil { // We already know what we want.
990 _, err = io.ReadFull(sock, b[:68])
995 if string(b[:20]) != pp.Protocol {
998 CopyExact(&res.peerExtensionBytes, b[20:28])
999 CopyExact(&res.InfoHash, b[28:48])
1000 CopyExact(&res.peerID, b[48:68])
1001 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
1003 // TODO: Maybe we can just drop peers here if we're not interested. This
1004 // could prevent them trying to reconnect, falsely believing there was
1006 if ih == nil { // We were waiting for the peer to tell us what they wanted.
1007 post(res.InfoHash[:])
1015 // Wraps a raw connection and provides the interface we want for using the
1016 // connection in the message loop.
1017 type deadlineReader struct {
1022 func (me deadlineReader) Read(b []byte) (n int, err error) {
1023 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
1024 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
1026 err = fmt.Errorf("error setting read deadline: %s", err)
1028 n, err = me.r.Read(b)
1029 // Convert common errors into io.EOF.
1031 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
1033 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
1043 type readWriter struct {
1048 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
1049 var protocol [len(pp.Protocol)]byte
1050 _, err = io.ReadFull(rw, protocol[:])
1055 io.MultiReader(bytes.NewReader(protocol[:]), rw),
1058 if string(protocol[:]) == pp.Protocol {
1062 ret, err = mse.ReceiveHandshake(ret, skeys)
1066 func (cl *Client) receiveSkeys() (ret [][]byte) {
1067 for ih := range cl.torrents {
1068 ret = append(ret, ih[:])
1073 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1075 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1080 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1081 if ih != t.InfoHash {
1087 // Do encryption and bittorrent handshakes as receiver.
1088 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1090 skeys := cl.receiveSkeys()
1092 if !cl.config.DisableEncryption {
1093 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1095 if err == mse.ErrNoSecretKeyMatch {
1101 ih, ok, err := cl.connBTHandshake(c, nil)
1103 err = fmt.Errorf("error during bt handshake: %s", err)
1115 // Returns !ok if handshake failed for valid reasons.
1116 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1117 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1118 if err != nil || !ok {
1122 c.PeerExtensionBytes = res.peerExtensionBytes
1123 c.PeerID = res.peerID
1124 c.completedHandshake = time.Now()
1128 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1129 if c.PeerID == cl.peerID {
1130 // Only if we initiated the connection is the remote address a
1131 // listen addr for a doppleganger.
1133 addr := c.conn.RemoteAddr().String()
1134 cl.dopplegangerAddrs[addr] = struct{}{}
1137 return cl.runHandshookConn(c, t)
1140 func (cl *Client) runReceivedConn(c *connection) (err error) {
1141 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1145 t, err := cl.receiveHandshakes(c)
1147 err = fmt.Errorf("error receiving handshakes: %s", err)
1154 defer cl.mu.Unlock()
1155 if c.PeerID == cl.peerID {
1158 return cl.runHandshookConn(c, t)
1161 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1162 c.conn.SetWriteDeadline(time.Time{})
1164 deadlineReader{c.conn, c.rw},
1167 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1168 if !cl.addConnection(t, c) {
1171 defer cl.dropConnection(t, c)
1173 go c.writeOptimizer(time.Minute)
1174 cl.sendInitialMessages(c, t)
1176 t.initRequestOrdering(c)
1178 err = cl.connectionLoop(t, c)
1180 err = fmt.Errorf("error during connection loop: %s", err)
1185 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1186 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1187 conn.Post(pp.Message{
1189 ExtendedID: pp.HandshakeExtendedID,
1190 ExtendedPayload: func() []byte {
1191 d := map[string]interface{}{
1192 "m": func() (ret map[string]int) {
1193 ret = make(map[string]int, 2)
1194 ret["ut_metadata"] = metadataExtendedId
1195 if !me.config.DisablePEX {
1196 ret["ut_pex"] = pexExtendedId
1200 "v": extendedHandshakeClientVersion,
1201 // No upload queue is implemented yet.
1204 if !me.config.DisableEncryption {
1207 if torrent.metadataSizeKnown() {
1208 d["metadata_size"] = torrent.metadataSize()
1210 if p := me.incomingPeerPort(); p != 0 {
1213 yourip, err := addrCompactIP(conn.remoteAddr())
1215 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1217 d["yourip"] = yourip
1219 // log.Printf("sending %v", d)
1220 b, err := bencode.Marshal(d)
1228 if torrent.haveAnyPieces() {
1229 conn.Bitfield(torrent.bitfield())
1230 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1231 conn.Post(pp.Message{
1235 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1236 conn.Post(pp.Message{
1238 Port: uint16(AddrPort(me.dHT.Addr())),
1243 // Randomizes the piece order for this connection. Every connection will be
1244 // given a different ordering. Having it stored per connection saves having to
1245 // randomize during request filling, and constantly recalculate the ordering
1246 // based on piece priorities.
1247 func (t *torrent) initRequestOrdering(c *connection) {
1248 if c.pieceRequestOrder != nil || c.piecePriorities != nil {
1249 panic("double init of request ordering")
1251 c.pieceRequestOrder = pieceordering.New()
1252 for i := range iter.N(t.Info.NumPieces()) {
1253 if !c.PeerHasPiece(i) {
1256 if !t.wantPiece(i) {
1259 t.connPendPiece(c, i)
1263 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
1266 if c.PeerPieces == nil {
1267 c.PeerPieces = make([]bool, t.numPieces())
1270 for piece >= len(c.PeerPieces) {
1271 c.PeerPieces = append(c.PeerPieces, false)
1274 if piece >= len(c.PeerPieces) {
1275 return errors.New("peer got out of range piece index")
1277 c.PeerPieces[piece] = true
1279 if t.wantPiece(piece) {
1280 t.connPendPiece(c, piece)
1281 me.replenishConnRequests(t, c)
1286 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1287 me.replenishConnRequests(torrent, conn)
1290 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1293 postedCancels.Add(1)
1298 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1299 if !cn.RequestPending(r) {
1302 delete(cn.Requests, r)
1306 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1310 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1311 // Peer doesn't support this.
1314 // Request metadata pieces that we don't have in a random order.
1316 for index := 0; index < t.metadataPieceCount(); index++ {
1317 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1318 pending = append(pending, index)
1321 for _, i := range mathRand.Perm(len(pending)) {
1322 c.requestMetadataPiece(pending[i])
1326 func (cl *Client) completedMetadata(t *torrent) {
1330 CopyExact(&ih, h.Sum(nil))
1331 if ih != t.InfoHash {
1332 log.Print("bad metadata")
1333 t.invalidateMetadata()
1336 var info metainfo.Info
1337 err := bencode.Unmarshal(t.MetaData, &info)
1339 log.Printf("error unmarshalling metadata: %s", err)
1340 t.invalidateMetadata()
1343 // TODO(anacrolix): If this fails, I think something harsher should be
1345 err = cl.setMetaData(t, &info, t.MetaData)
1347 log.Printf("error setting metadata: %s", err)
1348 t.invalidateMetadata()
1351 if cl.config.Debug {
1352 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 // Extracts the port as an integer from an address string.
1407 func addrPort(addr net.Addr) int {
1408 return AddrPort(addr)
1411 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1412 cn.peerHasAll = true
1415 for i := 0; i < t.numPieces(); i++ {
1416 cl.peerGotPiece(t, cn, i)
1421 func (me *Client) upload(t *torrent, c *connection) {
1422 if me.config.NoUpload {
1425 if !c.PeerInterested {
1428 seeding := me.seeding(t)
1429 if !seeding && !t.connHasWantedPieces(c) {
1433 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1435 for r := range c.PeerRequests {
1436 err := me.sendChunk(t, c, r)
1438 log.Printf("error sending chunk %+v to peer: %s", r, err)
1440 delete(c.PeerRequests, r)
1448 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1449 // Count the chunk being sent, even if it isn't.
1451 b := make([]byte, r.Length)
1452 tp := &t.Pieces[r.Index]
1453 tp.pendingWritesMutex.Lock()
1454 for tp.pendingWrites != 0 {
1455 tp.noPendingWrites.Wait()
1457 tp.pendingWritesMutex.Unlock()
1458 p := t.Info.Piece(int(r.Index))
1459 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1472 uploadChunksPosted.Add(1)
1473 c.lastChunkSent = time.Now()
1477 // Processes incoming bittorrent messages. The client lock is held upon entry
1479 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1480 decoder := pp.Decoder{
1481 R: bufio.NewReader(c.rw),
1482 MaxLength: 256 * 1024,
1487 err := decoder.Decode(&msg)
1488 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1490 c.lastMessageReceived = time.Now()
1497 if me.stopped() || err == io.EOF {
1508 for r := range c.Requests {
1509 me.connDeleteRequest(t, c, r)
1511 // We can then reset our interest.
1512 me.replenishConnRequests(t, c)
1514 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1515 me.replenishConnRequests(t, c)
1517 c.PeerChoked = false
1518 me.peerUnchoked(t, c)
1520 c.PeerInterested = true
1522 case pp.NotInterested:
1523 c.PeerInterested = false
1526 me.peerGotPiece(t, c, int(msg.Index))
1531 if !c.PeerInterested {
1532 err = errors.New("peer sent request but isn't interested")
1535 if c.PeerRequests == nil {
1536 c.PeerRequests = make(map[request]struct{}, maxRequests)
1538 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1541 req := newRequest(msg.Index, msg.Begin, msg.Length)
1542 if !c.PeerCancel(req) {
1543 unexpectedCancels.Add(1)
1546 if c.PeerPieces != nil || c.peerHasAll {
1547 err = errors.New("received unexpected bitfield")
1551 if len(msg.Bitfield) < t.numPieces() {
1552 err = errors.New("received invalid bitfield")
1555 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1557 c.PeerPieces = msg.Bitfield
1558 for index, has := range c.PeerPieces {
1560 me.peerGotPiece(t, c, index)
1564 if c.PeerPieces != nil || c.peerHasAll {
1565 err = errors.New("unexpected have-all")
1570 if c.peerHasAll || c.PeerPieces != nil {
1571 err = errors.New("unexpected have-none")
1574 c.PeerPieces = make([]bool, func() int {
1576 return t.numPieces()
1582 err = me.downloadedChunk(t, c, &msg)
1584 switch msg.ExtendedID {
1585 case pp.HandshakeExtendedID:
1586 // TODO: Create a bencode struct for this.
1587 var d map[string]interface{}
1588 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1590 err = fmt.Errorf("error decoding extended message payload: %s", err)
1593 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1594 if reqq, ok := d["reqq"]; ok {
1595 if i, ok := reqq.(int64); ok {
1596 c.PeerMaxRequests = int(i)
1599 if v, ok := d["v"]; ok {
1600 c.PeerClientName = v.(string)
1604 err = errors.New("handshake missing m item")
1607 mTyped, ok := m.(map[string]interface{})
1609 err = errors.New("handshake m value is not dict")
1612 if c.PeerExtensionIDs == nil {
1613 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1615 for name, v := range mTyped {
1618 log.Printf("bad handshake m item extension ID type: %T", v)
1622 delete(c.PeerExtensionIDs, name)
1624 if c.PeerExtensionIDs[name] == 0 {
1625 supportedExtensionMessages.Add(name, 1)
1627 c.PeerExtensionIDs[name] = byte(id)
1630 metadata_sizeUntyped, ok := d["metadata_size"]
1632 metadata_size, ok := metadata_sizeUntyped.(int64)
1634 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1636 t.setMetadataSize(metadata_size, me)
1639 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1640 me.requestPendingMetadata(t, c)
1642 case metadataExtendedId:
1643 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1645 err = fmt.Errorf("error handling metadata extension message: %s", err)
1648 if me.config.DisablePEX {
1651 var pexMsg peerExchangeMessage
1652 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1654 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1659 me.addPeers(t, func() (ret []Peer) {
1660 for i, cp := range pexMsg.Added {
1662 IP: make([]byte, 4),
1664 Source: peerSourcePEX,
1666 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1667 p.SupportsEncryption = true
1669 CopyExact(p.IP, cp.IP[:])
1670 ret = append(ret, p)
1677 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1680 // That client uses its own extension IDs for outgoing message
1681 // types, which is incorrect.
1682 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1683 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1691 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1696 pingAddr.Port = int(msg.Port)
1698 _, err = me.dHT.Ping(pingAddr)
1700 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1708 // Returns true if connection is removed from torrent.Conns.
1709 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1710 for i0, _c := range t.Conns {
1714 i1 := len(t.Conns) - 1
1716 t.Conns[i0] = t.Conns[i1]
1718 t.Conns = t.Conns[:i1]
1724 func (me *Client) dropConnection(t *torrent, c *connection) {
1725 me.event.Broadcast()
1727 if c.piecePriorities != nil {
1728 t.connPiecePriorites.Put(c.piecePriorities)
1729 // I wonder if it's safe to set it to nil. Probably not. Since it's
1730 // only read, it doesn't particularly matter if a closing connection
1731 // shares the slice with another connection.
1733 if me.deleteConnection(t, c) {
1738 // Returns true if the connection is added.
1739 func (me *Client) addConnection(t *torrent, c *connection) bool {
1744 case <-t.ceasingNetworking:
1748 if !me.wantConns(t) {
1751 for _, c0 := range t.Conns {
1752 if c.PeerID == c0.PeerID {
1753 // Already connected to a client with that ID.
1754 duplicateClientConns.Add(1)
1758 if len(t.Conns) >= socketsPerTorrent {
1759 c := t.worstBadConn(me)
1763 if me.config.Debug && missinggo.CryHeard() {
1764 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1767 me.deleteConnection(t, c)
1769 if len(t.Conns) >= socketsPerTorrent {
1772 t.Conns = append(t.Conns, c)
1776 func (t *torrent) needData() bool {
1780 if len(t.urgent) != 0 {
1783 for i := range t.Pieces {
1785 if p.Priority != PiecePriorityNone {
1792 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1799 return c.supportsExtension("ut_metadata")
1802 return c.PeerInterested
1804 return t.connHasWantedPieces(c)
1807 func (me *Client) wantConns(t *torrent) bool {
1808 if !me.seeding(t) && !t.needData() {
1811 if len(t.Conns) < socketsPerTorrent {
1814 return t.worstBadConn(me) != nil
1817 func (me *Client) openNewConns(t *torrent) {
1819 case <-t.ceasingNetworking:
1823 for len(t.Peers) != 0 {
1824 if !me.wantConns(t) {
1827 if len(t.HalfOpen) >= me.halfOpenLimit {
1834 for k, p = range t.Peers {
1838 me.initiateConn(p, t)
1840 t.wantPeers.Broadcast()
1843 func (me *Client) addPeers(t *torrent, peers []Peer) {
1844 for _, p := range peers {
1845 if me.dopplegangerAddr(net.JoinHostPort(
1847 strconv.FormatInt(int64(p.Port), 10),
1851 if _, ok := me.ipBlockRange(p.IP); ok {
1855 // The spec says to scrub these yourselves. Fine.
1862 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1863 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1866 func (cl *Client) saveTorrentFile(t *torrent) error {
1867 path := cl.cachedMetaInfoFilename(t.InfoHash)
1868 os.MkdirAll(filepath.Dir(path), 0777)
1869 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1871 return fmt.Errorf("error opening file: %s", err)
1874 e := bencode.NewEncoder(f)
1875 err = e.Encode(t.MetaInfo())
1877 return fmt.Errorf("error marshalling metainfo: %s", err)
1879 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1881 // For example, a script kiddy makes us load too many files, and we're
1882 // able to save the torrent, but not load it again to check it.
1885 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1886 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1891 func (cl *Client) startTorrent(t *torrent) {
1892 if t.Info == nil || t.data == nil {
1895 // If the client intends to upload, it needs to know what state pieces are
1897 if !cl.config.NoUpload {
1898 // Queue all pieces for hashing. This is done sequentially to avoid
1899 // spamming goroutines.
1900 for i := range t.Pieces {
1901 t.Pieces[i].QueuedForHash = true
1904 for i := range t.Pieces {
1905 cl.verifyPiece(t, i)
1911 // Storage cannot be changed once it's set.
1912 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1913 err = t.setStorage(td)
1914 cl.event.Broadcast()
1922 type TorrentDataOpener func(*metainfo.Info) Data
1924 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1925 err = t.setMetadata(md, bytes)
1929 if !cl.config.DisableMetainfoCache {
1930 if err := cl.saveTorrentFile(t); err != nil {
1931 log.Printf("error saving torrent file for %s: %s", t, err)
1934 cl.event.Broadcast()
1935 close(t.gotMetainfo)
1936 td := cl.torrentDataOpener(md)
1937 err = cl.setStorage(t, td)
1941 // Prepare a Torrent without any attachment to a Client. That means we can
1942 // initialize fields all fields that don't require the Client without locking
1944 func newTorrent(ih InfoHash) (t *torrent, err error) {
1947 chunkSize: defaultChunkSize,
1948 Peers: make(map[PeersKey]Peer),
1950 closing: make(chan struct{}),
1951 ceasingNetworking: make(chan struct{}),
1953 gotMetainfo: make(chan struct{}),
1955 HalfOpen: make(map[string]struct{}),
1956 pieceStateChanges: pubsub.NewPubSub(),
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 clientTorrent) 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 clientTorrent) 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 clientTorrent) 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 clientTorrent) 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,
2146 if len(spec.Trackers) == 0 {
2147 spec.Trackers = [][]string{[]string{mi.Announce}}
2149 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
2152 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2156 // Add or merge a torrent spec. If the torrent is already present, the
2157 // trackers will be merged with the existing ones. If the Info isn't yet
2158 // known, it will be set. The display name is replaced if the new spec
2159 // provides one. Returns new if the torrent wasn't already in the client.
2160 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (D Torrent, new bool, err error) {
2161 T := clientTorrent{}
2165 defer cl.mu.Unlock()
2167 t, ok := cl.torrents[spec.InfoHash]
2171 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2172 err = errors.New("banned torrent")
2176 t, err = newTorrent(spec.InfoHash)
2180 if spec.ChunkSize != 0 {
2181 t.chunkSize = pp.Integer(spec.ChunkSize)
2184 if spec.DisplayName != "" {
2185 t.setDisplayName(spec.DisplayName)
2187 // Try to merge in info we have on the torrent. Any err left will
2188 // terminate the function.
2190 if spec.Info != nil {
2191 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2193 var mi *metainfo.MetaInfo
2194 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2196 log.Printf("error getting cached metainfo: %s", err)
2198 } else if mi != nil {
2199 t.addTrackers(mi.AnnounceList)
2200 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2207 t.addTrackers(spec.Trackers)
2209 cl.torrents[spec.InfoHash] = t
2212 // From this point onwards, we can consider the torrent a part of the
2215 if !cl.config.DisableTrackers {
2216 go cl.announceTorrentTrackers(T.torrent)
2219 go cl.announceTorrentDHT(T.torrent, true)
2225 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2226 t, ok := me.torrents[infoHash]
2228 err = fmt.Errorf("no such torrent")
2235 delete(me.torrents, infoHash)
2239 // Returns true when peers are required, or false if the torrent is closing.
2240 func (cl *Client) waitWantPeers(t *torrent) bool {
2242 defer cl.mu.Unlock()
2244 defer t.stateMu.Unlock()
2247 case <-t.ceasingNetworking:
2251 if len(t.Peers) > torrentPeersLowWater {
2254 if t.needData() || cl.seeding(t) {
2266 // Returns whether the client should make effort to seed the torrent.
2267 func (cl *Client) seeding(t *torrent) bool {
2268 if cl.config.NoUpload {
2271 if !cl.config.Seed {
2280 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2281 for cl.waitWantPeers(t) {
2282 // log.Printf("getting peers for %q from DHT", t)
2283 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2285 log.Printf("error getting peers from dht: %s", err)
2288 // Count all the unique addresses we got during this announce.
2289 allAddrs := make(map[string]struct{})
2293 case v, ok := <-ps.Peers:
2297 addPeers := make([]Peer, 0, len(v.Peers))
2298 for _, cp := range v.Peers {
2300 // Can't do anything with this.
2303 addPeers = append(addPeers, Peer{
2306 Source: peerSourceDHT,
2308 key := (&net.UDPAddr{
2312 allAddrs[key] = struct{}{}
2315 cl.addPeers(t, addPeers)
2316 numPeers := len(t.Peers)
2318 if numPeers >= torrentPeersHighWater {
2321 case <-t.ceasingNetworking:
2327 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2331 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2332 url_, err := url.Parse(tr.URL())
2336 host, _, err := net.SplitHostPort(url_.Host)
2340 addr, err := net.ResolveIPAddr("ip", host)
2345 _, blocked = cl.ipBlockRange(addr.IP)
2350 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2351 blocked, err := cl.trackerBlockedUnlocked(tr)
2353 return fmt.Errorf("error determining if tracker blocked: %s", err)
2356 return fmt.Errorf("tracker blocked: %s", tr)
2358 if err := tr.Connect(); err != nil {
2359 return fmt.Errorf("error connecting: %s", err)
2361 resp, err := tr.Announce(req)
2363 return fmt.Errorf("error announcing: %s", err)
2366 for _, peer := range resp.Peers {
2367 peers = append(peers, Peer{
2373 cl.addPeers(t, peers)
2376 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2378 time.Sleep(time.Second * time.Duration(resp.Interval))
2382 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2383 oks := make(chan bool)
2385 for _, tier := range trackers {
2386 for _, tr := range tier {
2388 go func(tr tracker.Client) {
2389 err := cl.announceTorrentSingleTracker(tr, req, t)
2394 for outstanding > 0 {
2404 // Announce torrent to its trackers.
2405 func (cl *Client) announceTorrentTrackers(t *torrent) {
2406 req := tracker.AnnounceRequest{
2407 Event: tracker.Started,
2409 Port: uint16(cl.incomingPeerPort()),
2411 InfoHash: t.InfoHash,
2413 if !cl.waitWantPeers(t) {
2417 req.Left = uint64(t.bytesLeft())
2418 trackers := t.Trackers
2420 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2421 req.Event = tracker.None
2424 for cl.waitWantPeers(t) {
2426 req.Left = uint64(t.bytesLeft())
2427 trackers = t.Trackers
2429 numTrackersTried := 0
2430 for _, tier := range trackers {
2431 for trIndex, tr := range tier {
2433 err := cl.announceTorrentSingleTracker(tr, &req, t)
2437 // Float the successful announce to the top of the tier. If
2438 // the trackers list has been changed, we'll be modifying an
2439 // old copy so it won't matter.
2441 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2444 req.Event = tracker.None
2445 continue newAnnounce
2448 if numTrackersTried != 0 {
2449 log.Printf("%s: all trackers failed", t)
2451 // TODO: Wait until trackers are added if there are none.
2452 time.Sleep(10 * time.Second)
2456 func (cl *Client) allTorrentsCompleted() bool {
2457 for _, t := range cl.torrents {
2461 if t.numPiecesCompleted() != t.numPieces() {
2468 // Returns true when all torrents are completely downloaded and false if the
2469 // client is stopped before that.
2470 func (me *Client) WaitAll() bool {
2472 defer me.mu.Unlock()
2473 for !me.allTorrentsCompleted() {
2482 func (me *Client) fillRequests(t *torrent, c *connection) {
2487 if len(c.Requests) > c.requestsLowWater {
2491 addRequest := func(req request) (again bool) {
2492 // TODO: Couldn't this check also be done *after* the request?
2493 if len(c.Requests) >= 64 {
2496 return c.Request(req)
2498 for req := range t.urgent {
2499 if !addRequest(req) {
2503 for e := c.pieceRequestOrder.First(); e != nil; e = e.Next() {
2504 pieceIndex := e.Piece()
2505 if !c.PeerHasPiece(pieceIndex) {
2506 panic("piece in request order but peer doesn't have it")
2508 if !t.wantPiece(pieceIndex) {
2509 log.Printf("unwanted piece %d in connection request order\n%s", pieceIndex, c)
2510 c.pieceRequestOrder.DeletePiece(pieceIndex)
2513 piece := &t.Pieces[pieceIndex]
2514 for _, cs := range piece.shuffledPendingChunkSpecs(t.pieceLength(pieceIndex), pp.Integer(t.chunkSize)) {
2515 r := request{pp.Integer(pieceIndex), cs}
2524 func (me *Client) replenishConnRequests(t *torrent, c *connection) {
2528 me.fillRequests(t, c)
2529 if len(c.Requests) == 0 && !c.PeerChoked {
2530 // So we're not choked, but we don't want anything right now. We may
2531 // have completed readahead, and the readahead window has not rolled
2532 // over to the next piece. Better to stay interested in case we're
2533 // going to want data in the near future.
2534 c.SetInterested(!t.haveAllPieces())
2538 // Handle a received chunk from a peer.
2539 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2540 chunksReceived.Add(1)
2542 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2544 // Request has been satisfied.
2545 if me.connDeleteRequest(t, c, req) {
2546 defer me.replenishConnRequests(t, c)
2548 unexpectedChunksReceived.Add(1)
2551 piece := &t.Pieces[req.Index]
2553 // Do we actually want this chunk?
2554 if !t.wantChunk(req) {
2555 unwantedChunksReceived.Add(1)
2556 c.UnwantedChunksReceived++
2560 c.UsefulChunksReceived++
2561 c.lastUsefulChunkReceived = time.Now()
2565 piece.pendingWritesMutex.Lock()
2566 piece.pendingWrites++
2567 piece.pendingWritesMutex.Unlock()
2570 piece.pendingWritesMutex.Lock()
2571 piece.pendingWrites--
2572 if piece.pendingWrites == 0 {
2573 piece.noPendingWrites.Broadcast()
2575 piece.pendingWritesMutex.Unlock()
2577 // Write the chunk out.
2578 tr := perf.NewTimer()
2579 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2581 log.Printf("error writing chunk: %s", err)
2584 tr.Stop("write chunk")
2586 if c.peerTouchedPieces == nil {
2587 c.peerTouchedPieces = make(map[int]struct{})
2589 c.peerTouchedPieces[int(req.Index)] = struct{}{}
2593 // log.Println("got chunk", req)
2594 me.event.Broadcast()
2595 defer t.publishPieceChange(int(req.Index))
2596 // Record that we have the chunk.
2597 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2598 delete(t.urgent, req)
2599 // It's important that the piece is potentially queued before we check if
2600 // the piece is still wanted, because if it is queued, it won't be wanted.
2601 if piece.numPendingChunks() == 0 {
2602 me.queuePieceCheck(t, int(req.Index))
2604 if !t.wantPiece(int(req.Index)) {
2605 for _, c := range t.Conns {
2606 c.pieceRequestOrder.DeletePiece(int(req.Index))
2610 // Cancel pending requests for this chunk.
2611 for _, c := range t.Conns {
2612 if me.connCancel(t, c, req) {
2613 me.replenishConnRequests(t, c)
2620 // Return the connections that touched a piece, and clear the entry while
2622 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2623 for _, c := range t.Conns {
2624 if _, ok := c.peerTouchedPieces[piece]; ok {
2625 ret = append(ret, c)
2626 delete(c.peerTouchedPieces, piece)
2632 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2633 p := &t.Pieces[piece]
2635 // Don't score the first time a piece is hashed, it could be an
2638 pieceHashedCorrect.Add(1)
2640 log.Printf("%s: piece %d failed hash", t, piece)
2641 pieceHashedNotCorrect.Add(1)
2645 touchers := me.reapPieceTouches(t, int(piece))
2647 err := t.data.PieceCompleted(int(piece))
2649 log.Printf("error completing piece: %s", err)
2652 } else if len(touchers) != 0 {
2653 log.Printf("dropping %d conns that touched piece", len(touchers))
2654 for _, c := range touchers {
2655 me.dropConnection(t, c)
2658 me.pieceChanged(t, int(piece))
2661 func (me *Client) pieceChanged(t *torrent, piece int) {
2662 correct := t.pieceComplete(piece)
2663 p := &t.Pieces[piece]
2664 defer t.publishPieceChange(piece)
2665 defer me.event.Broadcast()
2667 p.Priority = PiecePriorityNone
2668 p.PendingChunkSpecs = nil
2669 for req := range t.urgent {
2670 if int(req.Index) == piece {
2671 delete(t.urgent, req)
2675 if p.numPendingChunks() == 0 {
2676 t.pendAllChunkSpecs(int(piece))
2678 if t.wantPiece(piece) {
2682 for _, conn := range t.Conns {
2685 for r := range conn.Requests {
2686 if int(r.Index) == piece {
2690 conn.pieceRequestOrder.DeletePiece(int(piece))
2692 } else if t.wantPiece(piece) && conn.PeerHasPiece(piece) {
2693 t.connPendPiece(conn, int(piece))
2694 me.replenishConnRequests(t, conn)
2697 me.event.Broadcast()
2700 func (cl *Client) verifyPiece(t *torrent, piece int) {
2702 defer cl.mu.Unlock()
2703 p := &t.Pieces[piece]
2704 for p.Hashing || t.data == nil {
2707 p.QueuedForHash = false
2708 if t.isClosed() || t.pieceComplete(piece) {
2713 sum := t.hashPiece(piece)
2721 cl.pieceHashed(t, piece, sum == p.Hash)
2724 // Returns handles to all the torrents loaded in the Client.
2725 func (me *Client) Torrents() (ret []Torrent) {
2727 for _, t := range me.torrents {
2728 ret = append(ret, clientTorrent{me, t})
2734 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2735 spec, err := TorrentSpecFromMagnetURI(uri)
2739 T, _, err = me.AddTorrentSpec(spec)
2743 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2744 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2748 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2749 mi, err := metainfo.LoadFromFile(filename)
2753 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2757 func (me *Client) DHT() *dht.Server {