-
Notifications
You must be signed in to change notification settings - Fork 0
/
handshake_message.go
79 lines (69 loc) · 1.62 KB
/
handshake_message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"errors"
)
type HandshakeMessage struct {
PStrLen int
PStr string
InfoHash []byte
PeerId []byte
}
func NewHandshakeMessage(m *Metainfo) *HandshakeMessage {
return &HandshakeMessage{
PStrLen: 19,
PStr: "BitTorrent protocol",
InfoHash: m.InfoDictionary.Hash,
PeerId: peerId,
}
}
func ParseHandshakeMessageFromBytes(b []byte) (hm *HandshakeMessage, err error) {
if len(b) == 0 {
err = errors.New("Can't parse empty buffer")
}
pstrlen := int(b[0])
if pstrlen != 19 {
err = errors.New("Invalid handshake message")
return
}
pstrStart := 1
pstrEnd := pstrStart + pstrlen
if len(b) < pstrEnd {
err = errors.New("Unexpected EOF")
return
}
pstr := string(b[pstrStart:pstrEnd])
infoHashStart := pstrEnd + 8
infoHashEnd := infoHashStart + 20
if len(b) < infoHashEnd {
err = errors.New("unexpected EOF")
return
}
infoHash := b[infoHashStart:infoHashEnd]
peerIdStart := infoHashEnd
peerIdEnd := infoHashEnd + 20
if len(b) < peerIdEnd {
err = errors.New("unexpected EOF")
return
}
peerId := b[peerIdStart:peerIdEnd]
hm = &HandshakeMessage{
PStrLen: pstrlen,
PStr: pstr,
InfoHash: infoHash,
PeerId: peerId,
}
return
}
func (hm *HandshakeMessage) DeliverableBytes() (delivery []byte) {
pstrlen := []byte{byte(hm.PStrLen)}
pstr := []byte(hm.PStr)
reserved := []byte{0, 0, 0, 0, 0, 0, 0, 0}
infoHash := hm.InfoHash
peerId := []byte(hm.PeerId)
delivery = append(delivery, pstrlen...)
delivery = append(delivery, pstr...)
delivery = append(delivery, reserved...)
delivery = append(delivery, infoHash...)
delivery = append(delivery, peerId...)
return
}