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) {
203 host, port, err := missinggo.ParseHostPort(addr)
207 if tcp && utp && port == 0 {
208 // If both protocols are active, they need to have the same port.
209 return listenBothSameDynamicPort(networkSuffix, host)
217 tcpL, err = listenTCP(networkSuffix, addr)
226 listenedAddr = tcpL.Addr().String()
229 utpSock, err = listenUTP(networkSuffix, addr)
233 listenedAddr = utpSock.Addr().String()
238 // Creates a new client.
239 func NewClient(cfg *Config) (cl *Client, err error) {
250 halfOpenLimit: defaultHalfOpenConnsPerTorrent,
252 defaultStorage: cfg.DefaultStorage,
253 dopplegangerAddrs: make(map[string]struct{}),
254 torrents: make(map[metainfo.Hash]*Torrent),
256 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
258 if cl.defaultStorage == nil {
259 cl.defaultStorage = storage.NewFile(cfg.DataDir)
261 if cfg.IPBlocklist != nil {
262 cl.ipBlockList = cfg.IPBlocklist
265 if cfg.PeerID != "" {
266 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
268 o := copy(cl.peerID[:], bep20)
269 _, err = rand.Read(cl.peerID[o:])
271 panic("error generating peer id")
275 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
276 !cl.config.DisableTCP,
277 !cl.config.DisableUTP,
279 if cl.config.DisableIPv6 {
285 cl.config.ListenAddr)
289 if cl.tcpListener != nil {
290 go cl.acceptConnections(cl.tcpListener, false)
292 if cl.utpSock != nil {
293 go cl.acceptConnections(cl.utpSock, true)
296 dhtCfg := cfg.DHTConfig
297 if dhtCfg.IPBlocklist == nil {
298 dhtCfg.IPBlocklist = cl.ipBlockList
300 dhtCfg.Addr = firstNonEmptyString(dhtCfg.Addr, cl.listenAddr, cl.config.ListenAddr)
301 if dhtCfg.Conn == nil && cl.utpSock != nil {
302 dhtCfg.Conn = cl.utpSock
304 cl.dHT, err = dht.NewServer(&dhtCfg)
313 func firstNonEmptyString(ss ...string) string {
314 for _, s := range ss {
322 // Stops the client. All connections to peers are closed and all activity will
324 func (cl *Client) Close() {
331 if cl.utpSock != nil {
332 cl.utpSock.CloseNow()
334 if cl.tcpListener != nil {
335 cl.tcpListener.Close()
337 for _, t := range cl.torrents {
343 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
345 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
346 if cl.ipBlockList == nil {
350 // If blocklists are enabled, then block non-IPv4 addresses, because
351 // blocklists do not yet support IPv6.
353 if missinggo.CryHeard() {
354 log.Printf("blocking non-IPv4 address: %s", ip)
360 return cl.ipBlockList.Lookup(ip4)
363 func (cl *Client) waitAccept() {
365 for _, t := range cl.torrents {
370 if cl.closed.IsSet() {
377 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
383 conn, err := l.Accept()
384 conn = pproffd.WrapNetConn(conn)
386 if cl.closed.IsSet() {
394 // I think something harsher should happen here? Our accept
395 // routine just fucked off.
403 reject := cl.badPeerIPPort(
404 missinggo.AddrIP(conn.RemoteAddr()),
405 missinggo.AddrPort(conn.RemoteAddr()))
411 go cl.incomingConnection(conn, utp)
415 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
417 if tc, ok := nc.(*net.TCPConn); ok {
420 c := newConnection(nc, &cl.mu)
421 c.Discovery = peerSourceIncoming
423 cl.runReceivedConn(c)
426 // Returns a handle to the given torrent, if it's present in the client.
427 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
430 t, ok = cl.torrents[ih]
434 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
435 return cl.torrents[ih]
438 type dialResult struct {
443 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
444 conn, err := dial(addr, t)
449 conn = nil // Pedantic
451 ch <- dialResult{conn, utp}
453 successfulDials.Add(1)
456 unsuccessfulDials.Add(1)
459 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
460 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
461 if ret < minDialTimeout {
467 // Returns whether an address is known to connect to a client with our own ID.
468 func (cl *Client) dopplegangerAddr(addr string) bool {
469 _, ok := cl.dopplegangerAddrs[addr]
473 // Start the process of connecting to the given peer for the given torrent if
475 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
476 if peer.Id == cl.peerID {
479 if cl.badPeerIPPort(peer.IP, peer.Port) {
482 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
483 if t.addrActive(addr) {
486 t.halfOpen[addr] = struct{}{}
487 go cl.outgoingConnection(t, addr, peer.Source)
490 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
492 pendingPeers := len(t.peers)
494 return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
497 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
498 c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
500 c.(*net.TCPConn).SetLinger(0)
502 c = pproffd.WrapNetConn(c)
506 func (cl *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
507 return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
510 // Returns a connection over UTP or TCP, whichever is first to connect.
511 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
512 // Initiate connections via TCP and UTP simultaneously. Use the first one
515 if !cl.config.DisableUTP {
518 if !cl.config.DisableTCP {
521 resCh := make(chan dialResult, left)
522 if !cl.config.DisableUTP {
523 go doDial(cl.dialUTP, resCh, true, addr, t)
525 if !cl.config.DisableTCP {
526 go doDial(cl.dialTCP, resCh, false, addr, t)
529 // Wait for a successful connection.
530 for ; left > 0 && res.Conn == nil; left-- {
534 // There are still incompleted dials.
536 for ; left > 0; left-- {
537 conn := (<-resCh).Conn
549 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
550 if _, ok := t.halfOpen[addr]; !ok {
551 panic("invariant broken")
553 delete(t.halfOpen, addr)
557 // Performs initiator handshakes and returns a connection. Returns nil
558 // *connection if no connection for valid reasons.
559 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
560 c = newConnection(nc, &cl.mu)
561 c.encrypted = encrypted
563 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
567 ok, err := cl.initiateHandshakes(c, t)
574 // Returns nil connection and nil error if no connection could be established
575 // for valid reasons.
576 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
577 nc, utp := cl.dialFirst(addr, t)
581 c, err = cl.handshakesConnection(nc, t, !cl.config.DisableEncryption, utp)
589 if cl.config.DisableEncryption {
590 // We already tried without encryption.
593 // Try again without encryption, using whichever protocol type worked last
596 nc, err = cl.dialUTP(addr, t)
598 nc, err = cl.dialTCP(addr, t)
601 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
604 c, err = cl.handshakesConnection(nc, t, false, utp)
605 if err != nil || c == nil {
611 // Called to dial out and run a connection. The addr we're given is already
612 // considered half-open.
613 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
614 c, err := cl.establishOutgoingConn(t, addr)
617 // Don't release lock between here and addConnection, unless it's for
619 cl.noLongerHalfOpen(t, addr)
622 log.Printf("error establishing outgoing connection: %s", err)
631 cl.runInitiatedHandshookConn(c, t)
634 // The port number for incoming peer connections. 0 if the client isn't
636 func (cl *Client) incomingPeerPort() int {
637 if cl.listenAddr == "" {
640 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
647 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
648 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
649 func addrCompactIP(addr net.Addr) (string, error) {
650 host, _, err := net.SplitHostPort(addr.String())
654 ip := net.ParseIP(host)
655 if v4 := ip.To4(); v4 != nil {
659 return string(v4), nil
661 return string(ip.To16()), nil
664 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
676 peerExtensionBytes [8]byte
680 func (pex *peerExtensionBytes) SupportsExtended() bool {
681 return pex[5]&0x10 != 0
684 func (pex *peerExtensionBytes) SupportsDHT() bool {
685 return pex[7]&0x01 != 0
688 func (pex *peerExtensionBytes) SupportsFast() bool {
689 return pex[7]&0x04 != 0
692 type handshakeResult struct {
698 // ih is nil if we expect the peer to declare the InfoHash, such as when the
699 // peer initiated the connection. Returns ok if the handshake was successful,
700 // and err if there was an unexpected condition other than the peer simply
701 // abandoning the handshake.
702 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
703 // Bytes to be sent to the peer. Should never block the sender.
704 postCh := make(chan []byte, 4)
705 // A single error value sent when the writer completes.
706 writeDone := make(chan error, 1)
707 // Performs writes to the socket and ensures posts don't block.
708 go handshakeWriter(sock, postCh, writeDone)
711 close(postCh) // Done writing.
718 // Wait until writes complete before returning from handshake.
721 err = fmt.Errorf("error writing: %s", err)
725 post := func(bb []byte) {
729 panic("mustn't block while posting")
733 post([]byte(pp.Protocol))
735 if ih != nil { // We already know what we want.
740 _, err = io.ReadFull(sock, b[:68])
745 if string(b[:20]) != pp.Protocol {
748 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
749 missinggo.CopyExact(&res.Hash, b[28:48])
750 missinggo.CopyExact(&res.peerID, b[48:68])
751 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
753 // TODO: Maybe we can just drop peers here if we're not interested. This
754 // could prevent them trying to reconnect, falsely believing there was
756 if ih == nil { // We were waiting for the peer to tell us what they wanted.
765 // Wraps a raw connection and provides the interface we want for using the
766 // connection in the message loop.
767 type deadlineReader struct {
772 func (r deadlineReader) Read(b []byte) (n int, err error) {
773 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
774 err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
776 err = fmt.Errorf("error setting read deadline: %s", err)
779 // Convert common errors into io.EOF.
781 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
783 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
793 type readWriter struct {
798 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
799 var protocol [len(pp.Protocol)]byte
800 _, err = io.ReadFull(rw, protocol[:])
805 io.MultiReader(bytes.NewReader(protocol[:]), rw),
808 if string(protocol[:]) == pp.Protocol {
812 ret, err = mse.ReceiveHandshake(ret, skeys)
816 func (cl *Client) receiveSkeys() (ret [][]byte) {
817 for ih := range cl.torrents {
818 ret = append(ret, ih[:])
823 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
825 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
830 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
831 if ih != t.infoHash {
837 // Do encryption and bittorrent handshakes as receiver.
838 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
840 skeys := cl.receiveSkeys()
842 if !cl.config.DisableEncryption {
843 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
845 if err == mse.ErrNoSecretKeyMatch {
851 ih, ok, err := cl.connBTHandshake(c, nil)
853 err = fmt.Errorf("error during bt handshake: %s", err)
865 // Returns !ok if handshake failed for valid reasons.
866 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
867 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
868 if err != nil || !ok {
872 c.PeerExtensionBytes = res.peerExtensionBytes
873 c.PeerID = res.peerID
874 c.completedHandshake = time.Now()
878 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
879 if c.PeerID == cl.peerID {
881 addr := c.conn.RemoteAddr().String()
882 cl.dopplegangerAddrs[addr] = struct{}{}
885 cl.runHandshookConn(c, t)
888 func (cl *Client) runReceivedConn(c *connection) {
889 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
893 t, err := cl.receiveHandshakes(c)
896 log.Printf("error receiving handshakes: %s", err)
905 if c.PeerID == cl.peerID {
906 // Because the remote address is not necessarily the same as its
907 // client's torrent listen address, we won't record the remote address
908 // as a doppleganger. Instead, the initiator can record *us* as the
912 cl.runHandshookConn(c, t)
915 func (cl *Client) runHandshookConn(c *connection, t *Torrent) {
916 c.conn.SetWriteDeadline(time.Time{})
918 deadlineReader{c.conn, c.rw},
921 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
922 if !t.addConnection(c) {
925 defer t.dropConnection(c)
926 go c.writer(time.Minute)
927 cl.sendInitialMessages(c, t)
928 err := cl.connectionLoop(t, c)
929 if err != nil && cl.config.Debug {
930 log.Printf("error during connection loop: %s", err)
934 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
935 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
936 conn.Post(pp.Message{
938 ExtendedID: pp.HandshakeExtendedID,
939 ExtendedPayload: func() []byte {
940 d := map[string]interface{}{
941 "m": func() (ret map[string]int) {
942 ret = make(map[string]int, 2)
943 ret["ut_metadata"] = metadataExtendedId
944 if !cl.config.DisablePEX {
945 ret["ut_pex"] = pexExtendedId
949 "v": extendedHandshakeClientVersion,
950 // No upload queue is implemented yet.
953 if !cl.config.DisableEncryption {
956 if torrent.metadataSizeKnown() {
957 d["metadata_size"] = torrent.metadataSize()
959 if p := cl.incomingPeerPort(); p != 0 {
962 yourip, err := addrCompactIP(conn.remoteAddr())
964 log.Printf("error calculating yourip field value in extension handshake: %s", err)
968 // log.Printf("sending %v", d)
969 b, err := bencode.Marshal(d)
977 if torrent.haveAnyPieces() {
978 conn.Bitfield(torrent.bitfield())
979 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
980 conn.Post(pp.Message{
984 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
985 conn.Post(pp.Message{
987 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
992 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
993 conn.updateRequests()
996 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1004 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1005 if !cn.RequestPending(r) {
1008 delete(cn.Requests, r)
1012 // Process incoming ut_metadata message.
1013 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1014 var d map[string]int
1015 err := bencode.Unmarshal(payload, &d)
1017 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1019 msgType, ok := d["msg_type"]
1021 return errors.New("missing msg_type field")
1025 case pp.DataMetadataExtensionMsgType:
1026 if !c.requestedMetadataPiece(piece) {
1027 return fmt.Errorf("got unexpected piece %d", piece)
1029 c.metadataRequests[piece] = false
1030 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1031 if begin < 0 || begin >= len(payload) {
1032 return fmt.Errorf("data has bad offset in payload: %d", begin)
1034 t.saveMetadataPiece(piece, payload[begin:])
1035 c.UsefulChunksReceived++
1036 c.lastUsefulChunkReceived = time.Now()
1037 return t.maybeCompleteMetadata()
1038 case pp.RequestMetadataExtensionMsgType:
1039 if !t.haveMetadataPiece(piece) {
1040 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1043 start := (1 << 14) * piece
1044 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1046 case pp.RejectMetadataExtensionMsgType:
1049 return errors.New("unknown msg_type value")
1053 func (cl *Client) upload(t *Torrent, c *connection) {
1054 if cl.config.NoUpload {
1057 if !c.PeerInterested {
1060 seeding := t.seeding()
1061 if !seeding && !t.connHasWantedPieces(c) {
1065 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1067 for r := range c.PeerRequests {
1068 err := cl.sendChunk(t, c, r)
1071 if t.pieceComplete(i) {
1072 t.updatePieceCompletion(i)
1073 if !t.pieceComplete(i) {
1074 // We had the piece, but not anymore.
1078 log.Printf("error sending chunk %+v to peer: %s", r, err)
1079 // If we failed to send a chunk, choke the peer to ensure they
1080 // flush all their requests. We've probably dropped a piece,
1081 // but there's no way to communicate this to the peer. If they
1082 // ask for it again, we'll kick them to allow us to send them
1083 // an updated bitfield.
1086 delete(c.PeerRequests, r)
1094 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1095 // Count the chunk being sent, even if it isn't.
1096 b := make([]byte, r.Length)
1097 p := t.info.Piece(int(r.Index))
1098 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1101 panic("expected error")
1112 uploadChunksPosted.Add(1)
1113 c.lastChunkSent = time.Now()
1117 // Processes incoming bittorrent messages. The client lock is held upon entry
1118 // and exit. Returning will end the connection.
1119 func (cl *Client) connectionLoop(t *Torrent, c *connection) error {
1120 decoder := pp.Decoder{
1121 R: bufio.NewReader(c.rw),
1122 MaxLength: 256 * 1024,
1127 err := decoder.Decode(&msg)
1129 if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1136 c.lastMessageReceived = time.Now()
1138 receivedKeepalives.Add(1)
1141 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1146 // We can then reset our interest.
1149 cl.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1152 c.PeerChoked = false
1153 cl.peerUnchoked(t, c)
1155 c.PeerInterested = true
1157 case pp.NotInterested:
1158 c.PeerInterested = false
1161 err = c.peerSentHave(int(msg.Index))
1166 if !c.PeerInterested {
1167 err = errors.New("peer sent request but isn't interested")
1170 if !t.havePiece(msg.Index.Int()) {
1171 // This isn't necessarily them screwing up. We can drop pieces
1172 // from our storage, and can't communicate this to peers
1173 // except by reconnecting.
1174 requestsReceivedForMissingPieces.Add(1)
1175 err = errors.New("peer requested piece we don't have")
1178 if c.PeerRequests == nil {
1179 c.PeerRequests = make(map[request]struct{}, maxRequests)
1181 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1184 req := newRequest(msg.Index, msg.Begin, msg.Length)
1185 if !c.PeerCancel(req) {
1186 unexpectedCancels.Add(1)
1189 err = c.peerSentBitfield(msg.Bitfield)
1191 err = c.peerSentHaveAll()
1193 err = c.peerSentHaveNone()
1195 cl.downloadedChunk(t, c, &msg)
1197 switch msg.ExtendedID {
1198 case pp.HandshakeExtendedID:
1199 // TODO: Create a bencode struct for this.
1200 var d map[string]interface{}
1201 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1203 err = fmt.Errorf("error decoding extended message payload: %s", err)
1206 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1207 if reqq, ok := d["reqq"]; ok {
1208 if i, ok := reqq.(int64); ok {
1209 c.PeerMaxRequests = int(i)
1212 if v, ok := d["v"]; ok {
1213 c.PeerClientName = v.(string)
1217 err = errors.New("handshake missing m item")
1220 mTyped, ok := m.(map[string]interface{})
1222 err = errors.New("handshake m value is not dict")
1225 if c.PeerExtensionIDs == nil {
1226 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1228 for name, v := range mTyped {
1231 log.Printf("bad handshake m item extension ID type: %T", v)
1235 delete(c.PeerExtensionIDs, name)
1237 if c.PeerExtensionIDs[name] == 0 {
1238 supportedExtensionMessages.Add(name, 1)
1240 c.PeerExtensionIDs[name] = byte(id)
1243 metadata_sizeUntyped, ok := d["metadata_size"]
1245 metadata_size, ok := metadata_sizeUntyped.(int64)
1247 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1249 err = t.setMetadataSize(metadata_size)
1251 err = fmt.Errorf("error setting metadata size to %d", metadata_size)
1256 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1257 c.requestPendingMetadata()
1259 case metadataExtendedId:
1260 err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1262 err = fmt.Errorf("error handling metadata extension message: %s", err)
1265 if cl.config.DisablePEX {
1268 var pexMsg peerExchangeMessage
1269 err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1271 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1276 t.addPeers(func() (ret []Peer) {
1277 for i, cp := range pexMsg.Added {
1279 IP: make([]byte, 4),
1281 Source: peerSourcePEX,
1283 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1284 p.SupportsEncryption = true
1286 missinggo.CopyExact(p.IP, cp.IP[:])
1287 ret = append(ret, p)
1294 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1297 // That client uses its own extension IDs for outgoing message
1298 // types, which is incorrect.
1299 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1300 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1308 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1313 pingAddr.Port = int(msg.Port)
1315 cl.dHT.Ping(pingAddr)
1317 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1325 func (cl *Client) openNewConns(t *Torrent) {
1326 defer t.updateWantPeersEvent()
1327 for len(t.peers) != 0 {
1331 if len(t.halfOpen) >= cl.halfOpenLimit {
1338 for k, p = range t.peers {
1342 cl.initiateConn(p, t)
1346 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1350 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1353 if _, ok := cl.ipBlockRange(ip); ok {
1356 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1362 // Return a Torrent ready for insertion into a Client.
1363 func (cl *Client) newTorrent(ih metainfo.Hash) (t *Torrent) {
1367 chunkSize: defaultChunkSize,
1368 peers: make(map[peersKey]Peer),
1370 halfOpen: make(map[string]struct{}),
1371 pieceStateChanges: pubsub.NewPubSub(),
1373 storageOpener: cl.defaultStorage,
1374 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1380 // For shuffling the tracker tiers.
1381 mathRand.Seed(time.Now().Unix())
1384 type trackerTier []string
1386 // The trackers within each tier must be shuffled before use.
1387 // http://stackoverflow.com/a/12267471/149482
1388 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1389 func shuffleTier(tier trackerTier) {
1390 for i := range tier {
1391 j := mathRand.Intn(i + 1)
1392 tier[i], tier[j] = tier[j], tier[i]
1396 // A file-like handle to some torrent data resource.
1397 type Handle interface {
1404 // Specifies a new torrent for adding to a client. There are helpers for
1405 // magnet URIs and torrent metainfo files.
1406 type TorrentSpec struct {
1407 // The tiered tracker URIs.
1409 InfoHash metainfo.Hash
1410 Info *metainfo.InfoEx
1411 // The name to use if the Name field from the Info isn't available.
1413 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1416 Storage storage.Client
1419 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1420 m, err := metainfo.ParseMagnetURI(uri)
1424 spec = &TorrentSpec{
1425 Trackers: [][]string{m.Trackers},
1426 DisplayName: m.DisplayName,
1427 InfoHash: m.InfoHash,
1432 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1433 spec = &TorrentSpec{
1434 Trackers: mi.AnnounceList,
1436 DisplayName: mi.Info.Name,
1437 InfoHash: mi.Info.Hash(),
1439 if spec.Trackers == nil && mi.Announce != "" {
1440 spec.Trackers = [][]string{{mi.Announce}}
1445 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1447 defer cl.mu.Unlock()
1448 t, ok := cl.torrents[infoHash]
1453 t = cl.newTorrent(infoHash)
1457 cl.torrents[infoHash] = t
1458 t.updateWantPeersEvent()
1459 // Tickle Client.waitAccept, new torrent may want conns.
1460 cl.event.Broadcast()
1464 // Add or merge a torrent spec. If the torrent is already present, the
1465 // trackers will be merged with the existing ones. If the Info isn't yet
1466 // known, it will be set. The display name is replaced if the new spec
1467 // provides one. Returns new if the torrent wasn't already in the client.
1468 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1469 t, new = cl.AddTorrentInfoHash(spec.InfoHash)
1470 if spec.DisplayName != "" {
1471 t.SetDisplayName(spec.DisplayName)
1473 if spec.Info != nil {
1474 err = t.SetInfoBytes(spec.Info.Bytes)
1480 defer cl.mu.Unlock()
1481 if spec.ChunkSize != 0 {
1482 t.chunkSize = pp.Integer(spec.ChunkSize)
1484 t.addTrackers(spec.Trackers)
1489 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1490 t, ok := cl.torrents[infoHash]
1492 err = fmt.Errorf("no such torrent")
1499 delete(cl.torrents, infoHash)
1503 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1504 _url, err := url.Parse(announceURL)
1508 hmp := missinggo.SplitHostMaybePort(_url.Host)
1513 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1518 _, blocked = cl.ipBlockRange(addr.IP)
1521 hmp.Host = addr.String()
1522 _url.Host = hmp.String()
1523 urlToUse = _url.String()
1527 func (cl *Client) allTorrentsCompleted() bool {
1528 for _, t := range cl.torrents {
1532 if t.numPiecesCompleted() != t.numPieces() {
1539 // Returns true when all torrents are completely downloaded and false if the
1540 // client is stopped before that.
1541 func (cl *Client) WaitAll() bool {
1543 defer cl.mu.Unlock()
1544 for !cl.allTorrentsCompleted() {
1545 if cl.closed.IsSet() {
1553 // Handle a received chunk from a peer.
1554 func (cl *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
1555 chunksReceived.Add(1)
1557 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1559 // Request has been satisfied.
1560 if cl.connDeleteRequest(t, c, req) {
1561 defer c.updateRequests()
1563 unexpectedChunksReceived.Add(1)
1566 index := int(req.Index)
1567 piece := &t.pieces[index]
1569 // Do we actually want this chunk?
1570 if !t.wantPiece(req) {
1571 unwantedChunksReceived.Add(1)
1572 c.UnwantedChunksReceived++
1576 c.UsefulChunksReceived++
1577 c.lastUsefulChunkReceived = time.Now()
1581 // Need to record that it hasn't been written yet, before we attempt to do
1582 // anything with it.
1583 piece.incrementPendingWrites()
1584 // Record that we have the chunk.
1585 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1587 // Cancel pending requests for this chunk.
1588 for _, c := range t.conns {
1589 if cl.connCancel(t, c, req) {
1595 // Write the chunk out. Note that the upper bound on chunk writing
1596 // concurrency will be the number of connections.
1597 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1600 piece.decrementPendingWrites()
1603 log.Printf("%s: error writing chunk %v: %s", t, req, err)
1605 t.updatePieceCompletion(int(msg.Index))
1609 // It's important that the piece is potentially queued before we check if
1610 // the piece is still wanted, because if it is queued, it won't be wanted.
1611 if t.pieceAllDirty(index) {
1612 cl.queuePieceCheck(t, int(req.Index))
1615 if c.peerTouchedPieces == nil {
1616 c.peerTouchedPieces = make(map[int]struct{})
1618 c.peerTouchedPieces[index] = struct{}{}
1620 cl.event.Broadcast()
1621 t.publishPieceChange(int(req.Index))
1625 // Return the connections that touched a piece, and clear the entry while
1627 func (cl *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
1628 for _, c := range t.conns {
1629 if _, ok := c.peerTouchedPieces[piece]; ok {
1630 ret = append(ret, c)
1631 delete(c.peerTouchedPieces, piece)
1637 func (cl *Client) pieceHashed(t *Torrent, piece int, correct bool) {
1638 if t.closed.IsSet() {
1641 p := &t.pieces[piece]
1643 // Don't score the first time a piece is hashed, it could be an
1646 pieceHashedCorrect.Add(1)
1648 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
1649 pieceHashedNotCorrect.Add(1)
1653 touchers := cl.reapPieceTouches(t, piece)
1655 for _, c := range touchers {
1656 c.goodPiecesDirtied++
1658 err := p.Storage().MarkComplete()
1660 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1662 t.updatePieceCompletion(piece)
1663 } else if len(touchers) != 0 {
1664 log.Printf("dropping and banning %d conns that touched piece", len(touchers))
1665 for _, c := range touchers {
1666 c.badPiecesDirtied++
1667 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1671 cl.pieceChanged(t, piece)
1674 func (cl *Client) onCompletedPiece(t *Torrent, piece int) {
1675 t.pendingPieces.Remove(piece)
1676 t.pendAllChunkSpecs(piece)
1677 for _, conn := range t.conns {
1679 for r := range conn.Requests {
1680 if int(r.Index) == piece {
1684 // Could check here if peer doesn't have piece, but due to caching
1685 // some peers may have said they have a piece but they don't.
1690 func (cl *Client) onFailedPiece(t *Torrent, piece int) {
1691 if t.pieceAllDirty(piece) {
1692 t.pendAllChunkSpecs(piece)
1694 if !t.wantPieceIndex(piece) {
1698 for _, conn := range t.conns {
1699 if conn.PeerHasPiece(piece) {
1700 conn.updateRequests()
1705 func (cl *Client) pieceChanged(t *Torrent, piece int) {
1706 correct := t.pieceComplete(piece)
1707 defer cl.event.Broadcast()
1709 cl.onCompletedPiece(t, piece)
1711 cl.onFailedPiece(t, piece)
1713 if t.updatePiecePriority(piece) {
1714 t.piecePriorityChanged(piece)
1716 t.publishPieceChange(piece)
1719 func (cl *Client) verifyPiece(t *Torrent, piece int) {
1721 defer cl.mu.Unlock()
1722 p := &t.pieces[piece]
1723 for p.Hashing || t.storage == nil {
1726 p.QueuedForHash = false
1727 if t.closed.IsSet() || t.pieceComplete(piece) {
1728 t.updatePiecePriority(piece)
1729 t.publishPieceChange(piece)
1733 t.publishPieceChange(piece)
1735 sum := t.hashPiece(piece)
1738 cl.pieceHashed(t, piece, sum == p.Hash)
1741 // Returns handles to all the torrents loaded in the Client.
1742 func (cl *Client) Torrents() (ret []*Torrent) {
1744 for _, t := range cl.torrents {
1745 ret = append(ret, t)
1751 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1752 spec, err := TorrentSpecFromMagnetURI(uri)
1756 T, _, err = cl.AddTorrentSpec(spec)
1760 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1761 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1763 slices.MakeInto(&ss, mi.Nodes)
1768 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1769 mi, err := metainfo.LoadFromFile(filename)
1773 return cl.AddTorrent(mi)
1776 func (cl *Client) DHT() *dht.Server {
1780 func (cl *Client) AddDHTNodes(nodes []string) {
1781 for _, n := range nodes {
1782 hmp := missinggo.SplitHostMaybePort(n)
1783 ip := net.ParseIP(hmp.Host)
1785 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1788 ni := krpc.NodeInfo{
1794 cl.DHT().AddNode(ni)
1798 func (cl *Client) banPeerIP(ip net.IP) {
1799 if cl.badPeerIPs == nil {
1800 cl.badPeerIPs = make(map[string]struct{})
1802 cl.badPeerIPs[ip.String()] = struct{}{}