File: alpn.go

package info (click to toggle)
golang-github-pion-dtls-v3 3.0.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,124 kB
  • sloc: makefile: 4
file content (83 lines) | stat: -rw-r--r-- 2,117 bytes parent folder | download
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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package extension

import (
	"golang.org/x/crypto/cryptobyte"
)

// ALPN is a TLS extension for application-layer protocol negotiation within
// the TLS handshake.
//
// https://tools.ietf.org/html/rfc7301
type ALPN struct {
	ProtocolNameList []string
}

// TypeValue returns the extension TypeValue.
func (a ALPN) TypeValue() TypeValue {
	return ALPNTypeValue
}

// Marshal encodes the extension.
func (a *ALPN) Marshal() ([]byte, error) {
	var builder cryptobyte.Builder
	builder.AddUint16(uint16(a.TypeValue()))
	builder.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
			for _, proto := range a.ProtocolNameList {
				p := proto // Satisfy range scope lint
				b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
					b.AddBytes([]byte(p))
				})
			}
		})
	})

	return builder.Bytes()
}

// Unmarshal populates the extension from encoded data.
func (a *ALPN) Unmarshal(data []byte) error {
	val := cryptobyte.String(data)

	var extension uint16
	val.ReadUint16(&extension)
	if TypeValue(extension) != a.TypeValue() {
		return errInvalidExtensionType
	}

	var extData cryptobyte.String
	val.ReadUint16LengthPrefixed(&extData)

	var protoList cryptobyte.String
	if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
		return ErrALPNInvalidFormat
	}
	for !protoList.Empty() {
		var proto cryptobyte.String
		if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {
			return ErrALPNInvalidFormat
		}
		a.ProtocolNameList = append(a.ProtocolNameList, string(proto))
	}

	return nil
}

// ALPNProtocolSelection negotiates a shared protocol according to #3.2 of rfc7301.
func ALPNProtocolSelection(supportedProtocols, peerSupportedProtocols []string) (string, error) {
	if len(supportedProtocols) == 0 || len(peerSupportedProtocols) == 0 {
		return "", nil
	}
	for _, s := range supportedProtocols {
		for _, c := range peerSupportedProtocols {
			if s == c {
				return s, nil
			}
		}
	}

	return "", errALPNNoAppProto
}