19 "github.com/anacrolix/missinggo"
20 "github.com/anacrolix/missinggo/pproffd"
21 "github.com/anacrolix/missinggo/pubsub"
22 "github.com/anacrolix/missinggo/slices"
23 "github.com/anacrolix/sync"
24 "github.com/anacrolix/utp"
25 "github.com/dustin/go-humanize"
27 "github.com/anacrolix/torrent/bencode"
28 "github.com/anacrolix/torrent/dht"
29 "github.com/anacrolix/torrent/dht/krpc"
30 "github.com/anacrolix/torrent/iplist"
31 "github.com/anacrolix/torrent/metainfo"
32 "github.com/anacrolix/torrent/mse"
33 pp "github.com/anacrolix/torrent/peer_protocol"
34 "github.com/anacrolix/torrent/storage"
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 // The net.Addr.String part that should be common to all active listeners.
65 tcpListener net.Listener
68 ipBlockList iplist.Ranger
70 extensionBytes peerExtensionBytes
71 // Set of addresses that have our client ID. This intentionally will
72 // include ourselves if we end up trying to connect to our own address
73 // through legitimate channels.
74 dopplegangerAddrs map[string]struct{}
75 badPeerIPs map[string]struct{}
77 defaultStorage storage.Client
81 closed missinggo.Event
83 torrents map[metainfo.Hash]*Torrent
86 func (cl *Client) BadPeerIPs() []string {
89 return slices.FromMapKeys(cl.badPeerIPs).([]string)
92 func (cl *Client) IPBlockList() iplist.Ranger {
98 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
101 cl.ipBlockList = list
103 cl.dHT.SetIPBlockList(list)
107 func (cl *Client) PeerID() string {
108 return string(cl.peerID[:])
111 type torrentAddr string
113 func (me torrentAddr) Network() string { return "" }
115 func (me torrentAddr) String() string { return string(me) }
117 func (cl *Client) ListenAddr() net.Addr {
118 if cl.listenAddr == "" {
121 return torrentAddr(cl.listenAddr)
124 func (cl *Client) sortedTorrents() (ret []*Torrent) {
125 return slices.Sort(slices.FromMapElems(cl.torrents), func(l, r metainfo.Hash) bool {
126 return l.AsString() < r.AsString()
130 // Writes out a human readable status of the client, such as for writing to a
132 func (cl *Client) WriteStatus(_w io.Writer) {
133 w := bufio.NewWriter(_w)
135 if addr := cl.ListenAddr(); addr != nil {
136 fmt.Fprintf(w, "Listening on %s\n", addr)
138 fmt.Fprintln(w, "Not listening!")
140 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
141 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.BadPeerIPs()))
142 if dht := cl.DHT(); dht != nil {
143 dhtStats := dht.Stats()
144 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
145 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
146 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
147 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
148 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
150 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.Torrents()))
152 for _, t := range slices.Sort(append([]*Torrent(nil), cl.Torrents()...), func(l, r *Torrent) bool {
153 return l.InfoHash().AsString() < r.InfoHash().AsString()
156 fmt.Fprint(w, "<unknown name>")
158 fmt.Fprint(w, t.Name())
162 fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.BytesMissing())/float64(t.Info().TotalLength())), t.length, humanize.Bytes(uint64(t.Info().TotalLength())))
164 w.WriteString("<missing metainfo>")
172 func listenUTP(networkSuffix, addr string) (*utp.Socket, error) {
173 return utp.NewSocket("udp"+networkSuffix, addr)
176 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
177 return net.Listen("tcp"+networkSuffix, addr)
180 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
182 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
186 listenedAddr = tcpL.Addr().String()
187 utpSock, err = listenUTP(networkSuffix, listenedAddr)
192 if !strings.Contains(err.Error(), "address already in use") {
198 // Listen to enabled protocols, ensuring ports match.
199 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
206 host, port, err = missinggo.ParseHostPort(addr)
211 // If both protocols are active, they need to have the same port.
212 return listenBothSameDynamicPort(networkSuffix, host)
221 tcpL, err = listenTCP(networkSuffix, addr)
230 listenedAddr = tcpL.Addr().String()
233 utpSock, err = listenUTP(networkSuffix, addr)
237 listenedAddr = utpSock.Addr().String()
242 // Creates a new client.
243 func NewClient(cfg *Config) (cl *Client, err error) {
254 halfOpenLimit: defaultHalfOpenConnsPerTorrent,
256 defaultStorage: cfg.DefaultStorage,
257 dopplegangerAddrs: make(map[string]struct{}),
258 torrents: make(map[metainfo.Hash]*Torrent),
260 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
262 if cl.defaultStorage == nil {
263 cl.defaultStorage = storage.NewFile(cfg.DataDir)
265 if cfg.IPBlocklist != nil {
266 cl.ipBlockList = cfg.IPBlocklist
269 if cfg.PeerID != "" {
270 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
272 o := copy(cl.peerID[:], bep20)
273 _, err = rand.Read(cl.peerID[o:])
275 panic("error generating peer id")
279 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
280 !cl.config.DisableTCP,
281 !cl.config.DisableUTP,
283 if cl.config.DisableIPv6 {
289 cl.config.ListenAddr)
293 if cl.tcpListener != nil {
294 go cl.acceptConnections(cl.tcpListener, false)
296 if cl.utpSock != nil {
297 go cl.acceptConnections(cl.utpSock, true)
300 dhtCfg := cfg.DHTConfig
301 if dhtCfg.IPBlocklist == nil {
302 dhtCfg.IPBlocklist = cl.ipBlockList
304 dhtCfg.Addr = firstNonEmptyString(dhtCfg.Addr, cl.listenAddr, cl.config.ListenAddr)
305 if dhtCfg.Conn == nil && cl.utpSock != nil {
306 dhtCfg.Conn = cl.utpSock
308 cl.dHT, err = dht.NewServer(&dhtCfg)
317 func firstNonEmptyString(ss ...string) string {
318 for _, s := range ss {
326 // Stops the client. All connections to peers are closed and all activity will
328 func (cl *Client) Close() {
335 if cl.utpSock != nil {
336 cl.utpSock.CloseNow()
338 if cl.tcpListener != nil {
339 cl.tcpListener.Close()
341 for _, t := range cl.torrents {
347 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
349 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
350 if cl.ipBlockList == nil {
354 // If blocklists are enabled, then block non-IPv4 addresses, because
355 // blocklists do not yet support IPv6.
357 if missinggo.CryHeard() {
358 log.Printf("blocking non-IPv4 address: %s", ip)
364 return cl.ipBlockList.Lookup(ip4)
367 func (cl *Client) waitAccept() {
369 for _, t := range cl.torrents {
374 if cl.closed.IsSet() {
381 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
387 conn, err := l.Accept()
388 conn = pproffd.WrapNetConn(conn)
390 if cl.closed.IsSet() {
398 // I think something harsher should happen here? Our accept
399 // routine just fucked off.
407 reject := cl.badPeerIPPort(
408 missinggo.AddrIP(conn.RemoteAddr()),
409 missinggo.AddrPort(conn.RemoteAddr()))
415 go cl.incomingConnection(conn, utp)
419 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
421 if tc, ok := nc.(*net.TCPConn); ok {
424 c := newConnection(nc, &cl.mu)
425 c.Discovery = peerSourceIncoming
427 cl.runReceivedConn(c)
430 // Returns a handle to the given torrent, if it's present in the client.
431 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
434 t, ok = cl.torrents[ih]
438 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
439 return cl.torrents[ih]
442 type dialResult struct {
447 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
448 conn, err := dial(addr, t)
453 conn = nil // Pedantic
455 ch <- dialResult{conn, utp}
457 successfulDials.Add(1)
460 unsuccessfulDials.Add(1)
463 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
464 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
465 if ret < minDialTimeout {
471 // Returns whether an address is known to connect to a client with our own ID.
472 func (cl *Client) dopplegangerAddr(addr string) bool {
473 _, ok := cl.dopplegangerAddrs[addr]
477 // Start the process of connecting to the given peer for the given torrent if
479 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
480 if peer.Id == cl.peerID {
483 if cl.badPeerIPPort(peer.IP, peer.Port) {
486 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
487 if t.addrActive(addr) {
490 t.halfOpen[addr] = struct{}{}
491 go cl.outgoingConnection(t, addr, peer.Source)
494 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
496 pendingPeers := len(t.peers)
498 return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
501 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
502 c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
504 c.(*net.TCPConn).SetLinger(0)
506 c = pproffd.WrapNetConn(c)
510 func (cl *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
511 return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
514 // Returns a connection over UTP or TCP, whichever is first to connect.
515 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
516 // Initiate connections via TCP and UTP simultaneously. Use the first one
519 if !cl.config.DisableUTP {
522 if !cl.config.DisableTCP {
525 resCh := make(chan dialResult, left)
526 if !cl.config.DisableUTP {
527 go doDial(cl.dialUTP, resCh, true, addr, t)
529 if !cl.config.DisableTCP {
530 go doDial(cl.dialTCP, resCh, false, addr, t)
533 // Wait for a successful connection.
534 for ; left > 0 && res.Conn == nil; left-- {
538 // There are still incompleted dials.
540 for ; left > 0; left-- {
541 conn := (<-resCh).Conn
553 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
554 if _, ok := t.halfOpen[addr]; !ok {
555 panic("invariant broken")
557 delete(t.halfOpen, addr)
561 // Performs initiator handshakes and returns a connection. Returns nil
562 // *connection if no connection for valid reasons.
563 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
564 c = newConnection(nc, &cl.mu)
565 c.encrypted = encrypted
567 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
571 ok, err := cl.initiateHandshakes(c, t)
578 // Returns nil connection and nil error if no connection could be established
579 // for valid reasons.
580 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
581 nc, utp := cl.dialFirst(addr, t)
585 c, err = cl.handshakesConnection(nc, t, !cl.config.DisableEncryption, utp)
593 if cl.config.DisableEncryption {
594 // We already tried without encryption.
597 // Try again without encryption, using whichever protocol type worked last
600 nc, err = cl.dialUTP(addr, t)
602 nc, err = cl.dialTCP(addr, t)
605 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
608 c, err = cl.handshakesConnection(nc, t, false, utp)
609 if err != nil || c == nil {
615 // Called to dial out and run a connection. The addr we're given is already
616 // considered half-open.
617 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
618 c, err := cl.establishOutgoingConn(t, addr)
621 // Don't release lock between here and addConnection, unless it's for
623 cl.noLongerHalfOpen(t, addr)
626 log.Printf("error establishing outgoing connection: %s", err)
635 cl.runInitiatedHandshookConn(c, t)
638 // The port number for incoming peer connections. 0 if the client isn't
640 func (cl *Client) incomingPeerPort() int {
641 if cl.listenAddr == "" {
644 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
651 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
652 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
653 func addrCompactIP(addr net.Addr) (string, error) {
654 host, _, err := net.SplitHostPort(addr.String())
658 ip := net.ParseIP(host)
659 if v4 := ip.To4(); v4 != nil {
663 return string(v4), nil
665 return string(ip.To16()), nil
668 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
680 peerExtensionBytes [8]byte
684 func (pex *peerExtensionBytes) SupportsExtended() bool {
685 return pex[5]&0x10 != 0
688 func (pex *peerExtensionBytes) SupportsDHT() bool {
689 return pex[7]&0x01 != 0
692 func (pex *peerExtensionBytes) SupportsFast() bool {
693 return pex[7]&0x04 != 0
696 type handshakeResult struct {
702 // ih is nil if we expect the peer to declare the InfoHash, such as when the
703 // peer initiated the connection. Returns ok if the handshake was successful,
704 // and err if there was an unexpected condition other than the peer simply
705 // abandoning the handshake.
706 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
707 // Bytes to be sent to the peer. Should never block the sender.
708 postCh := make(chan []byte, 4)
709 // A single error value sent when the writer completes.
710 writeDone := make(chan error, 1)
711 // Performs writes to the socket and ensures posts don't block.
712 go handshakeWriter(sock, postCh, writeDone)
715 close(postCh) // Done writing.
722 // Wait until writes complete before returning from handshake.
725 err = fmt.Errorf("error writing: %s", err)
729 post := func(bb []byte) {
733 panic("mustn't block while posting")
737 post([]byte(pp.Protocol))
739 if ih != nil { // We already know what we want.
744 _, err = io.ReadFull(sock, b[:68])
749 if string(b[:20]) != pp.Protocol {
752 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
753 missinggo.CopyExact(&res.Hash, b[28:48])
754 missinggo.CopyExact(&res.peerID, b[48:68])
755 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
757 // TODO: Maybe we can just drop peers here if we're not interested. This
758 // could prevent them trying to reconnect, falsely believing there was
760 if ih == nil { // We were waiting for the peer to tell us what they wanted.
769 // Wraps a raw connection and provides the interface we want for using the
770 // connection in the message loop.
771 type deadlineReader struct {
776 func (r deadlineReader) Read(b []byte) (n int, err error) {
777 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
778 err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
780 err = fmt.Errorf("error setting read deadline: %s", err)
783 // Convert common errors into io.EOF.
785 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
787 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
797 type readWriter struct {
802 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
803 var protocol [len(pp.Protocol)]byte
804 _, err = io.ReadFull(rw, protocol[:])
809 io.MultiReader(bytes.NewReader(protocol[:]), rw),
812 if string(protocol[:]) == pp.Protocol {
816 ret, err = mse.ReceiveHandshake(ret, skeys)
820 func (cl *Client) receiveSkeys() (ret [][]byte) {
821 for ih := range cl.torrents {
822 ret = append(ret, ih[:])
827 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
829 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
834 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
835 if ih != t.infoHash {
841 // Do encryption and bittorrent handshakes as receiver.
842 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
844 skeys := cl.receiveSkeys()
846 if !cl.config.DisableEncryption {
847 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
849 if err == mse.ErrNoSecretKeyMatch {
855 ih, ok, err := cl.connBTHandshake(c, nil)
857 err = fmt.Errorf("error during bt handshake: %s", err)
869 // Returns !ok if handshake failed for valid reasons.
870 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
871 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
872 if err != nil || !ok {
876 c.PeerExtensionBytes = res.peerExtensionBytes
877 c.PeerID = res.peerID
878 c.completedHandshake = time.Now()
882 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
883 if c.PeerID == cl.peerID {
885 addr := c.conn.RemoteAddr().String()
886 cl.dopplegangerAddrs[addr] = struct{}{}
889 cl.runHandshookConn(c, t)
892 func (cl *Client) runReceivedConn(c *connection) {
893 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
897 t, err := cl.receiveHandshakes(c)
900 log.Printf("error receiving handshakes: %s", err)
909 if c.PeerID == cl.peerID {
910 // Because the remote address is not necessarily the same as its
911 // client's torrent listen address, we won't record the remote address
912 // as a doppleganger. Instead, the initiator can record *us* as the
916 cl.runHandshookConn(c, t)
919 func (cl *Client) runHandshookConn(c *connection, t *Torrent) {
920 c.conn.SetWriteDeadline(time.Time{})
922 deadlineReader{c.conn, c.rw},
925 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
926 if !t.addConnection(c) {
929 defer t.dropConnection(c)
930 go c.writer(time.Minute)
931 cl.sendInitialMessages(c, t)
932 err := cl.connectionLoop(t, c)
933 if err != nil && cl.config.Debug {
934 log.Printf("error during connection loop: %s", err)
938 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
939 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
940 conn.Post(pp.Message{
942 ExtendedID: pp.HandshakeExtendedID,
943 ExtendedPayload: func() []byte {
944 d := map[string]interface{}{
945 "m": func() (ret map[string]int) {
946 ret = make(map[string]int, 2)
947 ret["ut_metadata"] = metadataExtendedId
948 if !cl.config.DisablePEX {
949 ret["ut_pex"] = pexExtendedId
953 "v": extendedHandshakeClientVersion,
954 // No upload queue is implemented yet.
957 if !cl.config.DisableEncryption {
960 if torrent.metadataSizeKnown() {
961 d["metadata_size"] = torrent.metadataSize()
963 if p := cl.incomingPeerPort(); p != 0 {
966 yourip, err := addrCompactIP(conn.remoteAddr())
968 log.Printf("error calculating yourip field value in extension handshake: %s", err)
972 // log.Printf("sending %v", d)
973 b, err := bencode.Marshal(d)
981 if torrent.haveAnyPieces() {
982 conn.Bitfield(torrent.bitfield())
983 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
984 conn.Post(pp.Message{
988 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
989 conn.Post(pp.Message{
991 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
996 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
997 conn.updateRequests()
1000 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1003 postedCancels.Add(1)
1008 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1009 if !cn.RequestPending(r) {
1012 delete(cn.Requests, r)
1016 // Process incoming ut_metadata message.
1017 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1018 var d map[string]int
1019 err := bencode.Unmarshal(payload, &d)
1021 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1023 msgType, ok := d["msg_type"]
1025 return errors.New("missing msg_type field")
1029 case pp.DataMetadataExtensionMsgType:
1030 if !c.requestedMetadataPiece(piece) {
1031 return fmt.Errorf("got unexpected piece %d", piece)
1033 c.metadataRequests[piece] = false
1034 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1035 if begin < 0 || begin >= len(payload) {
1036 return fmt.Errorf("data has bad offset in payload: %d", begin)
1038 t.saveMetadataPiece(piece, payload[begin:])
1039 c.UsefulChunksReceived++
1040 c.lastUsefulChunkReceived = time.Now()
1041 return t.maybeCompleteMetadata()
1042 case pp.RequestMetadataExtensionMsgType:
1043 if !t.haveMetadataPiece(piece) {
1044 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1047 start := (1 << 14) * piece
1048 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1050 case pp.RejectMetadataExtensionMsgType:
1053 return errors.New("unknown msg_type value")
1057 func (cl *Client) upload(t *Torrent, c *connection) {
1058 if cl.config.NoUpload {
1061 if !c.PeerInterested {
1064 seeding := t.seeding()
1065 if !seeding && !t.connHasWantedPieces(c) {
1069 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1071 for r := range c.PeerRequests {
1072 err := cl.sendChunk(t, c, r)
1075 if t.pieceComplete(i) {
1076 t.updatePieceCompletion(i)
1077 if !t.pieceComplete(i) {
1078 // We had the piece, but not anymore.
1082 log.Printf("error sending chunk %+v to peer: %s", r, err)
1083 // If we failed to send a chunk, choke the peer to ensure they
1084 // flush all their requests. We've probably dropped a piece,
1085 // but there's no way to communicate this to the peer. If they
1086 // ask for it again, we'll kick them to allow us to send them
1087 // an updated bitfield.
1090 delete(c.PeerRequests, r)
1098 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1099 // Count the chunk being sent, even if it isn't.
1100 b := make([]byte, r.Length)
1101 p := t.info.Piece(int(r.Index))
1102 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1105 panic("expected error")
1116 uploadChunksPosted.Add(1)
1117 c.lastChunkSent = time.Now()
1121 // Processes incoming bittorrent messages. The client lock is held upon entry
1122 // and exit. Returning will end the connection.
1123 func (cl *Client) connectionLoop(t *Torrent, c *connection) error {
1124 decoder := pp.Decoder{
1125 R: bufio.NewReader(c.rw),
1126 MaxLength: 256 * 1024,
1131 err := decoder.Decode(&msg)
1133 if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1140 c.lastMessageReceived = time.Now()
1142 receivedKeepalives.Add(1)
1145 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1150 // We can then reset our interest.
1153 cl.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1156 c.PeerChoked = false
1157 cl.peerUnchoked(t, c)
1159 c.PeerInterested = true
1161 case pp.NotInterested:
1162 c.PeerInterested = false
1165 err = c.peerSentHave(int(msg.Index))
1170 if !c.PeerInterested {
1171 err = errors.New("peer sent request but isn't interested")
1174 if !t.havePiece(msg.Index.Int()) {
1175 // This isn't necessarily them screwing up. We can drop pieces
1176 // from our storage, and can't communicate this to peers
1177 // except by reconnecting.
1178 requestsReceivedForMissingPieces.Add(1)
1179 err = errors.New("peer requested piece we don't have")
1182 if c.PeerRequests == nil {
1183 c.PeerRequests = make(map[request]struct{}, maxRequests)
1185 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1188 req := newRequest(msg.Index, msg.Begin, msg.Length)
1189 if !c.PeerCancel(req) {
1190 unexpectedCancels.Add(1)
1193 err = c.peerSentBitfield(msg.Bitfield)
1195 err = c.peerSentHaveAll()
1197 err = c.peerSentHaveNone()
1199 cl.downloadedChunk(t, c, &msg)
1201 switch msg.ExtendedID {
1202 case pp.HandshakeExtendedID:
1203 // TODO: Create a bencode struct for this.
1204 var d map[string]interface{}
1205 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1207 err = fmt.Errorf("error decoding extended message payload: %s", err)
1210 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1211 if reqq, ok := d["reqq"]; ok {
1212 if i, ok := reqq.(int64); ok {
1213 c.PeerMaxRequests = int(i)
1216 if v, ok := d["v"]; ok {
1217 c.PeerClientName = v.(string)
1221 err = errors.New("handshake missing m item")
1224 mTyped, ok := m.(map[string]interface{})
1226 err = errors.New("handshake m value is not dict")
1229 if c.PeerExtensionIDs == nil {
1230 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1232 for name, v := range mTyped {
1235 log.Printf("bad handshake m item extension ID type: %T", v)
1239 delete(c.PeerExtensionIDs, name)
1241 if c.PeerExtensionIDs[name] == 0 {
1242 supportedExtensionMessages.Add(name, 1)
1244 c.PeerExtensionIDs[name] = byte(id)
1247 metadata_sizeUntyped, ok := d["metadata_size"]
1249 metadata_size, ok := metadata_sizeUntyped.(int64)
1251 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1253 err = t.setMetadataSize(metadata_size)
1255 err = fmt.Errorf("error setting metadata size to %d", metadata_size)
1260 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1261 c.requestPendingMetadata()
1263 case metadataExtendedId:
1264 err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1266 err = fmt.Errorf("error handling metadata extension message: %s", err)
1269 if cl.config.DisablePEX {
1272 var pexMsg peerExchangeMessage
1273 err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1275 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1280 t.addPeers(func() (ret []Peer) {
1281 for i, cp := range pexMsg.Added {
1283 IP: make([]byte, 4),
1285 Source: peerSourcePEX,
1287 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1288 p.SupportsEncryption = true
1290 missinggo.CopyExact(p.IP, cp.IP[:])
1291 ret = append(ret, p)
1298 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1301 // That client uses its own extension IDs for outgoing message
1302 // types, which is incorrect.
1303 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1304 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1312 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1317 pingAddr.Port = int(msg.Port)
1319 cl.dHT.Ping(pingAddr)
1321 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1329 func (cl *Client) openNewConns(t *Torrent) {
1330 defer t.updateWantPeersEvent()
1331 for len(t.peers) != 0 {
1335 if len(t.halfOpen) >= cl.halfOpenLimit {
1342 for k, p = range t.peers {
1346 cl.initiateConn(p, t)
1350 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1354 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1357 if _, ok := cl.ipBlockRange(ip); ok {
1360 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1366 // Return a Torrent ready for insertion into a Client.
1367 func (cl *Client) newTorrent(ih metainfo.Hash) (t *Torrent) {
1371 chunkSize: defaultChunkSize,
1372 peers: make(map[peersKey]Peer),
1374 halfOpen: make(map[string]struct{}),
1375 pieceStateChanges: pubsub.NewPubSub(),
1377 storageOpener: cl.defaultStorage,
1378 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1384 // For shuffling the tracker tiers.
1385 mathRand.Seed(time.Now().Unix())
1388 type trackerTier []string
1390 // The trackers within each tier must be shuffled before use.
1391 // http://stackoverflow.com/a/12267471/149482
1392 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1393 func shuffleTier(tier trackerTier) {
1394 for i := range tier {
1395 j := mathRand.Intn(i + 1)
1396 tier[i], tier[j] = tier[j], tier[i]
1400 // A file-like handle to some torrent data resource.
1401 type Handle interface {
1408 // Specifies a new torrent for adding to a client. There are helpers for
1409 // magnet URIs and torrent metainfo files.
1410 type TorrentSpec struct {
1411 // The tiered tracker URIs.
1413 InfoHash metainfo.Hash
1415 // The name to use if the Name field from the Info isn't available.
1417 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1420 Storage storage.Client
1423 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1424 m, err := metainfo.ParseMagnetURI(uri)
1428 spec = &TorrentSpec{
1429 Trackers: [][]string{m.Trackers},
1430 DisplayName: m.DisplayName,
1431 InfoHash: m.InfoHash,
1436 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1437 info := mi.UnmarshalInfo()
1438 spec = &TorrentSpec{
1439 Trackers: mi.AnnounceList,
1440 InfoBytes: mi.InfoBytes,
1441 DisplayName: info.Name,
1442 InfoHash: mi.HashInfoBytes(),
1444 if spec.Trackers == nil && mi.Announce != "" {
1445 spec.Trackers = [][]string{{mi.Announce}}
1450 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1452 defer cl.mu.Unlock()
1453 t, ok := cl.torrents[infoHash]
1458 t = cl.newTorrent(infoHash)
1462 cl.torrents[infoHash] = t
1463 t.updateWantPeersEvent()
1464 // Tickle Client.waitAccept, new torrent may want conns.
1465 cl.event.Broadcast()
1469 // Add or merge a torrent spec. If the torrent is already present, the
1470 // trackers will be merged with the existing ones. If the Info isn't yet
1471 // known, it will be set. The display name is replaced if the new spec
1472 // provides one. Returns new if the torrent wasn't already in the client.
1473 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1474 t, new = cl.AddTorrentInfoHash(spec.InfoHash)
1475 if spec.DisplayName != "" {
1476 t.SetDisplayName(spec.DisplayName)
1478 if spec.InfoBytes != nil {
1479 err = t.SetInfoBytes(spec.InfoBytes)
1485 defer cl.mu.Unlock()
1486 if spec.ChunkSize != 0 {
1487 t.chunkSize = pp.Integer(spec.ChunkSize)
1489 t.addTrackers(spec.Trackers)
1494 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1495 t, ok := cl.torrents[infoHash]
1497 err = fmt.Errorf("no such torrent")
1504 delete(cl.torrents, infoHash)
1508 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1509 _url, err := url.Parse(announceURL)
1513 hmp := missinggo.SplitHostMaybePort(_url.Host)
1518 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1523 _, blocked = cl.ipBlockRange(addr.IP)
1526 hmp.Host = addr.String()
1527 _url.Host = hmp.String()
1528 urlToUse = _url.String()
1532 func (cl *Client) allTorrentsCompleted() bool {
1533 for _, t := range cl.torrents {
1537 if t.numPiecesCompleted() != t.numPieces() {
1544 // Returns true when all torrents are completely downloaded and false if the
1545 // client is stopped before that.
1546 func (cl *Client) WaitAll() bool {
1548 defer cl.mu.Unlock()
1549 for !cl.allTorrentsCompleted() {
1550 if cl.closed.IsSet() {
1558 // Handle a received chunk from a peer.
1559 func (cl *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
1560 chunksReceived.Add(1)
1562 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1564 // Request has been satisfied.
1565 if cl.connDeleteRequest(t, c, req) {
1566 defer c.updateRequests()
1568 unexpectedChunksReceived.Add(1)
1571 index := int(req.Index)
1572 piece := &t.pieces[index]
1574 // Do we actually want this chunk?
1575 if !t.wantPiece(req) {
1576 unwantedChunksReceived.Add(1)
1577 c.UnwantedChunksReceived++
1581 c.UsefulChunksReceived++
1582 c.lastUsefulChunkReceived = time.Now()
1586 // Need to record that it hasn't been written yet, before we attempt to do
1587 // anything with it.
1588 piece.incrementPendingWrites()
1589 // Record that we have the chunk.
1590 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1592 // Cancel pending requests for this chunk.
1593 for _, c := range t.conns {
1594 if cl.connCancel(t, c, req) {
1600 // Write the chunk out. Note that the upper bound on chunk writing
1601 // concurrency will be the number of connections.
1602 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1605 piece.decrementPendingWrites()
1608 log.Printf("%s: error writing chunk %v: %s", t, req, err)
1610 t.updatePieceCompletion(int(msg.Index))
1614 // It's important that the piece is potentially queued before we check if
1615 // the piece is still wanted, because if it is queued, it won't be wanted.
1616 if t.pieceAllDirty(index) {
1617 cl.queuePieceCheck(t, int(req.Index))
1620 if c.peerTouchedPieces == nil {
1621 c.peerTouchedPieces = make(map[int]struct{})
1623 c.peerTouchedPieces[index] = struct{}{}
1625 cl.event.Broadcast()
1626 t.publishPieceChange(int(req.Index))
1630 // Return the connections that touched a piece, and clear the entry while
1632 func (cl *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
1633 for _, c := range t.conns {
1634 if _, ok := c.peerTouchedPieces[piece]; ok {
1635 ret = append(ret, c)
1636 delete(c.peerTouchedPieces, piece)
1642 func (cl *Client) pieceHashed(t *Torrent, piece int, correct bool) {
1643 if t.closed.IsSet() {
1646 p := &t.pieces[piece]
1648 // Don't score the first time a piece is hashed, it could be an
1651 pieceHashedCorrect.Add(1)
1653 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
1654 pieceHashedNotCorrect.Add(1)
1658 touchers := cl.reapPieceTouches(t, piece)
1660 for _, c := range touchers {
1661 c.goodPiecesDirtied++
1663 err := p.Storage().MarkComplete()
1665 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1667 t.updatePieceCompletion(piece)
1668 } else if len(touchers) != 0 {
1669 log.Printf("dropping and banning %d conns that touched piece", len(touchers))
1670 for _, c := range touchers {
1671 c.badPiecesDirtied++
1672 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1676 cl.pieceChanged(t, piece)
1679 func (cl *Client) onCompletedPiece(t *Torrent, piece int) {
1680 t.pendingPieces.Remove(piece)
1681 t.pendAllChunkSpecs(piece)
1682 for _, conn := range t.conns {
1684 for r := range conn.Requests {
1685 if int(r.Index) == piece {
1689 // Could check here if peer doesn't have piece, but due to caching
1690 // some peers may have said they have a piece but they don't.
1695 func (cl *Client) onFailedPiece(t *Torrent, piece int) {
1696 if t.pieceAllDirty(piece) {
1697 t.pendAllChunkSpecs(piece)
1699 if !t.wantPieceIndex(piece) {
1703 for _, conn := range t.conns {
1704 if conn.PeerHasPiece(piece) {
1705 conn.updateRequests()
1710 func (cl *Client) pieceChanged(t *Torrent, piece int) {
1711 correct := t.pieceComplete(piece)
1712 defer cl.event.Broadcast()
1714 cl.onCompletedPiece(t, piece)
1716 cl.onFailedPiece(t, piece)
1718 if t.updatePiecePriority(piece) {
1719 t.piecePriorityChanged(piece)
1721 t.publishPieceChange(piece)
1724 func (cl *Client) verifyPiece(t *Torrent, piece int) {
1726 defer cl.mu.Unlock()
1727 p := &t.pieces[piece]
1728 for p.Hashing || t.storage == nil {
1731 p.QueuedForHash = false
1732 if t.closed.IsSet() || t.pieceComplete(piece) {
1733 t.updatePiecePriority(piece)
1734 t.publishPieceChange(piece)
1738 t.publishPieceChange(piece)
1740 sum := t.hashPiece(piece)
1743 cl.pieceHashed(t, piece, sum == p.Hash)
1746 // Returns handles to all the torrents loaded in the Client.
1747 func (cl *Client) Torrents() (ret []*Torrent) {
1749 for _, t := range cl.torrents {
1750 ret = append(ret, t)
1756 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1757 spec, err := TorrentSpecFromMagnetURI(uri)
1761 T, _, err = cl.AddTorrentSpec(spec)
1765 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1766 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1768 slices.MakeInto(&ss, mi.Nodes)
1773 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1774 mi, err := metainfo.LoadFromFile(filename)
1778 return cl.AddTorrent(mi)
1781 func (cl *Client) DHT() *dht.Server {
1785 func (cl *Client) AddDHTNodes(nodes []string) {
1786 for _, n := range nodes {
1787 hmp := missinggo.SplitHostMaybePort(n)
1788 ip := net.ParseIP(hmp.Host)
1790 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1793 ni := krpc.NodeInfo{
1799 cl.DHT().AddNode(ni)
1803 func (cl *Client) banPeerIP(ip net.IP) {
1804 if cl.badPeerIPs == nil {
1805 cl.badPeerIPs = make(map[string]struct{})
1807 cl.badPeerIPs[ip.String()] = struct{}{}