summaryrefslogtreecommitdiffhomepage
path: root/dhcpv6/nclient6/client_test.go
blob: cba4ef8eb55c9aff5e41d15fdb6ad7475a96942a (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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Copyright 2018 the u-root Authors and Andrea Barberio. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build go1.12

package nclient6

import (
	"bytes"
	"context"
	"fmt"
	"net"
	"sync"
	"testing"
	"time"

	"github.com/hugelgupf/socketpair"
	"github.com/insomniacslk/dhcp/dhcpv6"
	"github.com/insomniacslk/dhcp/dhcpv6/server6"
)

type handler struct {
	mu       sync.Mutex
	received []*dhcpv6.Message

	// Each received packet can have more than one response (in theory,
	// from different servers sending different Advertise, for example).
	responses [][]*dhcpv6.Message
}

func (h *handler) handle(conn net.PacketConn, peer net.Addr, msg dhcpv6.DHCPv6) {
	h.mu.Lock()
	defer h.mu.Unlock()

	m := msg.(*dhcpv6.Message)

	h.received = append(h.received, m)

	if len(h.responses) > 0 {
		resps := h.responses[0]
		// What should we send in response?
		for _, resp := range resps {
			conn.WriteTo(resp.ToBytes(), peer)
		}
		h.responses = h.responses[1:]
	}
}

func serveAndClient(ctx context.Context, responses [][]*dhcpv6.Message, opt ...ClientOpt) (*Client, net.PacketConn) {
	// Fake connection between client and server. No raw sockets, no port
	// weirdness.
	clientRawConn, serverRawConn, err := socketpair.PacketSocketPair()
	if err != nil {
		panic(err)
	}

	o := []ClientOpt{WithConn(clientRawConn), WithRetry(1), WithTimeout(2 * time.Second)}
	o = append(o, opt...)
	mc, err := New(net.HardwareAddr{0xa, 0xb, 0xc, 0xd, 0xe, 0xf}, o...)
	if err != nil {
		panic(err)
	}

	h := &handler{
		responses: responses,
	}
	s, err := server6.NewServer(nil, h.handle, server6.WithConn(serverRawConn))
	if err != nil {
		panic(err)
	}
	go s.Serve()

	return mc, serverRawConn
}

func ComparePacket(got *dhcpv6.Message, want *dhcpv6.Message) error {
	if got == nil && got == want {
		return nil
	}
	if (want == nil || got == nil) && (got != want) {
		return fmt.Errorf("packet got %v, want %v", got, want)
	}
	if bytes.Compare(got.ToBytes(), want.ToBytes()) != 0 {
		return fmt.Errorf("packet got %v, want %v", got, want)
	}
	return nil
}

func pktsExpected(got []*dhcpv6.Message, want []*dhcpv6.Message) error {
	if len(got) != len(want) {
		return fmt.Errorf("got %d packets, want %d packets", len(got), len(want))
	}

	for i := range got {
		if err := ComparePacket(got[i], want[i]); err != nil {
			return err
		}
	}
	return nil
}

func newPacket(xid dhcpv6.TransactionID) *dhcpv6.Message {
	p, err := dhcpv6.NewMessage()
	if err != nil {
		panic(fmt.Sprintf("newpacket: %v", err))
	}
	p.TransactionID = xid
	return p
}

func TestSendAndReadUntil(t *testing.T) {
	for _, tt := range []struct {
		desc   string
		send   *dhcpv6.Message
		server []*dhcpv6.Message

		// If want is nil, we assume server contains what is wanted.
		want    *dhcpv6.Message
		wantErr error
	}{
		{
			desc: "two response packets",
			send: newPacket([3]byte{0x33, 0x33, 0x33}),
			server: []*dhcpv6.Message{
				newPacket([3]byte{0x33, 0x33, 0x33}),
				newPacket([3]byte{0x33, 0x33, 0x33}),
			},
			want: newPacket([3]byte{0x33, 0x33, 0x33}),
		},
		{
			desc: "one response packet",
			send: newPacket([3]byte{0x33, 0x33, 0x33}),
			server: []*dhcpv6.Message{
				newPacket([3]byte{0x33, 0x33, 0x33}),
			},
			want: newPacket([3]byte{0x33, 0x33, 0x33}),
		},
		{
			desc: "one response packet, one invalid XID",
			send: newPacket([3]byte{0x33, 0x33, 0x33}),
			server: []*dhcpv6.Message{
				newPacket([3]byte{0x77, 0x33, 0x33}),
				newPacket([3]byte{0x33, 0x33, 0x33}),
			},
			want: newPacket([3]byte{0x33, 0x33, 0x33}),
		},
		{
			desc: "discard wrong XID",
			send: newPacket([3]byte{0x33, 0x33, 0x33}),
			server: []*dhcpv6.Message{
				newPacket([3]byte{0, 0, 0}),
			},
			want:    nil,
			wantErr: ErrNoResponse,
		},
		{
			desc:    "no response, timeout",
			send:    newPacket([3]byte{0x33, 0x33, 0x33}),
			wantErr: ErrNoResponse,
		},
	} {
		t.Run(tt.desc, func(t *testing.T) {
			// Both server and client only get 2 seconds.
			ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
			defer cancel()

			mc, _ := serveAndClient(ctx, [][]*dhcpv6.Message{tt.server},
				// Use an unbuffered channel to make sure we
				// have no deadlocks.
				withBufferCap(0))
			defer mc.Close()

			rcvd, err := mc.SendAndRead(context.Background(), AllDHCPServers, tt.send, nil)
			if err != tt.wantErr {
				t.Error(err)
			}

			if err := ComparePacket(rcvd, tt.want); err != nil {
				t.Errorf("got unexpected packets: %v", err)
			}
		})
	}
}

func TestSimpleSendAndReadDiscardGarbage(t *testing.T) {
	pkt := newPacket([3]byte{0x33, 0x33, 0x33})

	responses := []*dhcpv6.Message{
		newPacket([3]byte{0x33, 0x33, 0x33}),
	}

	// Both the server and client only get 2 seconds.
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	mc, udpConn := serveAndClient(ctx, [][]*dhcpv6.Message{responses})
	defer mc.Close()

	// Too short for valid DHCPv4 packet.
	udpConn.WriteTo([]byte{0x01}, nil)

	rcvd, err := mc.SendAndRead(context.Background(), AllDHCPServers, pkt, nil)
	if err != nil {
		t.Error(err)
	}

	if err := ComparePacket(rcvd, responses[0]); err != nil {
		t.Errorf("got unexpected packets: %v", err)
	}
}

func TestMultipleSendAndReadOne(t *testing.T) {
	for _, tt := range []struct {
		desc    string
		send    []*dhcpv6.Message
		server  [][]*dhcpv6.Message
		wantErr []error
	}{
		{
			desc: "two requests, two responses",
			send: []*dhcpv6.Message{
				newPacket([3]byte{0x33, 0x33, 0x33}),
				newPacket([3]byte{0x44, 0x44, 0x44}),
			},
			server: [][]*dhcpv6.Message{
				[]*dhcpv6.Message{ // Response for first packet.
					newPacket([3]byte{0x33, 0x33, 0x33}),
				},
				[]*dhcpv6.Message{ // Response for second packet.
					newPacket([3]byte{0x44, 0x44, 0x44}),
				},
			},
			wantErr: []error{
				nil,
				nil,
			},
		},
	} {
		// Both server and client only get 2 seconds.
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()

		mc, _ := serveAndClient(ctx, tt.server)
		defer mc.conn.Close()

		for i, send := range tt.send {
			rcvd, err := mc.SendAndRead(context.Background(), AllDHCPServers, send, nil)

			if wantErr := tt.wantErr[i]; err != wantErr {
				t.Errorf("SendAndReadOne(%v): got %v, want %v", send, err, wantErr)
			}
			if err := pktsExpected([]*dhcpv6.Message{rcvd}, tt.server[i]); err != nil {
				t.Errorf("got unexpected packets: %v", err)
			}
		}
	}
}