13 "github.com/anacrolix/torrent/metainfo"
16 type ExtensionBit uint
18 // https://www.bittorrent.org/beps/bep_0004.html
19 // https://wiki.theory.org/BitTorrentSpecification.html#Reserved_Bytes
21 ExtensionBitDht = 0 // http://www.bittorrent.org/beps/bep_0005.html
22 ExtensionBitFast = 2 // http://www.bittorrent.org/beps/bep_0006.html
23 ExtensionBitV2 = 7 // "Hybrid torrent legacy to v2 upgrade"
24 ExtensionBitAzureusExtensionNegotiation1 = 16
25 ExtensionBitAzureusExtensionNegotiation2 = 17
26 // LibTorrent Extension Protocol, http://www.bittorrent.org/beps/bep_0010.html
28 // https://wiki.theory.org/BitTorrent_Location-aware_Protocol_1
29 ExtensionBitLocationAwareProtocol = 43
30 ExtensionBitAzureusMessagingProtocol = 63 // https://www.bittorrent.org/beps/bep_0004.html
34 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
46 PeerExtensionBits [8]byte
49 var bitTags = []struct {
53 // Ordered by their bit position left to right.
54 {ExtensionBitAzureusMessagingProtocol, "amp"},
55 {ExtensionBitLocationAwareProtocol, "loc"},
56 {ExtensionBitLtep, "ltep"},
57 {ExtensionBitAzureusExtensionNegotiation2, "azen2"},
58 {ExtensionBitAzureusExtensionNegotiation1, "azen1"},
59 {ExtensionBitV2, "v2"},
60 {ExtensionBitFast, "fast"},
61 {ExtensionBitDht, "dht"},
64 func (pex PeerExtensionBits) String() string {
65 pexHex := hex.EncodeToString(pex[:])
66 tags := make([]string, 0, len(bitTags)+1)
67 for _, bitTag := range bitTags {
68 if pex.GetBit(bitTag.bit) {
69 tags = append(tags, bitTag.tag)
70 pex.SetBit(bitTag.bit, false)
73 unknownCount := bits.OnesCount64(*(*uint64)((unsafe.Pointer(unsafe.SliceData(pex[:])))))
74 if unknownCount != 0 {
75 tags = append(tags, fmt.Sprintf("%v unknown", unknownCount))
77 return fmt.Sprintf("%v (%s)", pexHex, strings.Join(tags, ", "))
81 func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
82 for _, b := range bits {
88 func (pex PeerExtensionBits) SupportsExtended() bool {
89 return pex.GetBit(ExtensionBitLtep)
92 func (pex PeerExtensionBits) SupportsDHT() bool {
93 return pex.GetBit(ExtensionBitDht)
96 func (pex PeerExtensionBits) SupportsFast() bool {
97 return pex.GetBit(ExtensionBitFast)
100 func (pex *PeerExtensionBits) SetBit(bit ExtensionBit, on bool) {
102 pex[7-bit/8] |= 1 << (bit % 8)
104 pex[7-bit/8] &^= 1 << (bit % 8)
108 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
109 return pex[7-bit/8]&(1<<(bit%8)) != 0
112 type HandshakeResult struct {
118 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
119 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
120 // condition other than the peer simply abandoning the Handshake.
122 sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
124 res HandshakeResult, err error,
126 // Bytes to be sent to the peer. Should never block the sender.
127 postCh := make(chan []byte, 4)
128 // A single error value sent when the writer completes.
129 writeDone := make(chan error, 1)
130 // Performs writes to the socket and ensures posts don't block.
131 go handshakeWriter(sock, postCh, writeDone)
134 close(postCh) // Done writing.
138 // Wait until writes complete before returning from handshake.
141 err = fmt.Errorf("error writing: %w", err)
145 post := func(bb []byte) {
149 panic("mustn't block while posting")
153 post([]byte(Protocol))
155 if ih != nil { // We already know what we want.
160 _, err = io.ReadFull(sock, b[:68])
162 return res, fmt.Errorf("while reading: %w", err)
164 if string(b[:20]) != Protocol {
165 return res, errors.New("unexpected protocol string")
168 copyExact := func(dst, src []byte) {
169 if dstLen, srcLen := uint64(len(dst)), uint64(len(src)); dstLen != srcLen {
170 panic("dst len " + strconv.FormatUint(dstLen, 10) + " != src len " + strconv.FormatUint(srcLen, 10))
174 copyExact(res.PeerExtensionBits[:], b[20:28])
175 copyExact(res.Hash[:], b[28:48])
176 copyExact(res.PeerID[:], b[48:68])
177 // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
179 // TODO: Maybe we can just drop peers here if we're not interested. This
180 // could prevent them trying to reconnect, falsely believing there was
182 if ih == nil { // We were waiting for the peer to tell us what they wanted.