10 "github.com/anacrolix/torrent/metainfo"
13 type ExtensionBit uint
16 ExtensionBitDHT = 0 // http://www.bittorrent.org/beps/bep_0005.html
17 ExtensionBitExtended = 20 // http://www.bittorrent.org/beps/bep_0010.html
18 ExtensionBitFast = 2 // http://www.bittorrent.org/beps/bep_0006.html
21 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
33 PeerExtensionBits [8]byte
36 func (pex PeerExtensionBits) String() string {
37 return hex.EncodeToString(pex[:])
40 func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
41 for _, b := range bits {
47 func (pex PeerExtensionBits) SupportsExtended() bool {
48 return pex.GetBit(ExtensionBitExtended)
51 func (pex PeerExtensionBits) SupportsDHT() bool {
52 return pex.GetBit(ExtensionBitDHT)
55 func (pex PeerExtensionBits) SupportsFast() bool {
56 return pex.GetBit(ExtensionBitFast)
59 func (pex *PeerExtensionBits) SetBit(bit ExtensionBit, on bool) {
61 pex[7-bit/8] |= 1 << (bit % 8)
63 pex[7-bit/8] &^= 1 << (bit % 8)
67 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
68 return pex[7-bit/8]&(1<<(bit%8)) != 0
71 type HandshakeResult struct {
77 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
78 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
79 // condition other than the peer simply abandoning the Handshake.
81 sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
83 res HandshakeResult, err error,
85 // Bytes to be sent to the peer. Should never block the sender.
86 postCh := make(chan []byte, 4)
87 // A single error value sent when the writer completes.
88 writeDone := make(chan error, 1)
89 // Performs writes to the socket and ensures posts don't block.
90 go handshakeWriter(sock, postCh, writeDone)
93 close(postCh) // Done writing.
97 // Wait until writes complete before returning from handshake.
100 err = fmt.Errorf("error writing: %w", err)
104 post := func(bb []byte) {
108 panic("mustn't block while posting")
112 post([]byte(Protocol))
114 if ih != nil { // We already know what we want.
119 _, err = io.ReadFull(sock, b[:68])
121 return res, fmt.Errorf("while reading: %w", err)
123 if string(b[:20]) != Protocol {
124 return res, errors.New("unexpected protocol string")
127 copyExact := func(dst []byte, src []byte) {
128 if dstLen, srcLen := uint64(len(dst)), uint64(len(src)); dstLen != srcLen {
129 panic("dst len " + strconv.FormatUint(dstLen, 10) + " != src len " + strconv.FormatUint(srcLen, 10))
133 copyExact(res.PeerExtensionBits[:], b[20:28])
134 copyExact(res.Hash[:], b[28:48])
135 copyExact(res.PeerID[:], b[48:68])
136 // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
138 // TODO: Maybe we can just drop peers here if we're not interested. This
139 // could prevent them trying to reconnect, falsely believing there was
141 if ih == nil { // We were waiting for the peer to tell us what they wanted.