...

Source file src/net/udpsock_test.go

Documentation: net

		 1  // Copyright 2012 The Go Authors. All rights reserved.
		 2  // Use of this source code is governed by a BSD-style
		 3  // license that can be found in the LICENSE file.
		 4  
		 5  //go:build !js
		 6  // +build !js
		 7  
		 8  package net
		 9  
		10  import (
		11  	"errors"
		12  	"internal/testenv"
		13  	"os"
		14  	"reflect"
		15  	"runtime"
		16  	"testing"
		17  	"time"
		18  )
		19  
		20  func BenchmarkUDP6LinkLocalUnicast(b *testing.B) {
		21  	testHookUninstaller.Do(uninstallTestHooks)
		22  
		23  	if !supportsIPv6() {
		24  		b.Skip("IPv6 is not supported")
		25  	}
		26  	ifi := loopbackInterface()
		27  	if ifi == nil {
		28  		b.Skip("loopback interface not found")
		29  	}
		30  	lla := ipv6LinkLocalUnicastAddr(ifi)
		31  	if lla == "" {
		32  		b.Skip("IPv6 link-local unicast address not found")
		33  	}
		34  
		35  	c1, err := ListenPacket("udp6", JoinHostPort(lla+"%"+ifi.Name, "0"))
		36  	if err != nil {
		37  		b.Fatal(err)
		38  	}
		39  	defer c1.Close()
		40  	c2, err := ListenPacket("udp6", JoinHostPort(lla+"%"+ifi.Name, "0"))
		41  	if err != nil {
		42  		b.Fatal(err)
		43  	}
		44  	defer c2.Close()
		45  
		46  	var buf [1]byte
		47  	for i := 0; i < b.N; i++ {
		48  		if _, err := c1.WriteTo(buf[:], c2.LocalAddr()); err != nil {
		49  			b.Fatal(err)
		50  		}
		51  		if _, _, err := c2.ReadFrom(buf[:]); err != nil {
		52  			b.Fatal(err)
		53  		}
		54  	}
		55  }
		56  
		57  type resolveUDPAddrTest struct {
		58  	network			 string
		59  	litAddrOrName string
		60  	addr					*UDPAddr
		61  	err					 error
		62  }
		63  
		64  var resolveUDPAddrTests = []resolveUDPAddrTest{
		65  	{"udp", "127.0.0.1:0", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 0}, nil},
		66  	{"udp4", "127.0.0.1:65535", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 65535}, nil},
		67  
		68  	{"udp", "[::1]:0", &UDPAddr{IP: ParseIP("::1"), Port: 0}, nil},
		69  	{"udp6", "[::1]:65535", &UDPAddr{IP: ParseIP("::1"), Port: 65535}, nil},
		70  
		71  	{"udp", "[::1%en0]:1", &UDPAddr{IP: ParseIP("::1"), Port: 1, Zone: "en0"}, nil},
		72  	{"udp6", "[::1%911]:2", &UDPAddr{IP: ParseIP("::1"), Port: 2, Zone: "911"}, nil},
		73  
		74  	{"", "127.0.0.1:0", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 0}, nil}, // Go 1.0 behavior
		75  	{"", "[::1]:0", &UDPAddr{IP: ParseIP("::1"), Port: 0}, nil},				 // Go 1.0 behavior
		76  
		77  	{"udp", ":12345", &UDPAddr{Port: 12345}, nil},
		78  
		79  	{"http", "127.0.0.1:0", nil, UnknownNetworkError("http")},
		80  
		81  	{"udp", "127.0.0.1:domain", &UDPAddr{IP: ParseIP("127.0.0.1"), Port: 53}, nil},
		82  	{"udp", "[::ffff:127.0.0.1]:domain", &UDPAddr{IP: ParseIP("::ffff:127.0.0.1"), Port: 53}, nil},
		83  	{"udp", "[2001:db8::1]:domain", &UDPAddr{IP: ParseIP("2001:db8::1"), Port: 53}, nil},
		84  	{"udp4", "127.0.0.1:domain", &UDPAddr{IP: ParseIP("127.0.0.1"), Port: 53}, nil},
		85  	{"udp4", "[::ffff:127.0.0.1]:domain", &UDPAddr{IP: ParseIP("127.0.0.1"), Port: 53}, nil},
		86  	{"udp6", "[2001:db8::1]:domain", &UDPAddr{IP: ParseIP("2001:db8::1"), Port: 53}, nil},
		87  
		88  	{"udp4", "[2001:db8::1]:domain", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "2001:db8::1"}},
		89  	{"udp6", "127.0.0.1:domain", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "127.0.0.1"}},
		90  	{"udp6", "[::ffff:127.0.0.1]:domain", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "::ffff:127.0.0.1"}},
		91  }
		92  
		93  func TestResolveUDPAddr(t *testing.T) {
		94  	origTestHookLookupIP := testHookLookupIP
		95  	defer func() { testHookLookupIP = origTestHookLookupIP }()
		96  	testHookLookupIP = lookupLocalhost
		97  
		98  	for _, tt := range resolveUDPAddrTests {
		99  		addr, err := ResolveUDPAddr(tt.network, tt.litAddrOrName)
	 100  		if !reflect.DeepEqual(addr, tt.addr) || !reflect.DeepEqual(err, tt.err) {
	 101  			t.Errorf("ResolveUDPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr, err, tt.addr, tt.err)
	 102  			continue
	 103  		}
	 104  		if err == nil {
	 105  			addr2, err := ResolveUDPAddr(addr.Network(), addr.String())
	 106  			if !reflect.DeepEqual(addr2, tt.addr) || err != tt.err {
	 107  				t.Errorf("(%q, %q): ResolveUDPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr.Network(), addr.String(), addr2, err, tt.addr, tt.err)
	 108  			}
	 109  		}
	 110  	}
	 111  }
	 112  
	 113  func TestWriteToUDP(t *testing.T) {
	 114  	switch runtime.GOOS {
	 115  	case "plan9":
	 116  		t.Skipf("not supported on %s", runtime.GOOS)
	 117  	}
	 118  
	 119  	c, err := ListenPacket("udp", "127.0.0.1:0")
	 120  	if err != nil {
	 121  		t.Fatal(err)
	 122  	}
	 123  	defer c.Close()
	 124  
	 125  	testWriteToConn(t, c.LocalAddr().String())
	 126  	testWriteToPacketConn(t, c.LocalAddr().String())
	 127  }
	 128  
	 129  func testWriteToConn(t *testing.T, raddr string) {
	 130  	c, err := Dial("udp", raddr)
	 131  	if err != nil {
	 132  		t.Fatal(err)
	 133  	}
	 134  	defer c.Close()
	 135  
	 136  	ra, err := ResolveUDPAddr("udp", raddr)
	 137  	if err != nil {
	 138  		t.Fatal(err)
	 139  	}
	 140  
	 141  	b := []byte("CONNECTED-MODE SOCKET")
	 142  	_, err = c.(*UDPConn).WriteToUDP(b, ra)
	 143  	if err == nil {
	 144  		t.Fatal("should fail")
	 145  	}
	 146  	if err != nil && err.(*OpError).Err != ErrWriteToConnected {
	 147  		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
	 148  	}
	 149  	_, err = c.(*UDPConn).WriteTo(b, ra)
	 150  	if err == nil {
	 151  		t.Fatal("should fail")
	 152  	}
	 153  	if err != nil && err.(*OpError).Err != ErrWriteToConnected {
	 154  		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
	 155  	}
	 156  	_, err = c.Write(b)
	 157  	if err != nil {
	 158  		t.Fatal(err)
	 159  	}
	 160  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, ra)
	 161  	if err == nil {
	 162  		t.Fatal("should fail")
	 163  	}
	 164  	if err != nil && err.(*OpError).Err != ErrWriteToConnected {
	 165  		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
	 166  	}
	 167  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, nil)
	 168  	if err != nil {
	 169  		t.Fatal(err)
	 170  	}
	 171  }
	 172  
	 173  func testWriteToPacketConn(t *testing.T, raddr string) {
	 174  	c, err := ListenPacket("udp", "127.0.0.1:0")
	 175  	if err != nil {
	 176  		t.Fatal(err)
	 177  	}
	 178  	defer c.Close()
	 179  
	 180  	ra, err := ResolveUDPAddr("udp", raddr)
	 181  	if err != nil {
	 182  		t.Fatal(err)
	 183  	}
	 184  
	 185  	b := []byte("UNCONNECTED-MODE SOCKET")
	 186  	_, err = c.(*UDPConn).WriteToUDP(b, ra)
	 187  	if err != nil {
	 188  		t.Fatal(err)
	 189  	}
	 190  	_, err = c.WriteTo(b, ra)
	 191  	if err != nil {
	 192  		t.Fatal(err)
	 193  	}
	 194  	_, err = c.(*UDPConn).Write(b)
	 195  	if err == nil {
	 196  		t.Fatal("should fail")
	 197  	}
	 198  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, nil)
	 199  	if err == nil {
	 200  		t.Fatal("should fail")
	 201  	}
	 202  	if err != nil && err.(*OpError).Err != errMissingAddress {
	 203  		t.Fatalf("should fail as errMissingAddress: %v", err)
	 204  	}
	 205  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, ra)
	 206  	if err != nil {
	 207  		t.Fatal(err)
	 208  	}
	 209  }
	 210  
	 211  var udpConnLocalNameTests = []struct {
	 212  	net	 string
	 213  	laddr *UDPAddr
	 214  }{
	 215  	{"udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)}},
	 216  	{"udp4", &UDPAddr{}},
	 217  	{"udp4", nil},
	 218  }
	 219  
	 220  func TestUDPConnLocalName(t *testing.T) {
	 221  	testenv.MustHaveExternalNetwork(t)
	 222  
	 223  	for _, tt := range udpConnLocalNameTests {
	 224  		c, err := ListenUDP(tt.net, tt.laddr)
	 225  		if err != nil {
	 226  			t.Fatal(err)
	 227  		}
	 228  		defer c.Close()
	 229  		la := c.LocalAddr()
	 230  		if a, ok := la.(*UDPAddr); !ok || a.Port == 0 {
	 231  			t.Fatalf("got %v; expected a proper address with non-zero port number", la)
	 232  		}
	 233  	}
	 234  }
	 235  
	 236  func TestUDPConnLocalAndRemoteNames(t *testing.T) {
	 237  	for _, laddr := range []string{"", "127.0.0.1:0"} {
	 238  		c1, err := ListenPacket("udp", "127.0.0.1:0")
	 239  		if err != nil {
	 240  			t.Fatal(err)
	 241  		}
	 242  		defer c1.Close()
	 243  
	 244  		var la *UDPAddr
	 245  		if laddr != "" {
	 246  			var err error
	 247  			if la, err = ResolveUDPAddr("udp", laddr); err != nil {
	 248  				t.Fatal(err)
	 249  			}
	 250  		}
	 251  		c2, err := DialUDP("udp", la, c1.LocalAddr().(*UDPAddr))
	 252  		if err != nil {
	 253  			t.Fatal(err)
	 254  		}
	 255  		defer c2.Close()
	 256  
	 257  		var connAddrs = [4]struct {
	 258  			got Addr
	 259  			ok	bool
	 260  		}{
	 261  			{c1.LocalAddr(), true},
	 262  			{c1.(*UDPConn).RemoteAddr(), false},
	 263  			{c2.LocalAddr(), true},
	 264  			{c2.RemoteAddr(), true},
	 265  		}
	 266  		for _, ca := range connAddrs {
	 267  			if a, ok := ca.got.(*UDPAddr); ok != ca.ok || ok && a.Port == 0 {
	 268  				t.Fatalf("got %v; expected a proper address with non-zero port number", ca.got)
	 269  			}
	 270  		}
	 271  	}
	 272  }
	 273  
	 274  func TestIPv6LinkLocalUnicastUDP(t *testing.T) {
	 275  	testenv.MustHaveExternalNetwork(t)
	 276  
	 277  	if !supportsIPv6() {
	 278  		t.Skip("IPv6 is not supported")
	 279  	}
	 280  
	 281  	for i, tt := range ipv6LinkLocalUnicastUDPTests {
	 282  		c1, err := ListenPacket(tt.network, tt.address)
	 283  		if err != nil {
	 284  			// It might return "LookupHost returned no
	 285  			// suitable address" error on some platforms.
	 286  			t.Log(err)
	 287  			continue
	 288  		}
	 289  		ls, err := (&packetListener{PacketConn: c1}).newLocalServer()
	 290  		if err != nil {
	 291  			t.Fatal(err)
	 292  		}
	 293  		defer ls.teardown()
	 294  		ch := make(chan error, 1)
	 295  		handler := func(ls *localPacketServer, c PacketConn) { packetTransponder(c, ch) }
	 296  		if err := ls.buildup(handler); err != nil {
	 297  			t.Fatal(err)
	 298  		}
	 299  		if la, ok := c1.LocalAddr().(*UDPAddr); !ok || !tt.nameLookup && la.Zone == "" {
	 300  			t.Fatalf("got %v; expected a proper address with zone identifier", la)
	 301  		}
	 302  
	 303  		c2, err := Dial(tt.network, ls.PacketConn.LocalAddr().String())
	 304  		if err != nil {
	 305  			t.Fatal(err)
	 306  		}
	 307  		defer c2.Close()
	 308  		if la, ok := c2.LocalAddr().(*UDPAddr); !ok || !tt.nameLookup && la.Zone == "" {
	 309  			t.Fatalf("got %v; expected a proper address with zone identifier", la)
	 310  		}
	 311  		if ra, ok := c2.RemoteAddr().(*UDPAddr); !ok || !tt.nameLookup && ra.Zone == "" {
	 312  			t.Fatalf("got %v; expected a proper address with zone identifier", ra)
	 313  		}
	 314  
	 315  		if _, err := c2.Write([]byte("UDP OVER IPV6 LINKLOCAL TEST")); err != nil {
	 316  			t.Fatal(err)
	 317  		}
	 318  		b := make([]byte, 32)
	 319  		if _, err := c2.Read(b); err != nil {
	 320  			t.Fatal(err)
	 321  		}
	 322  
	 323  		for err := range ch {
	 324  			t.Errorf("#%d: %v", i, err)
	 325  		}
	 326  	}
	 327  }
	 328  
	 329  func TestUDPZeroBytePayload(t *testing.T) {
	 330  	switch runtime.GOOS {
	 331  	case "plan9":
	 332  		t.Skipf("not supported on %s", runtime.GOOS)
	 333  	case "darwin", "ios":
	 334  		testenv.SkipFlaky(t, 29225)
	 335  	}
	 336  
	 337  	c, err := newLocalPacketListener("udp")
	 338  	if err != nil {
	 339  		t.Fatal(err)
	 340  	}
	 341  	defer c.Close()
	 342  
	 343  	for _, genericRead := range []bool{false, true} {
	 344  		n, err := c.WriteTo(nil, c.LocalAddr())
	 345  		if err != nil {
	 346  			t.Fatal(err)
	 347  		}
	 348  		if n != 0 {
	 349  			t.Errorf("got %d; want 0", n)
	 350  		}
	 351  		c.SetReadDeadline(time.Now().Add(30 * time.Second))
	 352  		var b [1]byte
	 353  		var name string
	 354  		if genericRead {
	 355  			_, err = c.(Conn).Read(b[:])
	 356  			name = "Read"
	 357  		} else {
	 358  			_, _, err = c.ReadFrom(b[:])
	 359  			name = "ReadFrom"
	 360  		}
	 361  		if err != nil {
	 362  			t.Errorf("%s of zero byte packet failed: %v", name, err)
	 363  		}
	 364  	}
	 365  }
	 366  
	 367  func TestUDPZeroByteBuffer(t *testing.T) {
	 368  	switch runtime.GOOS {
	 369  	case "plan9":
	 370  		t.Skipf("not supported on %s", runtime.GOOS)
	 371  	}
	 372  
	 373  	c, err := newLocalPacketListener("udp")
	 374  	if err != nil {
	 375  		t.Fatal(err)
	 376  	}
	 377  	defer c.Close()
	 378  
	 379  	b := []byte("UDP ZERO BYTE BUFFER TEST")
	 380  	for _, genericRead := range []bool{false, true} {
	 381  		n, err := c.WriteTo(b, c.LocalAddr())
	 382  		if err != nil {
	 383  			t.Fatal(err)
	 384  		}
	 385  		if n != len(b) {
	 386  			t.Errorf("got %d; want %d", n, len(b))
	 387  		}
	 388  		c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	 389  		if genericRead {
	 390  			_, err = c.(Conn).Read(nil)
	 391  		} else {
	 392  			_, _, err = c.ReadFrom(nil)
	 393  		}
	 394  		switch err {
	 395  		case nil: // ReadFrom succeeds
	 396  		default: // Read may timeout, it depends on the platform
	 397  			if nerr, ok := err.(Error); (!ok || !nerr.Timeout()) && runtime.GOOS != "windows" { // Windows returns WSAEMSGSIZE
	 398  				t.Fatal(err)
	 399  			}
	 400  		}
	 401  	}
	 402  }
	 403  
	 404  func TestUDPReadSizeError(t *testing.T) {
	 405  	switch runtime.GOOS {
	 406  	case "plan9":
	 407  		t.Skipf("not supported on %s", runtime.GOOS)
	 408  	}
	 409  
	 410  	c1, err := newLocalPacketListener("udp")
	 411  	if err != nil {
	 412  		t.Fatal(err)
	 413  	}
	 414  	defer c1.Close()
	 415  
	 416  	c2, err := Dial("udp", c1.LocalAddr().String())
	 417  	if err != nil {
	 418  		t.Fatal(err)
	 419  	}
	 420  	defer c2.Close()
	 421  
	 422  	b1 := []byte("READ SIZE ERROR TEST")
	 423  	for _, genericRead := range []bool{false, true} {
	 424  		n, err := c2.Write(b1)
	 425  		if err != nil {
	 426  			t.Fatal(err)
	 427  		}
	 428  		if n != len(b1) {
	 429  			t.Errorf("got %d; want %d", n, len(b1))
	 430  		}
	 431  		c1.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	 432  		b2 := make([]byte, len(b1)-1)
	 433  		if genericRead {
	 434  			n, err = c1.(Conn).Read(b2)
	 435  		} else {
	 436  			n, _, err = c1.ReadFrom(b2)
	 437  		}
	 438  		switch err {
	 439  		case nil: // ReadFrom succeeds
	 440  		default: // Read may timeout, it depends on the platform
	 441  			if nerr, ok := err.(Error); (!ok || !nerr.Timeout()) && runtime.GOOS != "windows" { // Windows returns WSAEMSGSIZE
	 442  				t.Fatal(err)
	 443  			}
	 444  		}
	 445  		if n != len(b1)-1 {
	 446  			t.Fatalf("got %d; want %d", n, len(b1)-1)
	 447  		}
	 448  	}
	 449  }
	 450  
	 451  // TestUDPReadTimeout verifies that ReadFromUDP with timeout returns an error
	 452  // without data or an address.
	 453  func TestUDPReadTimeout(t *testing.T) {
	 454  	la, err := ResolveUDPAddr("udp4", "127.0.0.1:0")
	 455  	if err != nil {
	 456  		t.Fatal(err)
	 457  	}
	 458  	c, err := ListenUDP("udp4", la)
	 459  	if err != nil {
	 460  		t.Fatal(err)
	 461  	}
	 462  	defer c.Close()
	 463  
	 464  	c.SetDeadline(time.Now())
	 465  	b := make([]byte, 1)
	 466  	n, addr, err := c.ReadFromUDP(b)
	 467  	if !errors.Is(err, os.ErrDeadlineExceeded) {
	 468  		t.Errorf("ReadFromUDP got err %v want os.ErrDeadlineExceeded", err)
	 469  	}
	 470  	if n != 0 {
	 471  		t.Errorf("ReadFromUDP got n %d want 0", n)
	 472  	}
	 473  	if addr != nil {
	 474  		t.Errorf("ReadFromUDP got addr %+#v want nil", addr)
	 475  	}
	 476  }
	 477  
	 478  func BenchmarkWriteToReadFromUDP(b *testing.B) {
	 479  	conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
	 480  	if err != nil {
	 481  		b.Fatal(err)
	 482  	}
	 483  	addr := conn.LocalAddr()
	 484  	buf := make([]byte, 8)
	 485  	b.ResetTimer()
	 486  	b.ReportAllocs()
	 487  	for i := 0; i < b.N; i++ {
	 488  		_, err := conn.WriteTo(buf, addr)
	 489  		if err != nil {
	 490  			b.Fatal(err)
	 491  		}
	 492  		_, _, err = conn.ReadFromUDP(buf)
	 493  		if err != nil {
	 494  			b.Fatal(err)
	 495  		}
	 496  	}
	 497  }
	 498  

View as plain text