25 "github.com/anacrolix/missinggo"
26 "github.com/anacrolix/missinggo/bitmap"
27 "github.com/anacrolix/missinggo/pproffd"
28 "github.com/anacrolix/missinggo/pubsub"
29 "github.com/anacrolix/sync"
30 "github.com/anacrolix/utp"
32 "github.com/anacrolix/torrent/bencode"
33 "github.com/anacrolix/torrent/dht"
34 "github.com/anacrolix/torrent/iplist"
35 "github.com/anacrolix/torrent/metainfo"
36 "github.com/anacrolix/torrent/mse"
37 pp "github.com/anacrolix/torrent/peer_protocol"
38 "github.com/anacrolix/torrent/storage"
39 "github.com/anacrolix/torrent/tracker"
42 // I could move a lot of these counters to their own file, but I suspect they
43 // may be attached to a Client someday.
45 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
46 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
47 chunksReceived = expvar.NewInt("chunksReceived")
49 peersAddedBySource = expvar.NewMap("peersAddedBySource")
51 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
52 unexpectedCancels = expvar.NewInt("unexpectedCancels")
53 postedCancels = expvar.NewInt("postedCancels")
54 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
56 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
57 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
59 unsuccessfulDials = expvar.NewInt("dialSuccessful")
60 successfulDials = expvar.NewInt("dialUnsuccessful")
62 acceptUTP = expvar.NewInt("acceptUTP")
63 acceptTCP = expvar.NewInt("acceptTCP")
64 acceptReject = expvar.NewInt("acceptReject")
66 peerExtensions = expvar.NewMap("peerExtensions")
67 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
68 // Count of connections to peer with same client ID.
69 connsToSelf = expvar.NewInt("connsToSelf")
70 // Number of completed connections to a client we're already connected with.
71 duplicateClientConns = expvar.NewInt("duplicateClientConns")
72 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
73 receivedKeepalives = expvar.NewInt("receivedKeepalives")
74 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
75 postedMessageTypes = expvar.NewMap("postedMessageTypes")
76 postedKeepalives = expvar.NewInt("postedKeepalives")
77 // Requests received for pieces we don't have.
78 requestsReceivedForMissingPieces = expvar.NewInt("requestsReceivedForMissingPieces")
82 // Justification for set bits follows.
84 // Extension protocol ([5]|=0x10):
85 // http://www.bittorrent.org/beps/bep_0010.html
87 // Fast Extension ([7]|=0x04):
88 // http://bittorrent.org/beps/bep_0006.html.
89 // Disabled until AllowedFast is implemented.
92 // http://www.bittorrent.org/beps/bep_0005.html
93 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
95 socketsPerTorrent = 80
96 torrentPeersHighWater = 200
97 torrentPeersLowWater = 50
99 // Limit how long handshake can take. This is to reduce the lingering
100 // impact of a few bad apples. 4s loses 1% of successful handshakes that
101 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
102 handshakesTimeout = 20 * time.Second
104 // These are our extended message IDs.
105 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
108 // Updated occasionally to when there's been some changes to client
109 // behaviour in case other clients are assuming anything of us. See also
111 extendedHandshakeClientVersion = "go.torrent dev 20150624"
114 // Currently doesn't really queue, but should in the future.
115 func (cl *Client) queuePieceCheck(t *Torrent, pieceIndex int) {
116 piece := &t.pieces[pieceIndex]
117 if piece.QueuedForHash {
120 piece.QueuedForHash = true
121 t.publishPieceChange(int(pieceIndex))
122 go cl.verifyPiece(t, int(pieceIndex))
125 // Queue a piece check if one isn't already queued, and the piece has never
126 // been checked before.
127 func (cl *Client) queueFirstHash(t *Torrent, piece int) {
128 p := &t.pieces[piece]
129 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
132 cl.queuePieceCheck(t, piece)
135 // Clients contain zero or more Torrents. A client manages a blocklist, the
136 // TCP/UDP protocol ports, and DHT as desired.
140 listeners []net.Listener
143 ipBlockList iplist.Ranger
144 bannedTorrents map[metainfo.Hash]struct{}
146 pruneTimer *time.Timer
147 extensionBytes peerExtensionBytes
148 // Set of addresses that have our client ID. This intentionally will
149 // include ourselves if we end up trying to connect to our own address
150 // through legitimate channels.
151 dopplegangerAddrs map[string]struct{}
153 defaultStorage storage.I
157 closed missinggo.Event
159 torrents map[metainfo.Hash]*Torrent
162 func (me *Client) IPBlockList() iplist.Ranger {
165 return me.ipBlockList
168 func (me *Client) SetIPBlockList(list iplist.Ranger) {
171 me.ipBlockList = list
173 me.dHT.SetIPBlockList(list)
177 func (me *Client) PeerID() string {
178 return string(me.peerID[:])
181 func (me *Client) ListenAddr() (addr net.Addr) {
182 for _, l := range me.listeners {
189 type hashSorter struct {
190 Hashes []metainfo.Hash
193 func (me hashSorter) Len() int {
194 return len(me.Hashes)
197 func (me hashSorter) Less(a, b int) bool {
198 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
201 func (me hashSorter) Swap(a, b int) {
202 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
205 func (cl *Client) sortedTorrents() (ret []*Torrent) {
207 for ih := range cl.torrents {
208 hs.Hashes = append(hs.Hashes, ih)
211 for _, ih := range hs.Hashes {
212 ret = append(ret, cl.torrent(ih))
217 // Writes out a human readable status of the client, such as for writing to a
219 func (cl *Client) WriteStatus(_w io.Writer) {
221 defer cl.mu.RUnlock()
222 w := bufio.NewWriter(_w)
224 if addr := cl.ListenAddr(); addr != nil {
225 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
227 fmt.Fprintln(w, "Not listening!")
229 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
231 dhtStats := cl.dHT.Stats()
232 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
233 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
234 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
235 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
236 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
238 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
240 for _, t := range cl.sortedTorrents() {
242 fmt.Fprint(w, "<unknown name>")
244 fmt.Fprint(w, t.name())
248 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length)
250 w.WriteString("<missing metainfo>")
258 func (cl *Client) configDir() string {
259 if cl.config.ConfigDir == "" {
260 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
262 return cl.config.ConfigDir
265 // The directory where the Client expects to find and store configuration
266 // data. Defaults to $HOME/.config/torrent.
267 func (cl *Client) ConfigDir() string {
268 return cl.configDir()
271 // Creates a new client.
272 func NewClient(cfg *Config) (cl *Client, err error) {
283 halfOpenLimit: socketsPerTorrent,
285 defaultStorage: cfg.DefaultStorage,
286 dopplegangerAddrs: make(map[string]struct{}),
287 torrents: make(map[metainfo.Hash]*Torrent),
289 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
291 if cl.defaultStorage == nil {
292 cl.defaultStorage = storage.NewFile(cfg.DataDir)
294 if cfg.IPBlocklist != nil {
295 cl.ipBlockList = cfg.IPBlocklist
298 if cfg.PeerID != "" {
299 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
301 o := copy(cl.peerID[:], bep20)
302 _, err = rand.Read(cl.peerID[o:])
304 panic("error generating peer id")
308 // Returns the laddr string to listen on for the next Listen call.
309 listenAddr := func() string {
310 if addr := cl.ListenAddr(); addr != nil {
313 if cfg.ListenAddr == "" {
316 return cfg.ListenAddr
318 if !cl.config.DisableTCP {
320 l, err = net.Listen(func() string {
321 if cl.config.DisableIPv6 {
330 cl.listeners = append(cl.listeners, l)
331 go cl.acceptConnections(l, false)
333 if !cl.config.DisableUTP {
334 cl.utpSock, err = utp.NewSocket(func() string {
335 if cl.config.DisableIPv6 {
344 cl.listeners = append(cl.listeners, cl.utpSock)
345 go cl.acceptConnections(cl.utpSock, true)
348 dhtCfg := cfg.DHTConfig
349 if dhtCfg.IPBlocklist == nil {
350 dhtCfg.IPBlocklist = cl.ipBlockList
352 if dhtCfg.Addr == "" {
353 dhtCfg.Addr = listenAddr()
355 if dhtCfg.Conn == nil && cl.utpSock != nil {
356 dhtCfg.Conn = cl.utpSock
358 cl.dHT, err = dht.NewServer(&dhtCfg)
367 // Stops the client. All connections to peers are closed and all activity will
369 func (me *Client) Close() {
376 for _, l := range me.listeners {
379 for _, t := range me.torrents {
385 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
387 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
388 if cl.ipBlockList == nil {
392 // If blocklists are enabled, then block non-IPv4 addresses, because
393 // blocklists do not yet support IPv6.
395 if missinggo.CryHeard() {
396 log.Printf("blocking non-IPv4 address: %s", ip)
402 return cl.ipBlockList.Lookup(ip4)
405 func (cl *Client) waitAccept() {
409 for _, t := range cl.torrents {
414 if cl.closed.IsSet() {
421 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
424 conn, err := l.Accept()
425 conn = pproffd.WrapNetConn(conn)
426 if cl.closed.IsSet() {
434 // I think something harsher should happen here? Our accept
435 // routine just fucked off.
444 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
445 _, blocked := cl.ipBlockRange(missinggo.AddrIP(conn.RemoteAddr()))
447 if blocked || doppleganger {
449 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
453 go cl.incomingConnection(conn, utp)
457 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
459 if tc, ok := nc.(*net.TCPConn); ok {
465 c.Discovery = peerSourceIncoming
467 err := cl.runReceivedConn(c)
473 // Returns a handle to the given torrent, if it's present in the client.
474 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
477 t, ok = cl.torrents[ih]
481 func (me *Client) torrent(ih metainfo.Hash) *Torrent {
482 return me.torrents[ih]
485 type dialResult struct {
490 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
491 conn, err := dial(addr, t)
496 conn = nil // Pedantic
498 ch <- dialResult{conn, utp}
500 successfulDials.Add(1)
503 unsuccessfulDials.Add(1)
506 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
507 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
508 if ret < minDialTimeout {
514 // Returns whether an address is known to connect to a client with our own ID.
515 func (me *Client) dopplegangerAddr(addr string) bool {
516 _, ok := me.dopplegangerAddrs[addr]
520 // Start the process of connecting to the given peer for the given torrent if
522 func (me *Client) initiateConn(peer Peer, t *Torrent) {
523 if peer.Id == me.peerID {
526 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
527 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
528 duplicateConnsAvoided.Add(1)
531 if r, ok := me.ipBlockRange(peer.IP); ok {
532 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
535 t.halfOpen[addr] = struct{}{}
536 go me.outgoingConnection(t, addr, peer.Source)
539 func (me *Client) dialTimeout(t *Torrent) time.Duration {
541 pendingPeers := len(t.peers)
543 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
546 func (me *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
547 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
549 c.(*net.TCPConn).SetLinger(0)
554 func (me *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
555 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
558 // Returns a connection over UTP or TCP, whichever is first to connect.
559 func (me *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
560 // Initiate connections via TCP and UTP simultaneously. Use the first one
563 if !me.config.DisableUTP {
566 if !me.config.DisableTCP {
569 resCh := make(chan dialResult, left)
570 if !me.config.DisableUTP {
571 go doDial(me.dialUTP, resCh, true, addr, t)
573 if !me.config.DisableTCP {
574 go doDial(me.dialTCP, resCh, false, addr, t)
577 // Wait for a successful connection.
578 for ; left > 0 && res.Conn == nil; left-- {
582 // There are still incompleted dials.
584 for ; left > 0; left-- {
585 conn := (<-resCh).Conn
597 func (me *Client) noLongerHalfOpen(t *Torrent, addr string) {
598 if _, ok := t.halfOpen[addr]; !ok {
599 panic("invariant broken")
601 delete(t.halfOpen, addr)
605 // Performs initiator handshakes and returns a connection. Returns nil
606 // *connection if no connection for valid reasons.
607 func (me *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
611 c.encrypted = encrypted
613 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
617 ok, err := me.initiateHandshakes(c, t)
624 // Returns nil connection and nil error if no connection could be established
625 // for valid reasons.
626 func (me *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
627 nc, utp := me.dialFirst(addr, t)
631 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
639 if me.config.DisableEncryption {
640 // We already tried without encryption.
643 // Try again without encryption, using whichever protocol type worked last
646 nc, err = me.dialUTP(addr, t)
648 nc, err = me.dialTCP(addr, t)
651 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
654 c, err = me.handshakesConnection(nc, t, false, utp)
655 if err != nil || c == nil {
661 // Called to dial out and run a connection. The addr we're given is already
662 // considered half-open.
663 func (me *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
664 c, err := me.establishOutgoingConn(t, addr)
667 // Don't release lock between here and addConnection, unless it's for
669 me.noLongerHalfOpen(t, addr)
672 log.Printf("error establishing outgoing connection: %s", err)
681 err = me.runInitiatedHandshookConn(c, t)
684 log.Printf("error in established outgoing connection: %s", err)
689 // The port number for incoming peer connections. 0 if the client isn't
691 func (cl *Client) incomingPeerPort() int {
692 listenAddr := cl.ListenAddr()
693 if listenAddr == nil {
696 return missinggo.AddrPort(listenAddr)
699 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
700 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
701 func addrCompactIP(addr net.Addr) (string, error) {
702 host, _, err := net.SplitHostPort(addr.String())
706 ip := net.ParseIP(host)
707 if v4 := ip.To4(); v4 != nil {
711 return string(v4), nil
713 return string(ip.To16()), nil
716 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
728 peerExtensionBytes [8]byte
732 func (me *peerExtensionBytes) SupportsExtended() bool {
733 return me[5]&0x10 != 0
736 func (me *peerExtensionBytes) SupportsDHT() bool {
737 return me[7]&0x01 != 0
740 func (me *peerExtensionBytes) SupportsFast() bool {
741 return me[7]&0x04 != 0
744 type handshakeResult struct {
750 // ih is nil if we expect the peer to declare the InfoHash, such as when the
751 // peer initiated the connection. Returns ok if the handshake was successful,
752 // and err if there was an unexpected condition other than the peer simply
753 // abandoning the handshake.
754 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
755 // Bytes to be sent to the peer. Should never block the sender.
756 postCh := make(chan []byte, 4)
757 // A single error value sent when the writer completes.
758 writeDone := make(chan error, 1)
759 // Performs writes to the socket and ensures posts don't block.
760 go handshakeWriter(sock, postCh, writeDone)
763 close(postCh) // Done writing.
770 // Wait until writes complete before returning from handshake.
773 err = fmt.Errorf("error writing: %s", err)
777 post := func(bb []byte) {
781 panic("mustn't block while posting")
785 post([]byte(pp.Protocol))
787 if ih != nil { // We already know what we want.
792 _, err = io.ReadFull(sock, b[:68])
797 if string(b[:20]) != pp.Protocol {
800 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
801 missinggo.CopyExact(&res.Hash, b[28:48])
802 missinggo.CopyExact(&res.peerID, b[48:68])
803 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
805 // TODO: Maybe we can just drop peers here if we're not interested. This
806 // could prevent them trying to reconnect, falsely believing there was
808 if ih == nil { // We were waiting for the peer to tell us what they wanted.
817 // Wraps a raw connection and provides the interface we want for using the
818 // connection in the message loop.
819 type deadlineReader struct {
824 func (me deadlineReader) Read(b []byte) (n int, err error) {
825 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
826 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
828 err = fmt.Errorf("error setting read deadline: %s", err)
830 n, err = me.r.Read(b)
831 // Convert common errors into io.EOF.
833 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
835 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
845 type readWriter struct {
850 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
851 var protocol [len(pp.Protocol)]byte
852 _, err = io.ReadFull(rw, protocol[:])
857 io.MultiReader(bytes.NewReader(protocol[:]), rw),
860 if string(protocol[:]) == pp.Protocol {
864 ret, err = mse.ReceiveHandshake(ret, skeys)
868 func (cl *Client) receiveSkeys() (ret [][]byte) {
869 for ih := range cl.torrents {
870 ret = append(ret, ih[:])
875 func (me *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
877 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
882 ih, ok, err := me.connBTHandshake(c, &t.infoHash)
883 if ih != t.infoHash {
889 // Do encryption and bittorrent handshakes as receiver.
890 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
892 skeys := cl.receiveSkeys()
894 if !cl.config.DisableEncryption {
895 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
897 if err == mse.ErrNoSecretKeyMatch {
903 ih, ok, err := cl.connBTHandshake(c, nil)
905 err = fmt.Errorf("error during bt handshake: %s", err)
917 // Returns !ok if handshake failed for valid reasons.
918 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
919 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
920 if err != nil || !ok {
924 c.PeerExtensionBytes = res.peerExtensionBytes
925 c.PeerID = res.peerID
926 c.completedHandshake = time.Now()
930 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) (err error) {
931 if c.PeerID == cl.peerID {
932 // Only if we initiated the connection is the remote address a
933 // listen addr for a doppleganger.
935 addr := c.conn.RemoteAddr().String()
936 cl.dopplegangerAddrs[addr] = struct{}{}
939 return cl.runHandshookConn(c, t)
942 func (cl *Client) runReceivedConn(c *connection) (err error) {
943 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
947 t, err := cl.receiveHandshakes(c)
949 err = fmt.Errorf("error receiving handshakes: %s", err)
957 if c.PeerID == cl.peerID {
960 return cl.runHandshookConn(c, t)
963 func (cl *Client) runHandshookConn(c *connection, t *Torrent) (err error) {
964 c.conn.SetWriteDeadline(time.Time{})
966 deadlineReader{c.conn, c.rw},
969 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
970 if !cl.addConnection(t, c) {
973 defer cl.dropConnection(t, c)
975 go c.writeOptimizer(time.Minute)
976 cl.sendInitialMessages(c, t)
977 err = cl.connectionLoop(t, c)
979 err = fmt.Errorf("error during connection loop: %s", err)
984 func (me *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
985 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
986 conn.Post(pp.Message{
988 ExtendedID: pp.HandshakeExtendedID,
989 ExtendedPayload: func() []byte {
990 d := map[string]interface{}{
991 "m": func() (ret map[string]int) {
992 ret = make(map[string]int, 2)
993 ret["ut_metadata"] = metadataExtendedId
994 if !me.config.DisablePEX {
995 ret["ut_pex"] = pexExtendedId
999 "v": extendedHandshakeClientVersion,
1000 // No upload queue is implemented yet.
1003 if !me.config.DisableEncryption {
1006 if torrent.metadataSizeKnown() {
1007 d["metadata_size"] = torrent.metadataSize()
1009 if p := me.incomingPeerPort(); p != 0 {
1012 yourip, err := addrCompactIP(conn.remoteAddr())
1014 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1016 d["yourip"] = yourip
1018 // log.Printf("sending %v", d)
1019 b, err := bencode.Marshal(d)
1027 if torrent.haveAnyPieces() {
1028 conn.Bitfield(torrent.bitfield())
1029 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1030 conn.Post(pp.Message{
1034 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1035 conn.Post(pp.Message{
1037 Port: uint16(missinggo.AddrPort(me.dHT.Addr())),
1042 func (me *Client) peerUnchoked(torrent *Torrent, conn *connection) {
1043 conn.updateRequests()
1046 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1049 postedCancels.Add(1)
1054 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1055 if !cn.RequestPending(r) {
1058 delete(cn.Requests, r)
1062 func (cl *Client) requestPendingMetadata(t *Torrent, c *connection) {
1066 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1067 // Peer doesn't support this.
1070 // Request metadata pieces that we don't have in a random order.
1072 for index := 0; index < t.metadataPieceCount(); index++ {
1073 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1074 pending = append(pending, index)
1077 for _, i := range mathRand.Perm(len(pending)) {
1078 c.requestMetadataPiece(pending[i])
1082 func (cl *Client) completedMetadata(t *Torrent) {
1084 h.Write(t.metadataBytes)
1085 var ih metainfo.Hash
1086 missinggo.CopyExact(&ih, h.Sum(nil))
1087 if ih != t.infoHash {
1088 log.Print("bad metadata")
1089 t.invalidateMetadata()
1092 var info metainfo.Info
1093 err := bencode.Unmarshal(t.metadataBytes, &info)
1095 log.Printf("error unmarshalling metadata: %s", err)
1096 t.invalidateMetadata()
1099 // TODO(anacrolix): If this fails, I think something harsher should be
1101 err = cl.setMetaData(t, &info, t.metadataBytes)
1103 log.Printf("error setting metadata: %s", err)
1104 t.invalidateMetadata()
1107 if cl.config.Debug {
1108 log.Printf("%s: got metadata from peers", t)
1112 // Process incoming ut_metadata message.
1113 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) (err error) {
1114 var d map[string]int
1115 err = bencode.Unmarshal(payload, &d)
1117 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1120 msgType, ok := d["msg_type"]
1122 err = errors.New("missing msg_type field")
1127 case pp.DataMetadataExtensionMsgType:
1131 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1132 if begin < 0 || begin >= len(payload) {
1133 log.Printf("got bad metadata piece")
1136 if !c.requestedMetadataPiece(piece) {
1137 log.Printf("got unexpected metadata piece %d", piece)
1140 c.metadataRequests[piece] = false
1141 t.saveMetadataPiece(piece, payload[begin:])
1142 c.UsefulChunksReceived++
1143 c.lastUsefulChunkReceived = time.Now()
1144 if !t.haveAllMetadataPieces() {
1147 cl.completedMetadata(t)
1148 case pp.RequestMetadataExtensionMsgType:
1149 if !t.haveMetadataPiece(piece) {
1150 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1153 start := (1 << 14) * piece
1154 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1155 case pp.RejectMetadataExtensionMsgType:
1157 err = errors.New("unknown msg_type value")
1162 func (me *Client) upload(t *Torrent, c *connection) {
1163 if me.config.NoUpload {
1166 if !c.PeerInterested {
1169 seeding := me.seeding(t)
1170 if !seeding && !t.connHasWantedPieces(c) {
1174 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1176 for r := range c.PeerRequests {
1177 err := me.sendChunk(t, c, r)
1179 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1180 // We had the piece, but not anymore.
1182 log.Printf("error sending chunk %+v to peer: %s", r, err)
1184 // If we failed to send a chunk, choke the peer to ensure they
1185 // flush all their requests. We've probably dropped a piece,
1186 // but there's no way to communicate this to the peer. If they
1187 // ask for it again, we'll kick them to allow us to send them
1188 // an updated bitfield.
1191 delete(c.PeerRequests, r)
1199 func (me *Client) sendChunk(t *Torrent, c *connection, r request) error {
1200 // Count the chunk being sent, even if it isn't.
1201 b := make([]byte, r.Length)
1202 p := t.info.Piece(int(r.Index))
1203 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1206 panic("expected error")
1217 uploadChunksPosted.Add(1)
1218 c.lastChunkSent = time.Now()
1222 // Processes incoming bittorrent messages. The client lock is held upon entry
1224 func (me *Client) connectionLoop(t *Torrent, c *connection) error {
1225 decoder := pp.Decoder{
1226 R: bufio.NewReader(c.rw),
1227 MaxLength: 256 * 1024,
1232 err := decoder.Decode(&msg)
1234 if me.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1240 c.lastMessageReceived = time.Now()
1242 receivedKeepalives.Add(1)
1245 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1250 // We can then reset our interest.
1253 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1256 c.PeerChoked = false
1257 me.peerUnchoked(t, c)
1259 c.PeerInterested = true
1261 case pp.NotInterested:
1262 c.PeerInterested = false
1265 err = c.peerSentHave(int(msg.Index))
1270 if !c.PeerInterested {
1271 err = errors.New("peer sent request but isn't interested")
1274 if !t.havePiece(msg.Index.Int()) {
1275 // This isn't necessarily them screwing up. We can drop pieces
1276 // from our storage, and can't communicate this to peers
1277 // except by reconnecting.
1278 requestsReceivedForMissingPieces.Add(1)
1279 err = errors.New("peer requested piece we don't have")
1282 if c.PeerRequests == nil {
1283 c.PeerRequests = make(map[request]struct{}, maxRequests)
1285 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1288 req := newRequest(msg.Index, msg.Begin, msg.Length)
1289 if !c.PeerCancel(req) {
1290 unexpectedCancels.Add(1)
1293 err = c.peerSentBitfield(msg.Bitfield)
1295 err = c.peerSentHaveAll()
1297 err = c.peerSentHaveNone()
1299 me.downloadedChunk(t, c, &msg)
1301 switch msg.ExtendedID {
1302 case pp.HandshakeExtendedID:
1303 // TODO: Create a bencode struct for this.
1304 var d map[string]interface{}
1305 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1307 err = fmt.Errorf("error decoding extended message payload: %s", err)
1310 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1311 if reqq, ok := d["reqq"]; ok {
1312 if i, ok := reqq.(int64); ok {
1313 c.PeerMaxRequests = int(i)
1316 if v, ok := d["v"]; ok {
1317 c.PeerClientName = v.(string)
1321 err = errors.New("handshake missing m item")
1324 mTyped, ok := m.(map[string]interface{})
1326 err = errors.New("handshake m value is not dict")
1329 if c.PeerExtensionIDs == nil {
1330 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1332 for name, v := range mTyped {
1335 log.Printf("bad handshake m item extension ID type: %T", v)
1339 delete(c.PeerExtensionIDs, name)
1341 if c.PeerExtensionIDs[name] == 0 {
1342 supportedExtensionMessages.Add(name, 1)
1344 c.PeerExtensionIDs[name] = byte(id)
1347 metadata_sizeUntyped, ok := d["metadata_size"]
1349 metadata_size, ok := metadata_sizeUntyped.(int64)
1351 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1353 t.setMetadataSize(metadata_size, me)
1356 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1357 me.requestPendingMetadata(t, c)
1359 case metadataExtendedId:
1360 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1362 err = fmt.Errorf("error handling metadata extension message: %s", err)
1365 if me.config.DisablePEX {
1368 var pexMsg peerExchangeMessage
1369 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1371 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1376 me.addPeers(t, func() (ret []Peer) {
1377 for i, cp := range pexMsg.Added {
1379 IP: make([]byte, 4),
1381 Source: peerSourcePEX,
1383 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1384 p.SupportsEncryption = true
1386 missinggo.CopyExact(p.IP, cp.IP[:])
1387 ret = append(ret, p)
1394 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1397 // That client uses its own extension IDs for outgoing message
1398 // types, which is incorrect.
1399 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1400 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1408 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1413 pingAddr.Port = int(msg.Port)
1415 _, err = me.dHT.Ping(pingAddr)
1417 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1425 // Returns true if connection is removed from torrent.Conns.
1426 func (me *Client) deleteConnection(t *Torrent, c *connection) bool {
1427 for i0, _c := range t.conns {
1431 i1 := len(t.conns) - 1
1433 t.conns[i0] = t.conns[i1]
1435 t.conns = t.conns[:i1]
1441 func (me *Client) dropConnection(t *Torrent, c *connection) {
1442 me.event.Broadcast()
1444 if me.deleteConnection(t, c) {
1449 // Returns true if the connection is added.
1450 func (me *Client) addConnection(t *Torrent, c *connection) bool {
1451 if me.closed.IsSet() {
1455 case <-t.ceasingNetworking:
1459 if !me.wantConns(t) {
1462 for _, c0 := range t.conns {
1463 if c.PeerID == c0.PeerID {
1464 // Already connected to a client with that ID.
1465 duplicateClientConns.Add(1)
1469 if len(t.conns) >= socketsPerTorrent {
1470 c := t.worstBadConn(me)
1474 if me.config.Debug && missinggo.CryHeard() {
1475 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1478 me.deleteConnection(t, c)
1480 if len(t.conns) >= socketsPerTorrent {
1483 t.conns = append(t.conns, c)
1488 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1489 t.forReaderOffsetPieces(func(begin, end int) bool {
1490 ret.AddRange(begin, end)
1496 func (t *Torrent) needData() bool {
1500 if t.pendingPieces.Len() != 0 {
1503 return !t.readerPieces().IterTyped(func(piece int) bool {
1504 return t.pieceComplete(piece)
1508 func (cl *Client) usefulConn(t *Torrent, c *connection) bool {
1509 if c.closed.IsSet() {
1513 return c.supportsExtension("ut_metadata")
1516 return c.PeerInterested
1518 return t.connHasWantedPieces(c)
1521 func (me *Client) wantConns(t *Torrent) bool {
1522 if !me.seeding(t) && !t.needData() {
1525 if len(t.conns) < socketsPerTorrent {
1528 return t.worstBadConn(me) != nil
1531 func (me *Client) openNewConns(t *Torrent) {
1533 case <-t.ceasingNetworking:
1537 for len(t.peers) != 0 {
1538 if !me.wantConns(t) {
1541 if len(t.halfOpen) >= me.halfOpenLimit {
1548 for k, p = range t.peers {
1552 me.initiateConn(p, t)
1554 t.wantPeers.Broadcast()
1557 func (me *Client) addPeers(t *Torrent, peers []Peer) {
1558 for _, p := range peers {
1559 if me.dopplegangerAddr(net.JoinHostPort(
1561 strconv.FormatInt(int64(p.Port), 10),
1565 if _, ok := me.ipBlockRange(p.IP); ok {
1569 // The spec says to scrub these yourselves. Fine.
1576 func (cl *Client) cachedMetaInfoFilename(ih metainfo.Hash) string {
1577 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1580 func (cl *Client) saveTorrentFile(t *Torrent) error {
1581 path := cl.cachedMetaInfoFilename(t.infoHash)
1582 os.MkdirAll(filepath.Dir(path), 0777)
1583 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1585 return fmt.Errorf("error opening file: %s", err)
1588 e := bencode.NewEncoder(f)
1589 err = e.Encode(t.metainfo())
1591 return fmt.Errorf("error marshalling metainfo: %s", err)
1593 mi, err := cl.torrentCacheMetaInfo(t.infoHash)
1595 // For example, a script kiddy makes us load too many files, and we're
1596 // able to save the torrent, but not load it again to check it.
1599 if !bytes.Equal(mi.Info.Hash.Bytes(), t.infoHash[:]) {
1600 log.Fatalf("%x != %x", mi.Info.Hash, t.infoHash[:])
1605 func (cl *Client) setMetaData(t *Torrent, md *metainfo.Info, bytes []byte) (err error) {
1606 err = t.setMetadata(md, bytes)
1610 if !cl.config.DisableMetainfoCache {
1611 if err := cl.saveTorrentFile(t); err != nil {
1612 log.Printf("error saving torrent file for %s: %s", t, err)
1615 cl.event.Broadcast()
1616 close(t.gotMetainfo)
1620 // Prepare a Torrent without any attachment to a Client. That means we can
1621 // initialize fields all fields that don't require the Client without locking
1623 func newTorrent(ih metainfo.Hash) (t *Torrent) {
1626 chunkSize: defaultChunkSize,
1627 peers: make(map[peersKey]Peer),
1629 closing: make(chan struct{}),
1630 ceasingNetworking: make(chan struct{}),
1632 gotMetainfo: make(chan struct{}),
1634 halfOpen: make(map[string]struct{}),
1635 pieceStateChanges: pubsub.NewPubSub(),
1641 // For shuffling the tracker tiers.
1642 mathRand.Seed(time.Now().Unix())
1645 type trackerTier []string
1647 // The trackers within each tier must be shuffled before use.
1648 // http://stackoverflow.com/a/12267471/149482
1649 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1650 func shuffleTier(tier trackerTier) {
1651 for i := range tier {
1652 j := mathRand.Intn(i + 1)
1653 tier[i], tier[j] = tier[j], tier[i]
1657 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1658 for _, tier := range base {
1659 copy = append(copy, append(trackerTier(nil), tier...))
1664 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1666 for _, url := range newURLs {
1667 for _, trURL := range tier {
1672 tier = append(tier, url)
1677 func (t *Torrent) addTrackers(announceList [][]string) {
1678 newTrackers := copyTrackers(t.trackers)
1679 for tierIndex, tier := range announceList {
1680 if tierIndex < len(newTrackers) {
1681 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1683 newTrackers = append(newTrackers, mergeTier(nil, tier))
1685 shuffleTier(newTrackers[tierIndex])
1687 t.trackers = newTrackers
1690 // Don't call this before the info is available.
1691 func (t *Torrent) bytesCompleted() int64 {
1695 return t.info.TotalLength() - t.bytesLeft()
1698 // A file-like handle to some torrent data resource.
1699 type Handle interface {
1706 // Returns handles to the files in the torrent. This requires the metainfo is
1708 func (t *Torrent) Files() (ret []File) {
1716 for _, fi := range info.UpvertedFiles() {
1717 ret = append(ret, File{
1719 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1729 func (t *Torrent) AddPeers(pp []Peer) error {
1732 defer cl.mu.Unlock()
1737 // Marks the entire torrent for download. Requires the info first, see
1739 func (t *Torrent) DownloadAll() {
1741 defer t.cl.mu.Unlock()
1742 t.pendPieceRange(0, t.numPieces())
1745 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1746 // metainfo has the correct infohash.
1747 func (cl *Client) torrentCacheMetaInfo(ih metainfo.Hash) (mi *metainfo.MetaInfo, err error) {
1748 if cl.config.DisableMetainfoCache {
1751 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1753 if os.IsNotExist(err) {
1759 dec := bencode.NewDecoder(f)
1760 err = dec.Decode(&mi)
1764 if !bytes.Equal(mi.Info.Hash.Bytes(), ih[:]) {
1765 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1771 // Specifies a new torrent for adding to a client. There are helpers for
1772 // magnet URIs and torrent metainfo files.
1773 type TorrentSpec struct {
1774 // The tiered tracker URIs.
1776 InfoHash metainfo.Hash
1777 Info *metainfo.InfoEx
1778 // The name to use if the Name field from the Info isn't available.
1780 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1786 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1787 m, err := metainfo.ParseMagnetURI(uri)
1791 spec = &TorrentSpec{
1792 Trackers: [][]string{m.Trackers},
1793 DisplayName: m.DisplayName,
1794 InfoHash: m.InfoHash,
1799 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1800 spec = &TorrentSpec{
1801 Trackers: mi.AnnounceList,
1803 DisplayName: mi.Info.Name,
1806 if len(spec.Trackers) == 0 {
1807 spec.Trackers = [][]string{[]string{mi.Announce}}
1809 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
1812 missinggo.CopyExact(&spec.InfoHash, mi.Info.Hash)
1816 // Add or merge a torrent spec. If the torrent is already present, the
1817 // trackers will be merged with the existing ones. If the Info isn't yet
1818 // known, it will be set. The display name is replaced if the new spec
1819 // provides one. Returns new if the torrent wasn't already in the client.
1820 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1822 defer cl.mu.Unlock()
1824 t, ok := cl.torrents[spec.InfoHash]
1828 // TODO: This doesn't belong in the core client, it's more of a
1830 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
1831 err = errors.New("banned torrent")
1834 // TODO: Tidy this up?
1835 t = newTorrent(spec.InfoHash)
1837 t.wantPeers.L = &cl.mu
1838 if spec.ChunkSize != 0 {
1839 t.chunkSize = pp.Integer(spec.ChunkSize)
1841 t.storageOpener = spec.Storage
1842 if t.storageOpener == nil {
1843 t.storageOpener = cl.defaultStorage
1846 if spec.DisplayName != "" {
1847 t.setDisplayName(spec.DisplayName)
1849 // Try to merge in info we have on the torrent. Any err left will
1850 // terminate the function.
1852 if spec.Info != nil {
1853 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
1855 var mi *metainfo.MetaInfo
1856 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
1858 log.Printf("error getting cached metainfo: %s", err)
1860 } else if mi != nil {
1861 t.addTrackers(mi.AnnounceList)
1862 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
1869 t.addTrackers(spec.Trackers)
1871 cl.torrents[spec.InfoHash] = t
1874 // From this point onwards, we can consider the torrent a part of the
1877 if !cl.config.DisableTrackers {
1878 go cl.announceTorrentTrackers(t)
1881 go cl.announceTorrentDHT(t, true)
1887 func (me *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1888 t, ok := me.torrents[infoHash]
1890 err = fmt.Errorf("no such torrent")
1897 delete(me.torrents, infoHash)
1901 // Returns true when peers are required, or false if the torrent is closing.
1902 func (cl *Client) waitWantPeers(t *Torrent) bool {
1904 defer cl.mu.Unlock()
1907 case <-t.ceasingNetworking:
1911 if len(t.peers) > torrentPeersLowWater {
1914 if t.needData() || cl.seeding(t) {
1922 // Returns whether the client should make effort to seed the torrent.
1923 func (cl *Client) seeding(t *Torrent) bool {
1924 if cl.config.NoUpload {
1927 if !cl.config.Seed {
1936 func (cl *Client) announceTorrentDHT(t *Torrent, impliedPort bool) {
1937 for cl.waitWantPeers(t) {
1938 // log.Printf("getting peers for %q from DHT", t)
1939 ps, err := cl.dHT.Announce(string(t.infoHash[:]), cl.incomingPeerPort(), impliedPort)
1941 log.Printf("error getting peers from dht: %s", err)
1944 // Count all the unique addresses we got during this announce.
1945 allAddrs := make(map[string]struct{})
1949 case v, ok := <-ps.Peers:
1953 addPeers := make([]Peer, 0, len(v.Peers))
1954 for _, cp := range v.Peers {
1956 // Can't do anything with this.
1959 addPeers = append(addPeers, Peer{
1962 Source: peerSourceDHT,
1964 key := (&net.UDPAddr{
1968 allAddrs[key] = struct{}{}
1971 cl.addPeers(t, addPeers)
1972 numPeers := len(t.peers)
1974 if numPeers >= torrentPeersHighWater {
1977 case <-t.ceasingNetworking:
1983 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
1987 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
1988 url_, err := url.Parse(trRawURL)
1992 host, _, err := net.SplitHostPort(url_.Host)
1996 addr, err := net.ResolveIPAddr("ip", host)
2001 _, blocked = cl.ipBlockRange(addr.IP)
2006 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *Torrent) error {
2007 blocked, err := cl.trackerBlockedUnlocked(tr)
2009 return fmt.Errorf("error determining if tracker blocked: %s", err)
2012 return fmt.Errorf("tracker blocked: %s", tr)
2014 resp, err := tracker.Announce(tr, req)
2016 return fmt.Errorf("error announcing: %s", err)
2019 for _, peer := range resp.Peers {
2020 peers = append(peers, Peer{
2026 cl.addPeers(t, peers)
2029 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2031 time.Sleep(time.Second * time.Duration(resp.Interval))
2035 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *Torrent) (atLeastOne bool) {
2036 oks := make(chan bool)
2038 for _, tier := range trackers {
2039 for _, tr := range tier {
2041 go func(tr string) {
2042 err := cl.announceTorrentSingleTracker(tr, req, t)
2047 for outstanding > 0 {
2057 // Announce torrent to its trackers.
2058 func (cl *Client) announceTorrentTrackers(t *Torrent) {
2059 req := tracker.AnnounceRequest{
2060 Event: tracker.Started,
2062 Port: uint16(cl.incomingPeerPort()),
2064 InfoHash: t.infoHash,
2066 if !cl.waitWantPeers(t) {
2070 req.Left = t.bytesLeftAnnounce()
2071 trackers := t.trackers
2073 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2074 req.Event = tracker.None
2077 for cl.waitWantPeers(t) {
2079 req.Left = t.bytesLeftAnnounce()
2080 trackers = t.trackers
2082 numTrackersTried := 0
2083 for _, tier := range trackers {
2084 for trIndex, tr := range tier {
2086 err := cl.announceTorrentSingleTracker(tr, &req, t)
2090 // Float the successful announce to the top of the tier. If
2091 // the trackers list has been changed, we'll be modifying an
2092 // old copy so it won't matter.
2094 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2097 req.Event = tracker.None
2098 continue newAnnounce
2101 if numTrackersTried != 0 {
2102 log.Printf("%s: all trackers failed", t)
2104 // TODO: Wait until trackers are added if there are none.
2105 time.Sleep(10 * time.Second)
2109 func (cl *Client) allTorrentsCompleted() bool {
2110 for _, t := range cl.torrents {
2114 if t.numPiecesCompleted() != t.numPieces() {
2121 // Returns true when all torrents are completely downloaded and false if the
2122 // client is stopped before that.
2123 func (me *Client) WaitAll() bool {
2125 defer me.mu.Unlock()
2126 for !me.allTorrentsCompleted() {
2127 if me.closed.IsSet() {
2135 // Handle a received chunk from a peer.
2136 func (me *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
2137 chunksReceived.Add(1)
2139 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2141 // Request has been satisfied.
2142 if me.connDeleteRequest(t, c, req) {
2143 defer c.updateRequests()
2145 unexpectedChunksReceived.Add(1)
2148 index := int(req.Index)
2149 piece := &t.pieces[index]
2151 // Do we actually want this chunk?
2152 if !t.wantChunk(req) {
2153 unwantedChunksReceived.Add(1)
2154 c.UnwantedChunksReceived++
2158 c.UsefulChunksReceived++
2159 c.lastUsefulChunkReceived = time.Now()
2163 // Need to record that it hasn't been written yet, before we attempt to do
2164 // anything with it.
2165 piece.incrementPendingWrites()
2166 // Record that we have the chunk.
2167 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2169 // Cancel pending requests for this chunk.
2170 for _, c := range t.conns {
2171 if me.connCancel(t, c, req) {
2177 // Write the chunk out.
2178 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2181 piece.decrementPendingWrites()
2184 log.Printf("%s: error writing chunk %v: %s", t, req, err)
2186 t.updatePieceCompletion(int(msg.Index))
2190 // It's important that the piece is potentially queued before we check if
2191 // the piece is still wanted, because if it is queued, it won't be wanted.
2192 if t.pieceAllDirty(index) {
2193 me.queuePieceCheck(t, int(req.Index))
2196 if c.peerTouchedPieces == nil {
2197 c.peerTouchedPieces = make(map[int]struct{})
2199 c.peerTouchedPieces[index] = struct{}{}
2201 me.event.Broadcast()
2202 t.publishPieceChange(int(req.Index))
2206 // Return the connections that touched a piece, and clear the entry while
2208 func (me *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
2209 for _, c := range t.conns {
2210 if _, ok := c.peerTouchedPieces[piece]; ok {
2211 ret = append(ret, c)
2212 delete(c.peerTouchedPieces, piece)
2218 func (me *Client) pieceHashed(t *Torrent, piece int, correct bool) {
2219 p := &t.pieces[piece]
2221 // Don't score the first time a piece is hashed, it could be an
2224 pieceHashedCorrect.Add(1)
2226 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
2227 pieceHashedNotCorrect.Add(1)
2231 touchers := me.reapPieceTouches(t, int(piece))
2233 err := p.Storage().MarkComplete()
2235 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
2237 t.updatePieceCompletion(piece)
2238 } else if len(touchers) != 0 {
2239 log.Printf("dropping %d conns that touched piece", len(touchers))
2240 for _, c := range touchers {
2241 me.dropConnection(t, c)
2244 me.pieceChanged(t, int(piece))
2247 func (me *Client) onCompletedPiece(t *Torrent, piece int) {
2248 t.pendingPieces.Remove(piece)
2249 t.pendAllChunkSpecs(piece)
2250 for _, conn := range t.conns {
2252 for r := range conn.Requests {
2253 if int(r.Index) == piece {
2257 // Could check here if peer doesn't have piece, but due to caching
2258 // some peers may have said they have a piece but they don't.
2263 func (me *Client) onFailedPiece(t *Torrent, piece int) {
2264 if t.pieceAllDirty(piece) {
2265 t.pendAllChunkSpecs(piece)
2267 if !t.wantPiece(piece) {
2271 for _, conn := range t.conns {
2272 if conn.PeerHasPiece(piece) {
2273 conn.updateRequests()
2278 func (me *Client) pieceChanged(t *Torrent, piece int) {
2279 correct := t.pieceComplete(piece)
2280 defer me.event.Broadcast()
2282 me.onCompletedPiece(t, piece)
2284 me.onFailedPiece(t, piece)
2286 if t.updatePiecePriority(piece) {
2287 t.piecePriorityChanged(piece)
2289 t.publishPieceChange(piece)
2292 func (cl *Client) verifyPiece(t *Torrent, piece int) {
2294 defer cl.mu.Unlock()
2295 p := &t.pieces[piece]
2296 for p.Hashing || t.storage == nil {
2299 p.QueuedForHash = false
2300 if t.isClosed() || t.pieceComplete(piece) {
2301 t.updatePiecePriority(piece)
2302 t.publishPieceChange(piece)
2306 t.publishPieceChange(piece)
2308 sum := t.hashPiece(piece)
2316 cl.pieceHashed(t, piece, sum == p.Hash)
2319 // Returns handles to all the torrents loaded in the Client.
2320 func (me *Client) Torrents() (ret []*Torrent) {
2322 for _, t := range me.torrents {
2323 ret = append(ret, t)
2329 func (me *Client) AddMagnet(uri string) (T *Torrent, err error) {
2330 spec, err := TorrentSpecFromMagnetURI(uri)
2334 T, _, err = me.AddTorrentSpec(spec)
2338 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
2339 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2341 missinggo.CastSlice(&ss, mi.Nodes)
2346 func (me *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
2347 mi, err := metainfo.LoadFromFile(filename)
2351 return me.AddTorrent(mi)
2354 func (me *Client) DHT() *dht.Server {
2358 func (me *Client) AddDHTNodes(nodes []string) {
2359 for _, n := range nodes {
2360 hmp := missinggo.SplitHostMaybePort(n)
2361 ip := net.ParseIP(hmp.Host)
2363 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
2367 Addr: dht.NewAddr(&net.UDPAddr{
2372 me.DHT().AddNode(ni)