summaryrefslogtreecommitdiffhomepage
path: root/dhcpv4/option_userclass.go
blob: f79a0c66b87cd14f5bfddc6816037ea86c033c5b (plain)
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
package dhcpv4

import (
	"errors"
	"fmt"
	"strings"
)

// This option implements the User Class option
// https://tools.ietf.org/html/rfc3004

// OptUserClass represents an option encapsulating User Classes.
type OptUserClass struct {
	UserClasses [][]byte
}

// Code returns the option code
func (op *OptUserClass) Code() OptionCode {
	return OptionUserClassInformation
}

// ToBytes serializes the option and returns it as a sequence of bytes
func (op *OptUserClass) ToBytes() []byte {
	buf := []byte{byte(op.Code()), byte(op.Length())}
	for _, uc := range op.UserClasses {
		buf = append(buf, byte(len(uc)))
		buf = append(buf, uc...)
	}
	return buf
}

// Length returns the option length
func (op *OptUserClass) Length() int {
	ret := 0
	for _, uc := range op.UserClasses {
		ret += 1 + len(uc)
	}
	return ret
}

func (op *OptUserClass) String() string {
	ucStrings := make([]string, len(op.UserClasses))
	for _, uc := range op.UserClasses {
		ucStrings = append(ucStrings, string(uc))
	}
	return fmt.Sprintf("OptUserClass{userclass=[%s]}", strings.Join(ucStrings, ", "))
}

// ParseOptUserClass returns a new OptUserClass from a byte stream or
// error if any
func ParseOptUserClass(data []byte) (*OptUserClass, error) {
	opt := OptUserClass{}

	if len(data) < 4 {
		return nil, ErrShortByteStream
	}
	code := OptionCode(data[0])
	if code != OptionUserClassInformation {
		return nil, fmt.Errorf("expected code %v, got %v", OptionUserClassInformation, code)
	}

	totalLength := int(data[1])
	data = data[2:]
	if len(data) < totalLength {
		return nil, fmt.Errorf("ParseOptUserClass: short data: length is %d but got %d bytes",
			totalLength, len(data))
	}

	for i := 0; i < totalLength; {
		ucLen := int(data[i])
		if ucLen == 0 {
			return nil, errors.New("User Class value has invalid lenght of 0")
		}
		base := i + 1
		if len(data) < base+ucLen {
			return nil, fmt.Errorf("ParseOptUserClass: short data: %d bytes; want: %d", len(data), base+ucLen)
		}
		opt.UserClasses = append(opt.UserClasses, data[i+1:base+ucLen])
		i += base + ucLen
	}
	if len(opt.UserClasses) < 1 {
		return nil, errors.New("ParseOptUserClass: at least one user class is required")
	}
	return &opt, nil
}