forked from microsoft/go-winio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hvsock_test.go
660 lines (573 loc) · 15.3 KB
/
hvsock_test.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//go:build windows
package winio
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"strings"
"testing"
"time"
"golang.org/x/sys/windows"
"github.com/Microsoft/go-winio/internal/socket"
"github.com/Microsoft/go-winio/pkg/guid"
)
const testStr = "test"
func randHvsockAddr() *HvsockAddr {
p := rand.Uint32() //nolint:gosec // used for testing
return &HvsockAddr{
VMID: HvsockGUIDLoopback(),
ServiceID: VsockServiceID(p),
}
}
func serverListen(u testUtil) (l *HvsockListener, a *HvsockAddr) {
var err error
for i := 0; i < 3; i++ {
a = randHvsockAddr()
l, err = ListenHvsock(a)
if errors.Is(err, windows.WSAEADDRINUSE) {
u.T.Logf("address collision %v", a)
continue
}
break
}
u.Must(err, "could not listen")
u.T.Cleanup(func() {
if l != nil {
u.Must(l.Close(), "Hyper-V socket listener close")
}
})
return l, a
}
func clientServer(u testUtil) (cl, sv *HvsockConn, _ *HvsockAddr) {
l, addr := serverListen(u)
ch := u.Go(func() error {
conn, err := l.Accept()
if err != nil {
return fmt.Errorf("listener accept: %w", err)
}
sv = conn.(*HvsockConn)
if err := l.Close(); err != nil {
return err
}
l = nil
return nil
})
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
cl, err := Dial(ctx, addr)
u.Must(err, "could not dial")
u.T.Cleanup(func() {
if cl != nil {
u.Must(cl.Close(), "client close")
}
})
u.WaitErr(ch, time.Second)
u.T.Cleanup(func() {
if sv != nil {
u.Must(sv.Close(), "server close")
}
})
return cl, sv, addr
}
func TestHvSockConstants(t *testing.T) {
tests := []struct {
name string
want string
give guid.GUID
}{
{"wildcard", "00000000-0000-0000-0000-000000000000", HvsockGUIDWildcard()},
{"broadcast", "ffffffff-ffff-ffff-ffff-ffffffffffff", HvsockGUIDBroadcast()},
{"loopback", "e0e16197-dd56-4a10-9195-5ee7a155a838", HvsockGUIDLoopback()},
{"children", "90db8b89-0d35-4f79-8ce9-49ea0ac8b7cd", HvsockGUIDChildren()},
{"parent", "a42e7cda-d03f-480c-9cc2-a4de20abb878", HvsockGUIDParent()},
{"silohost", "36bd0c5c-7276-4223-88ba-7d03b654c568", HvsockGUIDSiloHost()},
{"vsock template", "00000000-facb-11e6-bd58-64006a7986d3", hvsockVsockServiceTemplate()},
}
for _, tt := range tests {
if tt.give.String() != tt.want {
t.Errorf("%s give: %v; want: %s", tt.name, tt.give, tt.want)
}
}
}
func TestHvSockListenerAddresses(t *testing.T) {
u := newUtil(t)
l, addr := serverListen(u)
la := (l.Addr()).(*HvsockAddr)
u.Assert(*la == *addr, fmt.Sprintf("give: %v; want: %v", la, addr))
ra := rawHvsockAddr{}
sa := HvsockAddr{}
u.Must(socket.GetSockName(windows.Handle(l.sock.handle), &ra))
sa.fromRaw(&ra)
u.Assert(sa == *addr, fmt.Sprintf("listener local addr give: %v; want: %v", sa, addr))
}
func TestHvSockAddresses(t *testing.T) {
u := newUtil(t)
cl, sv, addr := clientServer(u)
sra := (sv.RemoteAddr()).(*HvsockAddr)
sla := (sv.LocalAddr()).(*HvsockAddr)
cra := (cl.RemoteAddr()).(*HvsockAddr)
cla := (cl.LocalAddr()).(*HvsockAddr)
t.Run("Info", func(t *testing.T) {
tests := []struct {
name string
give *HvsockAddr
want HvsockAddr
}{
{"client local", cla, HvsockAddr{HvsockGUIDChildren(), sra.ServiceID}},
{"client remote", cra, *addr},
{"server local", sla, HvsockAddr{HvsockGUIDChildren(), addr.ServiceID}},
{"server remote", sra, HvsockAddr{HvsockGUIDLoopback(), cla.ServiceID}},
}
for _, tt := range tests {
if *tt.give != tt.want {
t.Errorf("%s address give: %v; want: %v", tt.name, tt.give, tt.want)
}
}
})
t.Run("OSinfo", func(t *testing.T) {
u := newUtil(t)
ra := rawHvsockAddr{}
sa := HvsockAddr{}
localTests := []struct {
name string
giveSock *win32File
wantAddr HvsockAddr
}{
{"client", cl.sock, HvsockAddr{HvsockGUIDChildren(), cla.ServiceID}},
// The server sockets local address seems arbitrary, so skip this test
// see comment in `(*HvsockListener) Accept()` for more info
// {"server", sv.sock, _sla},
}
for _, tt := range localTests {
u.Must(socket.GetSockName(windows.Handle(tt.giveSock.handle), &ra))
sa.fromRaw(&ra)
if sa != tt.wantAddr {
t.Errorf("%s local addr give: %v; want: %v", tt.name, sa, tt.wantAddr)
}
}
remoteTests := []struct {
name string
giveConn *HvsockConn
}{
{"client", cl},
{"server", sv},
}
for _, tt := range remoteTests {
u.Must(socket.GetPeerName(windows.Handle(tt.giveConn.sock.handle), &ra))
sa.fromRaw(&ra)
if sa != tt.giveConn.remote {
t.Errorf("%s remote addr give: %v; want: %v", tt.name, sa, tt.giveConn.remote)
}
}
})
}
func TestHvSockReadWrite(t *testing.T) {
u := newUtil(t)
l, addr := serverListen(u)
tests := []struct {
req, rsp string
}{
{"hello ", "world!"},
{"ping", "pong"},
}
// a sync.WaitGroup doesnt offer a channel to use in a select with a timeout
// could use an errgroup.Group, but for now dual channels work fine
svCh := u.Go(func() error {
c, err := l.Accept()
if err != nil {
return fmt.Errorf("listener accept: %w", err)
}
defer c.Close()
b := make([]byte, 64)
for _, tt := range tests {
n, err := c.Read(b)
if err != nil {
return fmt.Errorf("server rx: %w", err)
}
r := string(b[:n])
if r != tt.req {
return fmt.Errorf("server rx error: got %q; wanted %q", r, tt.req)
}
if _, err = c.Write([]byte(tt.rsp)); err != nil {
return fmt.Errorf("server tx error, could not send %q: %w", tt.rsp, err)
}
}
n, err := c.Read(b)
if n != 0 {
return errors.New("server did not get EOF")
}
if !errors.Is(err, io.EOF) {
return fmt.Errorf("server did not get EOF: %w", err)
}
return nil
})
clCh := u.Go(func() error {
cl, err := Dial(context.Background(), addr)
if err != nil {
return fmt.Errorf("client dial: %w", err)
}
defer cl.Close()
b := make([]byte, 64)
for _, tt := range tests {
_, err := cl.Write([]byte(tt.req))
if err != nil {
return fmt.Errorf("client tx error, could not send %q: %w", tt.req, err)
}
n, err := cl.Read(b)
if err != nil {
return fmt.Errorf("client tx: %w", err)
}
r := string(b[:n])
if r != tt.rsp {
return fmt.Errorf("client rx error: got %q; wanted %q", b[:n], tt.rsp)
}
}
return cl.CloseWrite()
})
u.WaitErr(svCh, 15*time.Second, "server")
u.WaitErr(clCh, 15*time.Second, "client")
}
func TestHvSockReadTooSmall(t *testing.T) {
u := newUtil(t)
s := "this is a really long string that hopefully takes up more than 16 bytes ..."
l, addr := serverListen(u)
svCh := u.Go(func() error {
c, err := l.Accept()
if err != nil {
return fmt.Errorf("listener accept: %w", err)
}
defer c.Close()
b := make([]byte, 16)
ss := ""
for {
n, err := c.Read(b)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("server rx: %w", err)
}
ss += string(b[:n])
}
if ss != s {
return fmt.Errorf("got %q, wanted: %q", ss, s)
}
return nil
})
clCh := u.Go(func() error {
cl, err := Dial(context.Background(), addr)
if err != nil {
return fmt.Errorf("client dial: %w", err)
}
defer cl.Close()
if _, err = cl.Write([]byte(s)); err != nil {
return fmt.Errorf("client tx error, could not send: %w", err)
}
return nil
})
u.WaitErr(svCh, 15*time.Second, "server")
u.WaitErr(clCh, 15*time.Second, "client")
}
func TestHvSockCloseReadWriteListener(t *testing.T) {
u := newUtil(t)
l, addr := serverListen(u)
ch := make(chan struct{})
svCh := u.Go(func() error {
defer close(ch)
c, err := l.Accept()
if err != nil {
return fmt.Errorf("listener accept: %w", err)
}
defer c.Close()
hv := c.(*HvsockConn)
//
// test CloseWrite()
//
n, err := c.Write([]byte(testStr))
if err != nil {
return fmt.Errorf("server tx: %w", err)
}
if n != len(testStr) {
return fmt.Errorf("server wrote %d bytes, wanted %d", n, len(testStr))
}
if err := hv.CloseWrite(); err != nil {
return fmt.Errorf("server close write: %w", err)
}
if _, err = c.Write([]byte(testStr)); !errors.Is(err, windows.WSAESHUTDOWN) {
return fmt.Errorf("server did not shutdown writes: %w", err)
}
// safe to call multiple times
if err := hv.CloseWrite(); err != nil {
return fmt.Errorf("server second close write: %w", err)
}
//
// test CloseRead()
//
b := make([]byte, 256)
n, err = c.Read(b)
if err != nil {
return fmt.Errorf("server read: %w", err)
}
if n != len(testStr) {
return fmt.Errorf("server read %d bytes, wanted %d", n, len(testStr))
}
if string(b[:n]) != testStr {
return fmt.Errorf("server got %q; wanted %q", b[:n], testStr)
}
if err := hv.CloseRead(); err != nil {
return fmt.Errorf("server close read: %w", err)
}
ch <- struct{}{}
// signal the client to send more info
// if it was sent before, the read would succeed if the data was buffered prior
_, err = c.Read(b)
if !errors.Is(err, windows.WSAESHUTDOWN) {
return fmt.Errorf("server did not shutdown reads: %w", err)
}
// safe to call multiple times
if err := hv.CloseRead(); err != nil {
return fmt.Errorf("server second close read: %w", err)
}
c.Close()
if err := hv.CloseWrite(); !errors.Is(err, socket.ErrSocketClosed) {
return fmt.Errorf("server close write: %w", err)
}
if err := hv.CloseRead(); !errors.Is(err, socket.ErrSocketClosed) {
return fmt.Errorf("server close read: %w", err)
}
return nil
})
cl, err := Dial(context.Background(), addr)
u.Must(err, "could not dial")
defer cl.Close()
b := make([]byte, 256)
n, err := cl.Read(b)
u.Must(err, "client read")
u.Assert(n == len(testStr), fmt.Sprintf("client read %d bytes, wanted %d", n, len(testStr)))
u.Assert(string(b[:n]) == testStr, fmt.Sprintf("client got %q; wanted %q", b[:n], testStr))
n, err = cl.Read(b)
u.Assert(n == 0, "client did not get EOF")
u.Is(err, io.EOF, "client did not get EOF")
n, err = cl.Write([]byte(testStr))
u.Must(err, "client write")
u.Assert(n == len(testStr), fmt.Sprintf("client wrote %d bytes, wanted %d", n, len(testStr)))
u.Wait(ch, time.Second)
// this should succeed
_, err = cl.Write([]byte("test2"))
u.Must(err, "client write")
u.WaitErr(svCh, time.Second, "server")
}
func TestHvSockCloseReadWriteDial(t *testing.T) {
u := newUtil(t)
l, addr := serverListen(u)
ch := make(chan struct{})
clCh := u.Go(func() error {
defer close(ch)
c, err := l.Accept()
if err != nil {
return fmt.Errorf("listener accept: %w", err)
}
defer c.Close()
b := make([]byte, 256)
n, err := c.Read(b)
if err != nil {
return fmt.Errorf("server read: %w", err)
}
if string(b[:n]) != testStr {
return fmt.Errorf("server got %q; wanted %q", b[:n], testStr)
}
n, err = c.Read(b)
if n != 0 {
return fmt.Errorf("server did not get EOF")
}
if !errors.Is(err, io.EOF) {
return errors.New("server did not get EOF")
}
_, err = c.Write([]byte(testStr))
if err != nil {
return fmt.Errorf("server tx: %w", err)
}
ch <- struct{}{}
_, err = c.Write([]byte(testStr))
if err != nil {
return fmt.Errorf("server tx: %w", err)
}
return c.Close()
})
cl, err := Dial(context.Background(), addr)
u.Must(err, "could not dial")
defer cl.Close()
//
// test CloseWrite()
//
_, err = cl.Write([]byte(testStr))
u.Must(err, "client write")
u.Must(cl.CloseWrite(), "client close write")
_, err = cl.Write([]byte(testStr))
u.Is(err, windows.WSAESHUTDOWN, "client did not shutdown writes")
// safe to call multiple times
u.Must(cl.CloseWrite(), "client second close write")
//
// test CloseRead()
//
b := make([]byte, 256)
n, err := cl.Read(b)
u.Must(err, "client read")
u.Assert(string(b[:n]) == testStr, fmt.Sprintf("client got %q; wanted %q", b[:n], testStr))
u.Must(cl.CloseRead(), "client close read")
u.Wait(ch, time.Millisecond)
// signal the client to send more info
// if it was sent before, the read would succeed if the data was buffered prior
_, err = cl.Read(b)
u.Is(err, windows.WSAESHUTDOWN, "client did not shutdown reads")
// safe to call multiple times
u.Must(cl.CloseRead(), "client second close write")
l.Close()
cl.Close()
wantErr := socket.ErrSocketClosed
u.Is(cl.CloseWrite(), wantErr, "client close write")
u.Is(cl.CloseRead(), wantErr, "client close read")
u.WaitErr(clCh, time.Second, "client")
}
func TestHvSockDialNoTimeout(t *testing.T) {
u := newUtil(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch := u.Go(func() error {
addr := randHvsockAddr()
cl, err := Dial(ctx, addr)
if err == nil {
cl.Close()
}
if !errors.Is(err, windows.WSAECONNREFUSED) {
return err
}
return nil
})
// connections usually take about ~500µs
u.WaitErr(ch, 2*time.Millisecond, "dial did not time out")
}
func TestHvSockDialDeadline(t *testing.T) {
u := newUtil(t)
d := &HvsockDialer{}
d.Deadline = time.Now().Add(50 * time.Microsecond)
d.Retries = 1
// we need the wait time to be long enough for the deadline goroutine to run first and signal
// timeout
d.RetryWait = 100 * time.Millisecond
addr := randHvsockAddr()
cl, err := d.Dial(context.Background(), addr)
if err == nil {
cl.Close()
t.Fatalf("dial should not have finished")
}
u.Is(err, context.DeadlineExceeded, "dial did not exceed deadline")
}
func TestHvSockDialContext(t *testing.T) {
u := newUtil(t)
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Microsecond, cancel)
d := &HvsockDialer{}
d.Retries = 1
d.RetryWait = 100 * time.Millisecond
addr := randHvsockAddr()
cl, err := d.Dial(ctx, addr)
if err == nil {
cl.Close()
t.Fatalf("dial should not have finished")
}
u.Is(err, context.Canceled, "dial was not canceled")
}
func TestHvSockAcceptClose(t *testing.T) {
u := newUtil(t)
l, _ := serverListen(u)
go func() {
time.Sleep(50 * time.Millisecond)
l.Close()
}()
c, err := l.Accept()
if err == nil {
c.Close()
t.Fatal("listener should not have accepted anything")
}
u.Is(err, ErrFileClosed)
}
//
// helpers
//
type testUtil struct {
T testing.TB
}
func newUtil(t testing.TB) testUtil {
return testUtil{
T: t,
}
}
// Go launches f in a go routine and returns a channel that can be monitored for the result.
// ch is closed after f completes.
//
// Intended for use with [testUtil.WaitErr].
func (*testUtil) Go(f func() error) chan error {
ch := make(chan error)
go func() {
defer close(ch)
ch <- f()
}()
return ch
}
func (u testUtil) Wait(ch <-chan struct{}, d time.Duration, msgs ...string) {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ch:
case <-t.C:
u.T.Helper()
u.T.Fatalf(msgJoin(msgs, "timed out after %v"), d)
}
}
func (u testUtil) WaitErr(ch <-chan error, d time.Duration, msgs ...string) {
t := time.NewTimer(d)
defer t.Stop()
select {
case err := <-ch:
if err != nil {
u.T.Helper()
u.T.Fatalf(msgJoin(msgs, "%v"), err)
}
case <-t.C:
u.T.Helper()
u.T.Fatalf(msgJoin(msgs, "timed out after %v"), d)
}
}
func (u testUtil) Assert(b bool, msgs ...string) {
if b {
return
}
u.T.Helper()
u.T.Fatalf(msgJoin(msgs, "failed assertion"))
}
func (u testUtil) Is(err, target error, msgs ...string) {
if errors.Is(err, target) {
return
}
u.T.Helper()
u.T.Fatalf(msgJoin(msgs, "got error %q; wanted %q"), err, target)
}
func (u testUtil) Must(err error, msgs ...string) {
if err == nil {
return
}
u.T.Helper()
u.T.Fatalf(msgJoin(msgs, "%v"), err)
}
// Check stops execution if testing failed in another go-routine.
func (u testUtil) Check() {
if u.T.Failed() {
u.T.FailNow()
}
}
func msgJoin(pre []string, s string) string {
return strings.Join(append(pre, s), ": ")
}