10 "github.com/anacrolix/missinggo"
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) {
61 pex[7-bit/8] |= 1 << (bit % 8)
64 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
65 return pex[7-bit/8]&(1<<(bit%8)) != 0
68 type HandshakeResult struct {
74 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
75 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
76 // condition other than the peer simply abandoning the Handshake.
78 sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
80 res HandshakeResult, err error,
82 // Bytes to be sent to the peer. Should never block the sender.
83 postCh := make(chan []byte, 4)
84 // A single error value sent when the writer completes.
85 writeDone := make(chan error, 1)
86 // Performs writes to the socket and ensures posts don't block.
87 go handshakeWriter(sock, postCh, writeDone)
90 close(postCh) // Done writing.
94 // Wait until writes complete before returning from handshake.
97 err = fmt.Errorf("error writing: %s", err)
101 post := func(bb []byte) {
105 panic("mustn't block while posting")
109 post([]byte(Protocol))
111 if ih != nil { // We already know what we want.
116 _, err = io.ReadFull(sock, b[:68])
118 err = xerrors.Errorf("while reading: %w", err)
121 if string(b[:20]) != Protocol {
122 err = xerrors.Errorf("unexpected protocol string")
125 missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
126 missinggo.CopyExact(&res.Hash, b[28:48])
127 missinggo.CopyExact(&res.PeerID, b[48:68])
128 // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
130 // TODO: Maybe we can just drop peers here if we're not interested. This
131 // could prevent them trying to reconnect, falsely believing there was
133 if ih == nil { // We were waiting for the peer to tell us what they wanted.