10 "github.com/anacrolix/missinggo/v2"
11 "github.com/anacrolix/torrent/metainfo"
14 type ExtensionBit uint
17 ExtensionBitDHT = 0 // http://www.bittorrent.org/beps/bep_0005.html
18 ExtensionBitExtended = 20 // http://www.bittorrent.org/beps/bep_0010.html
19 ExtensionBitFast = 2 // http://www.bittorrent.org/beps/bep_0006.html
22 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
34 PeerExtensionBits [8]byte
37 func (me PeerExtensionBits) String() string {
38 return hex.EncodeToString(me[:])
41 func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
42 for _, b := range bits {
48 func (pex PeerExtensionBits) SupportsExtended() bool {
49 return pex.GetBit(ExtensionBitExtended)
52 func (pex PeerExtensionBits) SupportsDHT() bool {
53 return pex.GetBit(ExtensionBitDHT)
56 func (pex PeerExtensionBits) SupportsFast() bool {
57 return pex.GetBit(ExtensionBitFast)
60 func (pex *PeerExtensionBits) SetBit(bit ExtensionBit, on bool) {
62 pex[7-bit/8] |= 1 << (bit % 8)
64 pex[7-bit/8] &^= 1 << (bit % 8)
68 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
69 return pex[7-bit/8]&(1<<(bit%8)) != 0
72 type HandshakeResult struct {
78 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
79 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
80 // condition other than the peer simply abandoning the Handshake.
82 sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
84 res HandshakeResult, err error,
86 // Bytes to be sent to the peer. Should never block the sender.
87 postCh := make(chan []byte, 4)
88 // A single error value sent when the writer completes.
89 writeDone := make(chan error, 1)
90 // Performs writes to the socket and ensures posts don't block.
91 go handshakeWriter(sock, postCh, writeDone)
94 close(postCh) // Done writing.
98 // Wait until writes complete before returning from handshake.
101 err = fmt.Errorf("error writing: %s", err)
105 post := func(bb []byte) {
109 panic("mustn't block while posting")
113 post([]byte(Protocol))
115 if ih != nil { // We already know what we want.
120 _, err = io.ReadFull(sock, b[:68])
122 err = xerrors.Errorf("while reading: %w", err)
125 if string(b[:20]) != Protocol {
126 err = xerrors.Errorf("unexpected protocol string")
129 missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
130 missinggo.CopyExact(&res.Hash, b[28:48])
131 missinggo.CopyExact(&res.PeerID, b[48:68])
132 // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
134 // TODO: Maybe we can just drop peers here if we're not interested. This
135 // could prevent them trying to reconnect, falsely believing there was
137 if ih == nil { // We were waiting for the peer to tell us what they wanted.