summaryrefslogtreecommitdiffhomepage
path: root/dhcpv6/dhcpv6relay.go
blob: 70fbc7f405612bd077f4e81c8f885f1afa142ef7 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package dhcpv6

import (
	"fmt"
	"net"
)

const RelayHeaderSize = 34

type DHCPv6Relay struct {
	messageType MessageType
	hopCount    uint8
	linkAddr    net.IP
	peerAddr    net.IP
	options     []Option
}

func (r *DHCPv6Relay) Type() MessageType {
	return r.messageType
}

func (r *DHCPv6Relay) MessageTypeToString() string {
	return MessageTypeToString(r.messageType)
}

func (r *DHCPv6Relay) String() string {
	ret := fmt.Sprintf(
		"DHCPv6Relay(messageType=%v hopcount=%v, linkaddr=%v, peeraddr=%v, %d options)",
		r.MessageTypeToString(), r.hopCount, r.linkAddr, r.peerAddr, len(r.options),
	)
	return ret
}

func (r *DHCPv6Relay) Summary() string {
	ret := fmt.Sprintf(
		"DHCPv6Relay\n"+
			"  messageType=%v\n"+
			"  hopcount=%v\n"+
			"  linkaddr=%v\n"+
			"  peeraddr=%v\n"+
			"  options=%v\n",
		r.MessageTypeToString(),
		r.hopCount,
		r.linkAddr,
		r.peerAddr,
		r.options,
	)
	return ret
}

func (r *DHCPv6Relay) ToBytes() []byte {
	ret := make([]byte, RelayHeaderSize)
	ret[0] = byte(r.messageType)
	ret[1] = byte(r.hopCount)
	copy(ret[2:18], r.peerAddr)
	copy(ret[18:34], r.linkAddr)
	for _, opt := range r.options {
		ret = append(ret, opt.ToBytes()...)
	}

	return ret
}

func (r *DHCPv6Relay) Length() int {
	mLen := RelayHeaderSize
	for _, opt := range r.options {
		mLen += opt.Length() + 4 // +4 for opt code and opt len
	}
	return mLen
}

func (r *DHCPv6Relay) Options() []Option {
	return r.options
}
func (r *DHCPv6Relay) GetOption(code OptionCode) []Option {
	return getOptions(r.options, code, false)
}

func (r *DHCPv6Relay) GetOneOption(code OptionCode) Option {
	return getOption(r.options, code)
}

func (r *DHCPv6Relay) IsRelay() bool {
	return true
}

// Recurse into a relay message and extract and return the inner DHCPv6Message.
// Return nil if none found (e.g. not a relay message).
func (d *DHCPv6Relay) GetInnerMessage() (DHCPv6, error) {
	var p DHCPv6
	p = d
	for {
		if !p.IsRelay() {
			return p, nil
		}
		opt := p.GetOneOption(OPTION_RELAY_MSG)
		if opt == nil {
			return nil, fmt.Errorf("No OptRelayMsg found")
		}
		relayOpt := opt.(*OptRelayMsg)
		if relayOpt.RelayMessage() == nil {
			return nil, fmt.Errorf("Relay message cannot be nil")
		}
		p = relayOpt.RelayMessage()
	}
}