8 "github.com/anacrolix/missinggo"
9 "github.com/anacrolix/torrent/metainfo"
12 type ExtensionBit uint
15 ExtensionBitDHT = 0 // http://www.bittorrent.org/beps/bep_0005.html
16 ExtensionBitExtended = 20 // http://www.bittorrent.org/beps/bep_0010.html
17 ExtensionBitFast = 2 // http://www.bittorrent.org/beps/bep_0006.html
20 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
32 PeerExtensionBits [8]byte
35 func (me PeerExtensionBits) String() string {
36 return hex.EncodeToString(me[:])
39 func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
40 for _, b := range bits {
46 func (pex PeerExtensionBits) SupportsExtended() bool {
47 return pex.GetBit(ExtensionBitExtended)
50 func (pex PeerExtensionBits) SupportsDHT() bool {
51 return pex.GetBit(ExtensionBitDHT)
54 func (pex PeerExtensionBits) SupportsFast() bool {
55 return pex.GetBit(ExtensionBitFast)
58 func (pex *PeerExtensionBits) SetBit(bit ExtensionBit) {
59 pex[7-bit/8] |= 1 << (bit % 8)
62 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
63 return pex[7-bit/8]&(1<<(bit%8)) != 0
66 type HandshakeResult struct {
72 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
73 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
74 // condition other than the peer simply abandoning the Handshake.
76 sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
78 res HandshakeResult, ok bool, err error,
80 // Bytes to be sent to the peer. Should never block the sender.
81 postCh := make(chan []byte, 4)
82 // A single error value sent when the writer completes.
83 writeDone := make(chan error, 1)
84 // Performs writes to the socket and ensures posts don't block.
85 go handshakeWriter(sock, postCh, writeDone)
88 close(postCh) // Done writing.
95 // Wait until writes complete before returning from handshake.
98 err = fmt.Errorf("error writing: %s", err)
102 post := func(bb []byte) {
106 panic("mustn't block while posting")
110 post([]byte(Protocol))
112 if ih != nil { // We already know what we want.
117 _, err = io.ReadFull(sock, b[:68])
122 if string(b[:20]) != Protocol {
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.