25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/bitmap"
28 "github.com/anacrolix/missinggo/pproffd"
29 "github.com/anacrolix/missinggo/pubsub"
30 "github.com/anacrolix/sync"
31 "github.com/anacrolix/utp"
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/iplist"
38 "github.com/anacrolix/torrent/metainfo"
39 "github.com/anacrolix/torrent/mse"
40 pp "github.com/anacrolix/torrent/peer_protocol"
41 "github.com/anacrolix/torrent/tracker"
44 // I could move a lot of these counters to their own file, but I suspect they
45 // may be attached to a Client someday.
47 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
48 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
49 chunksReceived = expvar.NewInt("chunksReceived")
51 peersAddedBySource = expvar.NewMap("peersAddedBySource")
53 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
54 unexpectedCancels = expvar.NewInt("unexpectedCancels")
55 postedCancels = expvar.NewInt("postedCancels")
56 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
58 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
59 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
61 unsuccessfulDials = expvar.NewInt("dialSuccessful")
62 successfulDials = expvar.NewInt("dialUnsuccessful")
64 acceptUTP = expvar.NewInt("acceptUTP")
65 acceptTCP = expvar.NewInt("acceptTCP")
66 acceptReject = expvar.NewInt("acceptReject")
68 peerExtensions = expvar.NewMap("peerExtensions")
69 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
70 // Count of connections to peer with same client ID.
71 connsToSelf = expvar.NewInt("connsToSelf")
72 // Number of completed connections to a client we're already connected with.
73 duplicateClientConns = expvar.NewInt("duplicateClientConns")
74 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
75 receivedKeepalives = expvar.NewInt("receivedKeepalives")
76 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
77 postedMessageTypes = expvar.NewMap("postedMessageTypes")
78 postedKeepalives = expvar.NewInt("postedKeepalives")
79 // Requests received for pieces we don't have.
80 requestsReceivedForMissingPieces = expvar.NewInt("requestsReceivedForMissingPieces")
84 // Justification for set bits follows.
86 // Extension protocol ([5]|=0x10):
87 // http://www.bittorrent.org/beps/bep_0010.html
89 // Fast Extension ([7]|=0x04):
90 // http://bittorrent.org/beps/bep_0006.html.
91 // Disabled until AllowedFast is implemented.
94 // http://www.bittorrent.org/beps/bep_0005.html
95 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
97 socketsPerTorrent = 80
98 torrentPeersHighWater = 200
99 torrentPeersLowWater = 50
101 // Limit how long handshake can take. This is to reduce the lingering
102 // impact of a few bad apples. 4s loses 1% of successful handshakes that
103 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
104 btHandshakeTimeout = 4 * time.Second
105 handshakesTimeout = 20 * time.Second
107 // These are our extended message IDs.
108 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
111 // Updated occasionally to when there's been some changes to client
112 // behaviour in case other clients are assuming anything of us. See also
114 extendedHandshakeClientVersion = "go.torrent dev 20150624"
117 // Currently doesn't really queue, but should in the future.
118 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
119 piece := &t.Pieces[pieceIndex]
120 if piece.QueuedForHash {
123 piece.QueuedForHash = true
124 t.publishPieceChange(int(pieceIndex))
125 go cl.verifyPiece(t, int(pieceIndex))
128 // Queue a piece check if one isn't already queued, and the piece has never
129 // been checked before.
130 func (cl *Client) queueFirstHash(t *torrent, piece int) {
131 p := &t.Pieces[piece]
132 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
135 cl.queuePieceCheck(t, piece)
138 // Clients contain zero or more Torrents. A client manages a blocklist, the
139 // TCP/UDP protocol ports, and DHT as desired.
143 listeners []net.Listener
146 ipBlockList iplist.Ranger
147 bannedTorrents map[InfoHash]struct{}
149 pruneTimer *time.Timer
150 extensionBytes peerExtensionBytes
151 // Set of addresses that have our client ID. This intentionally will
152 // include ourselves if we end up trying to connect to our own address
153 // through legitimate channels.
154 dopplegangerAddrs map[string]struct{}
156 torrentDataOpener TorrentDataOpener
160 closed missinggo.Event
162 torrents map[InfoHash]*torrent
165 func (me *Client) IPBlockList() iplist.Ranger {
168 return me.ipBlockList
171 func (me *Client) SetIPBlockList(list iplist.Ranger) {
174 me.ipBlockList = list
176 me.dHT.SetIPBlockList(list)
180 func (me *Client) PeerID() string {
181 return string(me.peerID[:])
184 func (me *Client) ListenAddr() (addr net.Addr) {
185 for _, l := range me.listeners {
192 type hashSorter struct {
196 func (me hashSorter) Len() int {
197 return len(me.Hashes)
200 func (me hashSorter) Less(a, b int) bool {
201 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
204 func (me hashSorter) Swap(a, b int) {
205 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
208 func (cl *Client) sortedTorrents() (ret []*torrent) {
210 for ih := range cl.torrents {
211 hs.Hashes = append(hs.Hashes, ih)
214 for _, ih := range hs.Hashes {
215 ret = append(ret, cl.torrent(ih))
220 // Writes out a human readable status of the client, such as for writing to a
222 func (cl *Client) WriteStatus(_w io.Writer) {
224 defer cl.mu.RUnlock()
225 w := bufio.NewWriter(_w)
227 if addr := cl.ListenAddr(); addr != nil {
228 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
230 fmt.Fprintln(w, "Not listening!")
232 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
234 dhtStats := cl.dHT.Stats()
235 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
236 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
237 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
238 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
239 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
241 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
243 for _, t := range cl.sortedTorrents() {
245 fmt.Fprint(w, "<unknown name>")
247 fmt.Fprint(w, t.Name())
251 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length)
253 w.WriteString("<missing metainfo>")
261 // Calculates the number of pieces to set to Readahead priority, after the
262 // Now, and Next pieces.
263 func readaheadPieces(readahead, pieceLength int64) (ret int) {
264 // Expand the readahead to fit any partial pieces. Subtract 1 for the
265 // "next" piece that is assigned.
266 ret = int((readahead+pieceLength-1)/pieceLength - 1)
267 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
268 // piece length is much larger than the readahead.
275 func (cl *Client) configDir() string {
276 if cl.config.ConfigDir == "" {
277 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
279 return cl.config.ConfigDir
282 // The directory where the Client expects to find and store configuration
283 // data. Defaults to $HOME/.config/torrent.
284 func (cl *Client) ConfigDir() string {
285 return cl.configDir()
288 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
289 f, err := os.Open(filename)
290 if os.IsNotExist(err) {
298 mm, err := mmap.Map(f, mmap.RDONLY, 0)
302 ret = iplist.NewFromPacked(mm)
306 func (cl *Client) setEnvBlocklist() (err error) {
307 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
308 defaultBlocklist := filename == ""
309 if defaultBlocklist {
310 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
314 if cl.ipBlockList != nil {
317 filename = filepath.Join(cl.configDir(), "blocklist")
319 f, err := os.Open(filename)
321 if defaultBlocklist {
327 cl.ipBlockList, err = iplist.NewFromReader(f)
331 func (cl *Client) initBannedTorrents() error {
332 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
334 if os.IsNotExist(err) {
337 return fmt.Errorf("error opening banned infohashes file: %s", err)
340 scanner := bufio.NewScanner(f)
341 cl.bannedTorrents = make(map[InfoHash]struct{})
343 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
347 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
349 return fmt.Errorf("error reading infohash: %s", err)
355 return errors.New("bad infohash")
359 cl.bannedTorrents[ih] = struct{}{}
361 if err := scanner.Err(); err != nil {
362 return fmt.Errorf("error scanning file: %s", err)
367 // Creates a new client.
368 func NewClient(cfg *Config) (cl *Client, err error) {
379 halfOpenLimit: socketsPerTorrent,
381 torrentDataOpener: func(md *metainfo.Info) Data {
382 return filePkg.TorrentData(md, cfg.DataDir)
384 dopplegangerAddrs: make(map[string]struct{}),
385 torrents: make(map[InfoHash]*torrent),
387 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
389 if cfg.TorrentDataOpener != nil {
390 cl.torrentDataOpener = cfg.TorrentDataOpener
393 if cfg.IPBlocklist != nil {
394 cl.ipBlockList = cfg.IPBlocklist
395 } else if !cfg.NoDefaultBlocklist {
396 err = cl.setEnvBlocklist()
402 if err = cl.initBannedTorrents(); err != nil {
403 err = fmt.Errorf("error initing banned torrents: %s", err)
407 if cfg.PeerID != "" {
408 CopyExact(&cl.peerID, cfg.PeerID)
410 o := copy(cl.peerID[:], bep20)
411 _, err = rand.Read(cl.peerID[o:])
413 panic("error generating peer id")
417 // Returns the laddr string to listen on for the next Listen call.
418 listenAddr := func() string {
419 if addr := cl.ListenAddr(); addr != nil {
422 if cfg.ListenAddr == "" {
425 return cfg.ListenAddr
427 if !cl.config.DisableTCP {
429 l, err = net.Listen(func() string {
430 if cl.config.DisableIPv6 {
439 cl.listeners = append(cl.listeners, l)
440 go cl.acceptConnections(l, false)
442 if !cl.config.DisableUTP {
443 cl.utpSock, err = utp.NewSocket(func() string {
444 if cl.config.DisableIPv6 {
453 cl.listeners = append(cl.listeners, cl.utpSock)
454 go cl.acceptConnections(cl.utpSock, true)
457 dhtCfg := cfg.DHTConfig
458 if dhtCfg.IPBlocklist == nil {
459 dhtCfg.IPBlocklist = cl.ipBlockList
461 if dhtCfg.Addr == "" {
462 dhtCfg.Addr = listenAddr()
464 if dhtCfg.Conn == nil && cl.utpSock != nil {
465 dhtCfg.Conn = cl.utpSock
467 cl.dHT, err = dht.NewServer(&dhtCfg)
476 // Stops the client. All connections to peers are closed and all activity will
478 func (me *Client) Close() {
485 for _, l := range me.listeners {
488 for _, t := range me.torrents {
494 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
496 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
497 if cl.ipBlockList == nil {
501 // If blocklists are enabled, then block non-IPv4 addresses, because
502 // blocklists do not yet support IPv6.
504 if missinggo.CryHeard() {
505 log.Printf("blocking non-IPv4 address: %s", ip)
511 return cl.ipBlockList.Lookup(ip4)
514 func (cl *Client) waitAccept() {
518 for _, t := range cl.torrents {
523 if cl.closed.IsSet() {
530 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
533 conn, err := l.Accept()
534 conn = pproffd.WrapNetConn(conn)
535 if cl.closed.IsSet() {
543 // I think something harsher should happen here? Our accept
544 // routine just fucked off.
553 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
554 _, blocked := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
556 if blocked || doppleganger {
558 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
562 go cl.incomingConnection(conn, utp)
566 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
568 if tc, ok := nc.(*net.TCPConn); ok {
574 c.Discovery = peerSourceIncoming
576 err := cl.runReceivedConn(c)
582 // Returns a handle to the given torrent, if it's present in the client.
583 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
586 t, ok := cl.torrents[ih]
594 func (me *Client) torrent(ih InfoHash) *torrent {
595 return me.torrents[ih]
598 type dialResult struct {
603 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
604 conn, err := dial(addr, t)
609 conn = nil // Pedantic
611 ch <- dialResult{conn, utp}
613 successfulDials.Add(1)
616 unsuccessfulDials.Add(1)
619 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
620 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
621 if ret < minDialTimeout {
627 // Returns whether an address is known to connect to a client with our own ID.
628 func (me *Client) dopplegangerAddr(addr string) bool {
629 _, ok := me.dopplegangerAddrs[addr]
633 // Start the process of connecting to the given peer for the given torrent if
635 func (me *Client) initiateConn(peer Peer, t *torrent) {
636 if peer.Id == me.peerID {
639 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
640 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
641 duplicateConnsAvoided.Add(1)
644 if r, ok := me.ipBlockRange(peer.IP); ok {
645 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
648 t.HalfOpen[addr] = struct{}{}
649 go me.outgoingConnection(t, addr, peer.Source)
652 func (me *Client) dialTimeout(t *torrent) time.Duration {
654 pendingPeers := len(t.Peers)
656 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
659 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
660 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
662 c.(*net.TCPConn).SetLinger(0)
667 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
668 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
671 // Returns a connection over UTP or TCP, whichever is first to connect.
672 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
673 // Initiate connections via TCP and UTP simultaneously. Use the first one
676 if !me.config.DisableUTP {
679 if !me.config.DisableTCP {
682 resCh := make(chan dialResult, left)
683 if !me.config.DisableUTP {
684 go doDial(me.dialUTP, resCh, true, addr, t)
686 if !me.config.DisableTCP {
687 go doDial(me.dialTCP, resCh, false, addr, t)
690 // Wait for a successful connection.
691 for ; left > 0 && res.Conn == nil; left-- {
695 // There are still incompleted dials.
697 for ; left > 0; left-- {
698 conn := (<-resCh).Conn
710 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
711 if _, ok := t.HalfOpen[addr]; !ok {
712 panic("invariant broken")
714 delete(t.HalfOpen, addr)
718 // Performs initiator handshakes and returns a connection. Returns nil
719 // *connection if no connection for valid reasons.
720 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
724 c.encrypted = encrypted
726 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
730 ok, err := me.initiateHandshakes(c, t)
737 // Returns nil connection and nil error if no connection could be established
738 // for valid reasons.
739 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
740 nc, utp := me.dialFirst(addr, t)
744 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
752 if me.config.DisableEncryption {
753 // We already tried without encryption.
756 // Try again without encryption, using whichever protocol type worked last
759 nc, err = me.dialUTP(addr, t)
761 nc, err = me.dialTCP(addr, t)
764 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
767 c, err = me.handshakesConnection(nc, t, false, utp)
768 if err != nil || c == nil {
774 // Called to dial out and run a connection. The addr we're given is already
775 // considered half-open.
776 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
777 c, err := me.establishOutgoingConn(t, addr)
780 // Don't release lock between here and addConnection, unless it's for
782 me.noLongerHalfOpen(t, addr)
785 log.Printf("error establishing outgoing connection: %s", err)
794 err = me.runInitiatedHandshookConn(c, t)
797 log.Printf("error in established outgoing connection: %s", err)
802 // The port number for incoming peer connections. 0 if the client isn't
804 func (cl *Client) incomingPeerPort() int {
805 listenAddr := cl.ListenAddr()
806 if listenAddr == nil {
809 return missinggo.AddrPort(listenAddr)
812 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
813 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
814 func addrCompactIP(addr net.Addr) (string, error) {
815 host, _, err := net.SplitHostPort(addr.String())
819 ip := net.ParseIP(host)
820 if v4 := ip.To4(); v4 != nil {
824 return string(v4), nil
826 return string(ip.To16()), nil
829 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
841 peerExtensionBytes [8]byte
845 func (me *peerExtensionBytes) SupportsExtended() bool {
846 return me[5]&0x10 != 0
849 func (me *peerExtensionBytes) SupportsDHT() bool {
850 return me[7]&0x01 != 0
853 func (me *peerExtensionBytes) SupportsFast() bool {
854 return me[7]&0x04 != 0
857 type handshakeResult struct {
863 // ih is nil if we expect the peer to declare the InfoHash, such as when the
864 // peer initiated the connection. Returns ok if the handshake was successful,
865 // and err if there was an unexpected condition other than the peer simply
866 // abandoning the handshake.
867 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
868 // Bytes to be sent to the peer. Should never block the sender.
869 postCh := make(chan []byte, 4)
870 // A single error value sent when the writer completes.
871 writeDone := make(chan error, 1)
872 // Performs writes to the socket and ensures posts don't block.
873 go handshakeWriter(sock, postCh, writeDone)
876 close(postCh) // Done writing.
883 // Wait until writes complete before returning from handshake.
886 err = fmt.Errorf("error writing: %s", err)
890 post := func(bb []byte) {
894 panic("mustn't block while posting")
898 post([]byte(pp.Protocol))
900 if ih != nil { // We already know what we want.
905 _, err = io.ReadFull(sock, b[:68])
910 if string(b[:20]) != pp.Protocol {
913 CopyExact(&res.peerExtensionBytes, b[20:28])
914 CopyExact(&res.InfoHash, b[28:48])
915 CopyExact(&res.peerID, b[48:68])
916 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
918 // TODO: Maybe we can just drop peers here if we're not interested. This
919 // could prevent them trying to reconnect, falsely believing there was
921 if ih == nil { // We were waiting for the peer to tell us what they wanted.
922 post(res.InfoHash[:])
930 // Wraps a raw connection and provides the interface we want for using the
931 // connection in the message loop.
932 type deadlineReader struct {
937 func (me deadlineReader) Read(b []byte) (n int, err error) {
938 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
939 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
941 err = fmt.Errorf("error setting read deadline: %s", err)
943 n, err = me.r.Read(b)
944 // Convert common errors into io.EOF.
946 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
948 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
958 type readWriter struct {
963 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
964 var protocol [len(pp.Protocol)]byte
965 _, err = io.ReadFull(rw, protocol[:])
970 io.MultiReader(bytes.NewReader(protocol[:]), rw),
973 if string(protocol[:]) == pp.Protocol {
977 ret, err = mse.ReceiveHandshake(ret, skeys)
981 func (cl *Client) receiveSkeys() (ret [][]byte) {
982 for ih := range cl.torrents {
983 ret = append(ret, ih[:])
988 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
990 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
995 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
996 if ih != t.InfoHash {
1002 // Do encryption and bittorrent handshakes as receiver.
1003 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1005 skeys := cl.receiveSkeys()
1007 if !cl.config.DisableEncryption {
1008 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1010 if err == mse.ErrNoSecretKeyMatch {
1016 ih, ok, err := cl.connBTHandshake(c, nil)
1018 err = fmt.Errorf("error during bt handshake: %s", err)
1030 // Returns !ok if handshake failed for valid reasons.
1031 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1032 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1033 if err != nil || !ok {
1037 c.PeerExtensionBytes = res.peerExtensionBytes
1038 c.PeerID = res.peerID
1039 c.completedHandshake = time.Now()
1043 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1044 if c.PeerID == cl.peerID {
1045 // Only if we initiated the connection is the remote address a
1046 // listen addr for a doppleganger.
1048 addr := c.conn.RemoteAddr().String()
1049 cl.dopplegangerAddrs[addr] = struct{}{}
1052 return cl.runHandshookConn(c, t)
1055 func (cl *Client) runReceivedConn(c *connection) (err error) {
1056 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1060 t, err := cl.receiveHandshakes(c)
1062 err = fmt.Errorf("error receiving handshakes: %s", err)
1069 defer cl.mu.Unlock()
1070 if c.PeerID == cl.peerID {
1073 return cl.runHandshookConn(c, t)
1076 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1077 c.conn.SetWriteDeadline(time.Time{})
1079 deadlineReader{c.conn, c.rw},
1082 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1083 if !cl.addConnection(t, c) {
1086 defer cl.dropConnection(t, c)
1088 go c.writeOptimizer(time.Minute)
1089 cl.sendInitialMessages(c, t)
1090 err = cl.connectionLoop(t, c)
1092 err = fmt.Errorf("error during connection loop: %s", err)
1097 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1098 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1099 conn.Post(pp.Message{
1101 ExtendedID: pp.HandshakeExtendedID,
1102 ExtendedPayload: func() []byte {
1103 d := map[string]interface{}{
1104 "m": func() (ret map[string]int) {
1105 ret = make(map[string]int, 2)
1106 ret["ut_metadata"] = metadataExtendedId
1107 if !me.config.DisablePEX {
1108 ret["ut_pex"] = pexExtendedId
1112 "v": extendedHandshakeClientVersion,
1113 // No upload queue is implemented yet.
1116 if !me.config.DisableEncryption {
1119 if torrent.metadataSizeKnown() {
1120 d["metadata_size"] = torrent.metadataSize()
1122 if p := me.incomingPeerPort(); p != 0 {
1125 yourip, err := addrCompactIP(conn.remoteAddr())
1127 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1129 d["yourip"] = yourip
1131 // log.Printf("sending %v", d)
1132 b, err := bencode.Marshal(d)
1140 if torrent.haveAnyPieces() {
1141 conn.Bitfield(torrent.bitfield())
1142 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1143 conn.Post(pp.Message{
1147 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1148 conn.Post(pp.Message{
1150 Port: uint16(AddrPort(me.dHT.Addr())),
1155 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1156 conn.updateRequests()
1159 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1162 postedCancels.Add(1)
1167 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1168 if !cn.RequestPending(r) {
1171 delete(cn.Requests, r)
1175 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1179 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1180 // Peer doesn't support this.
1183 // Request metadata pieces that we don't have in a random order.
1185 for index := 0; index < t.metadataPieceCount(); index++ {
1186 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1187 pending = append(pending, index)
1190 for _, i := range mathRand.Perm(len(pending)) {
1191 c.requestMetadataPiece(pending[i])
1195 func (cl *Client) completedMetadata(t *torrent) {
1199 CopyExact(&ih, h.Sum(nil))
1200 if ih != t.InfoHash {
1201 log.Print("bad metadata")
1202 t.invalidateMetadata()
1205 var info metainfo.Info
1206 err := bencode.Unmarshal(t.MetaData, &info)
1208 log.Printf("error unmarshalling metadata: %s", err)
1209 t.invalidateMetadata()
1212 // TODO(anacrolix): If this fails, I think something harsher should be
1214 err = cl.setMetaData(t, &info, t.MetaData)
1216 log.Printf("error setting metadata: %s", err)
1217 t.invalidateMetadata()
1220 if cl.config.Debug {
1221 log.Printf("%s: got metadata from peers", t)
1225 // Process incoming ut_metadata message.
1226 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1227 var d map[string]int
1228 err = bencode.Unmarshal(payload, &d)
1230 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1233 msgType, ok := d["msg_type"]
1235 err = errors.New("missing msg_type field")
1240 case pp.DataMetadataExtensionMsgType:
1244 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1245 if begin < 0 || begin >= len(payload) {
1246 log.Printf("got bad metadata piece")
1249 if !c.requestedMetadataPiece(piece) {
1250 log.Printf("got unexpected metadata piece %d", piece)
1253 c.metadataRequests[piece] = false
1254 t.saveMetadataPiece(piece, payload[begin:])
1255 c.UsefulChunksReceived++
1256 c.lastUsefulChunkReceived = time.Now()
1257 if !t.haveAllMetadataPieces() {
1260 cl.completedMetadata(t)
1261 case pp.RequestMetadataExtensionMsgType:
1262 if !t.haveMetadataPiece(piece) {
1263 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1266 start := (1 << 14) * piece
1267 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1268 case pp.RejectMetadataExtensionMsgType:
1270 err = errors.New("unknown msg_type value")
1275 func (me *Client) upload(t *torrent, c *connection) {
1276 if me.config.NoUpload {
1279 if !c.PeerInterested {
1282 seeding := me.seeding(t)
1283 if !seeding && !t.connHasWantedPieces(c) {
1287 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1289 for r := range c.PeerRequests {
1290 err := me.sendChunk(t, c, r)
1292 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1293 // We had the piece, but not anymore.
1295 log.Printf("error sending chunk %+v to peer: %s", r, err)
1297 // If we failed to send a chunk, choke the peer to ensure they
1298 // flush all their requests. We've probably dropped a piece,
1299 // but there's no way to communicate this to the peer. If they
1300 // ask for it again, we'll kick them to allow us to send them
1301 // an updated bitfield.
1304 delete(c.PeerRequests, r)
1312 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1313 // Count the chunk being sent, even if it isn't.
1314 b := make([]byte, r.Length)
1315 p := t.Info.Piece(int(r.Index))
1316 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1319 panic("expected error")
1330 uploadChunksPosted.Add(1)
1331 c.lastChunkSent = time.Now()
1335 // Processes incoming bittorrent messages. The client lock is held upon entry
1337 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1338 decoder := pp.Decoder{
1339 R: bufio.NewReader(c.rw),
1340 MaxLength: 256 * 1024,
1345 err := decoder.Decode(&msg)
1347 if me.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1353 c.lastMessageReceived = time.Now()
1355 receivedKeepalives.Add(1)
1358 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1363 // We can then reset our interest.
1366 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1369 c.PeerChoked = false
1370 me.peerUnchoked(t, c)
1372 c.PeerInterested = true
1374 case pp.NotInterested:
1375 c.PeerInterested = false
1378 err = c.peerSentHave(int(msg.Index))
1383 if !c.PeerInterested {
1384 err = errors.New("peer sent request but isn't interested")
1387 if !t.havePiece(msg.Index.Int()) {
1388 // This isn't necessarily them screwing up. We can drop pieces
1389 // from our storage, and can't communicate this to peers
1390 // except by reconnecting.
1391 requestsReceivedForMissingPieces.Add(1)
1392 err = errors.New("peer requested piece we don't have")
1395 if c.PeerRequests == nil {
1396 c.PeerRequests = make(map[request]struct{}, maxRequests)
1398 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1401 req := newRequest(msg.Index, msg.Begin, msg.Length)
1402 if !c.PeerCancel(req) {
1403 unexpectedCancels.Add(1)
1406 err = c.peerSentBitfield(msg.Bitfield)
1408 err = c.peerSentHaveAll()
1410 err = c.peerSentHaveNone()
1412 me.downloadedChunk(t, c, &msg)
1414 switch msg.ExtendedID {
1415 case pp.HandshakeExtendedID:
1416 // TODO: Create a bencode struct for this.
1417 var d map[string]interface{}
1418 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1420 err = fmt.Errorf("error decoding extended message payload: %s", err)
1423 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1424 if reqq, ok := d["reqq"]; ok {
1425 if i, ok := reqq.(int64); ok {
1426 c.PeerMaxRequests = int(i)
1429 if v, ok := d["v"]; ok {
1430 c.PeerClientName = v.(string)
1434 err = errors.New("handshake missing m item")
1437 mTyped, ok := m.(map[string]interface{})
1439 err = errors.New("handshake m value is not dict")
1442 if c.PeerExtensionIDs == nil {
1443 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1445 for name, v := range mTyped {
1448 log.Printf("bad handshake m item extension ID type: %T", v)
1452 delete(c.PeerExtensionIDs, name)
1454 if c.PeerExtensionIDs[name] == 0 {
1455 supportedExtensionMessages.Add(name, 1)
1457 c.PeerExtensionIDs[name] = byte(id)
1460 metadata_sizeUntyped, ok := d["metadata_size"]
1462 metadata_size, ok := metadata_sizeUntyped.(int64)
1464 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1466 t.setMetadataSize(metadata_size, me)
1469 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1470 me.requestPendingMetadata(t, c)
1472 case metadataExtendedId:
1473 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1475 err = fmt.Errorf("error handling metadata extension message: %s", err)
1478 if me.config.DisablePEX {
1481 var pexMsg peerExchangeMessage
1482 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1484 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1489 me.addPeers(t, func() (ret []Peer) {
1490 for i, cp := range pexMsg.Added {
1492 IP: make([]byte, 4),
1494 Source: peerSourcePEX,
1496 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1497 p.SupportsEncryption = true
1499 CopyExact(p.IP, cp.IP[:])
1500 ret = append(ret, p)
1507 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1510 // That client uses its own extension IDs for outgoing message
1511 // types, which is incorrect.
1512 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1513 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1521 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1526 pingAddr.Port = int(msg.Port)
1528 _, err = me.dHT.Ping(pingAddr)
1530 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1538 // Returns true if connection is removed from torrent.Conns.
1539 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1540 for i0, _c := range t.Conns {
1544 i1 := len(t.Conns) - 1
1546 t.Conns[i0] = t.Conns[i1]
1548 t.Conns = t.Conns[:i1]
1554 func (me *Client) dropConnection(t *torrent, c *connection) {
1555 me.event.Broadcast()
1557 if me.deleteConnection(t, c) {
1562 // Returns true if the connection is added.
1563 func (me *Client) addConnection(t *torrent, c *connection) bool {
1564 if me.closed.IsSet() {
1568 case <-t.ceasingNetworking:
1572 if !me.wantConns(t) {
1575 for _, c0 := range t.Conns {
1576 if c.PeerID == c0.PeerID {
1577 // Already connected to a client with that ID.
1578 duplicateClientConns.Add(1)
1582 if len(t.Conns) >= socketsPerTorrent {
1583 c := t.worstBadConn(me)
1587 if me.config.Debug && missinggo.CryHeard() {
1588 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1591 me.deleteConnection(t, c)
1593 if len(t.Conns) >= socketsPerTorrent {
1596 t.Conns = append(t.Conns, c)
1601 func (t *torrent) readerPieces() (ret bitmap.Bitmap) {
1602 t.forReaderOffsetPieces(func(begin, end int) bool {
1603 ret.AddRange(begin, end)
1609 func (t *torrent) needData() bool {
1613 if t.pendingPieces.Len() != 0 {
1616 return !t.readerPieces().IterTyped(func(piece int) bool {
1617 return t.pieceComplete(piece)
1621 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1622 if c.closed.IsSet() {
1626 return c.supportsExtension("ut_metadata")
1629 return c.PeerInterested
1631 return t.connHasWantedPieces(c)
1634 func (me *Client) wantConns(t *torrent) bool {
1635 if !me.seeding(t) && !t.needData() {
1638 if len(t.Conns) < socketsPerTorrent {
1641 return t.worstBadConn(me) != nil
1644 func (me *Client) openNewConns(t *torrent) {
1646 case <-t.ceasingNetworking:
1650 for len(t.Peers) != 0 {
1651 if !me.wantConns(t) {
1654 if len(t.HalfOpen) >= me.halfOpenLimit {
1661 for k, p = range t.Peers {
1665 me.initiateConn(p, t)
1667 t.wantPeers.Broadcast()
1670 func (me *Client) addPeers(t *torrent, peers []Peer) {
1671 for _, p := range peers {
1672 if me.dopplegangerAddr(net.JoinHostPort(
1674 strconv.FormatInt(int64(p.Port), 10),
1678 if _, ok := me.ipBlockRange(p.IP); ok {
1682 // The spec says to scrub these yourselves. Fine.
1689 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1690 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1693 func (cl *Client) saveTorrentFile(t *torrent) error {
1694 path := cl.cachedMetaInfoFilename(t.InfoHash)
1695 os.MkdirAll(filepath.Dir(path), 0777)
1696 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1698 return fmt.Errorf("error opening file: %s", err)
1701 e := bencode.NewEncoder(f)
1702 err = e.Encode(t.MetaInfo())
1704 return fmt.Errorf("error marshalling metainfo: %s", err)
1706 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1708 // For example, a script kiddy makes us load too many files, and we're
1709 // able to save the torrent, but not load it again to check it.
1712 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1713 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1718 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1720 cl.event.Broadcast()
1724 type TorrentDataOpener func(*metainfo.Info) Data
1726 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1727 err = t.setMetadata(md, bytes)
1731 if !cl.config.DisableMetainfoCache {
1732 if err := cl.saveTorrentFile(t); err != nil {
1733 log.Printf("error saving torrent file for %s: %s", t, err)
1736 cl.event.Broadcast()
1737 close(t.gotMetainfo)
1738 td := cl.torrentDataOpener(md)
1739 err = cl.setStorage(t, td)
1743 // Prepare a Torrent without any attachment to a Client. That means we can
1744 // initialize fields all fields that don't require the Client without locking
1746 func newTorrent(ih InfoHash) (t *torrent) {
1749 chunkSize: defaultChunkSize,
1750 Peers: make(map[peersKey]Peer),
1752 closing: make(chan struct{}),
1753 ceasingNetworking: make(chan struct{}),
1755 gotMetainfo: make(chan struct{}),
1757 HalfOpen: make(map[string]struct{}),
1758 pieceStateChanges: pubsub.NewPubSub(),
1764 // For shuffling the tracker tiers.
1765 mathRand.Seed(time.Now().Unix())
1768 type trackerTier []string
1770 // The trackers within each tier must be shuffled before use.
1771 // http://stackoverflow.com/a/12267471/149482
1772 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1773 func shuffleTier(tier trackerTier) {
1774 for i := range tier {
1775 j := mathRand.Intn(i + 1)
1776 tier[i], tier[j] = tier[j], tier[i]
1780 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1781 for _, tier := range base {
1782 copy = append(copy, append(trackerTier(nil), tier...))
1787 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1789 for _, url := range newURLs {
1790 for _, trURL := range tier {
1795 tier = append(tier, url)
1800 func (t *torrent) addTrackers(announceList [][]string) {
1801 newTrackers := copyTrackers(t.Trackers)
1802 for tierIndex, tier := range announceList {
1803 if tierIndex < len(newTrackers) {
1804 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1806 newTrackers = append(newTrackers, mergeTier(nil, tier))
1808 shuffleTier(newTrackers[tierIndex])
1810 t.Trackers = newTrackers
1813 // Don't call this before the info is available.
1814 func (t *torrent) bytesCompleted() int64 {
1818 return t.Info.TotalLength() - t.bytesLeft()
1821 // A file-like handle to some torrent data resource.
1822 type Handle interface {
1829 // Returns handles to the files in the torrent. This requires the metainfo is
1831 func (t Torrent) Files() (ret []File) {
1839 for _, fi := range info.UpvertedFiles() {
1840 ret = append(ret, File{
1842 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1852 func (t Torrent) AddPeers(pp []Peer) error {
1855 defer cl.mu.Unlock()
1856 cl.addPeers(t.torrent, pp)
1860 // Marks the entire torrent for download. Requires the info first, see
1862 func (t Torrent) DownloadAll() {
1864 defer t.cl.mu.Unlock()
1865 t.torrent.pendPieceRange(0, t.torrent.numPieces())
1868 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1869 // metainfo has the correct infohash.
1870 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1871 if cl.config.DisableMetainfoCache {
1874 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1876 if os.IsNotExist(err) {
1882 dec := bencode.NewDecoder(f)
1883 err = dec.Decode(&mi)
1887 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1888 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1894 // Specifies a new torrent for adding to a client. There are helpers for
1895 // magnet URIs and torrent metainfo files.
1896 type TorrentSpec struct {
1897 // The tiered tracker URIs.
1900 Info *metainfo.InfoEx
1901 // The name to use if the Name field from the Info isn't available.
1903 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1908 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1909 m, err := ParseMagnetURI(uri)
1913 spec = &TorrentSpec{
1914 Trackers: [][]string{m.Trackers},
1915 DisplayName: m.DisplayName,
1916 InfoHash: m.InfoHash,
1921 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1922 spec = &TorrentSpec{
1923 Trackers: mi.AnnounceList,
1925 DisplayName: mi.Info.Name,
1928 if len(spec.Trackers) == 0 {
1929 spec.Trackers = [][]string{[]string{mi.Announce}}
1931 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
1934 CopyExact(&spec.InfoHash, &mi.Info.Hash)
1938 // Add or merge a torrent spec. If the torrent is already present, the
1939 // trackers will be merged with the existing ones. If the Info isn't yet
1940 // known, it will be set. The display name is replaced if the new spec
1941 // provides one. Returns new if the torrent wasn't already in the client.
1942 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
1945 defer cl.mu.Unlock()
1947 t, ok := cl.torrents[spec.InfoHash]
1951 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
1952 err = errors.New("banned torrent")
1955 // TODO: Tidy this up?
1956 t = newTorrent(spec.InfoHash)
1958 t.wantPeers.L = &cl.mu
1959 if spec.ChunkSize != 0 {
1960 t.chunkSize = pp.Integer(spec.ChunkSize)
1963 if spec.DisplayName != "" {
1964 t.setDisplayName(spec.DisplayName)
1966 // Try to merge in info we have on the torrent. Any err left will
1967 // terminate the function.
1969 if spec.Info != nil {
1970 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
1972 var mi *metainfo.MetaInfo
1973 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
1975 log.Printf("error getting cached metainfo: %s", err)
1977 } else if mi != nil {
1978 t.addTrackers(mi.AnnounceList)
1979 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
1986 t.addTrackers(spec.Trackers)
1988 cl.torrents[spec.InfoHash] = t
1991 // From this point onwards, we can consider the torrent a part of the
1994 if !cl.config.DisableTrackers {
1995 go cl.announceTorrentTrackers(T.torrent)
1998 go cl.announceTorrentDHT(T.torrent, true)
2004 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2005 t, ok := me.torrents[infoHash]
2007 err = fmt.Errorf("no such torrent")
2014 delete(me.torrents, infoHash)
2018 // Returns true when peers are required, or false if the torrent is closing.
2019 func (cl *Client) waitWantPeers(t *torrent) bool {
2021 defer cl.mu.Unlock()
2024 case <-t.ceasingNetworking:
2028 if len(t.Peers) > torrentPeersLowWater {
2031 if t.needData() || cl.seeding(t) {
2039 // Returns whether the client should make effort to seed the torrent.
2040 func (cl *Client) seeding(t *torrent) bool {
2041 if cl.config.NoUpload {
2044 if !cl.config.Seed {
2053 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2054 for cl.waitWantPeers(t) {
2055 // log.Printf("getting peers for %q from DHT", t)
2056 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2058 log.Printf("error getting peers from dht: %s", err)
2061 // Count all the unique addresses we got during this announce.
2062 allAddrs := make(map[string]struct{})
2066 case v, ok := <-ps.Peers:
2070 addPeers := make([]Peer, 0, len(v.Peers))
2071 for _, cp := range v.Peers {
2073 // Can't do anything with this.
2076 addPeers = append(addPeers, Peer{
2079 Source: peerSourceDHT,
2081 key := (&net.UDPAddr{
2085 allAddrs[key] = struct{}{}
2088 cl.addPeers(t, addPeers)
2089 numPeers := len(t.Peers)
2091 if numPeers >= torrentPeersHighWater {
2094 case <-t.ceasingNetworking:
2100 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2104 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
2105 url_, err := url.Parse(trRawURL)
2109 host, _, err := net.SplitHostPort(url_.Host)
2113 addr, err := net.ResolveIPAddr("ip", host)
2118 _, blocked = cl.ipBlockRange(addr.IP)
2123 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *torrent) error {
2124 blocked, err := cl.trackerBlockedUnlocked(tr)
2126 return fmt.Errorf("error determining if tracker blocked: %s", err)
2129 return fmt.Errorf("tracker blocked: %s", tr)
2131 resp, err := tracker.Announce(tr, req)
2133 return fmt.Errorf("error announcing: %s", err)
2136 for _, peer := range resp.Peers {
2137 peers = append(peers, Peer{
2143 cl.addPeers(t, peers)
2146 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2148 time.Sleep(time.Second * time.Duration(resp.Interval))
2152 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *torrent) (atLeastOne bool) {
2153 oks := make(chan bool)
2155 for _, tier := range trackers {
2156 for _, tr := range tier {
2158 go func(tr string) {
2159 err := cl.announceTorrentSingleTracker(tr, req, t)
2164 for outstanding > 0 {
2174 // Announce torrent to its trackers.
2175 func (cl *Client) announceTorrentTrackers(t *torrent) {
2176 req := tracker.AnnounceRequest{
2177 Event: tracker.Started,
2179 Port: uint16(cl.incomingPeerPort()),
2181 InfoHash: t.InfoHash,
2183 if !cl.waitWantPeers(t) {
2187 req.Left = t.bytesLeftAnnounce()
2188 trackers := t.Trackers
2190 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2191 req.Event = tracker.None
2194 for cl.waitWantPeers(t) {
2196 req.Left = t.bytesLeftAnnounce()
2197 trackers = t.Trackers
2199 numTrackersTried := 0
2200 for _, tier := range trackers {
2201 for trIndex, tr := range tier {
2203 err := cl.announceTorrentSingleTracker(tr, &req, t)
2207 // Float the successful announce to the top of the tier. If
2208 // the trackers list has been changed, we'll be modifying an
2209 // old copy so it won't matter.
2211 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2214 req.Event = tracker.None
2215 continue newAnnounce
2218 if numTrackersTried != 0 {
2219 log.Printf("%s: all trackers failed", t)
2221 // TODO: Wait until trackers are added if there are none.
2222 time.Sleep(10 * time.Second)
2226 func (cl *Client) allTorrentsCompleted() bool {
2227 for _, t := range cl.torrents {
2231 if t.numPiecesCompleted() != t.numPieces() {
2238 // Returns true when all torrents are completely downloaded and false if the
2239 // client is stopped before that.
2240 func (me *Client) WaitAll() bool {
2242 defer me.mu.Unlock()
2243 for !me.allTorrentsCompleted() {
2244 if me.closed.IsSet() {
2252 // Handle a received chunk from a peer.
2253 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) {
2254 chunksReceived.Add(1)
2256 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2258 // Request has been satisfied.
2259 if me.connDeleteRequest(t, c, req) {
2260 defer c.updateRequests()
2262 unexpectedChunksReceived.Add(1)
2265 index := int(req.Index)
2266 piece := &t.Pieces[index]
2268 // Do we actually want this chunk?
2269 if !t.wantChunk(req) {
2270 unwantedChunksReceived.Add(1)
2271 c.UnwantedChunksReceived++
2275 c.UsefulChunksReceived++
2276 c.lastUsefulChunkReceived = time.Now()
2280 // Need to record that it hasn't been written yet, before we attempt to do
2281 // anything with it.
2282 piece.incrementPendingWrites()
2283 // Record that we have the chunk.
2284 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2286 // Cancel pending requests for this chunk.
2287 for _, c := range t.Conns {
2288 if me.connCancel(t, c, req) {
2294 // Write the chunk out.
2295 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2298 piece.decrementPendingWrites()
2301 log.Printf("error writing chunk: %s", err)
2306 // It's important that the piece is potentially queued before we check if
2307 // the piece is still wanted, because if it is queued, it won't be wanted.
2308 if t.pieceAllDirty(index) {
2309 me.queuePieceCheck(t, int(req.Index))
2312 if c.peerTouchedPieces == nil {
2313 c.peerTouchedPieces = make(map[int]struct{})
2315 c.peerTouchedPieces[index] = struct{}{}
2317 me.event.Broadcast()
2318 t.publishPieceChange(int(req.Index))
2322 // Return the connections that touched a piece, and clear the entry while
2324 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2325 for _, c := range t.Conns {
2326 if _, ok := c.peerTouchedPieces[piece]; ok {
2327 ret = append(ret, c)
2328 delete(c.peerTouchedPieces, piece)
2334 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2335 p := &t.Pieces[piece]
2337 // Don't score the first time a piece is hashed, it could be an
2340 pieceHashedCorrect.Add(1)
2342 log.Printf("%s: piece %d failed hash", t, piece)
2343 pieceHashedNotCorrect.Add(1)
2347 touchers := me.reapPieceTouches(t, int(piece))
2349 err := t.data.PieceCompleted(int(piece))
2351 log.Printf("%T: error completing piece %d: %s", t.data, piece, err)
2353 t.updatePieceCompletion(piece)
2354 } else if len(touchers) != 0 {
2355 log.Printf("dropping %d conns that touched piece", len(touchers))
2356 for _, c := range touchers {
2357 me.dropConnection(t, c)
2360 me.pieceChanged(t, int(piece))
2363 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2364 t.pendingPieces.Remove(piece)
2365 t.pendAllChunkSpecs(piece)
2366 for _, conn := range t.Conns {
2368 for r := range conn.Requests {
2369 if int(r.Index) == piece {
2373 // Could check here if peer doesn't have piece, but due to caching
2374 // some peers may have said they have a piece but they don't.
2379 func (me *Client) onFailedPiece(t *torrent, piece int) {
2380 if t.pieceAllDirty(piece) {
2381 t.pendAllChunkSpecs(piece)
2383 if !t.wantPiece(piece) {
2387 for _, conn := range t.Conns {
2388 if conn.PeerHasPiece(piece) {
2389 conn.updateRequests()
2394 func (me *Client) pieceChanged(t *torrent, piece int) {
2395 correct := t.pieceComplete(piece)
2396 defer me.event.Broadcast()
2398 me.onCompletedPiece(t, piece)
2400 me.onFailedPiece(t, piece)
2402 if t.updatePiecePriority(piece) {
2403 t.piecePriorityChanged(piece)
2405 t.publishPieceChange(piece)
2408 func (cl *Client) verifyPiece(t *torrent, piece int) {
2410 defer cl.mu.Unlock()
2411 p := &t.Pieces[piece]
2412 for p.Hashing || t.data == nil {
2415 p.QueuedForHash = false
2416 if t.isClosed() || t.pieceComplete(piece) {
2417 t.updatePiecePriority(piece)
2418 t.publishPieceChange(piece)
2422 t.publishPieceChange(piece)
2424 sum := t.hashPiece(piece)
2432 cl.pieceHashed(t, piece, sum == p.Hash)
2435 // Returns handles to all the torrents loaded in the Client.
2436 func (me *Client) Torrents() (ret []Torrent) {
2438 for _, t := range me.torrents {
2439 ret = append(ret, Torrent{me, t})
2445 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2446 spec, err := TorrentSpecFromMagnetURI(uri)
2450 T, _, err = me.AddTorrentSpec(spec)
2454 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2455 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2457 missinggo.CastSlice(&ss, mi.Nodes)
2462 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2463 mi, err := metainfo.LoadFromFile(filename)
2467 return me.AddTorrent(mi)
2470 func (me *Client) DHT() *dht.Server {
2474 func (me *Client) AddDHTNodes(nodes []string) {
2475 for _, n := range nodes {
2476 hmp := missinggo.SplitHostMaybePort(n)
2477 ip := net.ParseIP(hmp.Host)
2479 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
2483 Addr: dht.NewAddr(&net.UDPAddr{
2488 me.DHT().AddNode(ni)