21 "github.com/anacrolix/missinggo"
22 "github.com/anacrolix/missinggo/pproffd"
23 "github.com/anacrolix/missinggo/pubsub"
24 "github.com/anacrolix/sync"
25 "github.com/anacrolix/utp"
27 "github.com/anacrolix/torrent/bencode"
28 "github.com/anacrolix/torrent/dht"
29 "github.com/anacrolix/torrent/iplist"
30 "github.com/anacrolix/torrent/metainfo"
31 "github.com/anacrolix/torrent/mse"
32 pp "github.com/anacrolix/torrent/peer_protocol"
33 "github.com/anacrolix/torrent/storage"
34 "github.com/anacrolix/torrent/tracker"
37 // Currently doesn't really queue, but should in the future.
38 func (cl *Client) queuePieceCheck(t *Torrent, pieceIndex int) {
39 piece := &t.pieces[pieceIndex]
40 if piece.QueuedForHash {
43 piece.QueuedForHash = true
44 t.publishPieceChange(pieceIndex)
45 go cl.verifyPiece(t, pieceIndex)
48 // Queue a piece check if one isn't already queued, and the piece has never
49 // been checked before.
50 func (cl *Client) queueFirstHash(t *Torrent, piece int) {
52 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
55 cl.queuePieceCheck(t, piece)
58 // Clients contain zero or more Torrents. A Client manages a blocklist, the
59 // TCP/UDP protocol ports, and DHT as desired.
63 listeners []net.Listener
66 ipBlockList iplist.Ranger
68 pruneTimer *time.Timer
69 extensionBytes peerExtensionBytes
70 // Set of addresses that have our client ID. This intentionally will
71 // include ourselves if we end up trying to connect to our own address
72 // through legitimate channels.
73 dopplegangerAddrs map[string]struct{}
75 defaultStorage storage.I
79 closed missinggo.Event
81 torrents map[metainfo.Hash]*Torrent
84 func (cl *Client) IPBlockList() iplist.Ranger {
90 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
95 cl.dHT.SetIPBlockList(list)
99 func (cl *Client) PeerID() string {
100 return string(cl.peerID[:])
103 func (cl *Client) ListenAddr() (addr net.Addr) {
104 for _, l := range cl.listeners {
111 type hashSorter struct {
112 Hashes []metainfo.Hash
115 func (hs hashSorter) Len() int {
116 return len(hs.Hashes)
119 func (hs hashSorter) Less(a, b int) bool {
120 return (&big.Int{}).SetBytes(hs.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(hs.Hashes[b][:])) < 0
123 func (hs hashSorter) Swap(a, b int) {
124 hs.Hashes[a], hs.Hashes[b] = hs.Hashes[b], hs.Hashes[a]
127 func (cl *Client) sortedTorrents() (ret []*Torrent) {
129 for ih := range cl.torrents {
130 hs.Hashes = append(hs.Hashes, ih)
133 for _, ih := range hs.Hashes {
134 ret = append(ret, cl.torrent(ih))
139 // Writes out a human readable status of the client, such as for writing to a
141 func (cl *Client) WriteStatus(_w io.Writer) {
143 defer cl.mu.RUnlock()
144 w := bufio.NewWriter(_w)
146 if addr := cl.ListenAddr(); addr != nil {
147 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
149 fmt.Fprintln(w, "Not listening!")
151 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
153 dhtStats := cl.dHT.Stats()
154 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
155 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
156 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
157 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
158 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
160 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
162 for _, t := range cl.sortedTorrents() {
164 fmt.Fprint(w, "<unknown name>")
166 fmt.Fprint(w, t.name())
170 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length)
172 w.WriteString("<missing metainfo>")
180 // Creates a new client.
181 func NewClient(cfg *Config) (cl *Client, err error) {
192 halfOpenLimit: socketsPerTorrent,
194 defaultStorage: cfg.DefaultStorage,
195 dopplegangerAddrs: make(map[string]struct{}),
196 torrents: make(map[metainfo.Hash]*Torrent),
198 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
200 if cl.defaultStorage == nil {
201 cl.defaultStorage = storage.NewFile(cfg.DataDir)
203 if cfg.IPBlocklist != nil {
204 cl.ipBlockList = cfg.IPBlocklist
207 if cfg.PeerID != "" {
208 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
210 o := copy(cl.peerID[:], bep20)
211 _, err = rand.Read(cl.peerID[o:])
213 panic("error generating peer id")
217 // Returns the laddr string to listen on for the next Listen call.
218 listenAddr := func() string {
219 if addr := cl.ListenAddr(); addr != nil {
222 if cfg.ListenAddr == "" {
225 return cfg.ListenAddr
227 if !cl.config.DisableTCP {
229 l, err = net.Listen(func() string {
230 if cl.config.DisableIPv6 {
239 cl.listeners = append(cl.listeners, l)
240 go cl.acceptConnections(l, false)
242 if !cl.config.DisableUTP {
243 cl.utpSock, err = utp.NewSocket(func() string {
244 if cl.config.DisableIPv6 {
253 cl.listeners = append(cl.listeners, cl.utpSock)
254 go cl.acceptConnections(cl.utpSock, true)
257 dhtCfg := cfg.DHTConfig
258 if dhtCfg.IPBlocklist == nil {
259 dhtCfg.IPBlocklist = cl.ipBlockList
261 if dhtCfg.Addr == "" {
262 dhtCfg.Addr = listenAddr()
264 if dhtCfg.Conn == nil && cl.utpSock != nil {
265 dhtCfg.Conn = cl.utpSock
267 cl.dHT, err = dht.NewServer(&dhtCfg)
276 // Stops the client. All connections to peers are closed and all activity will
278 func (cl *Client) Close() {
285 for _, l := range cl.listeners {
288 for _, t := range cl.torrents {
294 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
296 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
297 if cl.ipBlockList == nil {
301 // If blocklists are enabled, then block non-IPv4 addresses, because
302 // blocklists do not yet support IPv6.
304 if missinggo.CryHeard() {
305 log.Printf("blocking non-IPv4 address: %s", ip)
311 return cl.ipBlockList.Lookup(ip4)
314 func (cl *Client) waitAccept() {
318 for _, t := range cl.torrents {
323 if cl.closed.IsSet() {
330 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
333 conn, err := l.Accept()
334 conn = pproffd.WrapNetConn(conn)
335 if cl.closed.IsSet() {
343 // I think something harsher should happen here? Our accept
344 // routine just fucked off.
353 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
354 _, blocked := cl.ipBlockRange(missinggo.AddrIP(conn.RemoteAddr()))
356 if blocked || doppleganger {
358 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
362 go cl.incomingConnection(conn, utp)
366 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
368 if tc, ok := nc.(*net.TCPConn); ok {
371 c := cl.newConnection(nc)
372 c.Discovery = peerSourceIncoming
374 err := cl.runReceivedConn(c)
380 // Returns a handle to the given torrent, if it's present in the client.
381 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
384 t, ok = cl.torrents[ih]
388 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
389 return cl.torrents[ih]
392 type dialResult struct {
397 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
398 conn, err := dial(addr, t)
403 conn = nil // Pedantic
405 ch <- dialResult{conn, utp}
407 successfulDials.Add(1)
410 unsuccessfulDials.Add(1)
413 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
414 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
415 if ret < minDialTimeout {
421 // Returns whether an address is known to connect to a client with our own ID.
422 func (cl *Client) dopplegangerAddr(addr string) bool {
423 _, ok := cl.dopplegangerAddrs[addr]
427 // Start the process of connecting to the given peer for the given torrent if
429 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
430 if peer.Id == cl.peerID {
433 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
434 if cl.dopplegangerAddr(addr) || t.addrActive(addr) {
435 duplicateConnsAvoided.Add(1)
438 if r, ok := cl.ipBlockRange(peer.IP); ok {
439 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
442 t.halfOpen[addr] = struct{}{}
443 go cl.outgoingConnection(t, addr, peer.Source)
446 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
448 pendingPeers := len(t.peers)
450 return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
453 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
454 c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
456 c.(*net.TCPConn).SetLinger(0)
461 func (cl *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
462 return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
465 // Returns a connection over UTP or TCP, whichever is first to connect.
466 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
467 // Initiate connections via TCP and UTP simultaneously. Use the first one
470 if !cl.config.DisableUTP {
473 if !cl.config.DisableTCP {
476 resCh := make(chan dialResult, left)
477 if !cl.config.DisableUTP {
478 go doDial(cl.dialUTP, resCh, true, addr, t)
480 if !cl.config.DisableTCP {
481 go doDial(cl.dialTCP, resCh, false, addr, t)
484 // Wait for a successful connection.
485 for ; left > 0 && res.Conn == nil; left-- {
489 // There are still incompleted dials.
491 for ; left > 0; left-- {
492 conn := (<-resCh).Conn
504 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
505 if _, ok := t.halfOpen[addr]; !ok {
506 panic("invariant broken")
508 delete(t.halfOpen, addr)
512 // Performs initiator handshakes and returns a connection. Returns nil
513 // *connection if no connection for valid reasons.
514 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
515 c = cl.newConnection(nc)
516 c.encrypted = encrypted
518 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
522 ok, err := cl.initiateHandshakes(c, t)
529 // Returns nil connection and nil error if no connection could be established
530 // for valid reasons.
531 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
532 nc, utp := cl.dialFirst(addr, t)
536 c, err = cl.handshakesConnection(nc, t, !cl.config.DisableEncryption, utp)
544 if cl.config.DisableEncryption {
545 // We already tried without encryption.
548 // Try again without encryption, using whichever protocol type worked last
551 nc, err = cl.dialUTP(addr, t)
553 nc, err = cl.dialTCP(addr, t)
556 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
559 c, err = cl.handshakesConnection(nc, t, false, utp)
560 if err != nil || c == nil {
566 // Called to dial out and run a connection. The addr we're given is already
567 // considered half-open.
568 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
569 c, err := cl.establishOutgoingConn(t, addr)
572 // Don't release lock between here and addConnection, unless it's for
574 cl.noLongerHalfOpen(t, addr)
577 log.Printf("error establishing outgoing connection: %s", err)
586 err = cl.runInitiatedHandshookConn(c, t)
589 log.Printf("error in established outgoing connection: %s", err)
594 // The port number for incoming peer connections. 0 if the client isn't
596 func (cl *Client) incomingPeerPort() int {
597 listenAddr := cl.ListenAddr()
598 if listenAddr == nil {
601 return missinggo.AddrPort(listenAddr)
604 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
605 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
606 func addrCompactIP(addr net.Addr) (string, error) {
607 host, _, err := net.SplitHostPort(addr.String())
611 ip := net.ParseIP(host)
612 if v4 := ip.To4(); v4 != nil {
616 return string(v4), nil
618 return string(ip.To16()), nil
621 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
633 peerExtensionBytes [8]byte
637 func (pex *peerExtensionBytes) SupportsExtended() bool {
638 return pex[5]&0x10 != 0
641 func (pex *peerExtensionBytes) SupportsDHT() bool {
642 return pex[7]&0x01 != 0
645 func (pex *peerExtensionBytes) SupportsFast() bool {
646 return pex[7]&0x04 != 0
649 type handshakeResult struct {
655 // ih is nil if we expect the peer to declare the InfoHash, such as when the
656 // peer initiated the connection. Returns ok if the handshake was successful,
657 // and err if there was an unexpected condition other than the peer simply
658 // abandoning the handshake.
659 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
660 // Bytes to be sent to the peer. Should never block the sender.
661 postCh := make(chan []byte, 4)
662 // A single error value sent when the writer completes.
663 writeDone := make(chan error, 1)
664 // Performs writes to the socket and ensures posts don't block.
665 go handshakeWriter(sock, postCh, writeDone)
668 close(postCh) // Done writing.
675 // Wait until writes complete before returning from handshake.
678 err = fmt.Errorf("error writing: %s", err)
682 post := func(bb []byte) {
686 panic("mustn't block while posting")
690 post([]byte(pp.Protocol))
692 if ih != nil { // We already know what we want.
697 _, err = io.ReadFull(sock, b[:68])
702 if string(b[:20]) != pp.Protocol {
705 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
706 missinggo.CopyExact(&res.Hash, b[28:48])
707 missinggo.CopyExact(&res.peerID, b[48:68])
708 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
710 // TODO: Maybe we can just drop peers here if we're not interested. This
711 // could prevent them trying to reconnect, falsely believing there was
713 if ih == nil { // We were waiting for the peer to tell us what they wanted.
722 // Wraps a raw connection and provides the interface we want for using the
723 // connection in the message loop.
724 type deadlineReader struct {
729 func (r deadlineReader) Read(b []byte) (n int, err error) {
730 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
731 err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
733 err = fmt.Errorf("error setting read deadline: %s", err)
736 // Convert common errors into io.EOF.
738 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
740 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
750 type readWriter struct {
755 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
756 var protocol [len(pp.Protocol)]byte
757 _, err = io.ReadFull(rw, protocol[:])
762 io.MultiReader(bytes.NewReader(protocol[:]), rw),
765 if string(protocol[:]) == pp.Protocol {
769 ret, err = mse.ReceiveHandshake(ret, skeys)
773 func (cl *Client) receiveSkeys() (ret [][]byte) {
774 for ih := range cl.torrents {
775 ret = append(ret, ih[:])
780 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
782 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
787 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
788 if ih != t.infoHash {
794 // Do encryption and bittorrent handshakes as receiver.
795 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
797 skeys := cl.receiveSkeys()
799 if !cl.config.DisableEncryption {
800 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
802 if err == mse.ErrNoSecretKeyMatch {
808 ih, ok, err := cl.connBTHandshake(c, nil)
810 err = fmt.Errorf("error during bt handshake: %s", err)
822 // Returns !ok if handshake failed for valid reasons.
823 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
824 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
825 if err != nil || !ok {
829 c.PeerExtensionBytes = res.peerExtensionBytes
830 c.PeerID = res.peerID
831 c.completedHandshake = time.Now()
835 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) (err error) {
836 if c.PeerID == cl.peerID {
837 // Only if we initiated the connection is the remote address a
838 // listen addr for a doppleganger.
840 addr := c.conn.RemoteAddr().String()
841 cl.dopplegangerAddrs[addr] = struct{}{}
844 return cl.runHandshookConn(c, t)
847 func (cl *Client) runReceivedConn(c *connection) (err error) {
848 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
852 t, err := cl.receiveHandshakes(c)
854 err = fmt.Errorf("error receiving handshakes: %s", err)
862 if c.PeerID == cl.peerID {
865 return cl.runHandshookConn(c, t)
868 func (cl *Client) runHandshookConn(c *connection, t *Torrent) (err error) {
869 c.conn.SetWriteDeadline(time.Time{})
871 deadlineReader{c.conn, c.rw},
874 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
875 if !cl.addConnection(t, c) {
878 defer cl.dropConnection(t, c)
879 go c.writer(time.Minute)
880 cl.sendInitialMessages(c, t)
881 err = cl.connectionLoop(t, c)
883 err = fmt.Errorf("error during connection loop: %s", err)
888 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
889 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
890 conn.Post(pp.Message{
892 ExtendedID: pp.HandshakeExtendedID,
893 ExtendedPayload: func() []byte {
894 d := map[string]interface{}{
895 "m": func() (ret map[string]int) {
896 ret = make(map[string]int, 2)
897 ret["ut_metadata"] = metadataExtendedId
898 if !cl.config.DisablePEX {
899 ret["ut_pex"] = pexExtendedId
903 "v": extendedHandshakeClientVersion,
904 // No upload queue is implemented yet.
907 if !cl.config.DisableEncryption {
910 if torrent.metadataSizeKnown() {
911 d["metadata_size"] = torrent.metadataSize()
913 if p := cl.incomingPeerPort(); p != 0 {
916 yourip, err := addrCompactIP(conn.remoteAddr())
918 log.Printf("error calculating yourip field value in extension handshake: %s", err)
922 // log.Printf("sending %v", d)
923 b, err := bencode.Marshal(d)
931 if torrent.haveAnyPieces() {
932 conn.Bitfield(torrent.bitfield())
933 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
934 conn.Post(pp.Message{
938 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
939 conn.Post(pp.Message{
941 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
946 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
947 conn.updateRequests()
950 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
958 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
959 if !cn.RequestPending(r) {
962 delete(cn.Requests, r)
966 func (cl *Client) requestPendingMetadata(t *Torrent, c *connection) {
970 if c.PeerExtensionIDs["ut_metadata"] == 0 {
971 // Peer doesn't support this.
974 // Request metadata pieces that we don't have in a random order.
976 for index := 0; index < t.metadataPieceCount(); index++ {
977 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
978 pending = append(pending, index)
981 for _, i := range mathRand.Perm(len(pending)) {
982 c.requestMetadataPiece(pending[i])
986 // Process incoming ut_metadata message.
987 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) (err error) {
989 err = bencode.Unmarshal(payload, &d)
991 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
994 msgType, ok := d["msg_type"]
996 err = errors.New("missing msg_type field")
1001 case pp.DataMetadataExtensionMsgType:
1002 if !c.requestedMetadataPiece(piece) {
1003 err = fmt.Errorf("got unexpected piece %d", piece)
1006 c.metadataRequests[piece] = false
1007 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1008 if begin < 0 || begin >= len(payload) {
1009 err = fmt.Errorf("data has bad offset in payload: %d", begin)
1012 t.saveMetadataPiece(piece, payload[begin:])
1013 c.UsefulChunksReceived++
1014 c.lastUsefulChunkReceived = time.Now()
1015 t.maybeMetadataCompleted()
1016 case pp.RequestMetadataExtensionMsgType:
1017 if !t.haveMetadataPiece(piece) {
1018 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1021 start := (1 << 14) * piece
1022 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1023 case pp.RejectMetadataExtensionMsgType:
1025 err = errors.New("unknown msg_type value")
1030 func (cl *Client) upload(t *Torrent, c *connection) {
1031 if cl.config.NoUpload {
1034 if !c.PeerInterested {
1037 seeding := cl.seeding(t)
1038 if !seeding && !t.connHasWantedPieces(c) {
1042 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1044 for r := range c.PeerRequests {
1045 err := cl.sendChunk(t, c, r)
1047 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1048 // We had the piece, but not anymore.
1050 log.Printf("error sending chunk %+v to peer: %s", r, err)
1052 // If we failed to send a chunk, choke the peer to ensure they
1053 // flush all their requests. We've probably dropped a piece,
1054 // but there's no way to communicate this to the peer. If they
1055 // ask for it again, we'll kick them to allow us to send them
1056 // an updated bitfield.
1059 delete(c.PeerRequests, r)
1067 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1068 // Count the chunk being sent, even if it isn't.
1069 b := make([]byte, r.Length)
1070 p := t.info.Piece(int(r.Index))
1071 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1074 panic("expected error")
1085 uploadChunksPosted.Add(1)
1086 c.lastChunkSent = time.Now()
1090 // Processes incoming bittorrent messages. The client lock is held upon entry
1092 func (cl *Client) connectionLoop(t *Torrent, c *connection) error {
1093 decoder := pp.Decoder{
1094 R: bufio.NewReader(c.rw),
1095 MaxLength: 256 * 1024,
1100 err := decoder.Decode(&msg)
1102 if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1108 c.lastMessageReceived = time.Now()
1110 receivedKeepalives.Add(1)
1113 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1118 // We can then reset our interest.
1121 cl.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1124 c.PeerChoked = false
1125 cl.peerUnchoked(t, c)
1127 c.PeerInterested = true
1129 case pp.NotInterested:
1130 c.PeerInterested = false
1133 err = c.peerSentHave(int(msg.Index))
1138 if !c.PeerInterested {
1139 err = errors.New("peer sent request but isn't interested")
1142 if !t.havePiece(msg.Index.Int()) {
1143 // This isn't necessarily them screwing up. We can drop pieces
1144 // from our storage, and can't communicate this to peers
1145 // except by reconnecting.
1146 requestsReceivedForMissingPieces.Add(1)
1147 err = errors.New("peer requested piece we don't have")
1150 if c.PeerRequests == nil {
1151 c.PeerRequests = make(map[request]struct{}, maxRequests)
1153 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1156 req := newRequest(msg.Index, msg.Begin, msg.Length)
1157 if !c.PeerCancel(req) {
1158 unexpectedCancels.Add(1)
1161 err = c.peerSentBitfield(msg.Bitfield)
1163 err = c.peerSentHaveAll()
1165 err = c.peerSentHaveNone()
1167 cl.downloadedChunk(t, c, &msg)
1169 switch msg.ExtendedID {
1170 case pp.HandshakeExtendedID:
1171 // TODO: Create a bencode struct for this.
1172 var d map[string]interface{}
1173 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1175 err = fmt.Errorf("error decoding extended message payload: %s", err)
1178 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1179 if reqq, ok := d["reqq"]; ok {
1180 if i, ok := reqq.(int64); ok {
1181 c.PeerMaxRequests = int(i)
1184 if v, ok := d["v"]; ok {
1185 c.PeerClientName = v.(string)
1189 err = errors.New("handshake missing m item")
1192 mTyped, ok := m.(map[string]interface{})
1194 err = errors.New("handshake m value is not dict")
1197 if c.PeerExtensionIDs == nil {
1198 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1200 for name, v := range mTyped {
1203 log.Printf("bad handshake m item extension ID type: %T", v)
1207 delete(c.PeerExtensionIDs, name)
1209 if c.PeerExtensionIDs[name] == 0 {
1210 supportedExtensionMessages.Add(name, 1)
1212 c.PeerExtensionIDs[name] = byte(id)
1215 metadata_sizeUntyped, ok := d["metadata_size"]
1217 metadata_size, ok := metadata_sizeUntyped.(int64)
1219 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1221 t.setMetadataSize(metadata_size, cl)
1224 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1225 cl.requestPendingMetadata(t, c)
1227 case metadataExtendedId:
1228 err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1230 err = fmt.Errorf("error handling metadata extension message: %s", err)
1233 if cl.config.DisablePEX {
1236 var pexMsg peerExchangeMessage
1237 err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1239 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1244 cl.addPeers(t, func() (ret []Peer) {
1245 for i, cp := range pexMsg.Added {
1247 IP: make([]byte, 4),
1249 Source: peerSourcePEX,
1251 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1252 p.SupportsEncryption = true
1254 missinggo.CopyExact(p.IP, cp.IP[:])
1255 ret = append(ret, p)
1262 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1265 // That client uses its own extension IDs for outgoing message
1266 // types, which is incorrect.
1267 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1268 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1276 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1281 pingAddr.Port = int(msg.Port)
1283 cl.dHT.Ping(pingAddr)
1285 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1293 // Returns true if connection is removed from torrent.Conns.
1294 func (cl *Client) deleteConnection(t *Torrent, c *connection) bool {
1295 for i0, _c := range t.conns {
1299 i1 := len(t.conns) - 1
1301 t.conns[i0] = t.conns[i1]
1303 t.conns = t.conns[:i1]
1309 func (cl *Client) dropConnection(t *Torrent, c *connection) {
1310 cl.event.Broadcast()
1312 if cl.deleteConnection(t, c) {
1317 // Returns true if the connection is added.
1318 func (cl *Client) addConnection(t *Torrent, c *connection) bool {
1319 if cl.closed.IsSet() {
1323 case <-t.ceasingNetworking:
1327 if !cl.wantConns(t) {
1330 for _, c0 := range t.conns {
1331 if c.PeerID == c0.PeerID {
1332 // Already connected to a client with that ID.
1333 duplicateClientConns.Add(1)
1337 if len(t.conns) >= socketsPerTorrent {
1338 c := t.worstBadConn(cl)
1342 if cl.config.Debug && missinggo.CryHeard() {
1343 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1346 cl.deleteConnection(t, c)
1348 if len(t.conns) >= socketsPerTorrent {
1351 t.conns = append(t.conns, c)
1356 func (cl *Client) usefulConn(t *Torrent, c *connection) bool {
1357 if c.closed.IsSet() {
1361 return c.supportsExtension("ut_metadata")
1364 return c.PeerInterested
1366 return t.connHasWantedPieces(c)
1369 func (cl *Client) wantConns(t *Torrent) bool {
1370 if !cl.seeding(t) && !t.needData() {
1373 if len(t.conns) < socketsPerTorrent {
1376 return t.worstBadConn(cl) != nil
1379 func (cl *Client) openNewConns(t *Torrent) {
1381 case <-t.ceasingNetworking:
1385 for len(t.peers) != 0 {
1386 if !cl.wantConns(t) {
1389 if len(t.halfOpen) >= cl.halfOpenLimit {
1396 for k, p = range t.peers {
1400 cl.initiateConn(p, t)
1402 t.wantPeers.Broadcast()
1405 func (cl *Client) addPeers(t *Torrent, peers []Peer) {
1406 for _, p := range peers {
1407 if cl.dopplegangerAddr(net.JoinHostPort(
1409 strconv.FormatInt(int64(p.Port), 10),
1413 if _, ok := cl.ipBlockRange(p.IP); ok {
1417 // The spec says to scrub these yourselves. Fine.
1424 // Prepare a Torrent without any attachment to a Client. That means we can
1425 // initialize fields all fields that don't require the Client without locking
1427 func (cl *Client) newTorrent(ih metainfo.Hash) (t *Torrent) {
1431 chunkSize: defaultChunkSize,
1432 peers: make(map[peersKey]Peer),
1434 closing: make(chan struct{}),
1435 ceasingNetworking: make(chan struct{}),
1437 halfOpen: make(map[string]struct{}),
1438 pieceStateChanges: pubsub.NewPubSub(),
1440 storageOpener: cl.defaultStorage,
1442 t.wantPeers.L = &cl.mu
1447 // For shuffling the tracker tiers.
1448 mathRand.Seed(time.Now().Unix())
1451 type trackerTier []string
1453 // The trackers within each tier must be shuffled before use.
1454 // http://stackoverflow.com/a/12267471/149482
1455 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1456 func shuffleTier(tier trackerTier) {
1457 for i := range tier {
1458 j := mathRand.Intn(i + 1)
1459 tier[i], tier[j] = tier[j], tier[i]
1463 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1464 for _, tier := range base {
1465 copy = append(copy, append(trackerTier(nil), tier...))
1470 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1472 for _, url := range newURLs {
1473 for _, trURL := range tier {
1478 tier = append(tier, url)
1483 // A file-like handle to some torrent data resource.
1484 type Handle interface {
1491 // Specifies a new torrent for adding to a client. There are helpers for
1492 // magnet URIs and torrent metainfo files.
1493 type TorrentSpec struct {
1494 // The tiered tracker URIs.
1496 InfoHash metainfo.Hash
1497 Info *metainfo.InfoEx
1498 // The name to use if the Name field from the Info isn't available.
1500 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1506 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1507 m, err := metainfo.ParseMagnetURI(uri)
1511 spec = &TorrentSpec{
1512 Trackers: [][]string{m.Trackers},
1513 DisplayName: m.DisplayName,
1514 InfoHash: m.InfoHash,
1519 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1520 spec = &TorrentSpec{
1521 Trackers: mi.AnnounceList,
1523 DisplayName: mi.Info.Name,
1524 InfoHash: mi.Info.Hash(),
1526 if len(spec.Trackers) == 0 {
1527 spec.Trackers = [][]string{[]string{mi.Announce}}
1529 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
1534 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1536 defer cl.mu.Unlock()
1537 t, ok := cl.torrents[infoHash]
1542 t = cl.newTorrent(infoHash)
1543 if !cl.config.DisableTrackers {
1544 go cl.announceTorrentTrackers(t)
1547 go cl.announceTorrentDHT(t, true)
1549 cl.torrents[infoHash] = t
1553 // Add or merge a torrent spec. If the torrent is already present, the
1554 // trackers will be merged with the existing ones. If the Info isn't yet
1555 // known, it will be set. The display name is replaced if the new spec
1556 // provides one. Returns new if the torrent wasn't already in the client.
1557 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1558 t, new = cl.AddTorrentInfoHash(spec.InfoHash)
1560 if spec.DisplayName != "" {
1561 t.SetDisplayName(spec.DisplayName)
1564 if spec.Info != nil {
1565 err = t.SetInfoBytes(spec.Info.Bytes)
1572 defer cl.mu.Unlock()
1574 t.addTrackers(spec.Trackers)
1581 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1582 t, ok := cl.torrents[infoHash]
1584 err = fmt.Errorf("no such torrent")
1591 delete(cl.torrents, infoHash)
1595 // Returns true when peers are required, or false if the torrent is closing.
1596 func (cl *Client) waitWantPeers(t *Torrent) bool {
1598 defer cl.mu.Unlock()
1601 case <-t.ceasingNetworking:
1605 if len(t.peers) > torrentPeersLowWater {
1608 if t.needData() || cl.seeding(t) {
1616 // Returns whether the client should make effort to seed the torrent.
1617 func (cl *Client) seeding(t *Torrent) bool {
1618 if cl.config.NoUpload {
1621 if !cl.config.Seed {
1630 func (cl *Client) announceTorrentDHT(t *Torrent, impliedPort bool) {
1631 for cl.waitWantPeers(t) {
1632 // log.Printf("getting peers for %q from DHT", t)
1633 ps, err := cl.dHT.Announce(string(t.infoHash[:]), cl.incomingPeerPort(), impliedPort)
1635 log.Printf("error getting peers from dht: %s", err)
1638 // Count all the unique addresses we got during this announce.
1639 allAddrs := make(map[string]struct{})
1643 case v, ok := <-ps.Peers:
1647 addPeers := make([]Peer, 0, len(v.Peers))
1648 for _, cp := range v.Peers {
1650 // Can't do anything with this.
1653 addPeers = append(addPeers, Peer{
1656 Source: peerSourceDHT,
1658 key := (&net.UDPAddr{
1662 allAddrs[key] = struct{}{}
1665 cl.addPeers(t, addPeers)
1666 numPeers := len(t.peers)
1668 if numPeers >= torrentPeersHighWater {
1671 case <-t.ceasingNetworking:
1677 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
1681 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
1682 url_, err := url.Parse(trRawURL)
1686 host, _, err := net.SplitHostPort(url_.Host)
1690 addr, err := net.ResolveIPAddr("ip", host)
1695 _, blocked = cl.ipBlockRange(addr.IP)
1700 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *Torrent) error {
1701 blocked, err := cl.trackerBlockedUnlocked(tr)
1703 return fmt.Errorf("error determining if tracker blocked: %s", err)
1706 return fmt.Errorf("tracker blocked: %s", tr)
1708 resp, err := tracker.Announce(tr, req)
1710 return fmt.Errorf("error announcing: %s", err)
1713 for _, peer := range resp.Peers {
1714 peers = append(peers, Peer{
1720 cl.addPeers(t, peers)
1723 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1725 time.Sleep(time.Second * time.Duration(resp.Interval))
1729 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *Torrent) (atLeastOne bool) {
1730 oks := make(chan bool)
1732 for _, tier := range trackers {
1733 for _, tr := range tier {
1735 go func(tr string) {
1736 err := cl.announceTorrentSingleTracker(tr, req, t)
1741 for outstanding > 0 {
1751 // Announce torrent to its trackers.
1752 func (cl *Client) announceTorrentTrackers(t *Torrent) {
1753 req := tracker.AnnounceRequest{
1754 Event: tracker.Started,
1756 Port: uint16(cl.incomingPeerPort()),
1758 InfoHash: t.infoHash,
1760 if !cl.waitWantPeers(t) {
1764 req.Left = t.bytesLeftAnnounce()
1765 trackers := t.trackers
1767 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
1768 req.Event = tracker.None
1771 for cl.waitWantPeers(t) {
1773 req.Left = t.bytesLeftAnnounce()
1774 trackers = t.trackers
1776 numTrackersTried := 0
1777 for _, tier := range trackers {
1778 for trIndex, tr := range tier {
1780 err := cl.announceTorrentSingleTracker(tr, &req, t)
1784 // Float the successful announce to the top of the tier. If
1785 // the trackers list has been changed, we'll be modifying an
1786 // old copy so it won't matter.
1788 tier[0], tier[trIndex] = tier[trIndex], tier[0]
1791 req.Event = tracker.None
1792 continue newAnnounce
1795 if numTrackersTried != 0 {
1796 log.Printf("%s: all trackers failed", t)
1798 // TODO: Wait until trackers are added if there are none.
1799 time.Sleep(10 * time.Second)
1803 func (cl *Client) allTorrentsCompleted() bool {
1804 for _, t := range cl.torrents {
1808 if t.numPiecesCompleted() != t.numPieces() {
1815 // Returns true when all torrents are completely downloaded and false if the
1816 // client is stopped before that.
1817 func (cl *Client) WaitAll() bool {
1819 defer cl.mu.Unlock()
1820 for !cl.allTorrentsCompleted() {
1821 if cl.closed.IsSet() {
1829 // Handle a received chunk from a peer.
1830 func (cl *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
1831 chunksReceived.Add(1)
1833 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1835 // Request has been satisfied.
1836 if cl.connDeleteRequest(t, c, req) {
1837 defer c.updateRequests()
1839 unexpectedChunksReceived.Add(1)
1842 index := int(req.Index)
1843 piece := &t.pieces[index]
1845 // Do we actually want this chunk?
1846 if !t.wantPiece(req) {
1847 unwantedChunksReceived.Add(1)
1848 c.UnwantedChunksReceived++
1852 c.UsefulChunksReceived++
1853 c.lastUsefulChunkReceived = time.Now()
1857 // Need to record that it hasn't been written yet, before we attempt to do
1858 // anything with it.
1859 piece.incrementPendingWrites()
1860 // Record that we have the chunk.
1861 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1863 // Cancel pending requests for this chunk.
1864 for _, c := range t.conns {
1865 if cl.connCancel(t, c, req) {
1871 // Write the chunk out.
1872 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1875 piece.decrementPendingWrites()
1878 log.Printf("%s: error writing chunk %v: %s", t, req, err)
1880 t.updatePieceCompletion(int(msg.Index))
1884 // It's important that the piece is potentially queued before we check if
1885 // the piece is still wanted, because if it is queued, it won't be wanted.
1886 if t.pieceAllDirty(index) {
1887 cl.queuePieceCheck(t, int(req.Index))
1890 if c.peerTouchedPieces == nil {
1891 c.peerTouchedPieces = make(map[int]struct{})
1893 c.peerTouchedPieces[index] = struct{}{}
1895 cl.event.Broadcast()
1896 t.publishPieceChange(int(req.Index))
1900 // Return the connections that touched a piece, and clear the entry while
1902 func (cl *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
1903 for _, c := range t.conns {
1904 if _, ok := c.peerTouchedPieces[piece]; ok {
1905 ret = append(ret, c)
1906 delete(c.peerTouchedPieces, piece)
1912 func (cl *Client) pieceHashed(t *Torrent, piece int, correct bool) {
1913 p := &t.pieces[piece]
1915 // Don't score the first time a piece is hashed, it could be an
1918 pieceHashedCorrect.Add(1)
1920 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
1921 pieceHashedNotCorrect.Add(1)
1925 touchers := cl.reapPieceTouches(t, piece)
1927 err := p.Storage().MarkComplete()
1929 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1931 t.updatePieceCompletion(piece)
1932 } else if len(touchers) != 0 {
1933 log.Printf("dropping %d conns that touched piece", len(touchers))
1934 for _, c := range touchers {
1935 cl.dropConnection(t, c)
1938 cl.pieceChanged(t, piece)
1941 func (cl *Client) onCompletedPiece(t *Torrent, piece int) {
1942 t.pendingPieces.Remove(piece)
1943 t.pendAllChunkSpecs(piece)
1944 for _, conn := range t.conns {
1946 for r := range conn.Requests {
1947 if int(r.Index) == piece {
1951 // Could check here if peer doesn't have piece, but due to caching
1952 // some peers may have said they have a piece but they don't.
1957 func (cl *Client) onFailedPiece(t *Torrent, piece int) {
1958 if t.pieceAllDirty(piece) {
1959 t.pendAllChunkSpecs(piece)
1961 if !t.wantPieceIndex(piece) {
1965 for _, conn := range t.conns {
1966 if conn.PeerHasPiece(piece) {
1967 conn.updateRequests()
1972 func (cl *Client) pieceChanged(t *Torrent, piece int) {
1973 correct := t.pieceComplete(piece)
1974 defer cl.event.Broadcast()
1976 cl.onCompletedPiece(t, piece)
1978 cl.onFailedPiece(t, piece)
1980 if t.updatePiecePriority(piece) {
1981 t.piecePriorityChanged(piece)
1983 t.publishPieceChange(piece)
1986 func (cl *Client) verifyPiece(t *Torrent, piece int) {
1988 defer cl.mu.Unlock()
1989 p := &t.pieces[piece]
1990 for p.Hashing || t.storage == nil {
1993 p.QueuedForHash = false
1994 if t.isClosed() || t.pieceComplete(piece) {
1995 t.updatePiecePriority(piece)
1996 t.publishPieceChange(piece)
2000 t.publishPieceChange(piece)
2002 sum := t.hashPiece(piece)
2010 cl.pieceHashed(t, piece, sum == p.Hash)
2013 // Returns handles to all the torrents loaded in the Client.
2014 func (cl *Client) Torrents() (ret []*Torrent) {
2016 for _, t := range cl.torrents {
2017 ret = append(ret, t)
2023 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
2024 spec, err := TorrentSpecFromMagnetURI(uri)
2028 T, _, err = cl.AddTorrentSpec(spec)
2032 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
2033 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2035 missinggo.CastSlice(&ss, mi.Nodes)
2040 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
2041 mi, err := metainfo.LoadFromFile(filename)
2045 return cl.AddTorrent(mi)
2048 func (cl *Client) DHT() *dht.Server {
2052 func (cl *Client) AddDHTNodes(nodes []string) {
2053 for _, n := range nodes {
2054 hmp := missinggo.SplitHostMaybePort(n)
2055 ip := net.ParseIP(hmp.Host)
2057 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
2061 Addr: dht.NewAddr(&net.UDPAddr{
2066 cl.DHT().AddNode(ni)