10 "github.com/anacrolix/missinggo"
12 "github.com/anacrolix/torrent/metainfo"
15 type ExtensionBit uint
18 ExtensionBitDHT = 0 // http://www.bittorrent.org/beps/bep_0005.html
19 ExtensionBitExtended = 20 // http://www.bittorrent.org/beps/bep_0010.html
20 ExtensionBitFast = 2 // http://www.bittorrent.org/beps/bep_0006.html
23 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
35 PeerExtensionBits [8]byte
38 func (me PeerExtensionBits) String() string {
39 return hex.EncodeToString(me[:])
42 func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
43 for _, b := range bits {
49 func (pex PeerExtensionBits) SupportsExtended() bool {
50 return pex.GetBit(ExtensionBitExtended)
53 func (pex PeerExtensionBits) SupportsDHT() bool {
54 return pex.GetBit(ExtensionBitDHT)
57 func (pex PeerExtensionBits) SupportsFast() bool {
58 return pex.GetBit(ExtensionBitFast)
61 func (pex *PeerExtensionBits) SetBit(bit ExtensionBit, on bool) {
63 pex[7-bit/8] |= 1 << (bit % 8)
65 pex[7-bit/8] &^= 1 << (bit % 8)
69 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
70 return pex[7-bit/8]&(1<<(bit%8)) != 0
73 type HandshakeResult struct {
79 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
80 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
81 // condition other than the peer simply abandoning the Handshake.
83 sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
85 res HandshakeResult, err error,
87 // Bytes to be sent to the peer. Should never block the sender.
88 postCh := make(chan []byte, 4)
89 // A single error value sent when the writer completes.
90 writeDone := make(chan error, 1)
91 // Performs writes to the socket and ensures posts don't block.
92 go handshakeWriter(sock, postCh, writeDone)
95 close(postCh) // Done writing.
99 // Wait until writes complete before returning from handshake.
102 err = fmt.Errorf("error writing: %s", err)
106 post := func(bb []byte) {
110 panic("mustn't block while posting")
114 post([]byte(Protocol))
116 if ih != nil { // We already know what we want.
121 _, err = io.ReadFull(sock, b[:68])
123 err = xerrors.Errorf("while reading: %w", err)
126 if string(b[:20]) != Protocol {
127 err = xerrors.Errorf("unexpected protocol string")
130 missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
131 missinggo.CopyExact(&res.Hash, b[28:48])
132 missinggo.CopyExact(&res.PeerID, b[48:68])
133 // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
135 // TODO: Maybe we can just drop peers here if we're not interested. This
136 // could prevent them trying to reconnect, falsely believing there was
138 if ih == nil { // We were waiting for the peer to tell us what they wanted.