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
73 // peer initiated the connection. Returns ok if the Handshake was successful,
74 // and err if there was an unexpected condition other than the peer simply
75 // abandoning the Handshake.
76 func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) {
77 // Bytes to be sent to the peer. Should never block the sender.
78 postCh := make(chan []byte, 4)
79 // A single error value sent when the writer completes.
80 writeDone := make(chan error, 1)
81 // Performs writes to the socket and ensures posts don't block.
82 go handshakeWriter(sock, postCh, writeDone)
85 close(postCh) // Done writing.
92 // Wait until writes complete before returning from handshake.
95 err = fmt.Errorf("error writing: %s", err)
99 post := func(bb []byte) {
103 panic("mustn't block while posting")
107 post([]byte(Protocol))
109 if ih != nil { // We already know what we want.
114 _, err = io.ReadFull(sock, b[:68])
119 if string(b[:20]) != Protocol {
122 missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
123 missinggo.CopyExact(&res.Hash, b[28:48])
124 missinggo.CopyExact(&res.PeerID, b[48:68])
125 // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
127 // TODO: Maybe we can just drop peers here if we're not interested. This
128 // could prevent them trying to reconnect, falsely believing there was
130 if ih == nil { // We were waiting for the peer to tell us what they wanted.