-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandshake.go
49 lines (42 loc) · 973 Bytes
/
handshake.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
package tcprouter
import (
"encoding/binary"
"io"
)
const (
// MagicNr is the bytes sent during handshake to identity a tcprouter client connection
// TODO: chose a valid magic number
MagicNr = 0x1111
)
// Handshake is the struct used to serialize the first frame sent to the server
type Handshake struct {
MagicNr uint16
Secret []byte
}
func (h Handshake) Write(w io.Writer) error {
b := make([]byte, 4+len(h.Secret))
binary.BigEndian.PutUint16(b[:2], h.MagicNr)
binary.BigEndian.PutUint16(b[2:4], uint16(len(h.Secret)))
copy(b[4:], h.Secret)
_, err := w.Write(b)
return err
}
func (h *Handshake) Read(r io.Reader) error {
b := make([]byte, 4)
n, err := r.Read(b)
if err != nil {
return err
}
b = b[:n]
h.MagicNr = binary.BigEndian.Uint16(b[:2])
size := binary.BigEndian.Uint16(b[2:4])
b = make([]byte, size)
n, err = r.Read(b)
if err != nil {
return err
}
b = b[:n]
h.Secret = make([]byte, size)
copy(h.Secret, b[:n])
return nil
}