forked from pion/dtls
/
handshake_message_server_hello.go
97 lines (77 loc) · 2.33 KB
/
handshake_message_server_hello.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package dtls
import (
"encoding/binary"
)
/*
The server will send this message in response to a ClientHello
message when it was able to find an acceptable set of algorithms.
If it cannot find such a match, it will respond with a handshake
failure alert.
https://tools.ietf.org/html/rfc5246#section-7.4.1.3
*/
type handshakeMessageServerHello struct {
version protocolVersion
random handshakeRandom
cipherSuite cipherSuite
compressionMethod *compressionMethod
extensions []extension
}
const handshakeMessageServerHelloVariableWidthStart = 2 + handshakeRandomLength
func (h handshakeMessageServerHello) handshakeType() handshakeType {
return handshakeTypeServerHello
}
func (h *handshakeMessageServerHello) Marshal() ([]byte, error) {
if h.cipherSuite == nil {
return nil, errCipherSuiteUnset
} else if h.compressionMethod == nil {
return nil, errCompressionmethodUnset
}
out := make([]byte, handshakeMessageServerHelloVariableWidthStart)
out[0] = h.version.major
out[1] = h.version.minor
rand, err := h.random.Marshal()
if err != nil {
return nil, err
}
copy(out[2:], rand)
out = append(out, 0x00) // SessionID
out = append(out, []byte{0x00, 0x00}...)
binary.BigEndian.PutUint16(out[len(out)-2:], uint16(h.cipherSuite.ID()))
out = append(out, byte(h.compressionMethod.id))
extensions, err := encodeExtensions(h.extensions)
if err != nil {
return nil, err
}
return append(out, extensions...), nil
}
func (h *handshakeMessageServerHello) Unmarshal(data []byte) error {
h.version.major = data[0]
h.version.minor = data[1]
if err := h.random.Unmarshal(data[2 : 2+handshakeRandomLength]); err != nil {
return err
}
currOffset := handshakeMessageServerHelloVariableWidthStart
currOffset += int(data[currOffset]) + 1 // SessionID
if c := cipherSuiteForID(cipherSuiteID(binary.BigEndian.Uint16(data[currOffset:]))); c != nil {
h.cipherSuite = c
currOffset += 2
} else {
return errInvalidCipherSuite
}
if compressionMethod, ok := compressionMethods[compressionMethodID(data[currOffset])]; ok {
h.compressionMethod = compressionMethod
currOffset++
} else {
return errInvalidCompressionMethod
}
if len(data) <= currOffset {
h.extensions = []extension{}
return nil
}
extensions, err := decodeExtensions(data[currOffset:])
if err != nil {
return err
}
h.extensions = extensions
return nil
}