author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
259,898
18.11.2020 13:26:47
28,800
d2b701758d3fb1c39162243521e6b985f8b5ef78
Remove the redundant containerIP parameter
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/dut.go", "new_path": "test/packetimpact/runner/dut.go", "diff": "@@ -96,7 +96,7 @@ func (l logger) Logf(format string, args ...interface{}) {\n}\n// TestWithDUT runs a packetimpact test with the given information.\n-func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Container) DUT, containerAddr net.IP) {\n+func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Container) DUT) {\nif testbenchBinary == \"\" {\nt.Fatal(\"--testbench_binary is missing\")\n}\n@@ -172,7 +172,7 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\n}\ndevice := mkDevice(dut)\n- remoteIPv6, remoteMAC, dutDeviceID, dutTestNetDev := device.Prepare(ctx, t, runOpts, ctrlNet, testNet, containerAddr)\n+ remoteIPv6, remoteMAC, dutDeviceID, dutTestNetDev := device.Prepare(ctx, t, runOpts, ctrlNet, testNet)\n// Create the Docker container for the testbench.\ntestbench := dockerutil.MakeNativeContainer(ctx, logger(\"testbench\"))\n@@ -285,7 +285,7 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\ntype DUT interface {\n// Prepare prepares the dut, starts posix_server and returns the IPv6, MAC\n// address, the interface ID, and the interface name for the testNet on DUT.\n- Prepare(ctx context.Context, t *testing.T, runOpts dockerutil.RunOpts, ctrlNet, testNet *dockerutil.Network, containerAddr net.IP) (net.IP, net.HardwareAddr, uint32, string)\n+ Prepare(ctx context.Context, t *testing.T, runOpts dockerutil.RunOpts, ctrlNet, testNet *dockerutil.Network) (net.IP, net.HardwareAddr, uint32, string)\n// Logs retrieves the logs from the dut.\nLogs(ctx context.Context) (string, error)\n}\n@@ -303,7 +303,7 @@ func NewDockerDUT(c *dockerutil.Container) DUT {\n}\n// Prepare implements DUT.Prepare.\n-func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockerutil.RunOpts, ctrlNet, testNet *dockerutil.Network, containerAddr net.IP) (net.IP, net.HardwareAddr, uint32, string) {\n+func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockerutil.RunOpts, ctrlNet, testNet *dockerutil.Network) (net.IP, net.HardwareAddr, uint32, string) {\nconst containerPosixServerBinary = \"/packetimpact/posix_server\"\ndut.c.CopyFiles(&runOpts, \"/packetimpact\", \"test/packetimpact/dut/posix_server\")\n@@ -311,7 +311,7 @@ func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockeru\nctx,\nrunOpts,\ndut.c,\n- containerAddr,\n+ DutAddr,\n[]*dockerutil.Network{ctrlNet, testNet},\ncontainerPosixServerBinary,\n\"--ip=0.0.0.0\",\n@@ -324,7 +324,7 @@ func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockeru\nt.Fatalf(\"%s on container %s never listened: %s\", containerPosixServerBinary, dut.c.Name, err)\n}\n- dutTestDevice, dutDeviceInfo, err := deviceByIP(ctx, dut.c, AddressInSubnet(containerAddr, *testNet.Subnet))\n+ dutTestDevice, dutDeviceInfo, err := deviceByIP(ctx, dut.c, AddressInSubnet(DutAddr, *testNet.Subnet))\nif err != nil {\nt.Fatal(err)\n}\n@@ -338,7 +338,7 @@ func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockeru\nt.Fatalf(\"unable to ip addr add on container %s: %s\", dut.c.Name, err)\n}\n// Now try again, to make sure that it worked.\n- _, dutDeviceInfo, err = deviceByIP(ctx, dut.c, AddressInSubnet(containerAddr, *testNet.Subnet))\n+ _, dutDeviceInfo, err = deviceByIP(ctx, dut.c, AddressInSubnet(DutAddr, *testNet.Subnet))\nif err != nil {\nt.Fatal(err)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/packetimpact_test.go", "new_path": "test/packetimpact/runner/packetimpact_test.go", "diff": "@@ -28,5 +28,5 @@ func init() {\n}\nfunc TestOne(t *testing.T) {\n- runner.TestWithDUT(context.Background(), t, runner.NewDockerDUT, runner.DutAddr)\n+ runner.TestWithDUT(context.Background(), t, runner.NewDockerDUT)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove the redundant containerIP parameter PiperOrigin-RevId: 343144023
259,907
18.11.2020 13:40:23
28,800
3e73c519a55191827dcc6e98ea0ffe977acbb73f
[netstack] Move SO_NO_CHECK option to SocketOptions.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1232,12 +1232,8 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nreturn nil, syserr.ErrInvalidArgument\n}\n- v, err := ep.GetSockOptBool(tcpip.NoChecksumOption)\n- if err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n- vP := primitive.Int32(boolToInt32(v))\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetNoChecksum()))\n+ return &v, nil\ncase linux.SO_ACCEPTCONN:\nif outLen < sizeOfInt32 {\n@@ -1977,7 +1973,8 @@ func setSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, nam\n}\nv := usermem.ByteOrder.Uint32(optVal)\n- return syserr.TranslateNetstackError(ep.SetSockOptBool(tcpip.NoChecksumOption, v != 0))\n+ ep.SocketOptions().SetNoChecksum(v != 0)\n+ return nil\ncase linux.SO_LINGER:\nif len(optVal) < linux.SizeOfLinger {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -32,6 +32,10 @@ type SocketOptions struct {\n// passCredEnabled determines whether SCM_CREDENTIALS socket control messages\n// are enabled.\npassCredEnabled uint32\n+\n+ // noChecksumEnabled determines whether UDP checksum is disabled while\n+ // transmitting for this socket.\n+ noChecksumEnabled uint32\n}\nfunc storeAtomicBool(addr *uint32, v bool) {\n@@ -61,3 +65,13 @@ func (so *SocketOptions) GetPassCred() bool {\nfunc (so *SocketOptions) SetPassCred(v bool) {\nstoreAtomicBool(&so.passCredEnabled, v)\n}\n+\n+// GetNoChecksum gets value for SO_NO_CHECK option.\n+func (so *SocketOptions) GetNoChecksum() bool {\n+ return atomic.LoadUint32(&so.noChecksumEnabled) != 0\n+}\n+\n+// SetNoChecksum sets value for SO_NO_CHECK option.\n+func (so *SocketOptions) SetNoChecksum(v bool) {\n+ storeAtomicBool(&so.noChecksumEnabled, v)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -108,7 +108,6 @@ type endpoint struct {\nmulticastLoop bool\nportFlags ports.Flags\nbindToDevice tcpip.NICID\n- noChecksum bool\nlastErrorMu sync.Mutex `state:\"nosave\"`\nlastError *tcpip.Error `state:\".(string)\"`\n@@ -550,7 +549,7 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-c\nlocalPort := e.ID.LocalPort\nsendTOS := e.sendTOS\nowner := e.owner\n- noChecksum := e.noChecksum\n+ noChecksum := e.SocketOptions().GetNoChecksum()\nlockReleased = true\ne.mu.RUnlock()\n@@ -583,11 +582,6 @@ func (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\ne.multicastLoop = v\ne.mu.Unlock()\n- case tcpip.NoChecksumOption:\n- e.mu.Lock()\n- e.noChecksum = v\n- e.mu.Unlock()\n-\ncase tcpip.ReceiveTOSOption:\ne.mu.Lock()\ne.receiveTOS = v\n@@ -858,12 +852,6 @@ func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\ne.mu.RUnlock()\nreturn v, nil\n- case tcpip.NoChecksumOption:\n- e.mu.RLock()\n- v := e.noChecksum\n- e.mu.RUnlock()\n- return v, nil\n-\ncase tcpip.ReceiveTOSOption:\ne.mu.RLock()\nv := e.receiveTOS\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -1454,16 +1454,12 @@ func TestNoChecksum(t *testing.T) {\nc.createEndpointForFlow(flow)\n// Disable the checksum generation.\n- if err := c.ep.SetSockOptBool(tcpip.NoChecksumOption, true); err != nil {\n- t.Fatalf(\"SetSockOptBool failed: %s\", err)\n- }\n+ c.ep.SocketOptions().SetNoChecksum(true)\n// This option is effective on IPv4 only.\ntestWrite(c, flow, checker.UDP(checker.NoChecksum(flow.isV4())))\n// Enable the checksum generation.\n- if err := c.ep.SetSockOptBool(tcpip.NoChecksumOption, false); err != nil {\n- t.Fatalf(\"SetSockOptBool failed: %s\", err)\n- }\n+ c.ep.SocketOptions().SetNoChecksum(false)\ntestWrite(c, flow, checker.UDP(checker.NoChecksum(false)))\n})\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_generic.cc", "new_path": "test/syscalls/linux/socket_generic.cc", "diff": "@@ -819,7 +819,7 @@ TEST_P(AllSocketPairTest, GetSockoptProtocol) {\n}\nTEST_P(AllSocketPairTest, SetAndGetBooleanSocketOptions) {\n- int sock_opts[] = {SO_BROADCAST, SO_PASSCRED};\n+ int sock_opts[] = {SO_BROADCAST, SO_PASSCRED, SO_NO_CHECK};\nfor (int sock_opt : sock_opts) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nint enable = -1;\n" } ]
Go
Apache License 2.0
google/gvisor
[netstack] Move SO_NO_CHECK option to SocketOptions. PiperOrigin-RevId: 343146856
259,992
18.11.2020 16:04:26
28,800
7158095d687dd9ede3a3fc8da1f4dfbb2ebc176e
Fix race condition in multi-container wait test Container is not thread-safe, locking must be done in the caller. The test was calling Container.Wait() from multiple threads with no synchronization. Also removed Container.WaitPID from test because the process might have already existed when wait is called.
[ { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -80,6 +80,7 @@ func validateID(id string) error {\n// - It calls 'runsc delete'. runc implementation kills --all SIGKILL once\n// again just to be sure, waits, and then proceeds with remaining teardown.\n//\n+// Container is thread-unsafe.\ntype Container struct {\n// ID is the container ID.\nID string `json:\"id\"`\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/multi_container_test.go", "new_path": "runsc/container/multi_container_test.go", "diff": "@@ -301,20 +301,8 @@ func TestMultiContainerWait(t *testing.T) {\n}\ndefer cleanup()\n- // Check via ps that multiple processes are running.\n- expectedPL := []*control.Process{\n- newProcessBuilder().PID(2).PPID(0).Cmd(\"sleep\").Process(),\n- }\n- if err := waitForProcessList(containers[1], expectedPL); err != nil {\n- t.Errorf(\"failed to wait for sleep to start: %v\", err)\n- }\n-\n- // Wait on the short lived container from multiple goroutines.\n- wg := sync.WaitGroup{}\n- for i := 0; i < 3; i++ {\n- wg.Add(1)\n- go func(c *Container) {\n- defer wg.Done()\n+ // Check that we can wait for the sub-container.\n+ c := containers[1]\nif ws, err := c.Wait(); err != nil {\nt.Errorf(\"failed to wait for process %s: %v\", c.Spec.Process.Args, err)\n} else if es := ws.ExitStatus(); es != 0 {\n@@ -323,32 +311,11 @@ func TestMultiContainerWait(t *testing.T) {\nif _, err := c.Wait(); err != nil {\nt.Errorf(\"wait for stopped container %s shouldn't fail: %v\", c.Spec.Process.Args, err)\n}\n- }(containers[1])\n- }\n-\n- // Also wait via PID.\n- for i := 0; i < 3; i++ {\n- wg.Add(1)\n- go func(c *Container) {\n- defer wg.Done()\n- const pid = 2\n- if ws, err := c.WaitPID(pid); err != nil {\n- t.Errorf(\"failed to wait for PID %d: %v\", pid, err)\n- } else if es := ws.ExitStatus(); es != 0 {\n- t.Errorf(\"PID %d exited with non-zero status %d\", pid, es)\n- }\n- if _, err := c.WaitPID(pid); err == nil {\n- t.Errorf(\"wait for stopped PID %d should fail\", pid)\n- }\n- }(containers[1])\n- }\n-\n- wg.Wait()\n// After Wait returns, ensure that the root container is running and\n// the child has finished.\n- expectedPL = []*control.Process{\n- newProcessBuilder().Cmd(\"sleep\").Process(),\n+ expectedPL := []*control.Process{\n+ newProcessBuilder().Cmd(\"sleep\").PID(1).Process(),\n}\nif err := waitForProcessList(containers[0], expectedPL); err != nil {\nt.Errorf(\"failed to wait for %q to start: %v\", strings.Join(containers[0].Spec.Process.Args, \" \"), err)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix race condition in multi-container wait test Container is not thread-safe, locking must be done in the caller. The test was calling Container.Wait() from multiple threads with no synchronization. Also removed Container.WaitPID from test because the process might have already existed when wait is called. PiperOrigin-RevId: 343176280
259,853
18.11.2020 18:35:14
28,800
764504c38fb589738f42a852c9288725dcf0f9f9
runsc: check whether cgroup exists or not for each controller We have seen a case when a memory cgroup exists but a perf_event one doesn't. Reported-by: Reported-by:
[ { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup.go", "new_path": "runsc/cgroup/cgroup.go", "diff": "@@ -234,7 +234,7 @@ func loadPathsHelper(cgroup io.Reader) (map[string]string, error) {\ntype Cgroup struct {\nName string `json:\"name\"`\nParents map[string]string `json:\"parents\"`\n- Own bool `json:\"own\"`\n+ Own map[string]bool `json:\"own\"`\n}\n// New creates a new Cgroup instance if the spec includes a cgroup path.\n@@ -251,9 +251,11 @@ func New(spec *specs.Spec) (*Cgroup, error) {\nreturn nil, fmt.Errorf(\"finding current cgroups: %w\", err)\n}\n}\n+ own := make(map[string]bool)\nreturn &Cgroup{\nName: spec.Linux.CgroupsPath,\nParents: parents,\n+ Own: own,\n}, nil\n}\n@@ -261,18 +263,8 @@ func New(spec *specs.Spec) (*Cgroup, error) {\n// already exists, it means that the caller has already provided a\n// pre-configured cgroups, and 'res' is ignored.\nfunc (c *Cgroup) Install(res *specs.LinuxResources) error {\n- if _, err := os.Stat(c.makePath(\"memory\")); err == nil {\n- // If cgroup has already been created; it has been setup by caller. Don't\n- // make any changes to configuration, just join when sandbox/gofer starts.\n- log.Debugf(\"Using pre-created cgroup %q\", c.Name)\n- return nil\n- }\n-\nlog.Debugf(\"Creating cgroup %q\", c.Name)\n- // Mark that cgroup resources are owned by me.\n- c.Own = true\n-\n// The Cleanup object cleans up partially created cgroups when an error occurs.\n// Errors occuring during cleanup itself are ignored.\nclean := cleanup.Make(func() { _ = c.Uninstall() })\n@@ -280,6 +272,16 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\nfor key, cfg := range controllers {\npath := c.makePath(key)\n+ if _, err := os.Stat(path); err == nil {\n+ // If cgroup has already been created; it has been setup by caller. Don't\n+ // make any changes to configuration, just join when sandbox/gofer starts.\n+ log.Debugf(\"Using pre-created cgroup %q\", path)\n+ continue\n+ }\n+\n+ // Mark that cgroup resources are owned by me.\n+ c.Own[key] = true\n+\nif err := os.MkdirAll(path, 0755); err != nil {\nif cfg.optional && errors.Is(err, syscall.EROFS) {\nlog.Infof(\"Skipping cgroup %q\", key)\n@@ -298,12 +300,12 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\n// Uninstall removes the settings done in Install(). If cgroup path already\n// existed when Install() was called, Uninstall is a noop.\nfunc (c *Cgroup) Uninstall() error {\n- if !c.Own {\n- // cgroup is managed by caller, don't touch it.\n- return nil\n- }\nlog.Debugf(\"Deleting cgroup %q\", c.Name)\nfor key := range controllers {\n+ if !c.Own[key] {\n+ // cgroup is managed by caller, don't touch it.\n+ continue\n+ }\npath := c.makePath(key)\nlog.Debugf(\"Removing cgroup controller for key=%q path=%q\", key, path)\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup_test.go", "new_path": "runsc/cgroup/cgroup_test.go", "diff": "@@ -29,7 +29,10 @@ func TestUninstallEnoent(t *testing.T) {\nc := Cgroup{\n// set a non-existent name\nName: \"runsc-test-uninstall-656e6f656e740a\",\n- Own: true,\n+ }\n+ c.Own = make(map[string]bool)\n+ for key := range controllers {\n+ c.Own[key] = true\n}\nif err := c.Uninstall(); err != nil {\nt.Errorf(\"Uninstall() failed: %v\", err)\n" } ]
Go
Apache License 2.0
google/gvisor
runsc: check whether cgroup exists or not for each controller We have seen a case when a memory cgroup exists but a perf_event one doesn't. Reported-by: [email protected] Reported-by: [email protected] PiperOrigin-RevId: 343200070
260,004
18.11.2020 20:19:31
28,800
93750a600bb01fdc90703b8fa9ea2e163c615c6c
Remove unused methods from stack.Route
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -397,23 +397,6 @@ func (r *Route) Clone() Route {\nreturn *r\n}\n-// MakeLoopedRoute duplicates the given route with special handling for routes\n-// used for sending multicast or broadcast packets. In those cases the\n-// multicast/broadcast address is the remote address when sending out, but for\n-// incoming (looped) packets it becomes the local address. Similarly, the local\n-// interface address that was the local address going out becomes the remote\n-// address coming in. This is different to unicast routes where local and\n-// remote addresses remain the same as they identify location (local vs remote)\n-// not direction (source vs destination).\n-func (r *Route) MakeLoopedRoute() Route {\n- l := r.Clone()\n- if r.RemoteAddress == header.IPv4Broadcast || header.IsV4MulticastAddress(r.RemoteAddress) || header.IsV6MulticastAddress(r.RemoteAddress) {\n- l.RemoteAddress, l.LocalAddress = l.LocalAddress, l.RemoteAddress\n- l.RemoteLinkAddress = l.LocalLinkAddress\n- }\n- return l\n-}\n-\n// Stack returns the instance of the Stack that owns this route.\nfunc (r *Route) Stack() *Stack {\nreturn r.outgoingNIC.stack\n@@ -434,27 +417,3 @@ func (r *Route) IsOutboundBroadcast() bool {\n// Only IPv4 has a notion of broadcast.\nreturn r.isV4Broadcast(r.RemoteAddress)\n}\n-\n-// isInboundBroadcast returns true if the route is for an inbound broadcast\n-// packet.\n-func (r *Route) isInboundBroadcast() bool {\n- // Only IPv4 has a notion of broadcast.\n- return r.isV4Broadcast(r.LocalAddress)\n-}\n-\n-// ReverseRoute returns new route with given source and destination address.\n-func (r *Route) ReverseRoute(src tcpip.Address, dst tcpip.Address) Route {\n- return Route{\n- NetProto: r.NetProto,\n- LocalAddress: dst,\n- LocalLinkAddress: r.RemoteLinkAddress,\n- RemoteAddress: src,\n- RemoteLinkAddress: r.LocalLinkAddress,\n- Loop: r.Loop,\n- localAddressNIC: r.localAddressNIC,\n- localAddressEndpoint: r.localAddressEndpoint,\n- outgoingNIC: r.outgoingNIC,\n- linkCache: r.linkCache,\n- linkRes: r.linkRes,\n- }\n-}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unused methods from stack.Route PiperOrigin-RevId: 343211553
259,907
18.11.2020 21:22:43
28,800
e5650d124032e38a26e4b8058778e1c5b5aacbf0
[netstack] Move SO_KEEPALIVE and SO_ACCEPTCONN option to SocketOptions.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1162,13 +1162,8 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nreturn nil, syserr.ErrInvalidArgument\n}\n- v, err := ep.GetSockOptBool(tcpip.KeepaliveEnabledOption)\n- if err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n-\n- vP := primitive.Int32(boolToInt32(v))\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetKeepAlive()))\n+ return &v, nil\ncase linux.SO_LINGER:\nif outLen < linux.SizeOfLinger {\n@@ -1231,12 +1226,8 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nreturn nil, syserr.ErrInvalidArgument\n}\n- v, err := ep.GetSockOptBool(tcpip.AcceptConnOption)\n- if err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n- vP := primitive.Int32(boolToInt32(v))\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetAcceptConn()))\n+ return &v, nil\ndefault:\nsocket.GetSockOptEmitUnimplementedEvent(t, name)\n@@ -1918,7 +1909,8 @@ func setSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, nam\n}\nv := usermem.ByteOrder.Uint32(optVal)\n- return syserr.TranslateNetstackError(ep.SetSockOptBool(tcpip.KeepaliveEnabledOption, v != 0))\n+ ep.SocketOptions().SetKeepAlive(v != 0)\n+ return nil\ncase linux.SO_SNDTIMEO:\nif len(optVal) < linux.SizeOfTimeval {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/unix.go", "new_path": "pkg/sentry/socket/unix/transport/unix.go", "diff": "@@ -873,15 +873,9 @@ func (e *baseEndpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\n}\nfunc (e *baseEndpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- switch opt {\n- case tcpip.KeepaliveEnabledOption, tcpip.AcceptConnOption:\n- return false, nil\n-\n- default:\nlog.Warningf(\"Unsupported socket option: %d\", opt)\nreturn false, tcpip.ErrUnknownProtocolOption\n}\n-}\nfunc (e *baseEndpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -19,14 +19,23 @@ import (\n)\n// SocketOptionsHandler holds methods that help define endpoint specific\n-// behavior for socket options. These must be implemented by endpoints to get\n-// notified when socket level options are set.\n+// behavior for socket options.\n+// These must be implemented by endpoints to:\n+// - Get notified when socket level options are set.\n+// - Provide endpoint specific socket options.\ntype SocketOptionsHandler interface {\n// OnReuseAddressSet is invoked when SO_REUSEADDR is set for an endpoint.\nOnReuseAddressSet(v bool)\n// OnReusePortSet is invoked when SO_REUSEPORT is set for an endpoint.\nOnReusePortSet(v bool)\n+\n+ // OnKeepAliveSet is invoked when SO_KEEPALIVE is set for an endpoint.\n+ OnKeepAliveSet(v bool)\n+\n+ // IsListening is invoked to fetch SO_ACCEPTCONN option value for an\n+ // endpoint. It is used to indicate if the socket is a listening socket.\n+ IsListening() bool\n}\n// DefaultSocketOptionsHandler is an embeddable type that implements no-op\n@@ -41,6 +50,12 @@ func (*DefaultSocketOptionsHandler) OnReuseAddressSet(bool) {}\n// OnReusePortSet implements SocketOptionsHandler.OnReusePortSet.\nfunc (*DefaultSocketOptionsHandler) OnReusePortSet(bool) {}\n+// OnKeepAliveSet implements SocketOptionsHandler.OnKeepAliveSet.\n+func (*DefaultSocketOptionsHandler) OnKeepAliveSet(bool) {}\n+\n+// IsListening implements SocketOptionsHandler.IsListening.\n+func (*DefaultSocketOptionsHandler) IsListening() bool { return false }\n+\n// SocketOptions contains all the variables which store values for SOL_SOCKET\n// level options.\n//\n@@ -69,6 +84,10 @@ type SocketOptions struct {\n// reusePortEnabled determines whether to permit multiple sockets to be bound\n// to an identical socket address.\nreusePortEnabled uint32\n+\n+ // keepAliveEnabled determines whether TCP keepalive is enabled for this\n+ // socket.\n+ keepAliveEnabled uint32\n}\n// InitHandler initializes the handler. This must be called before using the\n@@ -136,3 +155,20 @@ func (so *SocketOptions) SetReusePort(v bool) {\nstoreAtomicBool(&so.reusePortEnabled, v)\nso.handler.OnReusePortSet(v)\n}\n+\n+// GetKeepAlive gets value for SO_KEEPALIVE option.\n+func (so *SocketOptions) GetKeepAlive() bool {\n+ return atomic.LoadUint32(&so.keepAliveEnabled) != 0\n+}\n+\n+// SetKeepAlive sets value for SO_KEEPALIVE option.\n+func (so *SocketOptions) SetKeepAlive(v bool) {\n+ storeAtomicBool(&so.keepAliveEnabled, v)\n+ so.handler.OnKeepAliveSet(v)\n+}\n+\n+// GetAcceptConn gets value for SO_ACCEPTCONN option.\n+func (so *SocketOptions) GetAcceptConn() bool {\n+ // This option is completely endpoint dependent and unsettable.\n+ return so.handler.IsListening()\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -708,10 +708,6 @@ const (\n// TCP, it determines if the Nagle algorithm is on or off.\nDelayOption\n- // KeepaliveEnabledOption is used by SetSockOptBool/GetSockOptBool to\n- // specify whether TCP keepalive is enabled for this socket.\n- KeepaliveEnabledOption\n-\n// MulticastLoopOption is used by SetSockOptBool/GetSockOptBool to\n// specify whether multicast packets sent over a non-loopback interface\n// will be looped back.\n@@ -747,10 +743,6 @@ const (\n// endpoint that all packets being written have an IP header and the\n// endpoint should not attach an IP header.\nIPHdrIncludedOption\n-\n- // AcceptConnOption is used by GetSockOptBool to indicate if the\n- // socket is a listening socket.\n- AcceptConnOption\n)\n// SockOptInt represents socket options which values have the int type.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -383,14 +383,8 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- switch opt {\n- case tcpip.KeepaliveEnabledOption, tcpip.AcceptConnOption:\n- return false, nil\n-\n- default:\nreturn false, tcpip.ErrUnknownProtocolOption\n}\n-}\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint.go", "new_path": "pkg/tcpip/transport/packet/endpoint.go", "diff": "@@ -395,13 +395,8 @@ func (ep *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (*endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- switch opt {\n- case tcpip.AcceptConnOption:\n- return false, nil\n- default:\nreturn false, tcpip.ErrNotSupported\n}\n-}\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (ep *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -607,9 +607,6 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\nswitch opt {\n- case tcpip.KeepaliveEnabledOption, tcpip.AcceptConnOption:\n- return false, nil\n-\ncase tcpip.IPHdrIncludedOption:\ne.mu.Lock()\nv := e.hdrIncluded\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -1284,7 +1284,7 @@ func (e *endpoint) keepaliveTimerExpired() *tcpip.Error {\nuserTimeout := e.userTimeout\ne.keepalive.Lock()\n- if !e.keepalive.enabled || !e.keepalive.timer.checkExpiration() {\n+ if !e.SocketOptions().GetKeepAlive() || !e.keepalive.timer.checkExpiration() {\ne.keepalive.Unlock()\nreturn nil\n}\n@@ -1321,7 +1321,7 @@ func (e *endpoint) resetKeepaliveTimer(receivedData bool) {\n}\n// Start the keepalive timer IFF it's enabled and there is no pending\n// data to send.\n- if !e.keepalive.enabled || e.snd == nil || e.snd.sndUna != e.snd.sndNxt {\n+ if !e.SocketOptions().GetKeepAlive() || e.snd == nil || e.snd.sndUna != e.snd.sndNxt {\ne.keepalive.timer.disable()\ne.keepalive.Unlock()\nreturn\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -851,7 +851,6 @@ func (e *endpoint) recentTimestamp() uint32 {\n// +stateify savable\ntype keepalive struct {\nsync.Mutex `state:\"nosave\"`\n- enabled bool\nidle time.Duration\ninterval time.Duration\ncount int\n@@ -1643,6 +1642,11 @@ func (e *endpoint) OnReusePortSet(v bool) {\ne.UnlockUser()\n}\n+// OnKeepAliveSet implements tcpip.SocketOptionsHandler.OnKeepAliveSet.\n+func (e *endpoint) OnKeepAliveSet(v bool) {\n+ e.notifyProtocolGoroutine(notifyKeepaliveChanged)\n+}\n+\n// SetSockOptBool sets a socket option.\nfunc (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\nswitch opt {\n@@ -1669,12 +1673,6 @@ func (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\ne.sndWaker.Assert()\n}\n- case tcpip.KeepaliveEnabledOption:\n- e.keepalive.Lock()\n- e.keepalive.enabled = v\n- e.keepalive.Unlock()\n- e.notifyProtocolGoroutine(notifyKeepaliveChanged)\n-\ncase tcpip.QuickAckOption:\no := uint32(1)\nif v {\n@@ -1980,6 +1978,13 @@ func (e *endpoint) readyReceiveSize() (int, *tcpip.Error) {\nreturn e.rcvBufUsed, nil\n}\n+// IsListening implements tcpip.SocketOptionsHandler.IsListening.\n+func (e *endpoint) IsListening() bool {\n+ e.LockUser()\n+ defer e.UnlockUser()\n+ return e.EndpointState() == StateListen\n+}\n+\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\nswitch opt {\n@@ -1990,13 +1995,6 @@ func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\ncase tcpip.DelayOption:\nreturn atomic.LoadUint32(&e.delay) != 0, nil\n- case tcpip.KeepaliveEnabledOption:\n- e.keepalive.Lock()\n- v := e.keepalive.enabled\n- e.keepalive.Unlock()\n-\n- return v, nil\n-\ncase tcpip.QuickAckOption:\nv := atomic.LoadUint32(&e.slowAck) == 0\nreturn v, nil\n@@ -2016,12 +2014,6 @@ func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\ncase tcpip.MulticastLoopOption:\nreturn true, nil\n- case tcpip.AcceptConnOption:\n- e.LockUser()\n- defer e.UnlockUser()\n-\n- return e.EndpointState() == StateListen, nil\n-\ndefault:\nreturn false, tcpip.ErrUnknownProtocolOption\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -4984,9 +4984,7 @@ func TestKeepalive(t *testing.T) {\nif err := c.EP.SetSockOptInt(tcpip.KeepaliveCountOption, 5); err != nil {\nt.Fatalf(\"c.EP.SetSockOptInt(tcpip.KeepaliveCountOption, 5): %s\", err)\n}\n- if err := c.EP.SetSockOptBool(tcpip.KeepaliveEnabledOption, true); err != nil {\n- t.Fatalf(\"c.EP.SetSockOptBool(tcpip.KeepaliveEnabledOption, true): %s\", err)\n- }\n+ c.EP.SocketOptions().SetKeepAlive(true)\n// 5 unacked keepalives are sent. ACK each one, and check that the\n// connection stays alive after 5.\n@@ -7236,9 +7234,7 @@ func TestKeepaliveWithUserTimeout(t *testing.T) {\nif err := c.EP.SetSockOptInt(tcpip.KeepaliveCountOption, 10); err != nil {\nt.Fatalf(\"c.EP.SetSockOptInt(tcpip.KeepaliveCountOption, 10): %s\", err)\n}\n- if err := c.EP.SetSockOptBool(tcpip.KeepaliveEnabledOption, true); err != nil {\n- t.Fatalf(\"c.EP.SetSockOptBool(tcpip.KeepaliveEnabledOption, true): %s\", err)\n- }\n+ c.EP.SocketOptions().SetKeepAlive(true)\n// Set userTimeout to be the duration to be 1 keepalive\n// probes. Which means that after the first probe is sent\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -849,9 +849,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\nswitch opt {\n- case tcpip.KeepaliveEnabledOption:\n- return false, nil\n-\ncase tcpip.MulticastLoopOption:\ne.mu.RLock()\nv := e.multicastLoop\n@@ -893,9 +890,6 @@ func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\nreturn v, nil\n- case tcpip.AcceptConnOption:\n- return false, nil\n-\ndefault:\nreturn false, tcpip.ErrUnknownProtocolOption\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_generic.cc", "new_path": "test/syscalls/linux/socket_generic.cc", "diff": "@@ -819,8 +819,8 @@ TEST_P(AllSocketPairTest, GetSockoptProtocol) {\n}\nTEST_P(AllSocketPairTest, SetAndGetBooleanSocketOptions) {\n- int sock_opts[] = {SO_BROADCAST, SO_PASSCRED, SO_NO_CHECK, SO_REUSEADDR,\n- SO_REUSEPORT};\n+ int sock_opts[] = {SO_BROADCAST, SO_PASSCRED, SO_NO_CHECK,\n+ SO_REUSEADDR, SO_REUSEPORT, SO_KEEPALIVE};\nfor (int sock_opt : sock_opts) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nint enable = -1;\n" } ]
Go
Apache License 2.0
google/gvisor
[netstack] Move SO_KEEPALIVE and SO_ACCEPTCONN option to SocketOptions. PiperOrigin-RevId: 343217712
260,019
19.11.2020 17:58:24
-28,800
4f79706ccdc8b6515ad384c5f1896f5405e9d445
arm64 tlb: add support for tlbi-vale1ls/tlbi-aside1ls This patch adds support for tlbi-vale1ls/tlbi-aside1ls. And make the code consistent with the flush strategy of the x86 platform.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/kernel_arm64.go", "new_path": "pkg/sentry/platform/ring0/kernel_arm64.go", "diff": "@@ -53,7 +53,7 @@ func IsCanonical(addr uint64) bool {\nfunc (c *CPU) SwitchToUser(switchOpts SwitchOpts) (vector Vector) {\nstoreAppASID(uintptr(switchOpts.UserASID))\nif switchOpts.Flush {\n- FlushTlbAll()\n+ FlushTlbByASID(uintptr(switchOpts.UserASID))\n}\nregs := switchOpts.Registers\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/lib_arm64.go", "new_path": "pkg/sentry/platform/ring0/lib_arm64.go", "diff": "@@ -22,7 +22,13 @@ func storeAppASID(asid uintptr)\n// LocalFlushTlbAll same as FlushTlbAll, but only applies to the calling CPU.\nfunc LocalFlushTlbAll()\n-// FlushTlbAll flush all tlb.\n+// FlushTlbByVA invalidates tlb by VA/Last-level/Inner-Shareable.\n+func FlushTlbByVA(addr uintptr)\n+\n+// FlushTlbByASID invalidates tlb by ASID/Inner-Shareable.\n+func FlushTlbByASID(asid uintptr)\n+\n+// FlushTlbAll invalidates all tlb.\nfunc FlushTlbAll()\n// CPACREL1 returns the value of the CPACR_EL1 register.\n" } ]
Go
Apache License 2.0
google/gvisor
arm64 tlb: add support for tlbi-vale1ls/tlbi-aside1ls This patch adds support for tlbi-vale1ls/tlbi-aside1ls. And make the code consistent with the flush strategy of the x86 platform. Signed-off-by: Robin Luk <[email protected]>
260,003
19.11.2020 08:54:25
28,800
e8df1ccef91993be379021aec5e771577f8d9196
Fix some code not using NewPacketBuffer for creating a PacketBuffer.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp_test.go", "new_path": "pkg/tcpip/network/arp/arp_test.go", "diff": "@@ -319,9 +319,9 @@ func TestDirectRequestWithNeighborCache(t *testing.T) {\ncopy(h.HardwareAddressSender(), test.senderLinkAddr)\ncopy(h.ProtocolAddressSender(), test.senderAddr)\ncopy(h.ProtocolAddressTarget(), test.targetAddr)\n- c.linkEP.InjectInbound(arp.ProtocolNumber, &stack.PacketBuffer{\n+ c.linkEP.InjectInbound(arp.ProtocolNumber, stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: v.ToVectorisedView(),\n- })\n+ }))\nif !test.isValid {\n// No packets should be sent after receiving an invalid ARP request.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -333,9 +333,9 @@ func TestNeighorSolicitationWithSourceLinkLayerOptionUsingNeighborCache(t *testi\nt.Fatalf(\"got invalid = %d, want = 0\", got)\n}\n- e.InjectInbound(ProtocolNumber, &stack.PacketBuffer{\n+ e.InjectInbound(ProtocolNumber, stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: hdr.View().ToVectorisedView(),\n- })\n+ }))\nneighbors, err := s.Neighbors(nicID)\nif err != nil {\n@@ -912,9 +912,9 @@ func TestNeighorAdvertisementWithTargetLinkLayerOptionUsingNeighborCache(t *test\nt.Fatalf(\"got invalid = %d, want = 0\", got)\n}\n- e.InjectInbound(ProtocolNumber, &stack.PacketBuffer{\n+ e.InjectInbound(ProtocolNumber, stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: hdr.View().ToVectorisedView(),\n- })\n+ }))\nneighbors, err := s.Neighbors(nicID)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix some code not using NewPacketBuffer for creating a PacketBuffer. PiperOrigin-RevId: 343299993
259,927
19.11.2020 09:24:42
28,800
332671c33969c067398702f61071b004b988b24b
Remove unused NoChecksumOption Migration to unified socket options left this behind.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -713,10 +713,6 @@ const (\n// will be looped back.\nMulticastLoopOption\n- // NoChecksumOption is used by SetSockOptBool/GetSockOptBool to specify\n- // whether UDP checksum is disabled for this socket.\n- NoChecksumOption\n-\n// QuickAckOption is stubbed out in SetSockOptBool/GetSockOptBool.\nQuickAckOption\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unused NoChecksumOption Migration to unified socket options left this behind. PiperOrigin-RevId: 343305434
259,992
19.11.2020 15:08:47
28,800
209a95a35a2e4d38998962f6a351766e816805d8
Propagate IP address prefix from host to netstack Closes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -1118,6 +1118,16 @@ func (s *Stack) AddAddress(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber,\nreturn s.AddAddressWithOptions(id, protocol, addr, CanBePrimaryEndpoint)\n}\n+// AddAddressWithPrefix is the same as AddAddress, but allows you to specify\n+// the address prefix.\n+func (s *Stack) AddAddressWithPrefix(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.AddressWithPrefix) *tcpip.Error {\n+ ap := tcpip.ProtocolAddress{\n+ Protocol: protocol,\n+ AddressWithPrefix: addr,\n+ }\n+ return s.AddProtocolAddressWithOptions(id, ap, CanBePrimaryEndpoint)\n+}\n+\n// AddProtocolAddress adds a new network-layer protocol address to the\n// specified NIC.\nfunc (s *Stack) AddProtocolAddress(id tcpip.NICID, protocolAddress tcpip.ProtocolAddress) *tcpip.Error {\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -40,9 +40,9 @@ var (\n// \"::1/8\" on \"lo\" interface.\nDefaultLoopbackLink = LoopbackLink{\nName: \"lo\",\n- Addresses: []net.IP{\n- net.IP(\"\\x7f\\x00\\x00\\x01\"),\n- net.IPv6loopback,\n+ Addresses: []IPWithPrefix{\n+ {Address: net.IP(\"\\x7f\\x00\\x00\\x01\"), PrefixLen: 8},\n+ {Address: net.IPv6loopback, PrefixLen: 128},\n},\nRoutes: []Route{\n{\n@@ -82,7 +82,7 @@ type DefaultRoute struct {\ntype FDBasedLink struct {\nName string\nMTU int\n- Addresses []net.IP\n+ Addresses []IPWithPrefix\nRoutes []Route\nGSOMaxSize uint32\nSoftwareGSOEnabled bool\n@@ -99,7 +99,7 @@ type FDBasedLink struct {\n// LoopbackLink configures a loopback li nk.\ntype LoopbackLink struct {\nName string\n- Addresses []net.IP\n+ Addresses []IPWithPrefix\nRoutes []Route\n}\n@@ -117,6 +117,19 @@ type CreateLinksAndRoutesArgs struct {\nDefaultv6Gateway DefaultRoute\n}\n+// IPWithPrefix is an address with its subnet prefix length.\n+type IPWithPrefix struct {\n+ // Address is a network address.\n+ Address net.IP\n+\n+ // PrefixLen is the subnet prefix length.\n+ PrefixLen int\n+}\n+\n+func (ip IPWithPrefix) String() string {\n+ return fmt.Sprintf(\"%s/%d\", ip.Address, ip.PrefixLen)\n+}\n+\n// Empty returns true if route hasn't been set.\nfunc (r *Route) Empty() bool {\nreturn r.Destination.IP == nil && r.Destination.Mask == nil && r.Gateway == nil\n@@ -264,15 +277,19 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n// createNICWithAddrs creates a NIC in the network stack and adds the given\n// addresses.\n-func (n *Network) createNICWithAddrs(id tcpip.NICID, name string, ep stack.LinkEndpoint, addrs []net.IP) error {\n+func (n *Network) createNICWithAddrs(id tcpip.NICID, name string, ep stack.LinkEndpoint, addrs []IPWithPrefix) error {\nopts := stack.NICOptions{Name: name}\nif err := n.Stack.CreateNICWithOptions(id, sniffer.New(ep), opts); err != nil {\nreturn fmt.Errorf(\"CreateNICWithOptions(%d, _, %+v) failed: %v\", id, opts, err)\n}\nfor _, addr := range addrs {\n- proto, tcpipAddr := ipToAddressAndProto(addr)\n- if err := n.Stack.AddAddress(id, proto, tcpipAddr); err != nil {\n+ proto, tcpipAddr := ipToAddressAndProto(addr.Address)\n+ ap := tcpip.AddressWithPrefix{\n+ Address: tcpipAddr,\n+ PrefixLen: addr.PrefixLen,\n+ }\n+ if err := n.Stack.AddAddressWithPrefix(id, proto, ap); err != nil {\nreturn fmt.Errorf(\"AddAddress(%v, %v, %v) failed: %v\", id, proto, tcpipAddr, err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/network.go", "new_path": "runsc/sandbox/network.go", "diff": "@@ -127,7 +127,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\n// Get all interfaces in the namespace.\nifaces, err := net.Interfaces()\nif err != nil {\n- return fmt.Errorf(\"querying interfaces: %v\", err)\n+ return fmt.Errorf(\"querying interfaces: %w\", err)\n}\nisRoot, err := isRootNS()\n@@ -148,14 +148,14 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\nallAddrs, err := iface.Addrs()\nif err != nil {\n- return fmt.Errorf(\"fetching interface addresses for %q: %v\", iface.Name, err)\n+ return fmt.Errorf(\"fetching interface addresses for %q: %w\", iface.Name, err)\n}\n// We build our own loopback device.\nif iface.Flags&net.FlagLoopback != 0 {\nlink, err := loopbackLink(iface, allAddrs)\nif err != nil {\n- return fmt.Errorf(\"getting loopback link for iface %q: %v\", iface.Name, err)\n+ return fmt.Errorf(\"getting loopback link for iface %q: %w\", iface.Name, err)\n}\nargs.LoopbackLinks = append(args.LoopbackLinks, link)\ncontinue\n@@ -209,7 +209,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\n// Get the link for the interface.\nifaceLink, err := netlink.LinkByName(iface.Name)\nif err != nil {\n- return fmt.Errorf(\"getting link for interface %q: %v\", iface.Name, err)\n+ return fmt.Errorf(\"getting link for interface %q: %w\", iface.Name, err)\n}\nlink.LinkAddress = ifaceLink.Attrs().HardwareAddr\n@@ -219,7 +219,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\nlog.Debugf(\"Creating Channel %d\", i)\nsocketEntry, err := createSocket(iface, ifaceLink, hardwareGSO)\nif err != nil {\n- return fmt.Errorf(\"failed to createSocket for %s : %v\", iface.Name, err)\n+ return fmt.Errorf(\"failed to createSocket for %s : %w\", iface.Name, err)\n}\nif i == 0 {\nlink.GSOMaxSize = socketEntry.gsoMaxSize\n@@ -241,11 +241,12 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\n// Collect the addresses for the interface, enable forwarding,\n// and remove them from the host.\nfor _, addr := range ipAddrs {\n- link.Addresses = append(link.Addresses, addr.IP)\n+ prefix, _ := addr.Mask.Size()\n+ link.Addresses = append(link.Addresses, boot.IPWithPrefix{Address: addr.IP, PrefixLen: prefix})\n// Steal IP address from NIC.\nif err := removeAddress(ifaceLink, addr.String()); err != nil {\n- return fmt.Errorf(\"removing address %v from device %q: %v\", iface.Name, addr, err)\n+ return fmt.Errorf(\"removing address %v from device %q: %w\", addr, iface.Name, err)\n}\n}\n@@ -254,7 +255,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\nlog.Debugf(\"Setting up network, config: %+v\", args)\nif err := conn.Call(boot.NetworkCreateLinksAndRoutes, &args, nil); err != nil {\n- return fmt.Errorf(\"creating links and routes: %v\", err)\n+ return fmt.Errorf(\"creating links and routes: %w\", err)\n}\nreturn nil\n}\n@@ -339,9 +340,15 @@ func loopbackLink(iface net.Interface, addrs []net.Addr) (boot.LoopbackLink, err\nif !ok {\nreturn boot.LoopbackLink{}, fmt.Errorf(\"address is not IPNet: %+v\", addr)\n}\n+\n+ prefix, _ := ipNet.Mask.Size()\n+ link.Addresses = append(link.Addresses, boot.IPWithPrefix{\n+ Address: ipNet.IP,\n+ PrefixLen: prefix,\n+ })\n+\ndst := *ipNet\ndst.IP = dst.IP.Mask(dst.Mask)\n- link.Addresses = append(link.Addresses, ipNet.IP)\nlink.Routes = append(link.Routes, boot.Route{\nDestination: dst,\n})\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -2830,5 +2830,28 @@ INSTANTIATE_TEST_SUITE_P(\n} // namespace\n+// Check that loopback receives connections from any address in the range:\n+// 127.0.0.1 to 127.254.255.255. This behavior is exclusive to IPv4.\n+TEST_F(SocketInetLoopbackTest, LoopbackAddressRangeConnect) {\n+ TestAddress const& listener = V4Any();\n+\n+ in_addr_t addresses[] = {\n+ INADDR_LOOPBACK,\n+ INADDR_LOOPBACK + 1, // 127.0.0.2\n+ (in_addr_t)0x7f000101, // 127.0.1.1\n+ (in_addr_t)0x7f010101, // 127.1.1.1\n+ (in_addr_t)0x7ffeffff, // 127.254.255.255\n+ };\n+ for (const auto& address : addresses) {\n+ TestAddress connector(\"V4Loopback\");\n+ connector.addr.ss_family = AF_INET;\n+ connector.addr_len = sizeof(sockaddr_in);\n+ reinterpret_cast<sockaddr_in*>(&connector.addr)->sin_addr.s_addr =\n+ htonl(address);\n+\n+ tcpSimpleConnectTest(listener, connector, true);\n+ }\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Propagate IP address prefix from host to netstack Closes #4022 PiperOrigin-RevId: 343378647
260,024
19.11.2020 15:14:12
28,800
49adf36ed7d301e8cbd312eaa69ef915731c9d03
Fix possible panic due to bad data. Found by a Fuzzer. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -1140,6 +1140,12 @@ func handleTimestamp(tsOpt header.IPv4OptionTimestamp, localAddress tcpip.Addres\n}\npointer := tsOpt.Pointer()\n+ // RFC 791 page 22 states: \"The smallest legal value is 5.\"\n+ // Since the pointer is 1 based, and the header is 4 bytes long the\n+ // pointer must point beyond the header therefore 4 or less is bad.\n+ if pointer <= header.IPv4OptionTimestampHdrLength {\n+ return header.IPv4OptTSPointerOffset, errIPv4TimestampOptInvalidPointer\n+ }\n// To simplify processing below, base further work on the array of timestamps\n// beyond the header, rather than on the whole option. Also to aid\n// calculations set 'nextSlot' to be 0 based as in the packet it is 1 based.\n@@ -1226,7 +1232,15 @@ func handleRecordRoute(rrOpt header.IPv4OptionRecordRoute, localAddress tcpip.Ad\nreturn header.IPv4OptionLengthOffset, errIPv4RecordRouteOptInvalidLength\n}\n- nextSlot := rrOpt.Pointer() - 1 // Pointer is 1 based.\n+ pointer := rrOpt.Pointer()\n+ // RFC 791 page 20 states:\n+ // The pointer is relative to this option, and the\n+ // smallest legal value for the pointer is 4.\n+ // Since the pointer is 1 based, and the header is 3 bytes long the\n+ // pointer must point beyond the header therefore 3 or less is bad.\n+ if pointer <= header.IPv4OptionRecordRouteHdrLength {\n+ return header.IPv4OptRRPointerOffset, errIPv4RecordRouteOptInvalidPointer\n+ }\n// RFC 791 page 21 says\n// If the route data area is already full (the pointer exceeds the\n@@ -1241,14 +1255,14 @@ func handleRecordRoute(rrOpt header.IPv4OptionRecordRoute, localAddress tcpip.Ad\n// do this (as do most implementations). It is probable that the inclusion\n// of these words is a copy/paste error from the timestamp option where\n// there are two failure reasons given.\n- if nextSlot >= optlen {\n+ if pointer > optlen {\nreturn 0, nil\n}\n// The data area isn't full but there isn't room for a new entry.\n// Either Length or Pointer could be bad. We must select Pointer for Linux\n- // compatibility, even if only the length is bad.\n- if nextSlot+header.IPv4AddressSize > optlen {\n+ // compatibility, even if only the length is bad. NB. pointer is 1 based.\n+ if pointer+header.IPv4AddressSize > optlen+1 {\nif false {\n// This is what we would do if we were not being Linux compatible.\n// Check for bad pointer or length value. Must be a multiple of 4 after\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -661,6 +661,56 @@ func TestIPv4Sanity(t *testing.T) {\n0x00, 0xad, 0x1c, 0x40, // time we expect from fakeclock\n},\n},\n+ {\n+ // Timestamp pointer uses one based counting so 0 is invalid.\n+ name: \"timestamp pointer invalid\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{\n+ 68, 8, 0, 0x00,\n+ // ^ 0 instead of 5 or more.\n+ 0, 0, 0, 0,\n+ },\n+ shouldFail: true,\n+ expectErrorICMP: true,\n+ ICMPType: header.ICMPv4ParamProblem,\n+ ICMPCode: header.ICMPv4UnusedCode,\n+ paramProblemPointer: header.IPv4MinimumSize + 2,\n+ },\n+ {\n+ // Timestamp pointer cannot be less than 5. It must point past the header\n+ // which is 4 bytes. (1 based counting)\n+ name: \"timestamp pointer too small by 1\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{\n+ 68, 8, header.IPv4OptionTimestampHdrLength, 0x00,\n+ // ^ header is 4 bytes, so 4 should fail.\n+ 0, 0, 0, 0,\n+ },\n+ shouldFail: true,\n+ expectErrorICMP: true,\n+ ICMPType: header.ICMPv4ParamProblem,\n+ ICMPCode: header.ICMPv4UnusedCode,\n+ paramProblemPointer: header.IPv4MinimumSize + 2,\n+ },\n+ {\n+ name: \"valid timestamp pointer\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{\n+ 68, 8, header.IPv4OptionTimestampHdrLength + 1, 0x00,\n+ // ^ header is 4 bytes, so 5 should succeed.\n+ 0, 0, 0, 0,\n+ },\n+ replyOptions: header.IPv4Options{\n+ 68, 8, 9, 0x00,\n+ 0x00, 0xad, 0x1c, 0x40, // time we expect from fakeclock\n+ },\n+ },\n{\n// Needs 8 bytes for a type 1 timestamp but there are only 4 free.\nname: \"bad timer element alignment\",\n@@ -792,7 +842,61 @@ func TestIPv4Sanity(t *testing.T) {\n},\n},\n{\n- // Confirm linux bug for bug compatibility.\n+ // Pointer uses one based counting so 0 is invalid.\n+ name: \"record route pointer zero\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{\n+ 7, 8, 0, // 3 byte header\n+ 0, 0, 0, 0,\n+ 0,\n+ },\n+ shouldFail: true,\n+ expectErrorICMP: true,\n+ ICMPType: header.ICMPv4ParamProblem,\n+ ICMPCode: header.ICMPv4UnusedCode,\n+ paramProblemPointer: header.IPv4MinimumSize + 2,\n+ },\n+ {\n+ // Pointer must be 4 or more as it must point past the 3 byte header\n+ // using 1 based counting. 3 should fail.\n+ name: \"record route pointer too small by 1\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{\n+ 7, 8, header.IPv4OptionRecordRouteHdrLength, // 3 byte header\n+ 0, 0, 0, 0,\n+ 0,\n+ },\n+ shouldFail: true,\n+ expectErrorICMP: true,\n+ ICMPType: header.ICMPv4ParamProblem,\n+ ICMPCode: header.ICMPv4UnusedCode,\n+ paramProblemPointer: header.IPv4MinimumSize + 2,\n+ },\n+ {\n+ // Pointer must be 4 or more as it must point past the 3 byte header\n+ // using 1 based counting. Check 4 passes. (Duplicates \"single\n+ // record route with room\")\n+ name: \"valid record route pointer\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{\n+ 7, 7, header.IPv4OptionRecordRouteHdrLength + 1, // 3 byte header\n+ 0, 0, 0, 0,\n+ 0,\n+ },\n+ replyOptions: header.IPv4Options{\n+ 7, 7, 8, // 3 byte header\n+ 192, 168, 1, 58, // New IP Address.\n+ 0, // padding to multiple of 4 bytes.\n+ },\n+ },\n+ {\n+ // Confirm Linux bug for bug compatibility.\n// Linux returns slot 22 but the error is in slot 21.\nname: \"multiple record route with not enough room\",\nmaxTotalLength: ipv4.MaxTotalSize,\n" } ]
Go
Apache License 2.0
google/gvisor
Fix possible panic due to bad data. Found by a Fuzzer. Reported-by: [email protected] PiperOrigin-RevId: 343379575
260,004
19.11.2020 16:17:03
28,800
4cf7956dde56b29dda4ffd2b8bcb3aa6121c71c3
Add types to parse MLD messages Preparing for upcoming CLs that add MLD functionality. Bug Test: header.TestMLD
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/BUILD", "new_path": "pkg/tcpip/header/BUILD", "diff": "@@ -16,6 +16,7 @@ go_library(\n\"ipv6.go\",\n\"ipv6_extension_headers.go\",\n\"ipv6_fragment.go\",\n+ \"mld.go\",\n\"ndp_neighbor_advert.go\",\n\"ndp_neighbor_solicit.go\",\n\"ndp_options.go\",\n@@ -58,6 +59,7 @@ go_test(\nsrcs = [\n\"eth_test.go\",\n\"ipv6_extension_headers_test.go\",\n+ \"mld_test.go\",\n\"ndp_test.go\",\n],\nlibrary = \":header\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/header/mld.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package header\n+\n+import (\n+ \"encoding/binary\"\n+ \"fmt\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+)\n+\n+const (\n+ // mldMaximumResponseDelayOffset is the offset to the Maximum Response Delay\n+ // field within MLD.\n+ mldMaximumResponseDelayOffset = 0\n+\n+ // mldMulticastAddressOffset is the offset to the Multicast Address field\n+ // within MLD.\n+ mldMulticastAddressOffset = 4\n+)\n+\n+// MLD is a Multicast Listener Discovery message in an ICMPv6 packet.\n+//\n+// MLD will only contain the body of an ICMPv6 packet.\n+//\n+// As per RFC 2710 section 3, MLD messages have the following format (MLD only\n+// holds the bytes after the first four bytes in the diagram below):\n+//\n+// 0 1 2 3\n+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n+// | Type | Code | Checksum |\n+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n+// | Maximum Response Delay | Reserved |\n+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n+// | |\n+// + +\n+// | |\n+// + Multicast Address +\n+// | |\n+// + +\n+// | |\n+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n+type MLD []byte\n+\n+// MaximumResponseDelay returns the Maximum Response Delay.\n+func (m MLD) MaximumResponseDelay() time.Duration {\n+ // As per RFC 2710 section 3.4:\n+ //\n+ // The Maximum Response Delay field is meaningful only in Query\n+ // messages, and specifies the maximum allowed delay before sending a\n+ // responding Report, in units of milliseconds. In all other messages,\n+ // it is set to zero by the sender and ignored by receivers.\n+ return time.Duration(binary.BigEndian.Uint16(m[mldMaximumResponseDelayOffset:])) * time.Millisecond\n+}\n+\n+// SetMaximumResponseDelay sets the Maximum Response Delay field.\n+//\n+// maxRespDelayMS is the value in milliseconds.\n+func (m MLD) SetMaximumResponseDelay(maxRespDelayMS uint16) {\n+ binary.BigEndian.PutUint16(m[mldMaximumResponseDelayOffset:], maxRespDelayMS)\n+}\n+\n+// MulticastAddress returns the Multicast Address.\n+func (m MLD) MulticastAddress() tcpip.Address {\n+ // As per RFC 2710 section 3.5:\n+ //\n+ // In a Query message, the Multicast Address field is set to zero when\n+ // sending a General Query, and set to a specific IPv6 multicast address\n+ // when sending a Multicast-Address-Specific Query.\n+ //\n+ // In a Report or Done message, the Multicast Address field holds a\n+ // specific IPv6 multicast address to which the message sender is\n+ // listening or is ceasing to listen, respectively.\n+ return tcpip.Address(m[mldMulticastAddressOffset:][:IPv6AddressSize])\n+}\n+\n+// SetMulticastAddress sets the Multicast Address field.\n+func (m MLD) SetMulticastAddress(multicastAddress tcpip.Address) {\n+ if n := copy(m[mldMulticastAddressOffset:], multicastAddress); n != IPv6AddressSize {\n+ panic(fmt.Sprintf(\"copied %d bytes, expected to copy %d bytes\", n, IPv6AddressSize))\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/header/mld_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package header\n+\n+import (\n+ \"encoding/binary\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+)\n+\n+func TestMLD(t *testing.T) {\n+ b := []byte{\n+ // Maximum Response Delay\n+ 0, 0,\n+\n+ // Reserved\n+ 0, 0,\n+\n+ // MulticastAddress\n+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6,\n+ }\n+\n+ const maxRespDelay = 513\n+ binary.BigEndian.PutUint16(b, maxRespDelay)\n+\n+ mld := MLD(b)\n+\n+ if got, want := mld.MaximumResponseDelay(), maxRespDelay*time.Millisecond; got != want {\n+ t.Errorf(\"got mld.MaximumResponseDelay() = %s, want = %s\", got, want)\n+ }\n+\n+ const newMaxRespDelay = 1234\n+ mld.SetMaximumResponseDelay(newMaxRespDelay)\n+ if got, want := mld.MaximumResponseDelay(), newMaxRespDelay*time.Millisecond; got != want {\n+ t.Errorf(\"got mld.MaximumResponseDelay() = %s, want = %s\", got, want)\n+ }\n+\n+ if got, want := mld.MulticastAddress(), tcpip.Address([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}); got != want {\n+ t.Errorf(\"got mld.MulticastAddress() = %s, want = %s\", got, want)\n+ }\n+\n+ multicastAddress := tcpip.Address([]byte{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0})\n+ mld.SetMulticastAddress(multicastAddress)\n+ if got := mld.MulticastAddress(); got != multicastAddress {\n+ t.Errorf(\"got mld.MulticastAddress() = %s, want = %s\", got, multicastAddress)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add types to parse MLD messages Preparing for upcoming CLs that add MLD functionality. Bug #4861 Test: header.TestMLD PiperOrigin-RevId: 343391556
259,860
19.11.2020 16:50:25
28,800
d35a25cc887d2b52fb7e11ba23da6324054a43d0
Add a helpful message in stuck task logs. This also makes the formatting nicer; the caller will add ":\n" to the end of the message.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/watchdog/watchdog.go", "new_path": "pkg/sentry/watchdog/watchdog.go", "diff": "@@ -338,6 +338,7 @@ func (w *Watchdog) report(offenders map[*kernel.Task]*offender, newTaskFound boo\ntid := w.k.TaskSet().Root.IDOfTask(t)\nbuf.WriteString(fmt.Sprintf(\"\\tTask tid: %v (goroutine %d), entered RunSys state %v ago.\\n\", tid, t.GoroutineID(), now.Sub(o.lastUpdateTime)))\n}\n+ buf.WriteString(\"Search for 'goroutine <id>' in the stack dump to find the offending goroutine(s)\")\n// Force stack dump only if a new task is detected.\nw.doAction(w.TaskTimeoutAction, newTaskFound, &buf)\n" } ]
Go
Apache License 2.0
google/gvisor
Add a helpful message in stuck task logs. This also makes the formatting nicer; the caller will add ":\n" to the end of the message. PiperOrigin-RevId: 343397099
259,985
19.11.2020 16:57:17
28,800
9c553f2d4e4b0f2c3d296d0dfac6a31579b60347
Remove racy stringification of socket fds from /proc/net/*.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_net.go", "new_path": "pkg/sentry/fsimpl/proc/task_net.go", "diff": "@@ -208,7 +208,7 @@ func (n *netUnixData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nfor _, se := range n.kernel.ListSockets() {\ns := se.SockVFS2\nif !s.TryIncRef() {\n- log.Debugf(\"Couldn't get reference on %v in socket table, racing with destruction?\", s)\n+ // Racing with socket destruction, this is ok.\ncontinue\n}\nif family, _, _ := s.Impl().(socket.SocketVFS2).Type(); family != linux.AF_UNIX {\n@@ -351,7 +351,7 @@ func commonGenerateTCP(ctx context.Context, buf *bytes.Buffer, k *kernel.Kernel,\nfor _, se := range k.ListSockets() {\ns := se.SockVFS2\nif !s.TryIncRef() {\n- log.Debugf(\"Couldn't get reference on %v in socket table, racing with destruction?\", s)\n+ // Racing with socket destruction, this is ok.\ncontinue\n}\nsops, ok := s.Impl().(socket.SocketVFS2)\n@@ -516,7 +516,7 @@ func (d *netUDPData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nfor _, se := range d.kernel.ListSockets() {\ns := se.SockVFS2\nif !s.TryIncRef() {\n- log.Debugf(\"Couldn't get reference on %v in socket table, racing with destruction?\", s)\n+ // Racing with socket destruction, this is ok.\ncontinue\n}\nsops, ok := s.Impl().(socket.SocketVFS2)\n" } ]
Go
Apache License 2.0
google/gvisor
Remove racy stringification of socket fds from /proc/net/*. PiperOrigin-RevId: 343398191
260,019
21.11.2020 14:13:06
-28,800
6a85d13ccf68c5a647683569bdb774bdb79f6872
arm64 kvm: add to ext_dabt injection support If no vild syndrome(data abort outside memslots) was reported by kvm, let userspace to do the ext_dabt injection to bail out this issue.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_amd64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_amd64_unsafe.go", "diff": "@@ -91,6 +91,13 @@ func bluepillSigBus(c *vCPU) {\n}\n}\n+// bluepillHandleEnosys is reponsible for handling enosys error.\n+//\n+//go:nosplit\n+func bluepillHandleEnosys(c *vCPU) {\n+ throw(\"run failed: ENOSYS\")\n+}\n+\n// bluepillReadyStopGuest checks whether the current vCPU is ready for interrupt injection.\n//\n//go:nosplit\n@@ -126,3 +133,10 @@ func bluepillReadyStopGuest(c *vCPU) bool {\n}\nreturn true\n}\n+\n+// bluepillArchHandleExit checks architecture specific exitcode.\n+//\n+//go:nosplit\n+func bluepillArchHandleExit(c *vCPU, context unsafe.Pointer) {\n+ c.die(bluepillArchContext(context), \"unknown\")\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_arm64.go", "new_path": "pkg/sentry/platform/kvm/bluepill_arm64.go", "diff": "@@ -42,6 +42,13 @@ var (\nsErrEsr: _ESR_ELx_SERR_NMI,\n},\n}\n+\n+ // vcpuExtDabt is the event of ext_dabt.\n+ vcpuExtDabt = kvmVcpuEvents{\n+ exception: exception{\n+ extDabtPending: 1,\n+ },\n+ }\n)\n// getTLS returns the value of TPIDR_EL0 register.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go", "diff": "@@ -85,7 +85,7 @@ func bluepillStopGuest(c *vCPU) {\nuintptr(c.fd),\n_KVM_SET_VCPU_EVENTS,\nuintptr(unsafe.Pointer(&vcpuSErrBounce))); errno != 0 {\n- throw(\"sErr injection failed\")\n+ throw(\"bounce sErr injection failed\")\n}\n}\n@@ -93,18 +93,54 @@ func bluepillStopGuest(c *vCPU) {\n//\n//go:nosplit\nfunc bluepillSigBus(c *vCPU) {\n+ // Host must support ARM64_HAS_RAS_EXTN.\nif _, _, errno := syscall.RawSyscall( // escapes: no.\nsyscall.SYS_IOCTL,\nuintptr(c.fd),\n_KVM_SET_VCPU_EVENTS,\nuintptr(unsafe.Pointer(&vcpuSErrNMI))); errno != 0 {\n- throw(\"sErr injection failed\")\n+ if errno == syscall.EINVAL {\n+ throw(\"No ARM64_HAS_RAS_EXTN feature in host.\")\n+ }\n+ throw(\"nmi sErr injection failed\")\n+ }\n+}\n+\n+// bluepillExtDabt is reponsible for injecting external data abort.\n+//\n+//go:nosplit\n+func bluepillExtDabt(c *vCPU) {\n+ if _, _, errno := syscall.RawSyscall( // escapes: no.\n+ syscall.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_SET_VCPU_EVENTS,\n+ uintptr(unsafe.Pointer(&vcpuExtDabt))); errno != 0 {\n+ throw(\"ext_dabt injection failed\")\n}\n}\n+// bluepillHandleEnosys is reponsible for handling enosys error.\n+//\n+//go:nosplit\n+func bluepillHandleEnosys(c *vCPU) {\n+ bluepillExtDabt(c)\n+}\n+\n// bluepillReadyStopGuest checks whether the current vCPU is ready for sError injection.\n//\n//go:nosplit\nfunc bluepillReadyStopGuest(c *vCPU) bool {\nreturn true\n}\n+\n+// bluepillArchHandleExit checks architecture specific exitcode.\n+//\n+//go:nosplit\n+func bluepillArchHandleExit(c *vCPU, context unsafe.Pointer) {\n+ switch c.runData.exitReason {\n+ case _KVM_EXIT_ARM_NISV:\n+ bluepillExtDabt(c)\n+ default:\n+ c.die(bluepillArchContext(context), \"unknown\")\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go", "diff": "@@ -148,6 +148,9 @@ func bluepillHandler(context unsafe.Pointer) {\n// mode and have interrupts disabled.\nbluepillSigBus(c)\ncontinue // Rerun vCPU.\n+ case syscall.ENOSYS:\n+ bluepillHandleEnosys(c)\n+ continue\ndefault:\nthrow(\"run failed\")\n}\n@@ -220,7 +223,7 @@ func bluepillHandler(context unsafe.Pointer) {\nc.die(bluepillArchContext(context), \"entry failed\")\nreturn\ndefault:\n- c.die(bluepillArchContext(context), \"unknown\")\n+ bluepillArchHandleExit(c, context)\nreturn\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm_arm64.go", "new_path": "pkg/sentry/platform/kvm/kvm_arm64.go", "diff": "@@ -49,7 +49,8 @@ type userRegs struct {\ntype exception struct {\nsErrPending uint8\nsErrHasEsr uint8\n- pad [6]uint8\n+ extDabtPending uint8\n+ pad [5]uint8\nsErrEsr uint64\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm_const.go", "new_path": "pkg/sentry/platform/kvm/kvm_const.go", "diff": "@@ -56,6 +56,7 @@ const (\n_KVM_EXIT_FAIL_ENTRY = 0x9\n_KVM_EXIT_INTERNAL_ERROR = 0x11\n_KVM_EXIT_SYSTEM_EVENT = 0x18\n+ _KVM_EXIT_ARM_NISV = 0x1c\n)\n// KVM capability options.\n" } ]
Go
Apache License 2.0
google/gvisor
arm64 kvm: add to ext_dabt injection support If no vild syndrome(data abort outside memslots) was reported by kvm, let userspace to do the ext_dabt injection to bail out this issue. Signed-off-by: Robin Luk <[email protected]>
259,858
23.11.2020 13:36:19
28,800
5d5af881103b784374f7e5231224cacbf19ec2d4
Ignore permission failures in CheckDuplicatesRecursively. Not all files are always accessible by the process itself. This was specifically seen with map_files, but there's no rule that every entry must be accessible by the process itself.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -2478,6 +2478,10 @@ void CheckDuplicatesRecursively(std::string path) {\nabsl::EndsWith(path, \"/net\")) {\nbreak;\n}\n+ // We may also see permission failures traversing some files.\n+ if (errno == EACCES && absl::StartsWith(path, \"/proc/\")) {\n+ break;\n+ }\n// Otherwise, no errors are allowed.\nASSERT_EQ(errno, 0) << path;\n" } ]
Go
Apache License 2.0
google/gvisor
Ignore permission failures in CheckDuplicatesRecursively. Not all files are always accessible by the process itself. This was specifically seen with map_files, but there's no rule that every entry must be accessible by the process itself. PiperOrigin-RevId: 343919117
259,858
23.11.2020 14:15:43
28,800
b6c00520d314811d59485a42c2fba578f34b91ee
Omit sandbox from chown test. This test fails because it must include additional UIDs. Omit the bazel sandbox to ensure that it can function correctly.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -432,6 +432,9 @@ cc_binary(\ntestonly = 1,\nsrcs = [\"chown.cc\"],\nlinkstatic = 1,\n+ # We require additional UIDs for this test, so don't include the bazel\n+ # sandbox as standard.\n+ tags = [\"no-sandbox\"],\ndeps = [\n\"//test/util:capability_util\",\n\"//test/util:file_descriptor\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/chown.cc", "new_path": "test/syscalls/linux/chown.cc", "diff": "@@ -90,6 +90,7 @@ TEST_P(ChownParamTest, ChownFilePermissionDenied) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SETUID)));\nconst auto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileMode(0777));\n+ EXPECT_THAT(chmod(GetAbsoluteTestTmpdir().c_str(), 0777), SyscallSucceeds());\n// Drop privileges and change IDs only in child thread, or else this parent\n// thread won't be able to open some log files after the test ends.\n@@ -119,6 +120,7 @@ TEST_P(ChownParamTest, ChownFileSucceedsAsRoot) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability((CAP_SETUID))));\nconst std::string filename = NewTempAbsPath();\n+ EXPECT_THAT(chmod(GetAbsoluteTestTmpdir().c_str(), 0777), SyscallSucceeds());\nabsl::Notification fileCreated, fileChowned;\n// Change UID only in child thread, or else this parent thread won't be able\n" } ]
Go
Apache License 2.0
google/gvisor
Omit sandbox from chown test. This test fails because it must include additional UIDs. Omit the bazel sandbox to ensure that it can function correctly. PiperOrigin-RevId: 343927190
259,858
23.11.2020 14:16:20
28,800
2320ce5b7d992973182a90b2885e852b2059ee08
Fail gracefully if Docker is not configured with ipv6.
[ { "change_type": "MODIFY", "old_path": "pkg/test/dockerutil/container.go", "new_path": "pkg/test/dockerutil/container.go", "diff": "@@ -17,6 +17,7 @@ package dockerutil\nimport (\n\"bytes\"\n\"context\"\n+ \"errors\"\n\"fmt\"\n\"io/ioutil\"\n\"net\"\n@@ -351,6 +352,9 @@ func (c *Container) SandboxPid(ctx context.Context) (int, error) {\nreturn resp.ContainerJSONBase.State.Pid, nil\n}\n+// ErrNoIP indicates that no IP address is available.\n+var ErrNoIP = errors.New(\"no IP available\")\n+\n// FindIP returns the IP address of the container.\nfunc (c *Container) FindIP(ctx context.Context, ipv6 bool) (net.IP, error) {\nresp, err := c.client.ContainerInspect(ctx, c.id)\n@@ -365,7 +369,7 @@ func (c *Container) FindIP(ctx context.Context, ipv6 bool) (net.IP, error) {\nip = net.ParseIP(resp.NetworkSettings.DefaultNetworkSettings.IPAddress)\n}\nif ip == nil {\n- return net.IP{}, fmt.Errorf(\"invalid IP: %q\", ip)\n+ return net.IP{}, ErrNoIP\n}\nreturn ip, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -89,6 +89,10 @@ func iptablesTest(t *testing.T, test TestCase, ipv6 bool) {\n// Get the container IP.\nip, err := d.FindIP(ctx, ipv6)\nif err != nil {\n+ // If ipv6 is not configured, don't fail.\n+ if ipv6 && err == dockerutil.ErrNoIP {\n+ t.Skipf(\"No ipv6 address is available.\")\n+ }\nt.Fatalf(\"failed to get container IP: %v\", err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fail gracefully if Docker is not configured with ipv6. PiperOrigin-RevId: 343927315
259,858
23.11.2020 14:25:37
28,800
3deb5d0c043dcfd8523425792c6cf8ec13b19868
Fix link against runtime.goyield. This function does not exist in Go 1.13. We need to add an adaptor to build against Go 1.13, which is the default Ubuntu version.
[ { "change_type": "MODIFY", "old_path": "pkg/sync/BUILD", "new_path": "pkg/sync/BUILD", "diff": "@@ -40,6 +40,7 @@ go_library(\n\"race_unsafe.go\",\n\"rwmutex_unsafe.go\",\n\"seqcount.go\",\n+ \"spin_legacy_unsafe.go\",\n\"spin_unsafe.go\",\n\"sync.go\",\n],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sync/spin_legacy_unsafe.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Use of this source code is governed by a BSD-style\n+// license that can be found in the LICENSE file.\n+\n+// +build go1.13\n+// +build !go1.14\n+\n+package sync\n+\n+import (\n+ \"runtime\"\n+ _ \"unsafe\" // for go:linkname\n+)\n+\n+//go:linkname canSpin sync.runtime_canSpin\n+func canSpin(i int) bool\n+\n+//go:linkname doSpin sync.runtime_doSpin\n+func doSpin()\n+\n+func goyield() {\n+ // goyield is not available until Go 1.14.\n+ runtime.Gosched()\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/spin_unsafe.go", "new_path": "pkg/sync/spin_unsafe.go", "diff": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n-// +build go1.13\n+// +build go1.14\n// +build !go1.17\n// Check go:linkname function signatures when updating Go version.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix link against runtime.goyield. This function does not exist in Go 1.13. We need to add an adaptor to build against Go 1.13, which is the default Ubuntu version. PiperOrigin-RevId: 343929132
259,858
23.11.2020 14:43:42
28,800
756bc3e52b2344dc48e0cefb929b0ebf1b9becf6
Clean up build output. This change also simplifies and documents the build_cmd pipeline, and reduces general noise for debugging Makefile issues. It also drops the mapping for /etc/docker/daemon.json, which if it does not exist initially will create this as a directory (causing lots of confusion and breaks).
[ { "change_type": "MODIFY", "old_path": ".gitignore", "new_path": ".gitignore", "diff": "# Generated bazel symlinks.\n/bazel-*\n+# Generated build event file.\n+/.build_events.json\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "# limitations under the License.\n# Helpful pretty-printer.\n-MAKEBANNER := \\033[1;34mmake\\033[0m\n-submake = echo -e '$(MAKEBANNER) $1' >&2; $(MAKE) $1\n+ifeq (0,$(MAKELEVEL))\n+OPENLAST := || (rc=$$?; echo '^^^ +++' >&2; exit $$rc)\n+else\n+OPENLAST :=\n+endif\n+CMDLINE := $(shell cut -d '' -f2- /proc/$$PPID/cmdline | sed 's|\\x00| |g')\n+submake = echo '--- make $1' >&2 && \\\n+ $(MAKE) -s $1 && \\\n+ echo '--- make $(CMDLINE) (resume)' >&2 \\\n+ $(OPENLAST)\n# Described below.\nOPTIONS :=\n@@ -109,6 +117,13 @@ list-images: ## List all available images.\n## convenient entrypoints for testing changes. If you're adding a\n## new subsystem or workflow, consider adding a new target here.\n##\n+## Some targets support a PARTITION (1-indexed) and TOTAL_PARTITIONS\n+## environment variables for high-level test sharding. Unlike most\n+## other variables, these are sourced from the environment.\n+##\n+PARTITION ?= 1\n+TOTAL_PARTITIONS ?= 1\n+\nrunsc: ## Builds the runsc binary.\n@$(call submake,build OPTIONS=\"-c opt\" TARGETS=\"//runsc\")\n.PHONY: runsc\n@@ -156,12 +171,6 @@ syscall-tests: ## Run all system call tests.\n@$(call submake,test TARGETS=\"test/syscalls/...\")\n%-runtime-tests: load-runtimes_%\n-ifeq ($(PARTITION),)\n- @$(eval PARTITION := 1)\n-endif\n-ifeq ($(TOTAL_PARTITIONS),)\n- @$(eval TOTAL_PARTITIONS := 1)\n-endif\n@$(call submake,install-runtime)\n@$(call submake,test-runtime OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\n@@ -233,22 +242,22 @@ iptables-runsc-tests: load-iptables\npacketdrill-tests: load-packetdrill\n@$(call submake,install-runtime RUNTIME=\"packetdrill\")\n- @$(call submake,test-runtime RUNTIME=\"packetdrill\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetdrill, tests(//...))')\")\n+ @$(call submake,test-runtime RUNTIME=\"packetdrill\" TARGETS=\"$(shell $(MAKE) -s query TARGETS='attr(tags, packetdrill, tests(//...))')\")\n.PHONY: packetdrill-tests\npacketimpact-tests: load-packetimpact\n@sudo modprobe iptable_filter\n@sudo modprobe ip6table_filter\n@$(call submake,install-runtime RUNTIME=\"packetimpact\")\n- @$(call submake,test-runtime OPTIONS=\"--jobs=HOST_CPUS*3 --local_test_jobs=HOST_CPUS*3\" RUNTIME=\"packetimpact\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetimpact, tests(//...))')\")\n+ @$(call submake,test-runtime OPTIONS=\"--jobs=HOST_CPUS*3 --local_test_jobs=HOST_CPUS*3\" RUNTIME=\"packetimpact\" TARGETS=\"$(shell $(MAKE) -s query TARGETS='attr(tags, packetimpact, tests(//...))')\")\n.PHONY: packetimpact-tests\n# Specific containerd version tests.\ncontainerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_resolv load-basic_httpd load-basic_ubuntu\n@$(call submake,install-runtime RUNTIME=\"root\")\n- @CONTAINERD_VERSION=$* $(MAKE) sudo TARGETS=\"tools/installers:containerd\"\n- @$(MAKE) sudo TARGETS=\"tools/installers:shim\"\n- @$(MAKE) sudo TARGETS=\"test/root:root_test\" ARGS=\"--runtime=root -test.v\"\n+ @CONTAINERD_VERSION=$* $(MAKE) -s sudo TARGETS=\"tools/installers:containerd\"\n+ @$(MAKE) -s sudo TARGETS=\"tools/installers:shim\"\n+ @$(MAKE) -s sudo TARGETS=\"test/root:root_test\" ARGS=\"--runtime=root -test.v\"\n# Note that we can't run containerd-test-1.1.8 tests here.\n#\n@@ -284,7 +293,7 @@ BENCHMARKS_UPLOAD := false\nBENCHMARKS_OFFICIAL := false\nBENCHMARKS_PLATFORMS := ptrace\nBENCHMARKS_TARGETS := //test/benchmarks/base:startup_test\n-BENCHMARKS_ARGS := -test.bench=.\n+BENCHMARKS_ARGS := -test.bench=. -pprof-cpu -pprof-heap -pprof-heap -pprof-block\ninit-benchmark-table: ## Initializes a BigQuery table with the benchmark schema\n## (see //tools/bigquery/bigquery.go). If the table alread exists, this is a noop.\n@@ -293,27 +302,28 @@ init-benchmark-table: ## Initializes a BigQuery table with the benchmark schema\n.PHONY: init-benchmark-table\nbenchmark-platforms: load-benchmarks-images ## Runs benchmarks for runc and all given platforms in BENCHMARK_PLATFORMS.\n- $(call submake, run-benchmark RUNTIME=\"runc\")\n$(foreach PLATFORM,$(BENCHMARKS_PLATFORMS), \\\n- $(call submake,install-runtime RUNTIME=\"$(PLATFORM)\" ARGS=\"--platform=$(PLATFORM) --vfs2\") && \\\n- $(call submake,run-benchmark RUNTIME=\"$(PLATFORM)\") && \\\n- $(call submake,install-runtime RUNTIME=\"$(PLATFORM)_vfs1\" ARGS=\"--platform=$(PLATFORM)\") && \\\n- $(call submake,run-benchmark RUNTIME=\"$(PLATFORM)_vfs1\") && \\\n+ $(call submake,run-benchmark RUNTIME=\"$(PLATFORM)\" ARGS=\"--platform=$(PLATFORM) --vfs2\") && \\\n+ $(call submake,run-benchmark RUNTIME=\"$(PLATFORM)_vfs1\" ARGS=\"--platform=$(PLATFORM)\") && \\\n) \\\n- true\n+ $(call submake, run-benchmark RUNTIME=\"runc\")\n.PHONY: benchmark-platforms\n-run-benchmark: ## Runs single benchmark and optionally sends data to BigQuery.\n- @set -xeuo pipefail; T=$$(mktemp --tmpdir logs.$(RUNTIME).XXXXXX); \\\n- $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS)\" | tee $$T); \\\n- if [[ \"$(BENCHMARKS_UPLOAD)\" == \"true\" ]]; then \\\n- $(call submake,run TARGETS=tools/parsers:parser ARGS=\"parse --debug --file=$$T \\\n+run-benchmark: load-benchmarks-images ## Runs single benchmark and optionally sends data to BigQuery.\n+ @if [[ \"$(RUNTIME)\" != \"runc\" ]]; then $(call submake,install-runtime ARGS=\"$(ARGS) --profile\"); fi\n+ @T=$$(mktemp --tmpdir logs.$(RUNTIME).XXXXXX); \\\n+ $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS) | tee $$T\"); \\\n+ rc=$$?; \\\n+ if [[ $$rc -eq 0 ]] && [[ \"$(BENCHMARKS_UPLOAD)\" == \"true\" ]]; then \\\n+ $(call submake,run TARGETS=\"tools/parsers:parser\" ARGS=\"parse --debug --file=$$T \\\n--runtime=$(RUNTIME) --suite_name=$(BENCHMARKS_SUITE) \\\n--project=$(BENCHMARKS_PROJECT) --dataset=$(BENCHMARKS_DATASET) \\\n--table=$(BENCHMARKS_TABLE) --official=$(BENCHMARKS_OFFICIAL)\"); \\\nfi; \\\n- rm -rf $$T\n+ rm -rf $$T; \\\n+ exit $$rc\n.PHONY: run-benchmark\n+.PHONY: load-benchmarks-images\n##\n## Website & documentation helpers.\n@@ -419,7 +429,7 @@ RUNTIME_LOG_DIR := $(RUNTIME_DIR)/logs\nRUNTIME_LOGS := $(RUNTIME_LOG_DIR)/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\ndev: ## Installs a set of local runtimes. Requires sudo.\n- @$(call submake,refresh ARGS=\"--net-raw\")\n+ @$(call submake,refresh)\n@$(call submake,configure RUNTIME_NAME=\"$(RUNTIME)\" ARGS=\"--net-raw\")\n@$(call submake,configure RUNTIME_NAME=\"$(RUNTIME)-d\" ARGS=\"--net-raw --debug --strace --log-packets\")\n@$(call submake,configure RUNTIME_NAME=\"$(RUNTIME)-p\" ARGS=\"--net-raw --profile\")\n@@ -433,9 +443,8 @@ refresh: ## Refreshes the runtime binary (for development only). Must have calle\n.PHONY: refresh\ninstall-runtime: ## Installs the runtime for testing. Requires sudo.\n- @$(call submake,refresh ARGS=\"--net-raw --TESTONLY-test-name-env=RUNSC_TEST_NAME $(ARGS)\")\n- @$(call submake,configure RUNTIME_NAME=runsc)\n- @$(call submake,configure RUNTIME_NAME=\"$(RUNTIME)\")\n+ @$(call submake,refresh)\n+ @$(call submake,configure RUNTIME_NAME=\"$(RUNTIME)\" ARGS=\"$(ARGS) --TESTONLY-test-name-env=RUNSC_TEST_NAME\")\n@sudo systemctl restart docker\n@if [[ -f /etc/docker/daemon.json ]]; then \\\nsudo chmod 0755 /etc/docker && \\\n" }, { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -38,6 +38,12 @@ http_archive(\nhttp_archive(\nname = \"bazel_gazelle\",\n+ patch_args = [\"-p1\"],\n+ patches = [\n+ # False positive output complaining about Go logrus versions spam the\n+ # logs. Strip this message in this case. Does not affect control flow.\n+ \"//tools:bazel_gazelle.patch\",\n+ ],\nsha256 = \"b85f48fa105c4403326e9525ad2b2cc437babaa6e15a3fc0b1dbab0ab064bc7c\",\nurls = [\n\"https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.22.2/bazel-gazelle-v0.22.2.tar.gz\",\n" }, { "change_type": "MODIFY", "old_path": "images/Makefile", "new_path": "images/Makefile", "diff": "@@ -36,13 +36,13 @@ list-all-images:\n# Handy wrapper to allow load-all-images, push-all-images, etc.\n%-all-images:\n- @$(MAKE) $(patsubst %,$*-%,$(ALL_IMAGES))\n+ @$(MAKE) -s $(patsubst %,$*-%,$(ALL_IMAGES))\nload-all-images:\n- @$(MAKE) $(patsubst %,load-%,$(ALL_IMAGES))\n+ @$(MAKE) -s $(patsubst %,load-%,$(ALL_IMAGES))\n# Handy wrapper to load specified \"groups\", e.g. load-basic-images, etc.\nload-%-images:\n- @$(MAKE) $(patsubst %,load-%,$(subst /,_,$(subst ./,,$(shell find ./$* -name Dockerfile -exec dirname {} \\;))))\n+ @$(MAKE) -s $(patsubst %,load-%,$(subst /,_,$(subst ./,,$(shell find ./$* -name Dockerfile -exec dirname {} \\;))))\n# tag is a function that returns the tag name, given an image.\n#\n@@ -83,7 +83,7 @@ pull-%:\n# entrypoint, as it should never fail. The local tag should always be set after\n# this returns (either by the pull or the build).\nload-%:\n- $(MAKE) pull-$* || $(MAKE) rebuild-$*\n+ $(MAKE) -s pull-$* || $(MAKE) -s rebuild-$*\ndocker tag $(call remote_image,$*) $(call local_image,$*)\n# push pushes the remote image, after either pulling (to validate that the tag\n" }, { "change_type": "MODIFY", "old_path": "tools/bazel.mk", "new_path": "tools/bazel.mk", "diff": "@@ -36,11 +36,11 @@ DOCKER_PRIVILEGED := --privileged\nBAZEL_CACHE := $(shell readlink -m ~/.cache/bazel/)\nGCLOUD_CONFIG := $(shell readlink -m ~/.config/gcloud/)\nDOCKER_SOCKET := /var/run/docker.sock\n-DOCKER_CONFIG := /etc/docker/daemon.json\n+DOCKER_CONFIG := /etc/docker\n# Bazel flags.\nBAZEL := bazel $(STARTUP_OPTIONS)\n-OPTIONS += --color=no --curses=no\n+BASE_OPTIONS := --color=no --curses=no\n# Basic options.\nUID := $(shell id -u ${USER})\n@@ -81,8 +81,6 @@ endif\n# Add docker passthrough options.\nifneq ($(DOCKER_PRIVILEGED),)\nFULL_DOCKER_RUN_OPTIONS += -v \"$(DOCKER_SOCKET):$(DOCKER_SOCKET)\"\n-# TODO(gvisor.dev/issue/1624): Remove docker config volume. This is required\n-# temporarily for checking VFS1 vs VFS2 by some tests.\nFULL_DOCKER_RUN_OPTIONS += -v \"$(DOCKER_CONFIG):$(DOCKER_CONFIG)\"\nFULL_DOCKER_RUN_OPTIONS += $(DOCKER_PRIVILEGED)\nFULL_DOCKER_EXEC_OPTIONS += $(DOCKER_PRIVILEGED)\n@@ -161,20 +159,30 @@ bazel-alias: ## Emits an alias that can be used within the shell.\n.PHONY: bazel-alias\nbazel-server: ## Ensures that the server exists. Used as an internal target.\n- @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) true || $(MAKE) bazel-server-start\n+ @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) true >&2 || $(MAKE) bazel-server-start >&2\n.PHONY: bazel-server\n-build_cmd = docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c '$(BAZEL) build $(OPTIONS) \"$(TARGETS)\"'\n+# build_cmd builds the given targets in the bazel-server container.\n+build_cmd = docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c \\\n+ '$(BAZEL) build $(BASE_OPTIONS) $(OPTIONS) \"$(TARGETS)\"'\n-build_paths = $(build_cmd) 2>&1 \\\n- | tee /proc/self/fd/2 \\\n+# build_paths extracts the built binary from the bazel stderr output.\n+#\n+# This could be alternately done by parsing the bazel build event stream, but\n+# this is a complex schema, and begs the question: what will build the thing\n+# that parses the output? Bazel? Do we need a separate bootstrapping build\n+# command here? Yikes, let's just stick with the ugly shell pipeline.\n+#\n+# The last line is used to prevent terminal shenanigans.\n+build_paths = command_line=$$( $(build_cmd) 2>&1 \\\n| grep -A1 -E '^Target' \\\n| grep -E '^ ($(subst $(SPACE),|,$(BUILD_ROOTS)))' \\\n| sed \"s/ /\\n/g\" \\\n| strings -n 10 \\\n| awk '{$$1=$$1};1' \\\n| xargs -n 1 -I {} readlink -f \"{}\" \\\n- | xargs -n 1 -I {} sh -c \"$(1)\"\n+ | xargs -n 1 -I {} echo \"$(1)\" ) && \\\n+ (set -xeuo pipefail; eval $${command_line})\nbuild: bazel-server\n@$(call build_cmd)\n@@ -194,12 +202,21 @@ sudo: bazel-server\n@$(call build_paths,sudo -E {} $(ARGS))\n.PHONY: sudo\n-test: OPTIONS += --test_output=errors --keep_going --verbose_failures=true\ntest: bazel-server\n- @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) $(BAZEL) test $(OPTIONS) $(TARGETS)\n+ @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) \\\n+ $(BAZEL) test $(BASE_OPTIONS) \\\n+ --test_output=errors --keep_going --verbose_failures=true \\\n+ --build_event_json_file=.build_events.json \\\n+ $(OPTIONS) $(TARGETS)\n.PHONY: test\n-query:\n- @$(MAKE) bazel-server >&2 # If we need to start, ensure stdout is not polluted.\n- @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c '$(BAZEL) query $(OPTIONS) \"$(TARGETS)\" 2>/dev/null'\n+testlogs:\n+ @cat .build_events.json | jq -r \\\n+ 'select(.testSummary?.overallStatus? | tostring | test(\"(FAILED|FLAKY|TIMEOUT)\")) | .testSummary.failed | .[] | .uri' | \\\n+ awk -Ffile:// '{print $2;}'\n+.PHONY: testlogs\n+\n+query: bazel-server\n+ @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c \\\n+ '$(BAZEL) query $(BASE_OPTIONS) $(OPTIONS) \"$(TARGETS)\" 2>/dev/null'\n.PHONY: query\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/bazel_gazelle.patch", "diff": "+diff -r -u2 a/language/go/resolve.go b/language/go/resolve.go\n+--- a/language/go/resolve.go 2020-10-02 14:22:18.000000000 -0700\n++++ b/language/go/resolve.go 2020-11-17 19:40:59.770648029 -0800\n+@@ -20,5 +20,4 @@\n+ \"fmt\"\n+ \"go/build\"\n+- \"log\"\n+ \"path\"\n+ \"regexp\"\n+@@ -80,5 +79,5 @@\n+ resolve = ResolveGo\n+ }\n+- deps, errs := imports.Map(func(imp string) (string, error) {\n++ deps, _ := imports.Map(func(imp string) (string, error) {\n+ l, err := resolve(c, ix, rc, imp, from)\n+ if err == skipImportError {\n+@@ -95,7 +94,4 @@\n+ return l.String(), nil\n+ })\n+- for _, err := range errs {\n+- log.Print(err)\n+- }\n+ if !deps.IsEmpty() {\n+ if r.Kind() == \"go_proto_library\" {\n" } ]
Go
Apache License 2.0
google/gvisor
Clean up build output. This change also simplifies and documents the build_cmd pipeline, and reduces general noise for debugging Makefile issues. It also drops the mapping for /etc/docker/daemon.json, which if it does not exist initially will create this as a directory (causing lots of confusion and breaks). PiperOrigin-RevId: 343932456
259,858
23.11.2020 16:02:41
28,800
a94663ee569dd9ae340eb6b58a9a190715e15f57
Fix bad Makefile variable reference.
[ { "change_type": "MODIFY", "old_path": "tools/bazel.mk", "new_path": "tools/bazel.mk", "diff": "@@ -213,7 +213,7 @@ test: bazel-server\ntestlogs:\n@cat .build_events.json | jq -r \\\n'select(.testSummary?.overallStatus? | tostring | test(\"(FAILED|FLAKY|TIMEOUT)\")) | .testSummary.failed | .[] | .uri' | \\\n- awk -Ffile:// '{print $2;}'\n+ awk -Ffile:// '{print $$2;}'\n.PHONY: testlogs\nquery: bazel-server\n" } ]
Go
Apache License 2.0
google/gvisor
Fix bad Makefile variable reference. PiperOrigin-RevId: 343946859
259,885
23.11.2020 17:24:20
28,800
986683124c41e3ba2d24420a95d7cdb945055381
Don't evict gofer.dentries with inotify watches before saving.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -1353,16 +1353,11 @@ func (d *dentry) checkCachingLocked(ctx context.Context) {\nreturn\n}\nif refs > 0 {\n- if d.cached {\n// This isn't strictly necessary (fs.cachedDentries is permitted to\n// contain dentries with non-zero refs, which are skipped by\n- // fs.evictCachedDentryLocked() upon reaching the end of the LRU),\n- // but since we are already holding fs.renameMu for writing we may\n- // as well.\n- d.fs.cachedDentries.Remove(d)\n- d.fs.cachedDentriesLen--\n- d.cached = false\n- }\n+ // fs.evictCachedDentryLocked() upon reaching the end of the LRU), but\n+ // since we are already holding fs.renameMu for writing we may as well.\n+ d.removeFromCacheLocked()\nreturn\n}\n// Deleted and invalidated dentries with zero references are no longer\n@@ -1371,20 +1366,18 @@ func (d *dentry) checkCachingLocked(ctx context.Context) {\nif d.isDeleted() {\nd.watches.HandleDeletion(ctx)\n}\n- if d.cached {\n- d.fs.cachedDentries.Remove(d)\n- d.fs.cachedDentriesLen--\n- d.cached = false\n- }\n+ d.removeFromCacheLocked()\nd.destroyLocked(ctx)\nreturn\n}\n- // If d still has inotify watches and it is not deleted or invalidated, we\n- // cannot cache it and allow it to be evicted. Otherwise, we will lose its\n- // watches, even if a new dentry is created for the same file in the future.\n- // Note that the size of d.watches cannot concurrently transition from zero\n- // to non-zero, because adding a watch requires holding a reference on d.\n+ // If d still has inotify watches and it is not deleted or invalidated, it\n+ // can't be evicted. Otherwise, we will lose its watches, even if a new\n+ // dentry is created for the same file in the future. Note that the size of\n+ // d.watches cannot concurrently transition from zero to non-zero, because\n+ // adding a watch requires holding a reference on d.\nif d.watches.Size() > 0 {\n+ // As in the refs > 0 case, this is not strictly necessary.\n+ d.removeFromCacheLocked()\nreturn\n}\n@@ -1415,6 +1408,15 @@ func (d *dentry) checkCachingLocked(ctx context.Context) {\n}\n}\n+// Preconditions: d.fs.renameMu must be locked for writing.\n+func (d *dentry) removeFromCacheLocked() {\n+ if d.cached {\n+ d.fs.cachedDentries.Remove(d)\n+ d.fs.cachedDentriesLen--\n+ d.cached = false\n+ }\n+}\n+\n// Precondition: fs.renameMu must be locked for writing; it may be temporarily\n// unlocked.\nfunc (fs *filesystem) evictAllCachedDentriesLocked(ctx context.Context) {\n@@ -1428,12 +1430,10 @@ func (fs *filesystem) evictAllCachedDentriesLocked(ctx context.Context) {\n// * fs.cachedDentriesLen != 0.\nfunc (fs *filesystem) evictCachedDentryLocked(ctx context.Context) {\nvictim := fs.cachedDentries.Back()\n- fs.cachedDentries.Remove(victim)\n- fs.cachedDentriesLen--\n- victim.cached = false\n- // victim.refs may have become non-zero from an earlier path resolution\n- // since it was inserted into fs.cachedDentries.\n- if atomic.LoadInt64(&victim.refs) == 0 {\n+ victim.removeFromCacheLocked()\n+ // victim.refs or victim.watches.Size() may have become non-zero from an\n+ // earlier path resolution since it was inserted into fs.cachedDentries.\n+ if atomic.LoadInt64(&victim.refs) == 0 && victim.watches.Size() == 0 {\nif victim.parent != nil {\nvictim.parent.dirMu.Lock()\nif !victim.vfsd.IsDead() {\n" } ]
Go
Apache License 2.0
google/gvisor
Don't evict gofer.dentries with inotify watches before saving. PiperOrigin-RevId: 343959348
260,004
23.11.2020 22:45:42
28,800
ba2d5cb7e1f3ac69a65d0e790f1319082ee01de2
Use time.Duration for IGMP Max Response Time field Bug
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/checker/checker.go", "new_path": "pkg/tcpip/checker/checker.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"encoding/binary\"\n\"reflect\"\n\"testing\"\n+ \"time\"\n\"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -1267,7 +1268,7 @@ func IGMPType(want header.IGMPType) TransportChecker {\n}\n// IGMPMaxRespTime creates a checker that checks the IGMP Max Resp Time field.\n-func IGMPMaxRespTime(want byte) TransportChecker {\n+func IGMPMaxRespTime(want time.Duration) TransportChecker {\nreturn func(t *testing.T, h header.Transport) {\nt.Helper()\n@@ -1276,7 +1277,7 @@ func IGMPMaxRespTime(want byte) TransportChecker {\nt.Fatalf(\"got transport header = %T, want = header.IGMP\", h)\n}\nif got := igmp.MaxRespTime(); got != want {\n- t.Errorf(\"got igmp.MaxRespTime() = %d, want = %d\", got, want)\n+ t.Errorf(\"got igmp.MaxRespTime() = %s, want = %s\", got, want)\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/igmp.go", "new_path": "pkg/tcpip/header/igmp.go", "diff": "@@ -17,6 +17,7 @@ package header\nimport (\n\"encoding/binary\"\n\"fmt\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n@@ -103,7 +104,15 @@ func (b IGMP) SetType(t IGMPType) { b[igmpTypeOffset] = byte(t) }\n// MaxRespTime gets the MaxRespTimeField. This is meaningful only in Membership\n// Query messages, in other cases it is set to 0 by the sender and ignored by\n// the receiver.\n-func (b IGMP) MaxRespTime() byte { return b[igmpMaxRespTimeOffset] }\n+func (b IGMP) MaxRespTime() time.Duration {\n+ // As per RFC 2236 section 2.2,\n+ //\n+ // The Max Response Time field is meaningful only in Membership Query\n+ // messages, and specifies the maximum allowed time before sending a\n+ // responding report in units of 1/10 second. In all other messages, it\n+ // is set to zero by the sender and ignored by receivers.\n+ return DecisecondToDuration(b[igmpMaxRespTimeOffset])\n+}\n// SetMaxRespTime sets the MaxRespTimeField.\nfunc (b IGMP) SetMaxRespTime(m byte) { b[igmpMaxRespTimeOffset] = m }\n@@ -164,3 +173,9 @@ func IGMPCalculateChecksum(h IGMP) uint16 {\nh.SetChecksum(existingXsum)\nreturn xsum\n}\n+\n+// DecisecondToDuration converts a value representing deci-seconds to a\n+// time.Duration.\n+func DecisecondToDuration(ds uint8) time.Duration {\n+ return time.Duration(ds) * time.Second / 10\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/igmp_test.go", "new_path": "pkg/tcpip/header/igmp_test.go", "diff": "@@ -16,6 +16,7 @@ package header_test\nimport (\n\"testing\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -23,9 +24,10 @@ import (\n// TestIGMPHeader tests the functions within header.igmp\nfunc TestIGMPHeader(t *testing.T) {\n+ const maxRespTimeTenthSec = 0xF0\nb := []byte{\n0x11, // IGMP Type, Membership Query\n- 0xF0, // Maximum Response Time\n+ maxRespTimeTenthSec, // Maximum Response Time\n0xC0, 0xC0, // Checksum\n0x01, 0x02, 0x03, 0x04, // Group Address\n}\n@@ -36,8 +38,8 @@ func TestIGMPHeader(t *testing.T) {\nt.Errorf(\"got igmpHeader.Type() = %x, want = %x\", got, want)\n}\n- if got, want := igmpHeader.MaxRespTime(), byte(0xF0); got != want {\n- t.Errorf(\"got igmpHeader.MaxRespTime() = %x, want = %x\", got, want)\n+ if got, want := igmpHeader.MaxRespTime(), header.DecisecondToDuration(maxRespTimeTenthSec); got != want {\n+ t.Errorf(\"got igmpHeader.MaxRespTime() = %s, want = %s\", got, want)\n}\nif got, want := igmpHeader.Checksum(), uint16(0xC0C0); got != want {\n@@ -59,8 +61,8 @@ func TestIGMPHeader(t *testing.T) {\nrespTime := byte(0x02)\nigmpHeader.SetMaxRespTime(respTime)\n- if got := igmpHeader.MaxRespTime(); got != respTime {\n- t.Errorf(\"got igmpHeader.MaxRespTime() = %x, want = %x\", got, respTime)\n+ if got, want := igmpHeader.MaxRespTime(), header.DecisecondToDuration(respTime); got != want {\n+ t.Errorf(\"got igmpHeader.MaxRespTime() = %s, want = %s\", got, want)\n}\nchecksum := uint16(0x0102)\n@@ -99,3 +101,10 @@ func TestIGMPChecksum(t *testing.T) {\nt.Errorf(\"got IGMPCalculateChecksum = %x, want %x\", got, checksum)\n}\n}\n+\n+func TestDecisecondToDuration(t *testing.T) {\n+ const valueInDeciseconds = 5\n+ if got, want := header.DecisecondToDuration(valueInDeciseconds), valueInDeciseconds*time.Second/10; got != want {\n+ t.Fatalf(\"got header.DecisecondToDuration(%d) = %s, want = %s\", valueInDeciseconds, got, want)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/igmp.go", "new_path": "pkg/tcpip/network/ipv4/igmp.go", "diff": "@@ -35,15 +35,18 @@ const (\n// See note on igmpState.igmpV1Present for more detail.\nv1RouterPresentTimeout = 400 * time.Second\n- // v1MaxRespTimeTenthSec from RFC 2236 Section 4, Page 5. \"The IGMPv1 router\n+ // v1MaxRespTime from RFC 2236 Section 4, Page 5. \"The IGMPv1 router\n// will send General Queries with the Max Response Time set to 0. This MUST\n// be interpreted as a value of 100 (10 seconds).\"\n- v1MaxRespTimeTenthSec = 100\n+ //\n+ // Note that the Max Response Time field is a value in units of deciseconds.\n+ v1MaxRespTime = 10 * time.Second\n- // UnsolicitedReportIntervalMaxTenthSec from RFC 2236 Section 8.10, Page 19.\n- // As all IGMP delay timers are set to a random value between 0 and the\n- // interval, this is technically a maximum.\n- UnsolicitedReportIntervalMaxTenthSec = 100\n+ // UnsolicitedReportIntervalMax is the maximum delay between sending\n+ // unsolicited IGMP reports.\n+ //\n+ // Obtained from RFC 2236 Section 8.10, Page 19.\n+ UnsolicitedReportIntervalMax = 10 * time.Second\n)\n// igmpState is the per-interface IGMP state.\n@@ -185,7 +188,7 @@ func (igmp *igmpState) handleIGMP(pkt *stack.PacketBuffer) {\n}\n}\n-func (igmp *igmpState) handleMembershipQuery(groupAddress tcpip.Address, maxRespTime byte) {\n+func (igmp *igmpState) handleMembershipQuery(groupAddress tcpip.Address, maxRespTime time.Duration) {\nigmp.mu.Lock()\ndefer igmp.mu.Unlock()\n@@ -196,7 +199,7 @@ func (igmp *igmpState) handleMembershipQuery(groupAddress tcpip.Address, maxResp\nigmp.mu.igmpV1Job.Cancel()\nigmp.mu.igmpV1Job.Schedule(v1RouterPresentTimeout)\nigmp.mu.igmpV1Present = true\n- maxRespTime = v1MaxRespTimeTenthSec\n+ maxRespTime = v1MaxRespTime\n}\n// IPv4Any is the General Query Address.\n@@ -215,7 +218,7 @@ func (igmp *igmpState) handleMembershipQuery(groupAddress tcpip.Address, maxResp\n// modify IGMP state directly.\n//\n// Precondition: igmp.mu MUST be read locked.\n-func (igmp *igmpState) setDelayTimerForAddressRLocked(groupAddress tcpip.Address, info *membershipInfo, maxRespTime byte) {\n+func (igmp *igmpState) setDelayTimerForAddressRLocked(groupAddress tcpip.Address, info *membershipInfo, maxRespTime time.Duration) {\nif info.state == delayingMember {\n// As per RFC 2236 Section 3, page 3: \"If a timer for the group is already\n// running, it is reset to the random value only if the requested Max\n@@ -352,7 +355,7 @@ func (igmp *igmpState) joinGroup(groupAddress tcpip.Address) *tcpip.Error {\n// it should immediately transmit an unsolicited Version 2 Membership Report\n// for that group\" ... \"it is recommended that it be repeated\"\nigmp.sendReportLocked(groupAddress)\n- igmp.setDelayTimerForAddressRLocked(groupAddress, &info, UnsolicitedReportIntervalMaxTenthSec)\n+ igmp.setDelayTimerForAddressRLocked(groupAddress, &info, UnsolicitedReportIntervalMax)\nigmp.mu.memberships[groupAddress] = info\nreturn nil\n@@ -383,16 +386,7 @@ func (igmp *igmpState) leaveGroup(groupAddress tcpip.Address) {\n}\n// RFC 2236 Section 3, Page 3: The response time is set to a \"random value...\n-// selected from the range (0, Max Response Time]\" where Max Resp Time is given\n-// in units of 1/10 of a second.\n-func (igmp *igmpState) calculateDelayTimerDuration(maxRespTime byte) time.Duration {\n- maxRespTimeDuration := DecisecondToSecond(maxRespTime)\n- return time.Duration(igmp.ep.protocol.stack.Rand().Int63n(int64(maxRespTimeDuration)))\n-}\n-\n-// DecisecondToSecond converts a byte representing deci-seconds to a Duration\n-// type. This helper function exists because the IGMP stack sends and receives\n-// Max Response Times in deci-seconds.\n-func DecisecondToSecond(ds byte) time.Duration {\n- return time.Duration(ds) * time.Second / 10\n+// selected from the range (0, Max Response Time]\".\n+func (igmp *igmpState) calculateDelayTimerDuration(maxRespTime time.Duration) time.Duration {\n+ return time.Duration(igmp.ep.protocol.stack.Rand().Int63n(int64(maxRespTime)))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/igmp_test.go", "new_path": "pkg/tcpip/network/ipv4/igmp_test.go", "diff": "package ipv4_test\nimport (\n+ \"fmt\"\n\"testing\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -35,9 +37,16 @@ const (\n)\nvar (\n- // unsolicitedReportIntervalMax is the maximum amount of time the NIC will\n- // wait before sending an unsolicited report after joining a multicast group.\n- unsolicitedReportIntervalMax = ipv4.DecisecondToSecond(ipv4.UnsolicitedReportIntervalMaxTenthSec)\n+ // unsolicitedReportIntervalMaxTenthSec is the maximum amount of time the NIC\n+ // will wait before sending an unsolicited report after joining a multicast\n+ // group, in deciseconds.\n+ unsolicitedReportIntervalMaxTenthSec = func() uint8 {\n+ const decisecond = time.Second / 10\n+ if ipv4.UnsolicitedReportIntervalMax%decisecond != 0 {\n+ panic(fmt.Sprintf(\"UnsolicitedReportIntervalMax of %d is a lossy conversion to deciseconds\", ipv4.UnsolicitedReportIntervalMax))\n+ }\n+ return uint8(ipv4.UnsolicitedReportIntervalMax / decisecond)\n+ }()\n)\n// validateIgmpPacket checks that a passed PacketInfo is an IPv4 IGMP packet\n@@ -51,7 +60,7 @@ func validateIgmpPacket(t *testing.T, p channel.PacketInfo, remoteAddress tcpip.\nchecker.DstAddr(remoteAddress),\nchecker.IGMP(\nchecker.IGMPType(igmpType),\n- checker.IGMPMaxRespTime(maxRespTime),\n+ checker.IGMPMaxRespTime(header.DecisecondToDuration(maxRespTime)),\nchecker.IGMPGroupAddress(groupAddress),\n),\n)\n@@ -134,7 +143,7 @@ func TestIgmpDisabled(t *testing.T) {\n// Inject a General Membership Query, which is an IGMP Membership Query with\n// a zeroed Group Address (IPv4Any) to verify that it does not reach the\n// handler.\n- createAndInjectIGMPPacket(e, header.IGMPMembershipQuery, ipv4.UnsolicitedReportIntervalMaxTenthSec, header.IPv4Any)\n+ createAndInjectIGMPPacket(e, header.IGMPMembershipQuery, unsolicitedReportIntervalMaxTenthSec, header.IPv4Any)\nif got := s.Stats().IGMP.PacketsReceived.MembershipQuery.Value(); got != 0 {\nt.Fatalf(\"got Membership Queries received = %d, want = 0\", got)\n@@ -161,7 +170,7 @@ func TestIgmpReceivesIGMPMessages(t *testing.T) {\n{\nname: \"General Membership Query\",\nheaderType: header.IGMPMembershipQuery,\n- maxRespTime: ipv4.UnsolicitedReportIntervalMaxTenthSec,\n+ maxRespTime: unsolicitedReportIntervalMaxTenthSec,\ngroupAddress: header.IPv4Any,\nstatCounter: func(stats tcpip.IGMPReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.MembershipQuery\n@@ -234,12 +243,12 @@ func TestIgmpJoinGroup(t *testing.T) {\n}\n// Verify the second Membership Report is sent after a random interval up to\n- // the unsolicitedReportIntervalMax.\n+ // the maximum unsolicited report interval.\np, ok = e.Read()\nif ok {\nt.Fatalf(\"sent unexpected packet, expected V2MembershipReport only after advancing the clock = %+v\", p.Pkt)\n}\n- clock.Advance(unsolicitedReportIntervalMax)\n+ clock.Advance(ipv4.UnsolicitedReportIntervalMax)\np, ok = e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V2MembershipReport\")\n@@ -273,13 +282,13 @@ func TestIgmpLeaveGroup(t *testing.T) {\n}\n// Verify the second Membership Report is sent after a random interval up to\n- // the unsolicitedReportIntervalMax, and is sent to the multicast address\n- // being joined.\n+ // the maximum unsolicited report interval, and is sent to the multicast\n+ // address being joined.\np, ok = e.Read()\nif ok {\nt.Fatalf(\"sent unexpected packet, expected V2MembershipReport only after advancing the clock = %+v\", p.Pkt)\n}\n- clock.Advance(unsolicitedReportIntervalMax)\n+ clock.Advance(ipv4.UnsolicitedReportIntervalMax)\np, ok = e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V2MembershipReport\")\n@@ -334,7 +343,7 @@ func TestIgmpJoinLeaveGroup(t *testing.T) {\n// Wait for the standard IGMP Unsolicited Report Interval duration before\n// verifying that the unsolicited Membership Report was sent after leaving\n// the group.\n- clock.Advance(unsolicitedReportIntervalMax)\n+ clock.Advance(ipv4.UnsolicitedReportIntervalMax)\nif got := s.Stats().IGMP.PacketsSent.V2MembershipReport.Value(); got != 1 {\nt.Fatalf(\"got V2MembershipReport messages sent = %d, want = 1\", got)\n}\n@@ -365,7 +374,7 @@ func TestIgmpMembershipQueryReport(t *testing.T) {\nif ok {\nt.Fatalf(\"sent unexpected packet, expected V2MembershipReport only after advancing the clock = %+v\", p.Pkt)\n}\n- clock.Advance(unsolicitedReportIntervalMax)\n+ clock.Advance(ipv4.UnsolicitedReportIntervalMax)\np, ok = e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V2MembershipReport\")\n@@ -384,7 +393,7 @@ func TestIgmpMembershipQueryReport(t *testing.T) {\nif ok {\nt.Fatalf(\"sent unexpected packet, expected V2MembershipReport only after advancing the clock = %+v\", p.Pkt)\n}\n- clock.Advance(ipv4.DecisecondToSecond(maxRespTimeDS))\n+ clock.Advance(header.DecisecondToDuration(maxRespTimeDS))\np, ok = e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V2MembershipReport\")\n@@ -428,7 +437,7 @@ func TestIgmpMultipleHosts(t *testing.T) {\n// Wait to be sure that no Leave Group messages were sent up to the max\n// unsolicited report interval since it was not the last host to join this\n// group.\n- clock.Advance(unsolicitedReportIntervalMax)\n+ clock.Advance(ipv4.UnsolicitedReportIntervalMax)\nif got := s.Stats().IGMP.PacketsSent.LeaveGroup.Value(); got != 0 {\nt.Fatalf(\"got LeaveGroup messages sent = %d, want = 0\", got)\n}\n@@ -479,7 +488,7 @@ func TestIgmpV1Present(t *testing.T) {\nif ok {\nt.Fatalf(\"sent unexpected packet, expected V1MembershipReport only after advancing the clock = %+v\", p.Pkt)\n}\n- clock.Advance(unsolicitedReportIntervalMax)\n+ clock.Advance(ipv4.UnsolicitedReportIntervalMax)\np, ok = e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V1MembershipReport\")\n" } ]
Go
Apache License 2.0
google/gvisor
Use time.Duration for IGMP Max Response Time field Bug #4682 PiperOrigin-RevId: 343993297
260,004
24.11.2020 01:17:25
28,800
1de08889dfad93734c1ba45e72fedb0b2a974ccc
Deduplicate code in ipv6.protocol
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -273,7 +273,7 @@ func (e *endpoint) Enable() *tcpip.Error {\n}\n// Do not auto-generate an IPv6 link-local address for loopback devices.\n- if e.protocol.autoGenIPv6LinkLocal && !e.nic.IsLoopback() {\n+ if e.protocol.options.AutoGenLinkLocal && !e.nic.IsLoopback() {\n// The valid and preferred lifetime is infinite for the auto-generated\n// link-local address.\ne.mu.ndp.doSLAAC(header.IPv6LinkLocalPrefix.Subnet(), header.NDPInfiniteLifetime, header.NDPInfiniteLifetime)\n@@ -1408,6 +1408,7 @@ var _ fragmentation.TimeoutHandler = (*protocol)(nil)\ntype protocol struct {\nstack *stack.Stack\n+ options Options\nmu struct {\nsync.RWMutex\n@@ -1431,26 +1432,6 @@ type protocol struct {\nforwarding uint32\nfragmentation *fragmentation.Fragmentation\n-\n- // ndpDisp is the NDP event dispatcher that is used to send the netstack\n- // integrator NDP related events.\n- ndpDisp NDPDispatcher\n-\n- // ndpConfigs is the default NDP configurations used by an IPv6 endpoint.\n- ndpConfigs NDPConfigurations\n-\n- // opaqueIIDOpts hold the options for generating opaque interface identifiers\n- // (IIDs) as outlined by RFC 7217.\n- opaqueIIDOpts OpaqueInterfaceIdentifierOptions\n-\n- // tempIIDSeed is used to seed the initial temporary interface identifier\n- // history value used to generate IIDs for temporary SLAAC addresses.\n- tempIIDSeed []byte\n-\n- // autoGenIPv6LinkLocal determines whether or not the stack attempts to\n- // auto-generate an IPv6 link-local address for newly enabled non-loopback\n- // NICs. See the AutoGenIPv6LinkLocal field of Options for more details.\n- autoGenIPv6LinkLocal bool\n}\n// Number returns the ipv6 protocol number.\n@@ -1486,7 +1467,7 @@ func (p *protocol) NewEndpoint(nic stack.NetworkInterface, linkAddrCache stack.L\ne.mu.addressableEndpointState.Init(e)\ne.mu.ndp = ndpState{\nep: e,\n- configs: p.ndpConfigs,\n+ configs: p.options.NDPConfigs,\ndad: make(map[tcpip.Address]dadState),\ndefaultRouters: make(map[tcpip.Address]defaultRouterState),\nonLinkPrefixes: make(map[tcpip.Subnet]onLinkPrefixState),\n@@ -1615,17 +1596,17 @@ type Options struct {\n// NDPConfigs is the default NDP configurations used by interfaces.\nNDPConfigs NDPConfigurations\n- // AutoGenIPv6LinkLocal determines whether or not the stack attempts to\n- // auto-generate an IPv6 link-local address for newly enabled non-loopback\n+ // AutoGenLinkLocal determines whether or not the stack attempts to\n+ // auto-generate a link-local address for newly enabled non-loopback\n// NICs.\n//\n// Note, setting this to true does not mean that a link-local address is\n// assigned right away, or at all. If Duplicate Address Detection is enabled,\n// an address is only assigned if it successfully resolves. If it fails, no\n- // further attempts are made to auto-generate an IPv6 link-local adddress.\n+ // further attempts are made to auto-generate a link-local adddress.\n//\n// The generated link-local address follows RFC 4291 Appendix A guidelines.\n- AutoGenIPv6LinkLocal bool\n+ AutoGenLinkLocal bool\n// NDPDisp is the NDP event dispatcher that an integrator can provide to\n// receive NDP related events.\n@@ -1661,14 +1642,10 @@ func NewProtocolWithOptions(opts Options) stack.NetworkProtocolFactory {\nreturn func(s *stack.Stack) stack.NetworkProtocol {\np := &protocol{\nstack: s,\n+ options: opts,\n+\nids: ids,\nhashIV: hashIV,\n-\n- ndpDisp: opts.NDPDisp,\n- ndpConfigs: opts.NDPConfigs,\n- opaqueIIDOpts: opts.OpaqueIIDOpts,\n- tempIIDSeed: opts.TempIIDSeed,\n- autoGenIPv6LinkLocal: opts.AutoGenIPv6LinkLocal,\n}\np.fragmentation = fragmentation.NewFragmentation(header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, ReassembleTimeout, s.Clock(), p)\np.mu.eps = make(map[*endpoint]struct{})\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp.go", "new_path": "pkg/tcpip/network/ipv6/ndp.go", "diff": "@@ -648,7 +648,7 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\n// Consider DAD to have resolved even if no DAD messages were actually\n// transmitted.\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnDuplicateAddressDetectionStatus(ndp.ep.nic.ID(), addr, true, nil)\n}\n@@ -720,7 +720,7 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\n// integrator know DAD has completed.\ndelete(ndp.dad, addr)\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnDuplicateAddressDetectionStatus(ndp.ep.nic.ID(), addr, dadDone, err)\n}\n@@ -823,7 +823,7 @@ func (ndp *ndpState) stopDuplicateAddressDetection(addr tcpip.Address) {\ndelete(ndp.dad, addr)\n// Let the integrator know DAD did not resolve.\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnDuplicateAddressDetectionStatus(ndp.ep.nic.ID(), addr, false, nil)\n}\n}\n@@ -846,7 +846,7 @@ func (ndp *ndpState) handleRA(ip tcpip.Address, ra header.NDPRouterAdvert) {\n// Only worry about the DHCPv6 configuration if we have an NDPDispatcher as we\n// only inform the dispatcher on configuration changes. We do nothing else\n// with the information.\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nvar configuration DHCPv6ConfigurationFromNDPRA\nswitch {\ncase ra.ManagedAddrConfFlag():\n@@ -903,20 +903,20 @@ func (ndp *ndpState) handleRA(ip tcpip.Address, ra header.NDPRouterAdvert) {\nfor opt, done, _ := it.Next(); !done; opt, done, _ = it.Next() {\nswitch opt := opt.(type) {\ncase header.NDPRecursiveDNSServer:\n- if ndp.ep.protocol.ndpDisp == nil {\n+ if ndp.ep.protocol.options.NDPDisp == nil {\ncontinue\n}\naddrs, _ := opt.Addresses()\n- ndp.ep.protocol.ndpDisp.OnRecursiveDNSServerOption(ndp.ep.nic.ID(), addrs, opt.Lifetime())\n+ ndp.ep.protocol.options.NDPDisp.OnRecursiveDNSServerOption(ndp.ep.nic.ID(), addrs, opt.Lifetime())\ncase header.NDPDNSSearchList:\n- if ndp.ep.protocol.ndpDisp == nil {\n+ if ndp.ep.protocol.options.NDPDisp == nil {\ncontinue\n}\ndomainNames, _ := opt.DomainNames()\n- ndp.ep.protocol.ndpDisp.OnDNSSearchListOption(ndp.ep.nic.ID(), domainNames, opt.Lifetime())\n+ ndp.ep.protocol.options.NDPDisp.OnDNSSearchListOption(ndp.ep.nic.ID(), domainNames, opt.Lifetime())\ncase header.NDPPrefixInformation:\nprefix := opt.Subnet()\n@@ -964,7 +964,7 @@ func (ndp *ndpState) invalidateDefaultRouter(ip tcpip.Address) {\ndelete(ndp.defaultRouters, ip)\n// Let the integrator know a discovered default router is invalidated.\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnDefaultRouterInvalidated(ndp.ep.nic.ID(), ip)\n}\n}\n@@ -976,7 +976,7 @@ func (ndp *ndpState) invalidateDefaultRouter(ip tcpip.Address) {\n//\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) rememberDefaultRouter(ip tcpip.Address, rl time.Duration) {\n- ndpDisp := ndp.ep.protocol.ndpDisp\n+ ndpDisp := ndp.ep.protocol.options.NDPDisp\nif ndpDisp == nil {\nreturn\n}\n@@ -1006,7 +1006,7 @@ func (ndp *ndpState) rememberDefaultRouter(ip tcpip.Address, rl time.Duration) {\n//\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) rememberOnLinkPrefix(prefix tcpip.Subnet, l time.Duration) {\n- ndpDisp := ndp.ep.protocol.ndpDisp\n+ ndpDisp := ndp.ep.protocol.options.NDPDisp\nif ndpDisp == nil {\nreturn\n}\n@@ -1047,7 +1047,7 @@ func (ndp *ndpState) invalidateOnLinkPrefix(prefix tcpip.Subnet) {\ndelete(ndp.onLinkPrefixes, prefix)\n// Let the integrator know a discovered on-link prefix is invalidated.\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnOnLinkPrefixInvalidated(ndp.ep.nic.ID(), prefix)\n}\n}\n@@ -1225,7 +1225,7 @@ func (ndp *ndpState) doSLAAC(prefix tcpip.Subnet, pl, vl time.Duration) {\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) addAndAcquireSLAACAddr(addr tcpip.AddressWithPrefix, configType stack.AddressConfigType, deprecated bool) stack.AddressEndpoint {\n// Inform the integrator that we have a new SLAAC address.\n- ndpDisp := ndp.ep.protocol.ndpDisp\n+ ndpDisp := ndp.ep.protocol.options.NDPDisp\nif ndpDisp == nil {\nreturn nil\n}\n@@ -1272,7 +1272,7 @@ func (ndp *ndpState) generateSLAACAddr(prefix tcpip.Subnet, state *slaacPrefixSt\n}\ndadCounter := state.generationAttempts + state.stableAddr.localGenerationFailures\n- if oIID := ndp.ep.protocol.opaqueIIDOpts; oIID.NICNameFromID != nil {\n+ if oIID := ndp.ep.protocol.options.OpaqueIIDOpts; oIID.NICNameFromID != nil {\naddrBytes = header.AppendOpaqueInterfaceIdentifier(\naddrBytes[:header.IIDOffsetInIPv6Address],\nprefix,\n@@ -1676,7 +1676,7 @@ func (ndp *ndpState) deprecateSLAACAddress(addressEndpoint stack.AddressEndpoint\n}\naddressEndpoint.SetDeprecated(true)\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnAutoGenAddressDeprecated(ndp.ep.nic.ID(), addressEndpoint.AddressWithPrefix())\n}\n}\n@@ -1701,7 +1701,7 @@ func (ndp *ndpState) invalidateSLAACPrefix(prefix tcpip.Subnet, state slaacPrefi\n//\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) cleanupSLAACAddrResourcesAndNotify(addr tcpip.AddressWithPrefix, invalidatePrefix bool) {\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnAutoGenAddressInvalidated(ndp.ep.nic.ID(), addr)\n}\n@@ -1761,7 +1761,7 @@ func (ndp *ndpState) invalidateTempSLAACAddr(tempAddrs map[tcpip.Address]tempSLA\n//\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) cleanupTempSLAACAddrResourcesAndNotify(addr tcpip.AddressWithPrefix, invalidateAddr bool) {\n- if ndpDisp := ndp.ep.protocol.ndpDisp; ndpDisp != nil {\n+ if ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\nndpDisp.OnAutoGenAddressInvalidated(ndp.ep.nic.ID(), addr)\n}\n@@ -2005,7 +2005,7 @@ func (ndp *ndpState) stopSolicitingRouters() {\n// initializeTempAddrState initializes state related to temporary SLAAC\n// addresses.\nfunc (ndp *ndpState) initializeTempAddrState() {\n- header.InitialTempIID(ndp.temporaryIIDHistory[:], ndp.ep.protocol.tempIIDSeed, ndp.ep.nic.ID())\n+ header.InitialTempIID(ndp.temporaryIIDHistory[:], ndp.ep.protocol.options.TempIIDSeed, ndp.ep.nic.ID())\nif MaxDesyncFactor != 0 {\nndp.temporaryAddressDesyncFactor = time.Duration(rand.Int63n(int64(MaxDesyncFactor)))\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -2163,7 +2163,7 @@ func TestNoAutoGenTempAddrForLinkLocal(t *testing.T) {\nAutoGenTempGlobalAddresses: true,\n},\nNDPDisp: &ndpDisp,\n- AutoGenIPv6LinkLocal: true,\n+ AutoGenLinkLocal: true,\n})},\n})\n@@ -4044,7 +4044,7 @@ func TestAutoGenAddrInResponseToDADConflicts(t *testing.T) {\nndpConfigs.AutoGenAddressConflictRetries = maxRetries\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n- AutoGenIPv6LinkLocal: addrType.autoGenLinkLocal,\n+ AutoGenLinkLocal: addrType.autoGenLinkLocal,\nNDPConfigs: ndpConfigs,\nNDPDisp: &ndpDisp,\nOpaqueIIDOpts: ipv6.OpaqueInterfaceIdentifierOptions{\n@@ -4179,7 +4179,7 @@ func TestAutoGenAddrWithEUI64IIDNoDADRetries(t *testing.T) {\ne := channel.New(0, 1280, linkAddr1)\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n- AutoGenIPv6LinkLocal: addrType.autoGenLinkLocal,\n+ AutoGenLinkLocal: addrType.autoGenLinkLocal,\nNDPConfigs: addrType.ndpConfigs,\nNDPDisp: &ndpDisp,\n})},\n@@ -4708,7 +4708,7 @@ func TestCleanupNDPState(t *testing.T) {\n}\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n- AutoGenIPv6LinkLocal: true,\n+ AutoGenLinkLocal: true,\nNDPConfigs: ipv6.NDPConfigurations{\nHandleRAs: true,\nDiscoverDefaultRouters: true,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -2407,7 +2407,7 @@ func TestNICAutoGenLinkLocalAddr(t *testing.T) {\n}\nopts := stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n- AutoGenIPv6LinkLocal: test.autoGen,\n+ AutoGenLinkLocal: test.autoGen,\nNDPDisp: &ndpDisp,\nOpaqueIIDOpts: test.iidOpts,\n})},\n@@ -2502,7 +2502,7 @@ func TestNoLinkLocalAutoGenForLoopbackNIC(t *testing.T) {\nt.Run(test.name, func(t *testing.T) {\nopts := stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n- AutoGenIPv6LinkLocal: true,\n+ AutoGenLinkLocal: true,\nOpaqueIIDOpts: test.opaqueIIDOpts,\n})},\n}\n@@ -2537,7 +2537,7 @@ func TestNICAutoGenAddrDoesDAD(t *testing.T) {\nopts := stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\nNDPConfigs: ndpConfigs,\n- AutoGenIPv6LinkLocal: true,\n+ AutoGenLinkLocal: true,\nNDPDisp: &ndpDisp,\n})},\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/loopback_test.go", "new_path": "pkg/tcpip/tests/integration/loopback_test.go", "diff": "@@ -72,7 +72,7 @@ func TestInitialLoopbackAddresses(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocolWithOptions(ipv6.Options{\nNDPDisp: &ndpDispatcher{},\n- AutoGenIPv6LinkLocal: true,\n+ AutoGenLinkLocal: true,\nOpaqueIIDOpts: ipv6.OpaqueInterfaceIdentifierOptions{\nNICNameFromID: func(nicID tcpip.NICID, nicName string) string {\nt.Fatalf(\"should not attempt to get name for NIC with ID = %d; nicName = %s\", nicID, nicName)\n" } ]
Go
Apache License 2.0
google/gvisor
Deduplicate code in ipv6.protocol PiperOrigin-RevId: 344009602
259,860
24.11.2020 10:37:35
28,800
e5fd23c18d1fd602603babd8297dabf679c336aa
Remove outdated TODO. The bug has been fixed.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -91,9 +91,6 @@ var (\n// noCrashOnVerificationFailure indicates whether the sandbox should panic\n// whenever verification fails. If true, an error is returned instead of\n// panicking. This should only be set for tests.\n- //\n- // TODO(b/165661693): Decide whether to panic or return error based on this\n- // flag.\nnoCrashOnVerificationFailure bool\n// verityMu synchronizes concurrent operations that enable verity and perform\n" } ]
Go
Apache License 2.0
google/gvisor
Remove outdated TODO. The bug has been fixed. PiperOrigin-RevId: 344088206
259,967
24.11.2020 14:20:15
28,800
f90ab60a8a5ce9663a878c7cabcc4ad66922e265
Track number of packets queued to Failed neighbors Add a NIC-specific neighbor table statistic so we can determine how many packets have been queued to Failed neighbors, indicating an unhealthy local network. This change assists us to debug in-field issues where subsequent traffic to a neighbor fails. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -24,9 +24,16 @@ import (\nconst neighborCacheSize = 512 // max entries per interface\n+// NeighborStats holds metrics for the neighbor table.\n+type NeighborStats struct {\n+ // FailedEntryLookups counts the number of lookups performed on an entry in\n+ // Failed state.\n+ FailedEntryLookups *tcpip.StatCounter\n+}\n+\n// neighborCache maps IP addresses to link addresses. It uses the Least\n// Recently Used (LRU) eviction strategy to implement a bounded cache for\n-// dynmically acquired entries. It contains the state machine and configuration\n+// dynamically acquired entries. It contains the state machine and configuration\n// for running Neighbor Unreachability Detection (NUD).\n//\n// There are two types of entries in the neighbor cache:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -87,6 +87,7 @@ func newTestNeighborCache(nudDisp NUDDispatcher, config NUDConfigurations, clock\nnudDisp: nudDisp,\n},\nid: 1,\n+ stats: makeNICStats(),\n},\nstate: NewNUDState(config, rng),\ncache: make(map[tcpip.Address]*neighborEntry, neighborCacheSize),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -347,9 +347,10 @@ func (e *neighborEntry) handlePacketQueuedLocked(localAddr tcpip.Address) {\ne.setStateLocked(Delay)\ne.dispatchChangeEventLocked()\n- case Incomplete, Reachable, Delay, Probe, Static, Failed:\n+ case Incomplete, Reachable, Delay, Probe, Static:\n// Do nothing\n-\n+ case Failed:\n+ e.nic.stats.Neighbor.FailedEntryLookups.Increment()\ndefault:\npanic(fmt.Sprintf(\"Invalid cache entry state: %s\", e.neigh.State))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry_test.go", "new_path": "pkg/tcpip/stack/neighbor_entry_test.go", "diff": "@@ -89,7 +89,7 @@ func eventDiffOptsWithSort() []cmp.Option {\n// | Stale | Reachable | Solicited confirmation w/o address | Notify wakers | Changed |\n// | Stale | Stale | Override confirmation | Update LinkAddr | Changed |\n// | Stale | Stale | Probe w/ different address | Update LinkAddr | Changed |\n-// | Stale | Delay | Packet sent | | Changed |\n+// | Stale | Delay | Packet queued | | Changed |\n// | Delay | Reachable | Upper-layer confirmation | | Changed |\n// | Delay | Reachable | Solicited override confirmation | Update LinkAddr | Changed |\n// | Delay | Reachable | Solicited confirmation w/o address | Notify wakers | Changed |\n@@ -101,6 +101,7 @@ func eventDiffOptsWithSort() []cmp.Option {\n// | Probe | Stale | Probe or confirmation w/ different address | | Changed |\n// | Probe | Probe | Retransmit timer expired | Send probe | Changed |\n// | Probe | Failed | Max probes sent without reply | Notify wakers | Removed |\n+// | Failed | Failed | Packet queued | | |\n// | Failed | | Unreachability timer expired | Delete entry | |\ntype testEntryEventType uint8\n@@ -228,6 +229,7 @@ func entryTestSetup(c NUDConfigurations) (*neighborEntry, *testNUDDispatcher, *e\nclock: clock,\nnudDisp: &disp,\n},\n+ stats: makeNICStats(),\n}\nnic.networkEndpoints = map[tcpip.NetworkProtocolNumber]NetworkEndpoint{\nheader.IPv6ProtocolNumber: (&testIPv6Protocol{}).NewEndpoint(&nic, nil, nil, nil),\n@@ -3433,6 +3435,146 @@ func TestEntryProbeToFailed(t *testing.T) {\nnudDisp.mu.Unlock()\n}\n+func TestEntryFailedToFailed(t *testing.T) {\n+ c := DefaultNUDConfigurations()\n+ c.MaxMulticastProbes = 3\n+ c.MaxUnicastProbes = 3\n+ e, nudDisp, linkRes, clock := entryTestSetup(c)\n+\n+ // Verify the cache contains the entry.\n+ if _, ok := e.nic.neigh.cache[entryTestAddr1]; !ok {\n+ t.Errorf(\"expected entry %q to exist in the neighbor cache\", entryTestAddr1)\n+ }\n+\n+ // TODO(gvisor.dev/issue/4872): Use helper functions to start entry tests in\n+ // their expected state.\n+ e.mu.Lock()\n+ e.handlePacketQueuedLocked(entryTestAddr2)\n+ e.mu.Unlock()\n+\n+ runImmediatelyScheduledJobs(clock)\n+ {\n+ wantProbes := []entryTestProbeInfo{\n+ {\n+ RemoteAddress: entryTestAddr1,\n+ LocalAddress: entryTestAddr2,\n+ },\n+ }\n+ linkRes.mu.Lock()\n+ diff := cmp.Diff(linkRes.probes, wantProbes)\n+ linkRes.probes = nil\n+ linkRes.mu.Unlock()\n+ if diff != \"\" {\n+ t.Fatalf(\"link address resolver probes mismatch (-got, +want):\\n%s\", diff)\n+ }\n+ }\n+\n+ e.mu.Lock()\n+ e.handleConfirmationLocked(entryTestLinkAddr1, ReachabilityConfirmationFlags{\n+ Solicited: false,\n+ Override: false,\n+ IsRouter: false,\n+ })\n+ e.handlePacketQueuedLocked(entryTestAddr2)\n+ e.mu.Unlock()\n+\n+ waitFor := c.DelayFirstProbeTime + c.RetransmitTimer*time.Duration(c.MaxUnicastProbes)\n+ clock.Advance(waitFor)\n+ {\n+ wantProbes := []entryTestProbeInfo{\n+ {\n+ RemoteAddress: entryTestAddr1,\n+ RemoteLinkAddress: entryTestLinkAddr1,\n+ },\n+ {\n+ RemoteAddress: entryTestAddr1,\n+ RemoteLinkAddress: entryTestLinkAddr1,\n+ },\n+ {\n+ RemoteAddress: entryTestAddr1,\n+ RemoteLinkAddress: entryTestLinkAddr1,\n+ },\n+ }\n+ linkRes.mu.Lock()\n+ diff := cmp.Diff(linkRes.probes, wantProbes)\n+ linkRes.mu.Unlock()\n+ if diff != \"\" {\n+ t.Fatalf(\"link address resolver probes mismatch (-got, +want):\\n%s\", diff)\n+ }\n+ }\n+\n+ wantEvents := []testEntryEventInfo{\n+ {\n+ EventType: entryTestAdded,\n+ NICID: entryTestNICID,\n+ Entry: NeighborEntry{\n+ Addr: entryTestAddr1,\n+ LinkAddr: tcpip.LinkAddress(\"\"),\n+ State: Incomplete,\n+ },\n+ },\n+ {\n+ EventType: entryTestChanged,\n+ NICID: entryTestNICID,\n+ Entry: NeighborEntry{\n+ Addr: entryTestAddr1,\n+ LinkAddr: entryTestLinkAddr1,\n+ State: Stale,\n+ },\n+ },\n+ {\n+ EventType: entryTestChanged,\n+ NICID: entryTestNICID,\n+ Entry: NeighborEntry{\n+ Addr: entryTestAddr1,\n+ LinkAddr: entryTestLinkAddr1,\n+ State: Delay,\n+ },\n+ },\n+ {\n+ EventType: entryTestChanged,\n+ NICID: entryTestNICID,\n+ Entry: NeighborEntry{\n+ Addr: entryTestAddr1,\n+ LinkAddr: entryTestLinkAddr1,\n+ State: Probe,\n+ },\n+ },\n+ {\n+ EventType: entryTestRemoved,\n+ NICID: entryTestNICID,\n+ Entry: NeighborEntry{\n+ Addr: entryTestAddr1,\n+ LinkAddr: entryTestLinkAddr1,\n+ State: Probe,\n+ },\n+ },\n+ }\n+ nudDisp.mu.Lock()\n+ if diff := cmp.Diff(nudDisp.events, wantEvents, eventDiffOpts()...); diff != \"\" {\n+ t.Errorf(\"nud dispatcher events mismatch (-got, +want):\\n%s\", diff)\n+ }\n+ nudDisp.mu.Unlock()\n+\n+ failedLookups := e.nic.stats.Neighbor.FailedEntryLookups\n+ if got := failedLookups.Value(); got != 0 {\n+ t.Errorf(\"got Neighbor.FailedEntryLookups = %d, want = 0\", got)\n+ }\n+\n+ e.mu.Lock()\n+ // Verify queuing a packet to the entry immediately fails.\n+ e.handlePacketQueuedLocked(entryTestAddr2)\n+ state := e.neigh.State\n+ e.mu.Unlock()\n+ if state != Failed {\n+ t.Errorf(\"got e.neigh.State = %q, want = %q\", state, Failed)\n+ }\n+\n+ if got := failedLookups.Value(); got != 1 {\n+ t.Errorf(\"got Neighbor.FailedEntryLookups = %d, want = 1\", got)\n+ }\n+}\n+\nfunc TestEntryFailedGetsDeleted(t *testing.T) {\nc := DefaultNUDConfigurations()\nc.MaxMulticastProbes = 3\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -60,12 +60,14 @@ type NIC struct {\n}\n}\n-// NICStats includes transmitted and received stats.\n+// NICStats hold statistics for a NIC.\ntype NICStats struct {\nTx DirectionStats\nRx DirectionStats\nDisabledRx DirectionStats\n+\n+ Neighbor NeighborStats\n}\nfunc makeNICStats() NICStats {\n" } ]
Go
Apache License 2.0
google/gvisor
Track number of packets queued to Failed neighbors Add a NIC-specific neighbor table statistic so we can determine how many packets have been queued to Failed neighbors, indicating an unhealthy local network. This change assists us to debug in-field issues where subsequent traffic to a neighbor fails. Fixes #4819 PiperOrigin-RevId: 344131119
260,024
24.11.2020 15:23:31
28,800
4da63dc82e1a458404f0e30f8bba9391eb7dd806
Report correct pointer value for "bad next header" ICMP error Because the code handles a bad header as "payload" right up to the last moment we need to make sure payload handling does not remove the error information. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers.go", "diff": "@@ -47,6 +47,11 @@ const (\n// IPv6NoNextHeaderIdentifier is the header identifier used to signify the end\n// of an IPv6 payload, as per RFC 8200 section 4.7.\nIPv6NoNextHeaderIdentifier IPv6ExtensionHeaderIdentifier = 59\n+\n+ // IPv6UnknownExtHdrIdentifier is reserved by IANA.\n+ // https://www.iana.org/assignments/ipv6-parameters/ipv6-parameters.xhtml#extension-header\n+ // \"254 Use for experimentation and testing [RFC3692][RFC4727]\"\n+ IPv6UnknownExtHdrIdentifier IPv6ExtensionHeaderIdentifier = 254\n)\nconst (\n@@ -452,9 +457,11 @@ func (i *IPv6PayloadIterator) AsRawHeader(consume bool) IPv6RawPayloadHeader {\n// Since we consume the iterator, we return the payload as is.\nbuf = i.payload\n- // Mark i as done.\n+ // Mark i as done, but keep track of where we were for error reporting.\n*i = IPv6PayloadIterator{\nnextHdrIdentifier: IPv6NoNextHeaderIdentifier,\n+ headerOffset: i.headerOffset,\n+ nextOffset: i.nextOffset,\n}\n} else {\nbuf = i.payload.Clone(nil)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -34,7 +34,9 @@ import (\n)\nconst (\n+ // ReassembleTimeout controls how long a fragment will be held.\n// As per RFC 8200 section 4.5:\n+ //\n// If insufficient fragments are received to complete reassembly of a packet\n// within 60 seconds of the reception of the first-arriving fragment of that\n// packet, reassembly of that packet must be abandoned.\n@@ -1092,9 +1094,16 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\n//\n// Which when taken together indicate that an unknown protocol should\n// be treated as an unrecognized next header value.\n+ // The location of the Next Header field is in a different place in\n+ // the initial IPv6 header than it is in the extension headers so\n+ // treat it specially.\n+ prevHdrIDOffset := uint32(header.IPv6NextHeaderOffset)\n+ if previousHeaderStart != 0 {\n+ prevHdrIDOffset = previousHeaderStart\n+ }\n_ = e.protocol.returnError(&icmpReasonParameterProblem{\ncode: header.ICMPv6UnknownHeader,\n- pointer: it.ParseOffset(),\n+ pointer: prevHdrIDOffset,\n}, pkt)\ndefault:\npanic(fmt.Sprintf(\"unrecognized result from DeliverTransportPacket = %d\", res))\n@@ -1102,12 +1111,11 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\n}\ndefault:\n- _ = e.protocol.returnError(&icmpReasonParameterProblem{\n- code: header.ICMPv6UnknownHeader,\n- pointer: it.ParseOffset(),\n- }, pkt)\n- stats.UnknownProtocolRcvdPackets.Increment()\n- return\n+ // Since the iterator returns IPv6RawPayloadHeader for unknown Extension\n+ // Header IDs this should never happen unless we missed a supported type\n+ // here.\n+ panic(fmt.Sprintf(\"unrecognized type from it.Next() = %T\", extHdr))\n+\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -51,6 +51,7 @@ const (\nfragmentExtHdrID = uint8(header.IPv6FragmentExtHdrIdentifier)\ndestinationExtHdrID = uint8(header.IPv6DestinationOptionsExtHdrIdentifier)\nnoNextHdrID = uint8(header.IPv6NoNextHeaderIdentifier)\n+ unknownHdrID = uint8(header.IPv6UnknownExtHdrIdentifier)\nextraHeaderReserve = 50\n)\n@@ -572,6 +573,33 @@ func TestReceiveIPv6ExtHdrs(t *testing.T) {\nshouldAccept: false,\nexpectICMP: false,\n},\n+ {\n+ name: \"unknown next header (first)\",\n+ extHdr: func(nextHdr uint8) ([]byte, uint8) {\n+ return []byte{\n+ nextHdr, 0, 63, 4, 1, 2, 3, 4,\n+ }, unknownHdrID\n+ },\n+ shouldAccept: false,\n+ expectICMP: true,\n+ ICMPType: header.ICMPv6ParamProblem,\n+ ICMPCode: header.ICMPv6UnknownHeader,\n+ pointer: header.IPv6NextHeaderOffset,\n+ },\n+ {\n+ name: \"unknown next header (not first)\",\n+ extHdr: func(nextHdr uint8) ([]byte, uint8) {\n+ return []byte{\n+ unknownHdrID, 0,\n+ 63, 4, 1, 2, 3, 4,\n+ }, hopByHopExtHdrID\n+ },\n+ shouldAccept: false,\n+ expectICMP: true,\n+ ICMPType: header.ICMPv6ParamProblem,\n+ ICMPCode: header.ICMPv6UnknownHeader,\n+ pointer: header.IPv6FixedHeaderSize,\n+ },\n{\nname: \"destination with unknown option skippable action\",\nextHdr: func(nextHdr uint8) ([]byte, uint8) {\n@@ -754,11 +782,6 @@ func TestReceiveIPv6ExtHdrs(t *testing.T) {\nICMPCode: header.ICMPv6UnknownHeader,\npointer: header.IPv6FixedHeaderSize,\n},\n- {\n- name: \"No next header\",\n- extHdr: func(nextHdr uint8) ([]byte, uint8) { return []byte{}, noNextHdrID },\n- shouldAccept: false,\n- },\n{\nname: \"hopbyhop (with skippable unknown) - routing - atomic fragment - destination (with skippable unknown)\",\nextHdr: func(nextHdr uint8) ([]byte, uint8) {\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/defs.bzl", "new_path": "test/packetimpact/runner/defs.bzl", "diff": "@@ -243,8 +243,6 @@ ALL_TESTS = [\n),\nPacketimpactTestInfo(\nname = \"icmpv6_param_problem\",\n- # TODO(b/153485026): Fix netstack then remove the line below.\n- expect_netstack_failure = True,\n),\nPacketimpactTestInfo(\nname = \"ipv6_unknown_options_action\",\n" } ]
Go
Apache License 2.0
google/gvisor
Report correct pointer value for "bad next header" ICMP error Because the code handles a bad header as "payload" right up to the last moment we need to make sure payload handling does not remove the error information. Fixes #4909 PiperOrigin-RevId: 344141690
259,967
24.11.2020 15:35:47
28,800
99f2d0ea2f2ec7a9758584d53db64008be33fac4
Correctly lock when removing neighbor entries Fix a panic when two entries in Failed state are removed at the same time.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -233,6 +233,8 @@ func (n *neighborCache) addStaticEntry(addr tcpip.Address, linkAddr tcpip.LinkAd\n}\n// removeEntryLocked removes the specified entry from the neighbor cache.\n+//\n+// Prerequisite: n.mu and entry.mu MUST be locked.\nfunc (n *neighborCache) removeEntryLocked(entry *neighborEntry) {\nif entry.neigh.State != Static {\nn.dynamic.lru.Remove(entry)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -80,7 +80,7 @@ func entryDiffOptsWithSort() []cmp.Option {\nfunc newTestNeighborCache(nudDisp NUDDispatcher, config NUDConfigurations, clock tcpip.Clock) *neighborCache {\nconfig.resetInvalidFields()\nrng := rand.New(rand.NewSource(time.Now().UnixNano()))\n- return &neighborCache{\n+ neigh := &neighborCache{\nnic: &NIC{\nstack: &Stack{\nclock: clock,\n@@ -92,6 +92,8 @@ func newTestNeighborCache(nudDisp NUDDispatcher, config NUDConfigurations, clock\nstate: NewNUDState(config, rng),\ncache: make(map[tcpip.Address]*neighborEntry, neighborCacheSize),\n}\n+ neigh.nic.neigh = neigh\n+ return neigh\n}\n// testEntryStore contains a set of IP to NeighborEntry mappings.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -258,7 +258,7 @@ func (e *neighborEntry) setStateLocked(next NeighborState) {\ncase Failed:\ne.notifyWakersLocked()\n- e.job = e.nic.stack.newJob(&e.mu, func() {\n+ e.job = e.nic.stack.newJob(&doubleLock{first: &e.nic.neigh.mu, second: &e.mu}, func() {\ne.nic.neigh.removeEntryLocked(e)\n})\ne.job.Schedule(config.UnreachableTime)\n@@ -512,3 +512,23 @@ func (e *neighborEntry) handleUpperLevelConfirmationLocked() {\npanic(fmt.Sprintf(\"Invalid cache entry state: %s\", e.neigh.State))\n}\n}\n+\n+// doubleLock combines two locks into one while maintaining lock ordering.\n+//\n+// TODO(gvisor.dev/issue/4796): Remove this once subsequent traffic to a Failed\n+// neighbor is allowed.\n+type doubleLock struct {\n+ first, second sync.Locker\n+}\n+\n+// Lock locks both locks in order: first then second.\n+func (l *doubleLock) Lock() {\n+ l.first.Lock()\n+ l.second.Lock()\n+}\n+\n+// Unlock unlocks both locks in reverse order: second then first.\n+func (l *doubleLock) Unlock() {\n+ l.second.Unlock()\n+ l.first.Unlock()\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Correctly lock when removing neighbor entries Fix a panic when two entries in Failed state are removed at the same time. PiperOrigin-RevId: 344143777
260,019
25.11.2020 13:41:43
-28,800
be71d3569cacc9da7e260895914272e3f5b81764
arm64 test: add exceptions related test cases For now, I only added a halt test case for Arm64.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -621,10 +621,7 @@ cc_binary(\ncc_binary(\nname = \"exceptions_test\",\ntestonly = 1,\n- srcs = select_arch(\n- amd64 = [\"exceptions.cc\"],\n- arm64 = [],\n- ),\n+ srcs = [\"exceptions.cc\"],\nlinkstatic = 1,\ndeps = [\ngtest,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/exceptions.cc", "new_path": "test/syscalls/linux/exceptions.cc", "diff": "namespace gvisor {\nnamespace testing {\n+#if defined(__x86_64__)\n// Default value for the x87 FPU control word. See Intel SDM Vol 1, Ch 8.1.5\n// \"x87 FPU Control Word\".\nconstexpr uint16_t kX87ControlWordDefault = 0x37f;\n@@ -93,6 +94,9 @@ void InIOHelper(int width, int value) {\n},\n::testing::KilledBySignal(SIGSEGV), \"\");\n}\n+#elif defined(__aarch64__)\n+void inline Halt() { asm(\"hlt #0\\r\\n\"); }\n+#endif\nTEST(ExceptionTest, Halt) {\n// In order to prevent the regular handler from messing with things (and\n@@ -102,9 +106,14 @@ TEST(ExceptionTest, Halt) {\nsa.sa_handler = SIG_DFL;\nauto const cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGSEGV, sa));\n+#if defined(__x86_64__)\nEXPECT_EXIT(Halt(), ::testing::KilledBySignal(SIGSEGV), \"\");\n+#elif defined(__aarch64__)\n+ EXPECT_EXIT(Halt(), ::testing::KilledBySignal(SIGILL), \"\");\n+#endif\n}\n+#if defined(__x86_64__)\nTEST(ExceptionTest, DivideByZero) {\n// See above.\nstruct sigaction sa = {};\n@@ -362,6 +371,7 @@ TEST(ExceptionTest, Int3Compact) {\nEXPECT_EXIT(Int3Compact(), ::testing::KilledBySignal(SIGTRAP), \"\");\n}\n+#endif\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
arm64 test: add exceptions related test cases For now, I only added a halt test case for Arm64. Signed-off-by: Robin Luk <[email protected]>
260,019
25.11.2020 14:36:38
-28,800
3868c7dd407b954e6830fbb6e6557af459567e3c
arm64 kvm: add more handling of el0_exceptions Add more comments and more handling for exceptions.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go", "diff": "@@ -235,12 +235,12 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *arch.SignalInfo)\nttbr0App := switchOpts.PageTables.TTBR0_EL1(false, 0)\nc.SetTtbr0App(uintptr(ttbr0App))\n- // TODO(gvisor.dev/issue/1238): full context-switch supporting for Arm64.\n+ // Full context-switch supporting for Arm64.\n// The Arm64 user-mode execution state consists of:\n// x0-x30\n// PC, SP, PSTATE\n// V0-V31: 32 128-bit registers for floating point, and simd\n- // FPSR\n+ // FPSR, FPCR\n// TPIDR_EL0, used for TLS\nappRegs := switchOpts.Registers\nc.SetAppAddr(ring0.KernelStartAddress | uintptr(unsafe.Pointer(appRegs)))\n@@ -254,15 +254,30 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *arch.SignalInfo)\ncase ring0.Syscall:\n// Fast path: system call executed.\nreturn usermem.NoAccess, nil\n-\ncase ring0.PageFault:\nreturn c.fault(int32(syscall.SIGSEGV), info)\ncase ring0.El0ErrNMI:\nreturn c.fault(int32(syscall.SIGBUS), info)\n- case ring0.Vector(bounce): // ring0.VirtualizationException\n+ case ring0.Vector(bounce): // ring0.VirtualizationException.\nreturn usermem.NoAccess, platform.ErrContextInterrupt\ncase ring0.El0SyncUndef:\nreturn c.fault(int32(syscall.SIGILL), info)\n+ case ring0.El0SyncDbg:\n+ *info = arch.SignalInfo{\n+ Signo: int32(syscall.SIGTRAP),\n+ Code: 1, // TRAP_BRKPT (breakpoint).\n+ }\n+ info.SetAddr(switchOpts.Registers.Pc) // Include address.\n+ return usermem.AccessType{}, platform.ErrContextSignal\n+ case ring0.El0SyncSpPc:\n+ *info = arch.SignalInfo{\n+ Signo: int32(syscall.SIGBUS),\n+ Code: 2, // BUS_ADRERR (physical address does not exist).\n+ }\n+ return usermem.NoAccess, platform.ErrContextSignal\n+ case ring0.El0SyncSys,\n+ ring0.El0SyncWfx:\n+ return usermem.NoAccess, nil // skip for now.\ndefault:\npanic(fmt.Sprintf(\"unexpected vector: 0x%x\", vector))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/aarch64.go", "new_path": "pkg/sentry/platform/ring0/aarch64.go", "diff": "@@ -95,6 +95,7 @@ const (\nEl0SyncSpPc\nEl0SyncUndef\nEl0SyncDbg\n+ El0SyncWfx\nEl0SyncInv\nEl0ErrNMI\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/offsets_arm64.go", "new_path": "pkg/sentry/platform/ring0/offsets_arm64.go", "diff": "@@ -75,6 +75,7 @@ func Emit(w io.Writer) {\nfmt.Fprintf(w, \"#define El0SyncSpPc 0x%02x\\n\", El0SyncSpPc)\nfmt.Fprintf(w, \"#define El0SyncUndef 0x%02x\\n\", El0SyncUndef)\nfmt.Fprintf(w, \"#define El0SyncDbg 0x%02x\\n\", El0SyncDbg)\n+ fmt.Fprintf(w, \"#define El0SyncWfx 0x%02x\\n\", El0SyncWfx)\nfmt.Fprintf(w, \"#define El0SyncInv 0x%02x\\n\", El0SyncInv)\nfmt.Fprintf(w, \"#define El0ErrNMI 0x%02x\\n\", El0ErrNMI)\n" } ]
Go
Apache License 2.0
google/gvisor
arm64 kvm: add more handling of el0_exceptions Add more comments and more handling for exceptions. Signed-off-by: Robin Luk <[email protected]>
259,898
24.11.2020 23:19:46
28,800
d04144fbb7b9fcb055e3aa3c2246f9b498923cc0
[2/3] Support isolated containers for parallel packetimpact tests Added a new flag num_duts to the test runner to create multiple DUTs for the testbench can connect to.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/BUILD", "new_path": "test/packetimpact/runner/BUILD", "diff": "@@ -32,6 +32,7 @@ go_library(\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/packetimpact/netdevs\",\n+ \"//test/packetimpact/testbench\",\n\"@com_github_docker_docker//api/types/mount:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/defs.bzl", "new_path": "test/packetimpact/runner/defs.bzl", "diff": "@@ -12,10 +12,11 @@ def _packetimpact_test_impl(ctx):\n# current user, and no other users will be mapped in that namespace.\n# Make sure that everything is readable here.\n\"find . -type f -or -type d -exec chmod a+rx {} \\\\;\",\n- \"%s %s --testbench_binary %s $@\\n\" % (\n+ \"%s %s --testbench_binary %s --num_duts %d $@\\n\" % (\ntest_runner.short_path,\n\" \".join(ctx.attr.flags),\nctx.files.testbench_binary[0].short_path,\n+ ctx.attr.num_duts,\n),\n])\nctx.actions.write(bench, bench_content, is_executable = True)\n@@ -51,6 +52,10 @@ _packetimpact_test = rule(\nmandatory = False,\ndefault = [],\n),\n+ \"num_duts\": attr.int(\n+ mandatory = False,\n+ default = 1,\n+ ),\n},\ntest = True,\nimplementation = _packetimpact_test_impl,\n@@ -110,24 +115,27 @@ def packetimpact_netstack_test(\n**kwargs\n)\n-def packetimpact_go_test(name, expect_native_failure = False, expect_netstack_failure = False):\n+def packetimpact_go_test(name, expect_native_failure = False, expect_netstack_failure = False, num_duts = 1):\n\"\"\"Add packetimpact tests written in go.\nArgs:\nname: name of the test\nexpect_native_failure: the test must fail natively\nexpect_netstack_failure: the test must fail for Netstack\n+ num_duts: how many DUTs are needed for the test\n\"\"\"\ntestbench_binary = name + \"_test\"\npacketimpact_native_test(\nname = name,\nexpect_failure = expect_native_failure,\ntestbench_binary = testbench_binary,\n+ num_duts = num_duts,\n)\npacketimpact_netstack_test(\nname = name,\nexpect_failure = expect_netstack_failure,\ntestbench_binary = testbench_binary,\n+ num_duts = num_duts,\n)\ndef packetimpact_testbench(name, size = \"small\", pure = True, **kwargs):\n@@ -153,7 +161,7 @@ def packetimpact_testbench(name, size = \"small\", pure = True, **kwargs):\nPacketimpactTestInfo = provider(\ndoc = \"Provide information for packetimpact tests\",\n- fields = [\"name\", \"expect_netstack_failure\"],\n+ fields = [\"name\", \"expect_netstack_failure\", \"num_duts\"],\n)\nALL_TESTS = [\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/dut.go", "new_path": "test/packetimpact/runner/dut.go", "diff": "@@ -17,6 +17,7 @@ package runner\nimport (\n\"context\"\n+ \"encoding/json\"\n\"flag\"\n\"fmt\"\n\"io/ioutil\"\n@@ -34,6 +35,7 @@ import (\n\"github.com/docker/docker/api/types/mount\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/test/packetimpact/netdevs\"\n+ \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n// stringList implements flag.Value.\n@@ -56,9 +58,10 @@ var (\ntshark = false\nextraTestArgs = stringList{}\nexpectFailure = false\n+ numDUTs = 1\n- // DutAddr is the IP addres for DUT.\n- DutAddr = net.IPv4(0, 0, 0, 10)\n+ // DUTAddr is the IP addres for DUT.\n+ DUTAddr = net.IPv4(0, 0, 0, 10)\ntestbenchAddr = net.IPv4(0, 0, 0, 20)\n)\n@@ -71,10 +74,15 @@ func RegisterFlags(fs *flag.FlagSet) {\nfs.BoolVar(&tshark, \"tshark\", false, \"use more verbose tshark in logs instead of tcpdump\")\nfs.Var(&extraTestArgs, \"extra_test_arg\", \"extra arguments to pass to the testbench\")\nfs.BoolVar(&expectFailure, \"expect_failure\", false, \"expect that the test will fail when run\")\n+ fs.IntVar(&numDUTs, \"num_duts\", numDUTs, \"the number of duts to create\")\n}\n+const (\n// CtrlPort is the port that posix_server listens on.\n-const CtrlPort = \"40000\"\n+ CtrlPort uint16 = 40000\n+ // testOutputDir is the directory in each container that holds test output.\n+ testOutputDir = \"/tmp/testoutput\"\n+)\n// logger implements testutil.Logger.\n//\n@@ -102,9 +110,14 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\n}\ndockerutil.EnsureSupportedDockerVersion()\n- // Create the networks needed for the test. One control network is needed for\n- // the gRPC control packets and one test network on which to transmit the test\n- // packets.\n+ var dockerNetworks []*dockerutil.Network\n+ var dutTestNets []*testbench.DUTTestNet\n+ var duts []DUT\n+\n+ for i := 0; i < numDUTs; i++ {\n+ // Create the networks needed for the test. One control network is needed\n+ // for the gRPC control packets and one test network on which to transmit\n+ // the test packets.\nctrlNet := dockerutil.NewNetwork(ctx, logger(\"ctrlNet\"))\ntestNet := dockerutil.NewNetwork(ctx, logger(\"testNet\"))\nfor _, dn := range []*dockerutil.Network{ctrlNet, testNet} {\n@@ -113,8 +126,8 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\nt.Log(\"creating docker network:\", err)\nconst wait = 100 * time.Millisecond\nt.Logf(\"sleeping %s and will try creating docker network again\", wait)\n- // This can fail if another docker network claimed the same IP so we'll\n- // just try again.\n+ // This can fail if another docker network claimed the same IP so we\n+ // will just try again.\ntime.Sleep(wait)\ncontinue\n}\n@@ -133,109 +146,109 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\nt.Fatalf(\"name mismatch for network want: %s got: %s\", dn.Name, inspect.Name)\n}\n}\n-\n- tmpDir, err := ioutil.TempDir(\"\", \"container-output\")\n- if err != nil {\n- t.Fatal(\"creating temp dir:\", err)\n- }\n- t.Cleanup(func() {\n- if err := exec.Command(\"/bin/cp\", \"-r\", tmpDir, os.Getenv(\"TEST_UNDECLARED_OUTPUTS_DIR\")).Run(); err != nil {\n- t.Errorf(\"unable to copy container output files: %s\", err)\n- }\n- if err := os.RemoveAll(tmpDir); err != nil {\n- t.Errorf(\"failed to remove tmpDir %s: %s\", tmpDir, err)\n- }\n- })\n-\n- const testOutputDir = \"/tmp/testoutput\"\n+ dockerNetworks = append(dockerNetworks, ctrlNet, testNet)\n// Create the Docker container for the DUT.\n- var dut *dockerutil.Container\n+ var dut DUT\nif native {\n- dut = dockerutil.MakeNativeContainer(ctx, logger(\"dut\"))\n+ dut = mkDevice(dockerutil.MakeNativeContainer(ctx, logger(fmt.Sprintf(\"dut-%d\", i))))\n} else {\n- dut = dockerutil.MakeContainer(ctx, logger(\"dut\"))\n+ dut = mkDevice(dockerutil.MakeContainer(ctx, logger(fmt.Sprintf(\"dut-%d\", i))))\n}\n- t.Cleanup(func() {\n- dut.CleanUp(ctx)\n- })\n+ duts = append(duts, dut)\nrunOpts := dockerutil.RunOpts{\nImage: \"packetimpact\",\nCapAdd: []string{\"NET_ADMIN\"},\n- Mounts: []mount.Mount{{\n- Type: mount.TypeBind,\n- Source: tmpDir,\n- Target: testOutputDir,\n- ReadOnly: false,\n- }},\n}\n-\n- device := mkDevice(dut)\n- remoteIPv6, remoteMAC, dutDeviceID, dutTestNetDev := device.Prepare(ctx, t, runOpts, ctrlNet, testNet)\n-\n+ mountTempDirectory(t, &runOpts, \"dut-output\", testOutputDir)\n+\n+ remoteIPv6, remoteMAC, dutDeviceID, dutTestNetDev := dut.Prepare(ctx, t, runOpts, ctrlNet, testNet)\n+ ipv4PrefixLength, _ := testNet.Subnet.Mask.Size()\n+ dutTestNets = append(dutTestNets, &testbench.DUTTestNet{\n+ RemoteMAC: remoteMAC,\n+ RemoteIPv4: AddressInSubnet(DUTAddr, *testNet.Subnet),\n+ RemoteIPv6: remoteIPv6,\n+ RemoteDevID: dutDeviceID,\n+ RemoteDevName: dutTestNetDev,\n+ LocalIPv4: AddressInSubnet(testbenchAddr, *testNet.Subnet),\n+ IPv4PrefixLength: ipv4PrefixLength,\n+ POSIXServerIP: AddressInSubnet(DUTAddr, *ctrlNet.Subnet),\n+ POSIXServerPort: CtrlPort,\n+ })\n+ }\n// Create the Docker container for the testbench.\ntestbench := dockerutil.MakeNativeContainer(ctx, logger(\"testbench\"))\n+ const containerDUTTestNetsDir = \"/tmp/dut-test-nets\"\n+ const dutTestNetsFileName = \"pool.json\"\n+ runOpts := dockerutil.RunOpts{\n+ Image: \"packetimpact\",\n+ CapAdd: []string{\"NET_ADMIN\"},\n+ }\n+ mountTempDirectory(t, &runOpts, \"testbench-output\", testOutputDir)\ntbb := path.Base(testbenchBinary)\ncontainerTestbenchBinary := filepath.Join(\"/packetimpact\", tbb)\ntestbench.CopyFiles(&runOpts, \"/packetimpact\", filepath.Join(\"test/packetimpact/tests\", tbb))\n- // snifferNetDev is a network device on the test orchestrator that we will\n- // run sniffer (tcpdump or tshark) on and inject traffic to, not to be\n- // confused with the device on the DUT.\n- const snifferNetDev = \"eth2\"\n- // Run tcpdump in the test bench unbuffered, without DNS resolution, just on\n- // the interface with the test packets.\n- snifferArgs := []string{\n- \"tcpdump\",\n- \"-S\", \"-vvv\", \"-U\", \"-n\",\n- \"-i\", snifferNetDev,\n- \"-w\", testOutputDir + \"/dump.pcap\",\n- }\n- snifferRegex := \"tcpdump: listening.*\\n\"\n- if tshark {\n- // Run tshark in the test bench unbuffered, without DNS resolution, just on\n- // the interface with the test packets.\n- snifferArgs = []string{\n- \"tshark\", \"-V\", \"-l\", \"-n\", \"-i\", snifferNetDev,\n- \"-o\", \"tcp.check_checksum:TRUE\",\n- \"-o\", \"udp.check_checksum:TRUE\",\n- }\n- snifferRegex = \"Capturing on.*\\n\"\n- }\n-\nif err := StartContainer(\nctx,\nrunOpts,\ntestbench,\ntestbenchAddr,\n- []*dockerutil.Network{ctrlNet, testNet},\n- snifferArgs...,\n+ dockerNetworks,\n+ \"tail\", \"-f\", \"/dev/null\",\n); err != nil {\n- t.Fatalf(\"failed to start docker container for testbench sniffer: %s\", err)\n+ t.Fatalf(\"cannot start testbench container: %s\", err)\n}\n- // Kill so that it will flush output.\n- t.Cleanup(func() {\n- time.Sleep(1 * time.Second)\n- testbench.Exec(ctx, dockerutil.ExecOpts{}, \"killall\", snifferArgs[0])\n- })\n- if _, err := testbench.WaitForOutput(ctx, snifferRegex, 60*time.Second); err != nil {\n- t.Fatalf(\"sniffer on %s never listened: %s\", dut.Name, err)\n+ for i := range dutTestNets {\n+ name, info, err := deviceByIP(ctx, testbench, dutTestNets[i].LocalIPv4)\n+ if err != nil {\n+ t.Fatalf(\"failed to get the device name associated with %s: %s\", dutTestNets[i].LocalIPv4, err)\n+ }\n+ dutTestNets[i].LocalDevName = name\n+ dutTestNets[i].LocalDevID = info.ID\n+ dutTestNets[i].LocalMAC = info.MAC\n+ localIPv6, err := getOrAssignIPv6Addr(ctx, testbench, name)\n+ if err != nil {\n+ t.Fatalf(\"failed to get IPV6 address on %s: %s\", testbench.Name, err)\n+ }\n+ dutTestNets[i].LocalIPv6 = localIPv6\n+ }\n+ dutTestNetsBytes, err := json.Marshal(dutTestNets)\n+ if err != nil {\n+ t.Fatalf(\"failed to marshal %v into json: %s\", dutTestNets, err)\n}\n+ snifferProg := \"tcpdump\"\n+ if tshark {\n+ snifferProg = \"tshark\"\n+ }\n+ for _, n := range dutTestNets {\n+ _, err := testbench.ExecProcess(ctx, dockerutil.ExecOpts{}, snifferArgs(n.LocalDevName)...)\n+ if err != nil {\n+ t.Fatalf(\"failed to start exec a sniffer on %s: %s\", n.LocalDevName, err)\n+ }\n// When the Linux kernel receives a SYN-ACK for a SYN it didn't send, it\n// will respond with an RST. In most packetimpact tests, the SYN is sent\n- // by the raw socket and the kernel knows nothing about the connection, this\n+ // by the raw socket, the kernel knows nothing about the connection, this\n// behavior will break lots of TCP related packetimpact tests. To prevent\n// this, we can install the following iptables rules. The raw socket that\n// packetimpact tests use will still be able to see everything.\nfor _, bin := range []string{\"iptables\", \"ip6tables\"} {\n- if logs, err := testbench.Exec(ctx, dockerutil.ExecOpts{}, bin, \"-A\", \"INPUT\", \"-i\", snifferNetDev, \"-p\", \"tcp\", \"-j\", \"DROP\"); err != nil {\n+ if logs, err := testbench.Exec(ctx, dockerutil.ExecOpts{}, bin, \"-A\", \"INPUT\", \"-i\", n.LocalDevName, \"-p\", \"tcp\", \"-j\", \"DROP\"); err != nil {\nt.Fatalf(\"unable to Exec %s on container %s: %s, logs from testbench:\\n%s\", bin, testbench.Name, err, logs)\n}\n}\n+ }\n+\n+ t.Cleanup(func() {\n+ time.Sleep(1 * time.Second)\n+ if logs, err := testbench.Exec(ctx, dockerutil.ExecOpts{}, \"killall\", snifferProg); err != nil {\n+ t.Errorf(\"failed to kill all sniffers: %s, logs: %s\", err, logs)\n+ }\n+ })\n// FIXME(b/156449515): Some piece of the system has a race. The old\n// bash script version had a sleep, so we have one too. The race should\n@@ -248,31 +261,29 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\ntestArgs := []string{containerTestbenchBinary}\ntestArgs = append(testArgs, extraTestArgs...)\ntestArgs = append(testArgs,\n- \"--posix_server_ip\", AddressInSubnet(DutAddr, *ctrlNet.Subnet).String(),\n- \"--posix_server_port\", CtrlPort,\n- \"--remote_ipv4\", AddressInSubnet(DutAddr, *testNet.Subnet).String(),\n- \"--local_ipv4\", AddressInSubnet(testbenchAddr, *testNet.Subnet).String(),\n- \"--remote_ipv6\", remoteIPv6.String(),\n- \"--remote_mac\", remoteMAC.String(),\n- \"--remote_interface_id\", fmt.Sprintf(\"%d\", dutDeviceID),\n- \"--local_device\", snifferNetDev,\n- \"--remote_device\", dutTestNetDev,\nfmt.Sprintf(\"--native=%t\", native),\n+ \"--dut_test_nets_json\", string(dutTestNetsBytes),\n)\ntestbenchLogs, err := testbench.Exec(ctx, dockerutil.ExecOpts{}, testArgs...)\nif (err != nil) != expectFailure {\nvar dutLogs string\n- if logs, err := device.Logs(ctx); err != nil {\n- dutLogs = fmt.Sprintf(\"failed to fetch DUT logs: %s\", err)\n- } else {\n- dutLogs = logs\n+ for i, dut := range duts {\n+ logs, err := dut.Logs(ctx)\n+ if err != nil {\n+ logs = fmt.Sprintf(\"failed to fetch DUT logs: %s\", err)\n}\n-\n- t.Errorf(`test error: %v, expect failure: %t\n+ dutLogs = fmt.Sprintf(`%s====== Begin of DUT-%d Logs ======\n%s\n-====== Begin of Testbench Logs ======\n+====== End of DUT-%d Logs ======\n+\n+`, dutLogs, i, logs, i)\n+ }\n+\n+ t.Errorf(`test error: %v, expect failure: %t\n+\n+%s====== Begin of Testbench Logs ======\n%s\n@@ -311,11 +322,11 @@ func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockeru\nctx,\nrunOpts,\ndut.c,\n- DutAddr,\n+ DUTAddr,\n[]*dockerutil.Network{ctrlNet, testNet},\ncontainerPosixServerBinary,\n\"--ip=0.0.0.0\",\n- \"--port=\"+CtrlPort,\n+ fmt.Sprintf(\"--port=%d\", CtrlPort),\n); err != nil {\nt.Fatalf(\"failed to start docker container for DUT: %s\", err)\n}\n@@ -324,28 +335,14 @@ func (dut *DockerDUT) Prepare(ctx context.Context, t *testing.T, runOpts dockeru\nt.Fatalf(\"%s on container %s never listened: %s\", containerPosixServerBinary, dut.c.Name, err)\n}\n- dutTestDevice, dutDeviceInfo, err := deviceByIP(ctx, dut.c, AddressInSubnet(DutAddr, *testNet.Subnet))\n+ dutTestDevice, dutDeviceInfo, err := deviceByIP(ctx, dut.c, AddressInSubnet(DUTAddr, *testNet.Subnet))\nif err != nil {\nt.Fatal(err)\n}\n- remoteMAC := dutDeviceInfo.MAC\n- remoteIPv6 := dutDeviceInfo.IPv6Addr\n- // Netstack as DUT doesn't assign IPv6 addresses automatically so do it if\n- // needed.\n- if remoteIPv6 == nil {\n- if _, err := dut.c.Exec(ctx, dockerutil.ExecOpts{}, \"ip\", \"addr\", \"add\", netdevs.MACToIP(remoteMAC).String(), \"scope\", \"link\", \"dev\", dutTestDevice); err != nil {\n- t.Fatalf(\"unable to ip addr add on container %s: %s\", dut.c.Name, err)\n- }\n- // Now try again, to make sure that it worked.\n- _, dutDeviceInfo, err = deviceByIP(ctx, dut.c, AddressInSubnet(DutAddr, *testNet.Subnet))\n+ remoteIPv6, err := getOrAssignIPv6Addr(ctx, dut.c, dutTestDevice)\nif err != nil {\n- t.Fatal(err)\n- }\n- remoteIPv6 = dutDeviceInfo.IPv6Addr\n- if remoteIPv6 == nil {\n- t.Fatalf(\"unable to set IPv6 address on container %s\", dut.c.Name)\n- }\n+ t.Fatalf(\"failed to get IPv6 address on %s: %s\", dut.c.Name, err)\n}\nconst testNetDev = \"eth2\"\n@@ -358,11 +355,7 @@ func (dut *DockerDUT) Logs(ctx context.Context) (string, error) {\nif err != nil {\nreturn \"\", err\n}\n- return fmt.Sprintf(`====== Begin of DUT Logs ======\n-\n-%s\n-\n-====== End of DUT Logs ======`, logs), nil\n+ return logs, nil\n}\n// AddNetworks connects docker network with the container and assigns the specific IP.\n@@ -378,8 +371,8 @@ func AddNetworks(ctx context.Context, d *dockerutil.Container, addr net.IP, netw\n}\n// AddressInSubnet combines the subnet provided with the address and returns a\n-// new address. The return address bits come from the subnet where the mask is 1\n-// and from the ip address where the mask is 0.\n+// new address. The return address bits come from the subnet where the mask is\n+// 1 and from the ip address where the mask is 0.\nfunc AddressInSubnet(addr net.IP, subnet net.IPNet) net.IP {\nvar octets []byte\nfor i := 0; i < 4; i++ {\n@@ -388,15 +381,25 @@ func AddressInSubnet(addr net.IP, subnet net.IPNet) net.IP {\nreturn net.IP(octets)\n}\n-// deviceByIP finds a deviceInfo and device name from an IP address.\n-func deviceByIP(ctx context.Context, d *dockerutil.Container, ip net.IP) (string, netdevs.DeviceInfo, error) {\n+// devicesInfo will run \"ip addr show\" on the container and parse the output\n+// to a map[string]netdevs.DeviceInfo.\n+func devicesInfo(ctx context.Context, d *dockerutil.Container) (map[string]netdevs.DeviceInfo, error) {\nout, err := d.Exec(ctx, dockerutil.ExecOpts{}, \"ip\", \"addr\", \"show\")\nif err != nil {\n- return \"\", netdevs.DeviceInfo{}, fmt.Errorf(\"listing devices on %s container: %w\\n%s\", d.Name, err, out)\n+ return map[string]netdevs.DeviceInfo{}, fmt.Errorf(\"listing devices on %s container: %w\\n%s\", d.Name, err, out)\n}\ndevs, err := netdevs.ParseDevices(out)\nif err != nil {\n- return \"\", netdevs.DeviceInfo{}, fmt.Errorf(\"parsing devices from %s container: %w\\n%s\", d.Name, err, out)\n+ return map[string]netdevs.DeviceInfo{}, fmt.Errorf(\"parsing devices from %s container: %w\\n%s\", d.Name, err, out)\n+ }\n+ return devs, nil\n+}\n+\n+// deviceByIP finds a deviceInfo and device name from an IP address.\n+func deviceByIP(ctx context.Context, d *dockerutil.Container, ip net.IP) (string, netdevs.DeviceInfo, error) {\n+ devs, err := devicesInfo(ctx, d)\n+ if err != nil {\n+ return \"\", netdevs.DeviceInfo{}, err\n}\ntestDevice, deviceInfo, err := netdevs.FindDeviceByIP(ip, devs)\nif err != nil {\n@@ -405,6 +408,36 @@ func deviceByIP(ctx context.Context, d *dockerutil.Container, ip net.IP) (string\nreturn testDevice, deviceInfo, nil\n}\n+// getOrAssignIPv6Addr will try to get the IPv6 address for the interface; if an\n+// address was not assigned, a link-local address based on MAC will be assigned\n+// to that interface.\n+func getOrAssignIPv6Addr(ctx context.Context, d *dockerutil.Container, iface string) (net.IP, error) {\n+ devs, err := devicesInfo(ctx, d)\n+ if err != nil {\n+ return net.IP{}, err\n+ }\n+ info := devs[iface]\n+ if info.IPv6Addr != nil {\n+ return info.IPv6Addr, nil\n+ }\n+ if info.MAC == nil {\n+ return nil, fmt.Errorf(\"unable to find MAC address of %s\", iface)\n+ }\n+ if logs, err := d.Exec(ctx, dockerutil.ExecOpts{}, \"ip\", \"addr\", \"add\", netdevs.MACToIP(info.MAC).String(), \"scope\", \"link\", \"dev\", iface); err != nil {\n+ return net.IP{}, fmt.Errorf(\"unable to ip addr add on container %s: %w, logs: %s\", d.Name, err, logs)\n+ }\n+ // Now try again, to make sure that it worked.\n+ devs, err = devicesInfo(ctx, d)\n+ if err != nil {\n+ return net.IP{}, err\n+ }\n+ info = devs[iface]\n+ if info.IPv6Addr == nil {\n+ return net.IP{}, fmt.Errorf(\"unable to set IPv6 address on container %s\", d.Name)\n+ }\n+ return info.IPv6Addr, nil\n+}\n+\n// createDockerNetwork makes a randomly-named network that will start with the\n// namePrefix. The network will be a random /24 subnet.\nfunc createDockerNetwork(ctx context.Context, n *dockerutil.Network) error {\n@@ -440,3 +473,51 @@ func StartContainer(ctx context.Context, runOpts dockerutil.RunOpts, c *dockerut\n}\nreturn nil\n}\n+\n+// MountTempDirectory creates a temporary directory on host with the template\n+// and then mounts it into the container under the name provided. The temporary\n+// directory name is returned. Content in that directory will be copied to\n+// TEST_UNDECLARED_OUTPUTS_DIR in cleanup phase.\n+func mountTempDirectory(t *testing.T, runOpts *dockerutil.RunOpts, hostDirTemplate, containerDir string) string {\n+ t.Helper()\n+ tmpDir, err := ioutil.TempDir(\"\", hostDirTemplate)\n+ if err != nil {\n+ t.Fatalf(\"failed to create a temp dir: %s\", err)\n+ }\n+ t.Cleanup(func() {\n+ if err := exec.Command(\"/bin/cp\", \"-r\", tmpDir, os.Getenv(\"TEST_UNDECLARED_OUTPUTS_DIR\")).Run(); err != nil {\n+ t.Errorf(\"unable to copy container output files: %s\", err)\n+ }\n+ if err := os.RemoveAll(tmpDir); err != nil {\n+ t.Errorf(\"failed to remove tmpDir %s: %s\", tmpDir, err)\n+ }\n+ })\n+ runOpts.Mounts = append(runOpts.Mounts, mount.Mount{\n+ Type: mount.TypeBind,\n+ Source: tmpDir,\n+ Target: containerDir,\n+ ReadOnly: false,\n+ })\n+ return tmpDir\n+}\n+\n+// snifferArgs returns the correct command line to run sniffer on the testbench.\n+func snifferArgs(devName string) []string {\n+ if tshark {\n+ // Run tshark in the test bench unbuffered, without DNS resolution, just\n+ // on the interface with the test packets.\n+ return []string{\n+ \"tshark\", \"-V\", \"-l\", \"-n\", \"-i\", devName,\n+ \"-o\", \"tcp.check_checksum:TRUE\",\n+ \"-o\", \"udp.check_checksum:TRUE\",\n+ }\n+ }\n+ // Run tcpdump in the test bench unbuffered, without DNS resolution, just\n+ // on the interface with the test packets.\n+ return []string{\n+ \"tcpdump\",\n+ \"-S\", \"-vvv\", \"-U\", \"-n\",\n+ \"-i\", devName,\n+ \"-w\", filepath.Join(testOutputDir, fmt.Sprintf(\"%s.pcap\", devName)),\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/BUILD", "new_path": "test/packetimpact/testbench/BUILD", "diff": "@@ -21,7 +21,6 @@ go_library(\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/seqnum\",\n\"//pkg/usermem\",\n- \"//test/packetimpact/netdevs\",\n\"//test/packetimpact/proto:posix_server_go_proto\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n\"@com_github_google_go_cmp//cmp/cmpopts:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/testbench.go", "new_path": "test/packetimpact/testbench/testbench.go", "diff": "package testbench\nimport (\n+ \"encoding/json\"\n\"flag\"\n\"fmt\"\n\"math/rand\"\n\"net\"\n- \"os/exec\"\n\"testing\"\n\"time\"\n-\n- \"gvisor.dev/gvisor/test/packetimpact/netdevs\"\n)\nvar (\n@@ -36,25 +34,12 @@ var (\n// RPCTimeout is the gRPC timeout.\nRPCTimeout = 100 * time.Millisecond\n+ // dutTestNetsJSON is the json string that describes all the test networks to\n+ // duts available to use.\n+ dutTestNetsJSON string\n// dutTestNets is the pool among which the testbench can choose a DUT to work\n// with.\ndutTestNets chan *DUTTestNet\n-\n- // TODO(zeling): Remove the following variables once the test runner side is\n- // ready.\n- localDevice = \"\"\n- remoteDevice = \"\"\n- localIPv4 = \"\"\n- remoteIPv4 = \"\"\n- ipv4PrefixLength = 0\n- localIPv6 = \"\"\n- remoteIPv6 = \"\"\n- localInterfaceID uint32\n- remoteInterfaceID uint64\n- localMAC = \"\"\n- remoteMAC = \"\"\n- posixServerIP = \"\"\n- posixServerPort = 40000\n)\n// DUTTestNet describes the test network setup on dut and how the testbench\n@@ -98,19 +83,10 @@ type DUTTestNet struct {\n// exported variables above. It should be called by tests in their init\n// functions.\nfunc registerFlags(fs *flag.FlagSet) {\n- fs.StringVar(&posixServerIP, \"posix_server_ip\", posixServerIP, \"ip address to listen to for UDP commands\")\n- fs.IntVar(&posixServerPort, \"posix_server_port\", posixServerPort, \"port to listen to for UDP commands\")\n- fs.StringVar(&localIPv4, \"local_ipv4\", localIPv4, \"local IPv4 address for test packets\")\n- fs.StringVar(&remoteIPv4, \"remote_ipv4\", remoteIPv4, \"remote IPv4 address for test packets\")\n- fs.StringVar(&remoteIPv6, \"remote_ipv6\", remoteIPv6, \"remote IPv6 address for test packets\")\n- fs.StringVar(&remoteMAC, \"remote_mac\", remoteMAC, \"remote mac address for test packets\")\n- fs.StringVar(&localDevice, \"local_device\", localDevice, \"local device to inject traffic\")\n- fs.StringVar(&remoteDevice, \"remote_device\", remoteDevice, \"remote device on the DUT\")\n- fs.Uint64Var(&remoteInterfaceID, \"remote_interface_id\", remoteInterfaceID, \"remote interface ID for test packets\")\n-\nfs.BoolVar(&Native, \"native\", Native, \"whether the test is running natively\")\nfs.DurationVar(&RPCTimeout, \"rpc_timeout\", RPCTimeout, \"gRPC timeout\")\nfs.DurationVar(&RPCKeepalive, \"rpc_keepalive\", RPCKeepalive, \"gRPC keepalive\")\n+ fs.StringVar(&dutTestNetsJSON, \"dut_test_nets_json\", dutTestNetsJSON, \"path to the dut test nets json file\")\n}\n// Initialize initializes the testbench, it parse the flags and sets up the\n@@ -118,61 +94,27 @@ func registerFlags(fs *flag.FlagSet) {\nfunc Initialize(fs *flag.FlagSet) {\nregisterFlags(fs)\nflag.Parse()\n- if err := genPseudoFlags(); err != nil {\n+ if err := loadDUTTestNets(); err != nil {\npanic(err)\n}\n- var dut DUTTestNet\n- var err error\n- dut.LocalMAC, err = net.ParseMAC(localMAC)\n- if err != nil {\n- panic(err)\n}\n- dut.RemoteMAC, err = net.ParseMAC(remoteMAC)\n- if err != nil {\n- panic(err)\n- }\n- dut.LocalIPv4 = net.ParseIP(localIPv4).To4()\n- dut.LocalIPv6 = net.ParseIP(localIPv6).To16()\n- dut.RemoteIPv4 = net.ParseIP(remoteIPv4).To4()\n- dut.RemoteIPv6 = net.ParseIP(remoteIPv6).To16()\n- dut.LocalDevID = uint32(localInterfaceID)\n- dut.RemoteDevID = uint32(remoteInterfaceID)\n- dut.LocalDevName = localDevice\n- dut.RemoteDevName = remoteDevice\n- dut.POSIXServerIP = net.ParseIP(posixServerIP)\n- dut.POSIXServerPort = uint16(posixServerPort)\n- dut.IPv4PrefixLength = ipv4PrefixLength\n- dutTestNets = make(chan *DUTTestNet, 1)\n- dutTestNets <- &dut\n+// loadDUTTestNets loads available DUT test networks from the json file, it\n+// must be called after flag.Parse().\n+func loadDUTTestNets() error {\n+ var parsedTestNets []DUTTestNet\n+ if err := json.Unmarshal([]byte(dutTestNetsJSON), &parsedTestNets); err != nil {\n+ return fmt.Errorf(\"failed to unmarshal JSON: %w\", err)\n}\n-\n-// genPseudoFlags populates flag-like global config based on real flags.\n-//\n-// genPseudoFlags must only be called after flag.Parse.\n-func genPseudoFlags() error {\n- out, err := exec.Command(\"ip\", \"addr\", \"show\").CombinedOutput()\n- if err != nil {\n- return fmt.Errorf(\"listing devices: %q: %w\", string(out), err)\n- }\n- devs, err := netdevs.ParseDevices(string(out))\n- if err != nil {\n- return fmt.Errorf(\"parsing devices: %w\", err)\n- }\n-\n- _, deviceInfo, err := netdevs.FindDeviceByIP(net.ParseIP(localIPv4), devs)\n- if err != nil {\n- return fmt.Errorf(\"can't find deviceInfo: %w\", err)\n+ if got, want := len(parsedTestNets), 1; got < want {\n+ return fmt.Errorf(\"got %d DUTs, the test requires at least %d DUTs\", got, want)\n}\n-\n- localMAC = deviceInfo.MAC.String()\n- localIPv6 = deviceInfo.IPv6Addr.String()\n- localInterfaceID = deviceInfo.ID\n-\n- if deviceInfo.IPv4Net != nil {\n- ipv4PrefixLength, _ = deviceInfo.IPv4Net.Mask.Size()\n- } else {\n- ipv4PrefixLength, _ = net.ParseIP(localIPv4).DefaultMask().Size()\n+ // Using a buffered channel as semaphore\n+ dutTestNets = make(chan *DUTTestNet, len(parsedTestNets))\n+ for i := range parsedTestNets {\n+ parsedTestNets[i].LocalIPv4 = parsedTestNets[i].LocalIPv4.To4()\n+ parsedTestNets[i].RemoteIPv4 = parsedTestNets[i].RemoteIPv4.To4()\n+ dutTestNets <- &parsedTestNets[i]\n}\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -371,4 +371,5 @@ validate_all_tests()\n[packetimpact_go_test(\nname = t.name,\nexpect_netstack_failure = hasattr(t, \"expect_netstack_failure\"),\n+ num_duts = t.num_duts if hasattr(t, \"num_duts\") else 1,\n) for t in ALL_TESTS]\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/udp_recv_mcast_bcast_test.go", "new_path": "test/packetimpact/tests/udp_recv_mcast_bcast_test.go", "diff": "@@ -44,7 +44,7 @@ func TestUDPRecvMcastBcast(t *testing.T) {\n{bound: subnetBcastAddr, to: subnetBcastAddr},\n- // FIXME(gvisor.dev/issues/4896): Previously by the time subnetBcastAddr is\n+ // FIXME(gvisor.dev/issue/4896): Previously by the time subnetBcastAddr is\n// created, IPv4PrefixLength is still 0 because genPseudoFlags is not called\n// yet, it was only called in NewDUT, so the test didn't do what the author\n// original intended to and becomes failing because we process all flags at\n" } ]
Go
Apache License 2.0
google/gvisor
[2/3] Support isolated containers for parallel packetimpact tests Added a new flag num_duts to the test runner to create multiple DUTs for the testbench can connect to. PiperOrigin-RevId: 344195435
259,907
26.11.2020 00:41:20
28,800
ad83112423ecf8729df582dd79cbe5a7e29bd937
[netstack] Add SOL_TCP options to SocketOptions. Ports the following options: TCP_NODELAY TCP_CORK TCP_QUICKACK Also deletes the {Get/Set}SockOptBool interface methods from all implementations
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -240,10 +240,6 @@ type commonEndpoint interface {\n// transport.Endpoint.SetSockOpt.\nSetSockOpt(tcpip.SettableSocketOption) *tcpip.Error\n- // SetSockOptBool implements tcpip.Endpoint.SetSockOptBool and\n- // transport.Endpoint.SetSockOptBool.\n- SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error\n-\n// SetSockOptInt implements tcpip.Endpoint.SetSockOptInt and\n// transport.Endpoint.SetSockOptInt.\nSetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error\n@@ -252,10 +248,6 @@ type commonEndpoint interface {\n// transport.Endpoint.GetSockOpt.\nGetSockOpt(tcpip.GettableSocketOption) *tcpip.Error\n- // GetSockOptBool implements tcpip.Endpoint.GetSockOptBool and\n- // transport.Endpoint.GetSockOpt.\n- GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error)\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt and\n// transport.Endpoint.GetSockOpt.\nGetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error)\n@@ -338,9 +330,7 @@ type socketOpsCommon struct {\n// New creates a new endpoint socket.\nfunc New(t *kernel.Task, family int, skType linux.SockType, protocol int, queue *waiter.Queue, endpoint tcpip.Endpoint) (*fs.File, *syserr.Error) {\nif skType == linux.SOCK_STREAM {\n- if err := endpoint.SetSockOptBool(tcpip.DelayOption, true); err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n+ endpoint.SocketOptions().SetDelayOption(true)\n}\ndirent := socket.NewDirent(t, netstackDevice)\n@@ -1007,7 +997,7 @@ func GetSockOpt(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, family in\nreturn getSockOptSocket(t, s, ep, family, skType, name, outLen)\ncase linux.SOL_TCP:\n- return getSockOptTCP(t, ep, name, outLen)\n+ return getSockOptTCP(t, s, ep, name, outLen)\ncase linux.SOL_IPV6:\nreturn getSockOptIPv6(t, s, ep, name, outPtr, outLen)\n@@ -1241,46 +1231,36 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\n}\n// getSockOptTCP implements GetSockOpt when level is SOL_TCP.\n-func getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (marshal.Marshallable, *syserr.Error) {\n+func getSockOptTCP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name, outLen int) (marshal.Marshallable, *syserr.Error) {\n+ if _, skType, skProto := s.Type(); !isTCPSocket(skType, skProto) {\n+ log.Warningf(\"SOL_TCP options are only supported on TCP sockets: skType, skProto = %v, %d\", skType, skProto)\n+ return nil, syserr.ErrUnknownProtocolOption\n+ }\n+\nswitch name {\ncase linux.TCP_NODELAY:\nif outLen < sizeOfInt32 {\nreturn nil, syserr.ErrInvalidArgument\n}\n- v, err := ep.GetSockOptBool(tcpip.DelayOption)\n- if err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n-\n- vP := primitive.Int32(boolToInt32(!v))\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(!ep.SocketOptions().GetDelayOption()))\n+ return &v, nil\ncase linux.TCP_CORK:\nif outLen < sizeOfInt32 {\nreturn nil, syserr.ErrInvalidArgument\n}\n- v, err := ep.GetSockOptBool(tcpip.CorkOption)\n- if err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n-\n- vP := primitive.Int32(boolToInt32(v))\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetCorkOption()))\n+ return &v, nil\ncase linux.TCP_QUICKACK:\nif outLen < sizeOfInt32 {\nreturn nil, syserr.ErrInvalidArgument\n}\n- v, err := ep.GetSockOptBool(tcpip.QuickAckOption)\n- if err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n-\n- vP := primitive.Int32(boolToInt32(v))\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetQuickAck()))\n+ return &v, nil\ncase linux.TCP_MAXSEG:\nif outLen < sizeOfInt32 {\n@@ -1804,7 +1784,7 @@ func SetSockOpt(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, level int\nreturn setSockOptSocket(t, s, ep, name, optVal)\ncase linux.SOL_TCP:\n- return setSockOptTCP(t, ep, name, optVal)\n+ return setSockOptTCP(t, s, ep, name, optVal)\ncase linux.SOL_IPV6:\nreturn setSockOptIPv6(t, s, ep, name, optVal)\n@@ -1994,7 +1974,12 @@ func setSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, nam\n}\n// setSockOptTCP implements SetSockOpt when level is SOL_TCP.\n-func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *syserr.Error {\n+func setSockOptTCP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name int, optVal []byte) *syserr.Error {\n+ if _, skType, skProto := s.Type(); !isTCPSocket(skType, skProto) {\n+ log.Warningf(\"SOL_TCP options are only supported on TCP sockets: skType, skProto = %v, %d\", skType, skProto)\n+ return syserr.ErrUnknownProtocolOption\n+ }\n+\nswitch name {\ncase linux.TCP_NODELAY:\nif len(optVal) < sizeOfInt32 {\n@@ -2002,7 +1987,8 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\n}\nv := usermem.ByteOrder.Uint32(optVal)\n- return syserr.TranslateNetstackError(ep.SetSockOptBool(tcpip.DelayOption, v == 0))\n+ ep.SocketOptions().SetDelayOption(v == 0)\n+ return nil\ncase linux.TCP_CORK:\nif len(optVal) < sizeOfInt32 {\n@@ -2010,7 +1996,8 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\n}\nv := usermem.ByteOrder.Uint32(optVal)\n- return syserr.TranslateNetstackError(ep.SetSockOptBool(tcpip.CorkOption, v != 0))\n+ ep.SocketOptions().SetCorkOption(v != 0)\n+ return nil\ncase linux.TCP_QUICKACK:\nif len(optVal) < sizeOfInt32 {\n@@ -2018,7 +2005,8 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\n}\nv := usermem.ByteOrder.Uint32(optVal)\n- return syserr.TranslateNetstackError(ep.SetSockOptBool(tcpip.QuickAckOption, v != 0))\n+ ep.SocketOptions().SetQuickAck(v != 0)\n+ return nil\ncase linux.TCP_MAXSEG:\nif len(optVal) < sizeOfInt32 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "new_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "diff": "@@ -51,9 +51,7 @@ var _ = socket.SocketVFS2(&SocketVFS2{})\n// NewVFS2 creates a new endpoint socket.\nfunc NewVFS2(t *kernel.Task, family int, skType linux.SockType, protocol int, queue *waiter.Queue, endpoint tcpip.Endpoint) (*vfs.FileDescription, *syserr.Error) {\nif skType == linux.SOCK_STREAM {\n- if err := endpoint.SetSockOptBool(tcpip.DelayOption, true); err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n+ endpoint.SocketOptions().SetDelayOption(true)\n}\nmnt := t.Kernel().SocketMount()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/unix.go", "new_path": "pkg/sentry/socket/unix/transport/unix.go", "diff": "@@ -178,10 +178,6 @@ type Endpoint interface {\n// SetSockOpt sets a socket option.\nSetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error\n- // SetSockOptBool sets a socket option for simple cases when a value has\n- // the int type.\n- SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error\n-\n// SetSockOptInt sets a socket option for simple cases when a value has\n// the int type.\nSetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error\n@@ -189,10 +185,6 @@ type Endpoint interface {\n// GetSockOpt gets a socket option.\nGetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error\n- // GetSockOptBool gets a socket option for simple cases when a return\n- // value has the int type.\n- GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error)\n-\n// GetSockOptInt gets a socket option for simple cases when a return\n// value has the int type.\nGetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error)\n@@ -857,11 +849,6 @@ func (e *baseEndpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\nreturn nil\n}\n-func (e *baseEndpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\n- log.Warningf(\"Unsupported socket option: %d\", opt)\n- return nil\n-}\n-\nfunc (e *baseEndpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nswitch opt {\ncase tcpip.SendBufferSizeOption:\n@@ -872,11 +859,6 @@ func (e *baseEndpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nreturn nil\n}\n-func (e *baseEndpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- log.Warningf(\"Unsupported socket option: %d\", opt)\n- return false, tcpip.ErrUnknownProtocolOption\n-}\n-\nfunc (e *baseEndpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\ncase tcpip.ReceiveQueueSizeOption:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -30,6 +30,13 @@ type SocketOptionsHandler interface {\n// OnKeepAliveSet is invoked when SO_KEEPALIVE is set for an endpoint.\nOnKeepAliveSet(v bool)\n+\n+ // OnDelayOptionSet is invoked when TCP_NODELAY is set for an endpoint.\n+ // Note that v will be the inverse of TCP_NODELAY option.\n+ OnDelayOptionSet(v bool)\n+\n+ // OnCorkOptionSet is invoked when TCP_CORK is set for an endpoint.\n+ OnCorkOptionSet(v bool)\n}\n// DefaultSocketOptionsHandler is an embeddable type that implements no-op\n@@ -47,8 +54,14 @@ func (*DefaultSocketOptionsHandler) OnReusePortSet(bool) {}\n// OnKeepAliveSet implements SocketOptionsHandler.OnKeepAliveSet.\nfunc (*DefaultSocketOptionsHandler) OnKeepAliveSet(bool) {}\n+// OnDelayOptionSet implements SocketOptionsHandler.OnDelayOptionSet.\n+func (*DefaultSocketOptionsHandler) OnDelayOptionSet(bool) {}\n+\n+// OnCorkOptionSet implements SocketOptionsHandler.OnCorkOptionSet.\n+func (*DefaultSocketOptionsHandler) OnCorkOptionSet(bool) {}\n+\n// SocketOptions contains all the variables which store values for SOL_SOCKET,\n-// SOL_IP and SOL_IPV6 level options.\n+// SOL_IP, SOL_IPV6 and SOL_TCP level options.\n//\n// +stateify savable\ntype SocketOptions struct {\n@@ -104,6 +117,19 @@ type SocketOptions struct {\n// v6OnlyEnabled is used to determine whether an IPv6 socket is to be\n// restricted to sending and receiving IPv6 packets only.\nv6OnlyEnabled uint32\n+\n+ // quickAckEnabled is used to represent the value of TCP_QUICKACK option.\n+ // It currently does not have any effect on the TCP endpoint.\n+ quickAckEnabled uint32\n+\n+ // delayOptionEnabled is used to specify if data should be sent out immediately\n+ // by the transport protocol. For TCP, it determines if the Nagle algorithm\n+ // is on or off.\n+ delayOptionEnabled uint32\n+\n+ // corkOptionEnabled is used to specify if data should be held until segments\n+ // are full by the TCP transport protocol.\n+ corkOptionEnabled uint32\n}\n// InitHandler initializes the handler. This must be called before using the\n@@ -244,3 +270,35 @@ func (so *SocketOptions) GetV6Only() bool {\nfunc (so *SocketOptions) SetV6Only(v bool) {\nstoreAtomicBool(&so.v6OnlyEnabled, v)\n}\n+\n+// GetQuickAck gets value for TCP_QUICKACK option.\n+func (so *SocketOptions) GetQuickAck() bool {\n+ return atomic.LoadUint32(&so.quickAckEnabled) != 0\n+}\n+\n+// SetQuickAck sets value for TCP_QUICKACK option.\n+func (so *SocketOptions) SetQuickAck(v bool) {\n+ storeAtomicBool(&so.quickAckEnabled, v)\n+}\n+\n+// GetDelayOption gets inverted value for TCP_NODELAY option.\n+func (so *SocketOptions) GetDelayOption() bool {\n+ return atomic.LoadUint32(&so.delayOptionEnabled) != 0\n+}\n+\n+// SetDelayOption sets inverted value for TCP_NODELAY option.\n+func (so *SocketOptions) SetDelayOption(v bool) {\n+ storeAtomicBool(&so.delayOptionEnabled, v)\n+ so.handler.OnDelayOptionSet(v)\n+}\n+\n+// GetCorkOption gets value for TCP_CORK option.\n+func (so *SocketOptions) GetCorkOption() bool {\n+ return atomic.LoadUint32(&so.corkOptionEnabled) != 0\n+}\n+\n+// SetCorkOption sets value for TCP_CORK option.\n+func (so *SocketOptions) SetCorkOption(v bool) {\n+ storeAtomicBool(&so.corkOptionEnabled, v)\n+ so.handler.OnCorkOptionSet(v)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_test.go", "new_path": "pkg/tcpip/stack/transport_test.go", "diff": "@@ -118,21 +118,11 @@ func (*fakeTransportEndpoint) SetSockOpt(tcpip.SettableSocketOption) *tcpip.Erro\nreturn tcpip.ErrInvalidEndpointState\n}\n-// SetSockOptBool sets a socket option. Currently not supported.\n-func (*fakeTransportEndpoint) SetSockOptBool(tcpip.SockOptBool, bool) *tcpip.Error {\n- return tcpip.ErrInvalidEndpointState\n-}\n-\n// SetSockOptInt sets a socket option. Currently not supported.\nfunc (*fakeTransportEndpoint) SetSockOptInt(tcpip.SockOptInt, int) *tcpip.Error {\nreturn tcpip.ErrInvalidEndpointState\n}\n-// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\n-func (*fakeTransportEndpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- return false, tcpip.ErrUnknownProtocolOption\n-}\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (*fakeTransportEndpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nreturn -1, tcpip.ErrUnknownProtocolOption\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -603,10 +603,6 @@ type Endpoint interface {\n// SetSockOpt sets a socket option.\nSetSockOpt(opt SettableSocketOption) *Error\n- // SetSockOptBool sets a socket option, for simple cases where a value\n- // has the bool type.\n- SetSockOptBool(opt SockOptBool, v bool) *Error\n-\n// SetSockOptInt sets a socket option, for simple cases where a value\n// has the int type.\nSetSockOptInt(opt SockOptInt, v int) *Error\n@@ -614,10 +610,6 @@ type Endpoint interface {\n// GetSockOpt gets a socket option.\nGetSockOpt(opt GettableSocketOption) *Error\n- // GetSockOptBool gets a socket option for simple cases where a return\n- // value has the bool type.\n- GetSockOptBool(SockOptBool) (bool, *Error)\n-\n// GetSockOptInt gets a socket option for simple cases where a return\n// value has the int type.\nGetSockOptInt(SockOptInt) (int, *Error)\n@@ -704,24 +696,6 @@ type WriteOptions struct {\nAtomic bool\n}\n-// SockOptBool represents socket options which values have the bool type.\n-type SockOptBool int\n-\n-const (\n- // CorkOption is used by SetSockOptBool/GetSockOptBool to specify if\n- // data should be held until segments are full by the TCP transport\n- // protocol.\n- CorkOption SockOptBool = iota\n-\n- // DelayOption is used by SetSockOptBool/GetSockOptBool to specify if\n- // data should be sent out immediately by the transport protocol. For\n- // TCP, it determines if the Nagle algorithm is on or off.\n- DelayOption\n-\n- // QuickAckOption is stubbed out in SetSockOptBool/GetSockOptBool.\n- QuickAckOption\n-)\n-\n// SockOptInt represents socket options which values have the int type.\ntype SockOptInt int\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -368,11 +368,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\nreturn nil\n}\n-// SetSockOptBool sets a socket option. Currently not supported.\n-func (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\n- return nil\n-}\n-\n// SetSockOptInt sets a socket option. Currently not supported.\nfunc (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nswitch opt {\n@@ -385,11 +380,6 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nreturn nil\n}\n-// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\n-func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- return false, tcpip.ErrUnknownProtocolOption\n-}\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint.go", "new_path": "pkg/tcpip/transport/packet/endpoint.go", "diff": "@@ -321,11 +321,6 @@ func (ep *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n}\n}\n-// SetSockOptBool implements tcpip.Endpoint.SetSockOptBool.\n-func (ep *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\n- return tcpip.ErrUnknownProtocolOption\n-}\n-\n// SetSockOptInt implements tcpip.Endpoint.SetSockOptInt.\nfunc (ep *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nswitch opt {\n@@ -393,11 +388,6 @@ func (ep *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n}\n}\n-// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\n-func (*endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- return false, tcpip.ErrNotSupported\n-}\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (ep *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -535,11 +535,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n}\n}\n-// SetSockOptBool implements tcpip.Endpoint.SetSockOptBool.\n-func (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\n- return tcpip.ErrUnknownProtocolOption\n-}\n-\n// SetSockOptInt implements tcpip.Endpoint.SetSockOptInt.\nfunc (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nswitch opt {\n@@ -598,11 +593,6 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n}\n}\n-// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\n-func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- return false, tcpip.ErrUnknownProtocolOption\n-}\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -497,24 +497,9 @@ type endpoint struct {\n// delay is a boolean (0 is false) and must be accessed atomically.\ndelay uint32\n- // cork holds back segments until full.\n- //\n- // cork is a boolean (0 is false) and must be accessed atomically.\n- cork uint32\n-\n// scoreboard holds TCP SACK Scoreboard information for this endpoint.\nscoreboard *SACKScoreboard\n- // The options below aren't implemented, but we remember the user\n- // settings because applications expect to be able to set/query these\n- // options.\n-\n- // slowAck holds the negated state of quick ack. It is stubbed out and\n- // does nothing.\n- //\n- // slowAck is a boolean (0 is false) and must be accessed atomically.\n- slowAck uint32\n-\n// segmentQueue is used to hand received segments to the protocol\n// goroutine. Segments are queued as long as the queue is not full,\n// and dropped when it is.\n@@ -874,6 +859,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\n}\ne.ops.InitHandler(e)\ne.ops.SetMulticastLoop(true)\n+ e.ops.SetQuickAck(true)\nvar ss tcpip.TCPSendBufferSizeRangeOption\nif err := s.TransportProtocolOption(ProtocolNumber, &ss); err == nil {\n@@ -897,7 +883,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\nvar de tcpip.TCPDelayEnabled\nif err := s.TransportProtocolOption(ProtocolNumber, &de); err == nil && de {\n- e.SetSockOptBool(tcpip.DelayOption, true)\n+ e.ops.SetDelayOption(true)\n}\nvar tcpLT tcpip.TCPLingerTimeoutOption\n@@ -1640,41 +1626,20 @@ func (e *endpoint) OnKeepAliveSet(v bool) {\ne.notifyProtocolGoroutine(notifyKeepaliveChanged)\n}\n-// SetSockOptBool sets a socket option.\n-func (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\n- switch opt {\n-\n- case tcpip.CorkOption:\n- e.LockUser()\n+// OnDelayOptionSet implements tcpip.SocketOptionsHandler.OnDelayOptionSet.\n+func (e *endpoint) OnDelayOptionSet(v bool) {\nif !v {\n- atomic.StoreUint32(&e.cork, 0)\n-\n- // Handle the corked data.\n- e.sndWaker.Assert()\n- } else {\n- atomic.StoreUint32(&e.cork, 1)\n- }\n- e.UnlockUser()\n-\n- case tcpip.DelayOption:\n- if v {\n- atomic.StoreUint32(&e.delay, 1)\n- } else {\n- atomic.StoreUint32(&e.delay, 0)\n-\n// Handle delayed data.\ne.sndWaker.Assert()\n}\n-\n- case tcpip.QuickAckOption:\n- o := uint32(1)\n- if v {\n- o = 0\n- }\n- atomic.StoreUint32(&e.slowAck, o)\n}\n- return nil\n+// OnCorkOptionSet implements tcpip.SocketOptionsHandler.OnCorkOptionSet.\n+func (e *endpoint) OnCorkOptionSet(v bool) {\n+ if !v {\n+ // Handle the corked data.\n+ e.sndWaker.Assert()\n+ }\n}\n// SetSockOptInt sets a socket option.\n@@ -1956,25 +1921,6 @@ func (e *endpoint) readyReceiveSize() (int, *tcpip.Error) {\nreturn e.rcvBufUsed, nil\n}\n-// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\n-func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- switch opt {\n-\n- case tcpip.CorkOption:\n- return atomic.LoadUint32(&e.cork) != 0, nil\n-\n- case tcpip.DelayOption:\n- return atomic.LoadUint32(&e.delay) != 0, nil\n-\n- case tcpip.QuickAckOption:\n- v := atomic.LoadUint32(&e.slowAck) == 0\n- return v, nil\n-\n- default:\n- return false, tcpip.ErrUnknownProtocolOption\n- }\n-}\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"fmt\"\n\"math\"\n\"sort\"\n- \"sync/atomic\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/sleep\"\n@@ -813,7 +812,7 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\n}\nif !nextTooBig && seg.data.Size() < available {\n// Segment is not full.\n- if s.outstanding > 0 && atomic.LoadUint32(&s.ep.delay) != 0 {\n+ if s.outstanding > 0 && s.ep.ops.GetDelayOption() {\n// Nagle's algorithm. From Wikipedia:\n// Nagle's algorithm works by\n// combining a number of small\n@@ -832,7 +831,7 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\n// send space and MSS.\n// TODO(gvisor.dev/issue/2833): Drain the held segments after a\n// timeout.\n- if seg.data.Size() < s.maxPayloadSize && atomic.LoadUint32(&s.ep.cork) != 0 {\n+ if seg.data.Size() < s.maxPayloadSize && s.ep.ops.GetCorkOption() {\nreturn false\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -2529,10 +2529,10 @@ func TestSegmentMerging(t *testing.T) {\n{\n\"cork\",\nfunc(ep tcpip.Endpoint) {\n- ep.SetSockOptBool(tcpip.CorkOption, true)\n+ ep.SocketOptions().SetCorkOption(true)\n},\nfunc(ep tcpip.Endpoint) {\n- ep.SetSockOptBool(tcpip.CorkOption, false)\n+ ep.SocketOptions().SetCorkOption(false)\n},\n},\n}\n@@ -2624,7 +2624,7 @@ func TestDelay(t *testing.T) {\nc.CreateConnected(789, 30000, -1 /* epRcvBuf */)\n- c.EP.SetSockOptBool(tcpip.DelayOption, true)\n+ c.EP.SocketOptions().SetDelayOption(true)\nvar allData []byte\nfor i, data := range [][]byte{{0}, {1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {10}, {11}} {\n@@ -2672,7 +2672,7 @@ func TestUndelay(t *testing.T) {\nc.CreateConnected(789, 30000, -1 /* epRcvBuf */)\n- c.EP.SetSockOptBool(tcpip.DelayOption, true)\n+ c.EP.SocketOptions().SetDelayOption(true)\nallData := [][]byte{{0}, {1, 2, 3}}\nfor i, data := range allData {\n@@ -2705,7 +2705,7 @@ func TestUndelay(t *testing.T) {\n// Check that we don't get the second packet yet.\nc.CheckNoPacketTimeout(\"delayed second packet transmitted\", 100*time.Millisecond)\n- c.EP.SetSockOptBool(tcpip.DelayOption, false)\n+ c.EP.SocketOptions().SetDelayOption(false)\n// Check that data is received.\nsecond := c.GetPacket()\n@@ -2742,8 +2742,8 @@ func TestMSSNotDelayed(t *testing.T) {\nfn func(tcpip.Endpoint)\n}{\n{\"no-op\", func(tcpip.Endpoint) {}},\n- {\"delay\", func(ep tcpip.Endpoint) { ep.SetSockOptBool(tcpip.DelayOption, true) }},\n- {\"cork\", func(ep tcpip.Endpoint) { ep.SetSockOptBool(tcpip.CorkOption, true) }},\n+ {\"delay\", func(ep tcpip.Endpoint) { ep.SocketOptions().SetDelayOption(true) }},\n+ {\"cork\", func(ep tcpip.Endpoint) { ep.SocketOptions().SetCorkOption(true) }},\n}\nfor _, test := range tests {\n@@ -6374,10 +6374,7 @@ func checkDelayOption(t *testing.T, c *context.Context, wantDelayEnabled tcpip.T\nif err != nil {\nt.Fatalf(\"NewEndPoint(tcp, ipv4, new(waiter.Queue)) failed: %s\", err)\n}\n- gotDelayOption, err := ep.GetSockOptBool(tcpip.DelayOption)\n- if err != nil {\n- t.Fatalf(\"ep.GetSockOptBool(tcpip.DelayOption) failed: %s\", err)\n- }\n+ gotDelayOption := ep.SocketOptions().GetDelayOption()\nif gotDelayOption != wantDelayOption {\nt.Errorf(\"ep.GetSockOptBool(tcpip.DelayOption) got: %t, want: %t\", gotDelayOption, wantDelayOption)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -575,11 +575,6 @@ func (e *endpoint) OnReusePortSet(v bool) {\ne.mu.Unlock()\n}\n-// SetSockOptBool implements tcpip.Endpoint.SetSockOptBool.\n-func (e *endpoint) SetSockOptBool(opt tcpip.SockOptBool, v bool) *tcpip.Error {\n- return nil\n-}\n-\n// SetSockOptInt implements tcpip.Endpoint.SetSockOptInt.\nfunc (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nswitch opt {\n@@ -789,11 +784,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\nreturn nil\n}\n-// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\n-func (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n- return false, tcpip.ErrUnknownProtocolOption\n-}\n-\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\nswitch opt {\n" } ]
Go
Apache License 2.0
google/gvisor
[netstack] Add SOL_TCP options to SocketOptions. Ports the following options: - TCP_NODELAY - TCP_CORK - TCP_QUICKACK Also deletes the {Get/Set}SockOptBool interface methods from all implementations PiperOrigin-RevId: 344378824
260,004
27.11.2020 12:53:48
28,800
4fd71a7b20d53ba070bd2d937bb980991305b19d
Don't add a temporary address to send DAD/RS packets Bug
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp.go", "new_path": "pkg/tcpip/network/ipv6/ndp.go", "diff": "@@ -471,17 +471,8 @@ type ndpState struct {\n// The default routers discovered through Router Advertisements.\ndefaultRouters map[tcpip.Address]defaultRouterState\n- rtrSolicit struct {\n- // The timer used to send the next router solicitation message.\n- timer tcpip.Timer\n-\n- // Used to let the Router Solicitation timer know that it has been stopped.\n- //\n- // Must only be read from or written to while protected by the lock of\n- // the IPv6 endpoint this ndpState is associated with. MUST be set when the\n- // timer is set.\n- done *bool\n- }\n+ // The job used to send the next router solicitation message.\n+ rtrSolicitJob *tcpip.Job\n// The on-link prefixes discovered through Router Advertisements' Prefix\n// Information option.\n@@ -507,7 +498,7 @@ type ndpState struct {\n// to the DAD goroutine that DAD should stop.\ntype dadState struct {\n// The DAD timer to send the next NS message, or resolve the address.\n- timer tcpip.Timer\n+ job *tcpip.Job\n// Used to let the DAD timer know that it has been stopped.\n//\n@@ -655,22 +646,11 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\nreturn nil\n}\n- var done bool\n- var timer tcpip.Timer\n- // We initially start a timer to fire immediately because some of the DAD work\n- // cannot be done while holding the IPv6 endpoint's lock. This is effectively\n- // the same as starting a goroutine but we use a timer that fires immediately\n- // so we can reset it for the next DAD iteration.\n- timer = ndp.ep.protocol.stack.Clock().AfterFunc(0, func() {\n- ndp.ep.mu.Lock()\n- defer ndp.ep.mu.Unlock()\n-\n- if done {\n- // If we reach this point, it means that the DAD timer fired after\n- // another goroutine already obtained the IPv6 endpoint lock and stopped\n- // DAD before this function obtained the NIC lock. Simply return here and\n- // do nothing further.\n- return\n+ state := dadState{\n+ job: ndp.ep.protocol.stack.NewJob(&ndp.ep.mu, func() {\n+ state, ok := ndp.dad[addr]\n+ if !ok {\n+ panic(fmt.Sprintf(\"ndpdad: DAD timer fired but missing state for %s on NIC(%d)\", addr, ndp.ep.nic.ID()))\n}\nif addressEndpoint.GetKind() != stack.PermanentTentative {\n@@ -683,25 +663,7 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\nvar err *tcpip.Error\nif !dadDone {\n- // Use the unspecified address as the source address when performing DAD.\n- addressEndpoint := ndp.ep.acquireAddressOrCreateTempLocked(header.IPv6Any, true /* createTemp */, stack.NeverPrimaryEndpoint)\n-\n- // Do not hold the lock when sending packets which may be a long running\n- // task or may block link address resolution. We know this is safe\n- // because immediately after obtaining the lock again, we check if DAD\n- // has been stopped before doing any work with the IPv6 endpoint. Note,\n- // DAD would be stopped if the IPv6 endpoint was disabled or closed, or if\n- // the address was removed.\n- ndp.ep.mu.Unlock()\nerr = ndp.sendDADPacket(addr, addressEndpoint)\n- ndp.ep.mu.Lock()\n- addressEndpoint.DecRef()\n- }\n-\n- if done {\n- // If we reach this point, it means that DAD was stopped after we released\n- // the IPv6 endpoint's read lock and before we obtained the write lock.\n- return\n}\nif dadDone {\n@@ -711,13 +673,13 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\n// DAD is not done and we had no errors when sending the last NDP NS,\n// schedule the next DAD timer.\nremaining--\n- timer.Reset(ndp.configs.RetransmitTimer)\n+ state.job.Schedule(ndp.configs.RetransmitTimer)\nreturn\n}\n- // At this point we know that either DAD is done or we hit an error sending\n- // the last NDP NS. Either way, clean up addr's DAD state and let the\n- // integrator know DAD has completed.\n+ // At this point we know that either DAD is done or we hit an error\n+ // sending the last NDP NS. Either way, clean up addr's DAD state and let\n+ // the integrator know DAD has completed.\ndelete(ndp.dad, addr)\nif ndpDisp := ndp.ep.protocol.options.NDPDisp; ndpDisp != nil {\n@@ -731,13 +693,16 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\n// of a new address for the SLAAC prefix.\nndp.regenerateTempSLAACAddr(addressEndpoint.AddressWithPrefix().Subnet(), true /* resetGenAttempts */)\n}\n- })\n-\n- ndp.dad[addr] = dadState{\n- timer: timer,\n- done: &done,\n+ }),\n}\n+ // We initially start a timer to fire immediately because some of the DAD work\n+ // cannot be done while holding the IPv6 endpoint's lock. This is effectively\n+ // the same as starting a goroutine but we use a timer that fires immediately\n+ // so we can reset it for the next DAD iteration.\n+ state.job.Schedule(0)\n+ ndp.dad[addr] = state\n+\nreturn nil\n}\n@@ -745,55 +710,31 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, addressE\n// addr.\n//\n// addr must be a tentative IPv6 address on ndp's IPv6 endpoint.\n-//\n-// The IPv6 endpoint that ndp belongs to MUST NOT be locked.\nfunc (ndp *ndpState) sendDADPacket(addr tcpip.Address, addressEndpoint stack.AddressEndpoint) *tcpip.Error {\nsnmc := header.SolicitedNodeAddr(addr)\n- r, err := ndp.ep.protocol.stack.FindRoute(ndp.ep.nic.ID(), header.IPv6Any, snmc, ProtocolNumber, false /* multicastLoop */)\n- if err != nil {\n- return err\n- }\n- defer r.Release()\n-\n- // Route should resolve immediately since snmc is a multicast address so a\n- // remote link address can be calculated without a resolution process.\n- if c, err := r.Resolve(nil); err != nil {\n- // Do not consider the NIC being unknown or disabled as a fatal error.\n- // Since this method is required to be called when the IPv6 endpoint is not\n- // locked, the NIC could have been disabled or removed by another goroutine.\n- if err == tcpip.ErrUnknownNICID || err != tcpip.ErrInvalidEndpointState {\n- return err\n- }\n-\n- panic(fmt.Sprintf(\"ndp: error when resolving route to send NDP NS for DAD (%s -> %s on NIC(%d)): %s\", header.IPv6Any, snmc, ndp.ep.nic.ID(), err))\n- } else if c != nil {\n- panic(fmt.Sprintf(\"ndp: route resolution not immediate for route to send NDP NS for DAD (%s -> %s on NIC(%d))\", header.IPv6Any, snmc, ndp.ep.nic.ID()))\n- }\n-\n- icmpData := header.ICMPv6(buffer.NewView(header.ICMPv6NeighborSolicitMinimumSize))\n- icmpData.SetType(header.ICMPv6NeighborSolicit)\n- ns := header.NDPNeighborSolicit(icmpData.MessageBody())\n+ icmp := header.ICMPv6(buffer.NewView(header.ICMPv6NeighborSolicitMinimumSize))\n+ icmp.SetType(header.ICMPv6NeighborSolicit)\n+ ns := header.NDPNeighborSolicit(icmp.MessageBody())\nns.SetTargetAddress(addr)\n- icmpData.SetChecksum(header.ICMPv6Checksum(icmpData, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n+ icmp.SetChecksum(header.ICMPv6Checksum(icmp, header.IPv6Any, snmc, buffer.VectorisedView{}))\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: int(r.MaxHeaderLength()),\n- Data: buffer.View(icmpData).ToVectorisedView(),\n+ ReserveHeaderBytes: int(ndp.ep.MaxHeaderLength()),\n+ Data: buffer.View(icmp).ToVectorisedView(),\n})\n- sent := r.Stats().ICMP.V6PacketsSent\n- if err := r.WritePacket(nil,\n- stack.NetworkHeaderParams{\n+ sent := ndp.ep.protocol.stack.Stats().ICMP.V6PacketsSent\n+ ndp.ep.addIPHeader(header.IPv6Any, snmc, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n- }, pkt,\n- ); err != nil {\n+ })\n+\n+ if err := ndp.ep.nic.WritePacketToRemote(header.EthernetAddressFromMulticastIPv6Address(snmc), nil /* gso */, ProtocolNumber, pkt); err != nil {\nsent.Dropped.Increment()\nreturn err\n}\nsent.NeighborSolicit.Increment()\n-\nreturn nil\n}\n@@ -812,14 +753,7 @@ func (ndp *ndpState) stopDuplicateAddressDetection(addr tcpip.Address) {\nreturn\n}\n- if dad.timer != nil {\n- dad.timer.Stop()\n- dad.timer = nil\n-\n- *dad.done = true\n- dad.done = nil\n- }\n-\n+ dad.job.Cancel()\ndelete(ndp.dad, addr)\n// Let the integrator know DAD did not resolve.\n@@ -1859,7 +1793,7 @@ func (ndp *ndpState) cleanupState(hostOnly bool) {\n//\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) startSolicitingRouters() {\n- if ndp.rtrSolicit.timer != nil {\n+ if ndp.rtrSolicitJob != nil {\n// We are already soliciting routers.\nreturn\n}\n@@ -1876,56 +1810,14 @@ func (ndp *ndpState) startSolicitingRouters() {\ndelay = time.Duration(rand.Int63n(int64(ndp.configs.MaxRtrSolicitationDelay)))\n}\n- var done bool\n- ndp.rtrSolicit.done = &done\n- ndp.rtrSolicit.timer = ndp.ep.protocol.stack.Clock().AfterFunc(delay, func() {\n- ndp.ep.mu.Lock()\n- if done {\n- // If we reach this point, it means that the RS timer fired after another\n- // goroutine already obtained the IPv6 endpoint lock and stopped\n- // solicitations. Simply return here and do nothing further.\n- ndp.ep.mu.Unlock()\n- return\n- }\n-\n+ ndp.rtrSolicitJob = ndp.ep.protocol.stack.NewJob(&ndp.ep.mu, func() {\n// As per RFC 4861 section 4.1, the source of the RS is an address assigned\n// to the sending interface, or the unspecified address if no address is\n// assigned to the sending interface.\n- addressEndpoint := ndp.ep.acquireOutgoingPrimaryAddressRLocked(header.IPv6AllRoutersMulticastAddress, false)\n- if addressEndpoint == nil {\n- // Incase this ends up creating a new temporary address, we need to hold\n- // onto the endpoint until a route is obtained. If we decrement the\n- // reference count before obtaing a route, the address's resources would\n- // be released and attempting to obtain a route after would fail. Once a\n- // route is obtainted, it is safe to decrement the reference count since\n- // obtaining a route increments the address's reference count.\n- addressEndpoint = ndp.ep.acquireAddressOrCreateTempLocked(header.IPv6Any, true /* createTemp */, stack.NeverPrimaryEndpoint)\n- }\n- ndp.ep.mu.Unlock()\n-\n- localAddr := addressEndpoint.AddressWithPrefix().Address\n- r, err := ndp.ep.protocol.stack.FindRoute(ndp.ep.nic.ID(), localAddr, header.IPv6AllRoutersMulticastAddress, ProtocolNumber, false /* multicastLoop */)\n+ localAddr := header.IPv6Any\n+ if addressEndpoint := ndp.ep.acquireOutgoingPrimaryAddressRLocked(header.IPv6AllRoutersMulticastAddress, false); addressEndpoint != nil {\n+ localAddr = addressEndpoint.AddressWithPrefix().Address\naddressEndpoint.DecRef()\n- if err != nil {\n- return\n- }\n- defer r.Release()\n-\n- // Route should resolve immediately since\n- // header.IPv6AllRoutersMulticastAddress is a multicast address so a\n- // remote link address can be calculated without a resolution process.\n- if c, err := r.Resolve(nil); err != nil {\n- // Do not consider the NIC being unknown or disabled as a fatal error.\n- // Since this method is required to be called when the IPv6 endpoint is\n- // not locked, the IPv6 endpoint could have been disabled or removed by\n- // another goroutine.\n- if err == tcpip.ErrUnknownNICID || err == tcpip.ErrInvalidEndpointState {\n- return\n- }\n-\n- panic(fmt.Sprintf(\"ndp: error when resolving route to send NDP RS (%s -> %s on NIC(%d)): %s\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.ep.nic.ID(), err))\n- } else if c != nil {\n- panic(fmt.Sprintf(\"ndp: route resolution not immediate for route to send NDP RS (%s -> %s on NIC(%d))\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.ep.nic.ID()))\n}\n// As per RFC 4861 section 4.1, an NDP RS SHOULD include the source\n@@ -1936,9 +1828,10 @@ func (ndp *ndpState) startSolicitingRouters() {\n// TODO(b/141011931): Validate a LinkEndpoint's link address (provided by\n// LinkEndpoint.LinkAddress) before reaching this point.\nvar optsSerializer header.NDPOptionsSerializer\n- if localAddr != header.IPv6Any && header.IsValidUnicastEthernetAddress(r.LocalLinkAddress) {\n+ linkAddress := ndp.ep.nic.LinkAddress()\n+ if localAddr != header.IPv6Any && header.IsValidUnicastEthernetAddress(linkAddress) {\noptsSerializer = header.NDPOptionsSerializer{\n- header.NDPSourceLinkLayerAddressOption(r.LocalLinkAddress),\n+ header.NDPSourceLinkLayerAddressOption(linkAddress),\n}\n}\npayloadSize := header.ICMPv6HeaderSize + header.NDPRSMinimumSize + int(optsSerializer.Length())\n@@ -1946,20 +1839,20 @@ func (ndp *ndpState) startSolicitingRouters() {\nicmpData.SetType(header.ICMPv6RouterSolicit)\nrs := header.NDPRouterSolicit(icmpData.MessageBody())\nrs.Options().Serialize(optsSerializer)\n- icmpData.SetChecksum(header.ICMPv6Checksum(icmpData, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n+ icmpData.SetChecksum(header.ICMPv6Checksum(icmpData, localAddr, header.IPv6AllRoutersMulticastAddress, buffer.VectorisedView{}))\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: int(r.MaxHeaderLength()),\n+ ReserveHeaderBytes: int(ndp.ep.MaxHeaderLength()),\nData: buffer.View(icmpData).ToVectorisedView(),\n})\n- sent := r.Stats().ICMP.V6PacketsSent\n- if err := r.WritePacket(nil,\n- stack.NetworkHeaderParams{\n+ sent := ndp.ep.protocol.stack.Stats().ICMP.V6PacketsSent\n+ ndp.ep.addIPHeader(localAddr, header.IPv6AllRoutersMulticastAddress, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n- }, pkt,\n- ); err != nil {\n+ })\n+\n+ if err := ndp.ep.nic.WritePacketToRemote(header.EthernetAddressFromMulticastIPv6Address(header.IPv6AllRoutersMulticastAddress), nil /* gso */, ProtocolNumber, pkt); err != nil {\nsent.Dropped.Increment()\nlog.Printf(\"startSolicitingRouters: error writing NDP router solicit message on NIC(%d); err = %s\", ndp.ep.nic.ID(), err)\n// Don't send any more messages if we had an error.\n@@ -1969,21 +1862,12 @@ func (ndp *ndpState) startSolicitingRouters() {\nremaining--\n}\n- ndp.ep.mu.Lock()\n- if done || remaining == 0 {\n- ndp.rtrSolicit.timer = nil\n- ndp.rtrSolicit.done = nil\n- } else if ndp.rtrSolicit.timer != nil {\n- // Note, we need to explicitly check to make sure that\n- // the timer field is not nil because if it was nil but\n- // we still reached this point, then we know the IPv6 endpoint\n- // was requested to stop soliciting routers so we don't\n- // need to send the next Router Solicitation message.\n- ndp.rtrSolicit.timer.Reset(ndp.configs.RtrSolicitationInterval)\n+ if remaining != 0 {\n+ ndp.rtrSolicitJob.Schedule(ndp.configs.RtrSolicitationInterval)\n}\n- ndp.ep.mu.Unlock()\n})\n+ ndp.rtrSolicitJob.Schedule(delay)\n}\n// stopSolicitingRouters stops soliciting routers. If routers are not currently\n@@ -1991,15 +1875,13 @@ func (ndp *ndpState) startSolicitingRouters() {\n//\n// The IPv6 endpoint that ndp belongs to MUST be locked.\nfunc (ndp *ndpState) stopSolicitingRouters() {\n- if ndp.rtrSolicit.timer == nil {\n+ if ndp.rtrSolicitJob == nil {\n// Nothing to do.\nreturn\n}\n- *ndp.rtrSolicit.done = true\n- ndp.rtrSolicit.timer.Stop()\n- ndp.rtrSolicit.timer = nil\n- ndp.rtrSolicit.done = nil\n+ ndp.rtrSolicitJob.Cancel()\n+ ndp.rtrSolicitJob = nil\n}\n// initializeTempAddrState initializes state related to temporary SLAAC\n" } ]
Go
Apache License 2.0
google/gvisor
Don't add a temporary address to send DAD/RS packets Bug #4803 PiperOrigin-RevId: 344553664
260,004
30.11.2020 14:22:01
28,800
e813008664ffb361211936dda8631754411cca4f
Perform IGMP/MLD when the NIC is enabled/disabled Test: ip_test.TestMGPWithNICLifecycle Bug
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -123,6 +123,15 @@ func (e *endpoint) Enable() *tcpip.Error {\n// We have no need for the address endpoint.\nep.DecRef()\n+ // Groups may have been joined while the endpoint was disabled, or the\n+ // endpoint may have left groups from the perspective of IGMP when the\n+ // endpoint was disabled. Either way, we need to let routers know to\n+ // send us multicast traffic.\n+ joinedGroups := e.mu.addressableEndpointState.JoinedGroups()\n+ for _, group := range joinedGroups {\n+ e.igmp.joinGroup(group)\n+ }\n+\n// As per RFC 1122 section 3.3.7, all hosts should join the all-hosts\n// multicast group. Note, the IANA calls the all-hosts multicast group the\n// all-systems multicast group.\n@@ -168,6 +177,13 @@ func (e *endpoint) disableLocked() {\npanic(fmt.Sprintf(\"unexpected error when leaving group = %s: %s\", header.IPv4AllSystems, err))\n}\n+ // Leave groups from the perspective of IGMP so that routers know that\n+ // we are no longer interested in the group.\n+ joinedGroups := e.mu.addressableEndpointState.JoinedGroups()\n+ for _, group := range joinedGroups {\n+ e.igmp.leaveGroup(group)\n+ }\n+\n// The address may have already been removed.\nif err := e.mu.addressableEndpointState.RemovePermanentAddress(ipv4BroadcastAddr.Address); err != nil && err != tcpip.ErrBadLocalAddress {\npanic(fmt.Sprintf(\"unexpected error when removing address = %s: %s\", ipv4BroadcastAddr.Address, err))\n@@ -853,6 +869,15 @@ func (e *endpoint) joinGroupLocked(addr tcpip.Address) (bool, *tcpip.Error) {\nreturn joined, err\n}\n+ // Only join the group from the perspective of IGMP when the endpoint is\n+ // enabled.\n+ //\n+ // If we are not enabled right now, we will join the group from the\n+ // perspective of IGMP when the endpoint is enabled.\n+ if !e.Enabled() {\n+ return true, nil\n+ }\n+\n// joinGroup only returns an error if we try to join a group twice, but we\n// checked above to make sure that the group was newly joined.\nif err := e.igmp.joinGroup(addr); err != nil {\n@@ -874,15 +899,12 @@ func (e *endpoint) LeaveGroup(addr tcpip.Address) (bool, *tcpip.Error) {\n// Precondition: e.mu must be locked.\nfunc (e *endpoint) leaveGroupLocked(addr tcpip.Address) (bool, *tcpip.Error) {\nleft, err := e.mu.addressableEndpointState.LeaveGroup(addr)\n- if err != nil {\n+ if err != nil || !left {\nreturn left, err\n}\n- if left {\ne.igmp.leaveGroup(addr)\n- }\n-\n- return left, nil\n+ return true, nil\n}\n// IsInGroup implements stack.GroupAddressableEndpoint.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -228,6 +228,15 @@ func (e *endpoint) Enable() *tcpip.Error {\nreturn nil\n}\n+ // Groups may have been joined when the endpoint was disabled, or the\n+ // endpoint may have left groups from the perspective of MLD when the\n+ // endpoint was disabled. Either way, we need to let routers know to\n+ // send us multicast traffic.\n+ joinedGroups := e.mu.addressableEndpointState.JoinedGroups()\n+ for _, group := range joinedGroups {\n+ e.mld.joinGroup(group)\n+ }\n+\n// Join the IPv6 All-Nodes Multicast group if the stack is configured to\n// use IPv6. This is required to ensure that this node properly receives\n// and responds to the various NDP messages that are destined to the\n@@ -338,6 +347,13 @@ func (e *endpoint) disableLocked() {\nif _, err := e.leaveGroupLocked(header.IPv6AllNodesMulticastAddress); err != nil && err != tcpip.ErrBadLocalAddress {\npanic(fmt.Sprintf(\"unexpected error when leaving group = %s: %s\", header.IPv6AllNodesMulticastAddress, err))\n}\n+\n+ // Leave groups from the perspective of MLD so that routers know that\n+ // we are no longer interested in the group.\n+ joinedGroups := e.mu.addressableEndpointState.JoinedGroups()\n+ for _, group := range joinedGroups {\n+ e.mld.leaveGroup(group)\n+ }\n}\n// stopDADForPermanentAddressesLocked stops DAD for all permaneent addresses.\n@@ -1409,6 +1425,15 @@ func (e *endpoint) joinGroupLocked(addr tcpip.Address) (bool, *tcpip.Error) {\nreturn joined, err\n}\n+ // Only join the group from the perspective of IGMP when the endpoint is\n+ // enabled.\n+ //\n+ // If we are not enabled right now, we will join the group from the\n+ // perspective of MLD when the endpoint is enabled.\n+ if !e.Enabled() {\n+ return true, nil\n+ }\n+\n// joinGroup only returns an error if we try to join a group twice, but we\n// checked above to make sure that the group was newly joined.\nif err := e.mld.joinGroup(addr); err != nil {\n@@ -1430,15 +1455,12 @@ func (e *endpoint) LeaveGroup(addr tcpip.Address) (bool, *tcpip.Error) {\n// Precondition: e.mu must be locked.\nfunc (e *endpoint) leaveGroupLocked(addr tcpip.Address) (bool, *tcpip.Error) {\nleft, err := e.mu.addressableEndpointState.LeaveGroup(addr)\n- if err != nil {\n+ if err != nil || !left {\nreturn left, err\n}\n- if left {\ne.mld.leaveGroup(addr)\n- }\n-\n- return left, nil\n+ return true, nil\n}\n// IsInGroup implements stack.GroupAddressableEndpoint.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/multicast_group_test.go", "new_path": "pkg/tcpip/network/multicast_group_test.go", "diff": "@@ -34,8 +34,12 @@ import (\nconst (\nlinkAddr = tcpip.LinkAddress(\"\\x02\\x02\\x03\\x04\\x05\\x06\")\n- ipv4MulticastAddr = tcpip.Address(\"\\xe0\\x00\\x00\\x03\")\n- ipv6MulticastAddr = tcpip.Address(\"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\")\n+ ipv4MulticastAddr1 = tcpip.Address(\"\\xe0\\x00\\x00\\x03\")\n+ ipv4MulticastAddr2 = tcpip.Address(\"\\xe0\\x00\\x00\\x04\")\n+ ipv4MulticastAddr3 = tcpip.Address(\"\\xe0\\x00\\x00\\x05\")\n+ ipv6MulticastAddr1 = tcpip.Address(\"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\")\n+ ipv6MulticastAddr2 = tcpip.Address(\"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\")\n+ ipv6MulticastAddr3 = tcpip.Address(\"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\")\nigmpMembershipQuery = uint8(header.IGMPMembershipQuery)\nigmpv1MembershipReport = uint8(header.IGMPv1MembershipReport)\n@@ -97,9 +101,9 @@ func validateIGMPPacket(t *testing.T, p channel.PacketInfo, remoteAddress tcpip.\nfunc createStack(t *testing.T, mgpEnabled bool) (*channel.Endpoint, *stack.Stack, *faketime.ManualClock) {\nt.Helper()\n- // Create an endpoint of queue size 1, since no more than 1 packets are ever\n+ // Create an endpoint of queue size 2, since no more than 2 packets are ever\n// queued in the tests in this file.\n- e := channel.New(1, 1280, linkAddr)\n+ e := channel.New(2, 1280, linkAddr)\nclock := faketime.NewManualClock()\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{\n@@ -198,7 +202,7 @@ func TestMGPDisabled(t *testing.T) {\n{\nname: \"IGMP\",\nprotoNum: ipv4.ProtocolNumber,\n- multicastAddr: ipv4MulticastAddr,\n+ multicastAddr: ipv4MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().IGMP.PacketsSent.V2MembershipReport\n},\n@@ -212,7 +216,7 @@ func TestMGPDisabled(t *testing.T) {\n{\nname: \"MLD\",\nprotoNum: ipv6.ProtocolNumber,\n- multicastAddr: ipv6MulticastAddr,\n+ multicastAddr: ipv6MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n},\n@@ -375,7 +379,7 @@ func TestMGPJoinGroup(t *testing.T) {\n{\nname: \"IGMP\",\nprotoNum: ipv4.ProtocolNumber,\n- multicastAddr: ipv4MulticastAddr,\n+ multicastAddr: ipv4MulticastAddr1,\nmaxUnsolicitedResponseDelay: ipv4.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().IGMP.PacketsSent.V2MembershipReport\n@@ -384,13 +388,15 @@ func TestMGPJoinGroup(t *testing.T) {\nreturn s.Stats().IGMP.PacketsReceived.MembershipQuery\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateIGMPPacket(t, p, ipv4MulticastAddr, igmpv2MembershipReport, 0, ipv4MulticastAddr)\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, ipv4MulticastAddr1, igmpv2MembershipReport, 0, ipv4MulticastAddr1)\n},\n},\n{\nname: \"MLD\",\nprotoNum: ipv6.ProtocolNumber,\n- multicastAddr: ipv6MulticastAddr,\n+ multicastAddr: ipv6MulticastAddr1,\nmaxUnsolicitedResponseDelay: ipv6.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n@@ -399,7 +405,9 @@ func TestMGPJoinGroup(t *testing.T) {\nreturn s.Stats().ICMP.V6PacketsReceived.MulticastListenerQuery\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateMLDPacket(t, p, ipv6MulticastAddr, mldReport, 0, ipv6MulticastAddr)\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, ipv6MulticastAddr1, mldReport, 0, ipv6MulticastAddr1)\n},\n},\n}\n@@ -466,7 +474,7 @@ func TestMGPLeaveGroup(t *testing.T) {\n{\nname: \"IGMP\",\nprotoNum: ipv4.ProtocolNumber,\n- multicastAddr: ipv4MulticastAddr,\n+ multicastAddr: ipv4MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().IGMP.PacketsSent.V2MembershipReport\n},\n@@ -474,16 +482,20 @@ func TestMGPLeaveGroup(t *testing.T) {\nreturn s.Stats().IGMP.PacketsSent.LeaveGroup\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateIGMPPacket(t, p, ipv4MulticastAddr, igmpv2MembershipReport, 0, ipv4MulticastAddr)\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, ipv4MulticastAddr1, igmpv2MembershipReport, 0, ipv4MulticastAddr1)\n},\nvalidateLeave: func(t *testing.T, p channel.PacketInfo) {\n- validateIGMPPacket(t, p, header.IPv4AllRoutersGroup, igmpLeaveGroup, 0, ipv4MulticastAddr)\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, header.IPv4AllRoutersGroup, igmpLeaveGroup, 0, ipv4MulticastAddr1)\n},\n},\n{\nname: \"MLD\",\nprotoNum: ipv6.ProtocolNumber,\n- multicastAddr: ipv6MulticastAddr,\n+ multicastAddr: ipv6MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n},\n@@ -491,10 +503,14 @@ func TestMGPLeaveGroup(t *testing.T) {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerDone\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateMLDPacket(t, p, ipv6MulticastAddr, mldReport, 0, ipv6MulticastAddr)\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, ipv6MulticastAddr1, mldReport, 0, ipv6MulticastAddr1)\n},\nvalidateLeave: func(t *testing.T, p channel.PacketInfo) {\n- validateMLDPacket(t, p, header.IPv6AllRoutersMulticastAddress, mldDone, 0, ipv6MulticastAddr)\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, header.IPv6AllRoutersMulticastAddress, mldDone, 0, ipv6MulticastAddr1)\n},\n},\n}\n@@ -557,7 +573,7 @@ func TestMGPQueryMessages(t *testing.T) {\n{\nname: \"IGMP\",\nprotoNum: ipv4.ProtocolNumber,\n- multicastAddr: ipv4MulticastAddr,\n+ multicastAddr: ipv4MulticastAddr1,\nmaxUnsolicitedResponseDelay: ipv4.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().IGMP.PacketsSent.V2MembershipReport\n@@ -569,14 +585,16 @@ func TestMGPQueryMessages(t *testing.T) {\ncreateAndInjectIGMPPacket(e, igmpMembershipQuery, maxRespTime, groupAddress)\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateIGMPPacket(t, p, ipv4MulticastAddr, igmpv2MembershipReport, 0, ipv4MulticastAddr)\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, ipv4MulticastAddr1, igmpv2MembershipReport, 0, ipv4MulticastAddr1)\n},\nmaxRespTimeToDuration: header.DecisecondToDuration,\n},\n{\nname: \"MLD\",\nprotoNum: ipv6.ProtocolNumber,\n- multicastAddr: ipv6MulticastAddr,\n+ multicastAddr: ipv6MulticastAddr1,\nmaxUnsolicitedResponseDelay: ipv6.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n@@ -588,7 +606,9 @@ func TestMGPQueryMessages(t *testing.T) {\ncreateAndInjectMLDPacket(e, mldQuery, maxRespTime, groupAddress)\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateMLDPacket(t, p, ipv6MulticastAddr, mldReport, 0, ipv6MulticastAddr)\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, ipv6MulticastAddr1, mldReport, 0, ipv6MulticastAddr1)\n},\nmaxRespTimeToDuration: func(d uint8) time.Duration {\nreturn time.Duration(d) * time.Millisecond\n@@ -702,7 +722,7 @@ func TestMGPReportMessages(t *testing.T) {\n{\nname: \"IGMP\",\nprotoNum: ipv4.ProtocolNumber,\n- multicastAddr: ipv4MulticastAddr,\n+ multicastAddr: ipv4MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().IGMP.PacketsSent.V2MembershipReport\n},\n@@ -710,17 +730,19 @@ func TestMGPReportMessages(t *testing.T) {\nreturn s.Stats().IGMP.PacketsSent.LeaveGroup\n},\nrxReport: func(e *channel.Endpoint) {\n- createAndInjectIGMPPacket(e, igmpv2MembershipReport, 0, ipv4MulticastAddr)\n+ createAndInjectIGMPPacket(e, igmpv2MembershipReport, 0, ipv4MulticastAddr1)\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateIGMPPacket(t, p, ipv4MulticastAddr, igmpv2MembershipReport, 0, ipv4MulticastAddr)\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, ipv4MulticastAddr1, igmpv2MembershipReport, 0, ipv4MulticastAddr1)\n},\nmaxRespTimeToDuration: header.DecisecondToDuration,\n},\n{\nname: \"MLD\",\nprotoNum: ipv6.ProtocolNumber,\n- multicastAddr: ipv6MulticastAddr,\n+ multicastAddr: ipv6MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n},\n@@ -728,10 +750,12 @@ func TestMGPReportMessages(t *testing.T) {\nreturn s.Stats().ICMP.V6PacketsSent.MulticastListenerDone\n},\nrxReport: func(e *channel.Endpoint) {\n- createAndInjectMLDPacket(e, mldReport, 0, ipv6MulticastAddr)\n+ createAndInjectMLDPacket(e, mldReport, 0, ipv6MulticastAddr1)\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\n- validateMLDPacket(t, p, ipv6MulticastAddr, mldReport, 0, ipv6MulticastAddr)\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, ipv6MulticastAddr1, mldReport, 0, ipv6MulticastAddr1)\n},\nmaxRespTimeToDuration: func(d uint8) time.Duration {\nreturn time.Duration(d) * time.Millisecond\n@@ -791,3 +815,254 @@ func TestMGPReportMessages(t *testing.T) {\n})\n}\n}\n+\n+func TestMGPWithNICLifecycle(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ protoNum tcpip.NetworkProtocolNumber\n+ multicastAddrs []tcpip.Address\n+ finalMulticastAddr tcpip.Address\n+ maxUnsolicitedResponseDelay time.Duration\n+ sentReportStat func(*stack.Stack) *tcpip.StatCounter\n+ sentLeaveStat func(*stack.Stack) *tcpip.StatCounter\n+ validateReport func(*testing.T, channel.PacketInfo, tcpip.Address)\n+ validateLeave func(*testing.T, channel.PacketInfo, tcpip.Address)\n+ getAndCheckGroupAddress func(*testing.T, map[tcpip.Address]bool, channel.PacketInfo) tcpip.Address\n+ }{\n+ {\n+ name: \"IGMP\",\n+ protoNum: ipv4.ProtocolNumber,\n+ multicastAddrs: []tcpip.Address{ipv4MulticastAddr1, ipv4MulticastAddr2},\n+ finalMulticastAddr: ipv4MulticastAddr3,\n+ maxUnsolicitedResponseDelay: ipv4.UnsolicitedReportIntervalMax,\n+ sentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n+ return s.Stats().IGMP.PacketsSent.V2MembershipReport\n+ },\n+ sentLeaveStat: func(s *stack.Stack) *tcpip.StatCounter {\n+ return s.Stats().IGMP.PacketsSent.LeaveGroup\n+ },\n+ validateReport: func(t *testing.T, p channel.PacketInfo, addr tcpip.Address) {\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, addr, igmpv2MembershipReport, 0, addr)\n+ },\n+ validateLeave: func(t *testing.T, p channel.PacketInfo, addr tcpip.Address) {\n+ t.Helper()\n+\n+ validateIGMPPacket(t, p, header.IPv4AllRoutersGroup, igmpLeaveGroup, 0, addr)\n+ },\n+ getAndCheckGroupAddress: func(t *testing.T, seen map[tcpip.Address]bool, p channel.PacketInfo) tcpip.Address {\n+ t.Helper()\n+\n+ ipv4 := header.IPv4(stack.PayloadSince(p.Pkt.NetworkHeader()))\n+ if got := tcpip.TransportProtocolNumber(ipv4.Protocol()); got != header.IGMPProtocolNumber {\n+ t.Fatalf(\"got ipv4.Protocol() = %d, want = %d\", got, header.IGMPProtocolNumber)\n+ }\n+ addr := header.IGMP(ipv4.Payload()).GroupAddress()\n+ s, ok := seen[addr]\n+ if !ok {\n+ t.Fatalf(\"unexpectedly got a packet for group %s\", addr)\n+ }\n+ if s {\n+ t.Fatalf(\"already saw packet for group %s\", addr)\n+ }\n+ seen[addr] = true\n+ return addr\n+ },\n+ },\n+ {\n+ name: \"MLD\",\n+ protoNum: ipv6.ProtocolNumber,\n+ multicastAddrs: []tcpip.Address{ipv6MulticastAddr1, ipv6MulticastAddr2},\n+ finalMulticastAddr: ipv6MulticastAddr3,\n+ maxUnsolicitedResponseDelay: ipv6.UnsolicitedReportIntervalMax,\n+ sentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n+ return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ },\n+ sentLeaveStat: func(s *stack.Stack) *tcpip.StatCounter {\n+ return s.Stats().ICMP.V6PacketsSent.MulticastListenerDone\n+ },\n+ validateReport: func(t *testing.T, p channel.PacketInfo, addr tcpip.Address) {\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, addr, mldReport, 0, addr)\n+ },\n+ validateLeave: func(t *testing.T, p channel.PacketInfo, addr tcpip.Address) {\n+ t.Helper()\n+\n+ validateMLDPacket(t, p, header.IPv6AllRoutersMulticastAddress, mldDone, 0, addr)\n+ },\n+ getAndCheckGroupAddress: func(t *testing.T, seen map[tcpip.Address]bool, p channel.PacketInfo) tcpip.Address {\n+ t.Helper()\n+\n+ ipv6 := header.IPv6(stack.PayloadSince(p.Pkt.NetworkHeader()))\n+ if got := tcpip.TransportProtocolNumber(ipv6.NextHeader()); got != header.ICMPv6ProtocolNumber {\n+ t.Fatalf(\"got ipv6.NextHeader() = %d, want = %d\", got, header.ICMPv6ProtocolNumber)\n+ }\n+ icmpv6 := header.ICMPv6(ipv6.Payload())\n+ if got := icmpv6.Type(); got != header.ICMPv6MulticastListenerReport && got != header.ICMPv6MulticastListenerDone {\n+ t.Fatalf(\"got icmpv6.Type() = %d, want = %d or %d\", got, header.ICMPv6MulticastListenerReport, header.ICMPv6MulticastListenerDone)\n+ }\n+ addr := header.MLD(icmpv6.MessageBody()).MulticastAddress()\n+ s, ok := seen[addr]\n+ if !ok {\n+ t.Fatalf(\"unexpectedly got a packet for group %s\", addr)\n+ }\n+ if s {\n+ t.Fatalf(\"already saw packet for group %s\", addr)\n+ }\n+ seen[addr] = true\n+ return addr\n+\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ e, s, clock := createStack(t, true)\n+\n+ sentReportStat := test.sentReportStat(s)\n+ var reportCounter uint64\n+ for _, a := range test.multicastAddrs {\n+ if err := s.JoinGroup(test.protoNum, nicID, a); err != nil {\n+ t.Fatalf(\"JoinGroup(%d, %d, %s): %s\", test.protoNum, nicID, a, err)\n+ }\n+ reportCounter++\n+ if got := sentReportStat.Value(); got != reportCounter {\n+ t.Errorf(\"got sentReportStat.Value() = %d, want = %d\", got, reportCounter)\n+ }\n+ if p, ok := e.Read(); !ok {\n+ t.Fatalf(\"expected a report message to be sent for %s\", a)\n+ } else {\n+ test.validateReport(t, p, a)\n+ }\n+ }\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+\n+ // Leave messages should be sent for the joined groups when the NIC is\n+ // disabled.\n+ if err := s.DisableNIC(nicID); err != nil {\n+ t.Fatalf(\"DisableNIC(%d): %s\", nicID, err)\n+ }\n+ sentLeaveStat := test.sentLeaveStat(s)\n+ leaveCounter := uint64(len(test.multicastAddrs))\n+ if got := sentLeaveStat.Value(); got != leaveCounter {\n+ t.Errorf(\"got sentLeaveStat.Value() = %d, want = %d\", got, leaveCounter)\n+ }\n+ {\n+ seen := make(map[tcpip.Address]bool)\n+ for _, a := range test.multicastAddrs {\n+ seen[a] = false\n+ }\n+\n+ for i, _ := range test.multicastAddrs {\n+ p, ok := e.Read()\n+ if !ok {\n+ t.Fatalf(\"expected (%d-th) leave message to be sent\", i)\n+ }\n+\n+ test.validateLeave(t, p, test.getAndCheckGroupAddress(t, seen, p))\n+ }\n+ }\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+\n+ // Reports should be sent for the joined groups when the NIC is enabled.\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"EnableNIC(%d): %s\", nicID, err)\n+ }\n+ reportCounter += uint64(len(test.multicastAddrs))\n+ if got := sentReportStat.Value(); got != reportCounter {\n+ t.Errorf(\"got sentReportStat.Value() = %d, want = %d\", got, reportCounter)\n+ }\n+ {\n+ seen := make(map[tcpip.Address]bool)\n+ for _, a := range test.multicastAddrs {\n+ seen[a] = false\n+ }\n+\n+ for i, _ := range test.multicastAddrs {\n+ p, ok := e.Read()\n+ if !ok {\n+ t.Fatalf(\"expected (%d-th) report message to be sent\", i)\n+ }\n+\n+ test.validateReport(t, p, test.getAndCheckGroupAddress(t, seen, p))\n+ }\n+ }\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+\n+ // Joining/leaving a group while disabled should not send any messages.\n+ if err := s.DisableNIC(nicID); err != nil {\n+ t.Fatalf(\"DisableNIC(%d): %s\", nicID, err)\n+ }\n+ leaveCounter += uint64(len(test.multicastAddrs))\n+ if got := sentLeaveStat.Value(); got != leaveCounter {\n+ t.Errorf(\"got sentLeaveStat.Value() = %d, want = %d\", got, leaveCounter)\n+ }\n+ for i, _ := range test.multicastAddrs {\n+ if _, ok := e.Read(); !ok {\n+ t.Fatalf(\"expected (%d-th) leave message to be sent\", i)\n+ }\n+ }\n+ for _, a := range test.multicastAddrs {\n+ if err := s.LeaveGroup(test.protoNum, nicID, a); err != nil {\n+ t.Fatalf(\"LeaveGroup(%d, nic, %s): %s\", test.protoNum, a, err)\n+ }\n+ if got := sentLeaveStat.Value(); got != leaveCounter {\n+ t.Errorf(\"got sentLeaveStat.Value() = %d, want = %d\", got, leaveCounter)\n+ }\n+ if p, ok := e.Read(); ok {\n+ t.Fatalf(\"leaving group %s on disabled NIC sent unexpected packet = %#v\", a, p.Pkt)\n+ }\n+ }\n+ if err := s.JoinGroup(test.protoNum, nicID, test.finalMulticastAddr); err != nil {\n+ t.Fatalf(\"JoinGroup(%d, %d, %s): %s\", test.protoNum, nicID, test.finalMulticastAddr, err)\n+ }\n+ if got := sentReportStat.Value(); got != reportCounter {\n+ t.Errorf(\"got sentReportStat.Value() = %d, want = %d\", got, reportCounter)\n+ }\n+ if p, ok := e.Read(); ok {\n+ t.Fatalf(\"joining group %s on disabled NIC sent unexpected packet = %#v\", test.finalMulticastAddr, p.Pkt)\n+ }\n+\n+ // A report should only be sent for the group we last joined after\n+ // enabling the NIC since the original groups were all left.\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"EnableNIC(%d): %s\", nicID, err)\n+ }\n+ reportCounter++\n+ if got := sentReportStat.Value(); got != reportCounter {\n+ t.Errorf(\"got sentReportStat.Value() = %d, want = %d\", got, reportCounter)\n+ }\n+ if p, ok := e.Read(); !ok {\n+ t.Fatal(\"expected a report message to be sent\")\n+ } else {\n+ test.validateReport(t, p, test.finalMulticastAddr)\n+ }\n+\n+ clock.Advance(test.maxUnsolicitedResponseDelay)\n+ reportCounter++\n+ if got := sentReportStat.Value(); got != reportCounter {\n+ t.Errorf(\"got sentReportState.Value() = %d, want = %d\", got, reportCounter)\n+ }\n+ if p, ok := e.Read(); !ok {\n+ t.Fatal(\"expected a report message to be sent\")\n+ } else {\n+ test.validateReport(t, p, test.finalMulticastAddr)\n+ }\n+\n+ // Should not send any more packets.\n+ clock.Advance(time.Hour)\n+ if p, ok := e.Read(); ok {\n+ t.Fatalf(\"sent unexpected packet = %#v\", p)\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/addressable_endpoint_state.go", "new_path": "pkg/tcpip/stack/addressable_endpoint_state.go", "diff": "@@ -625,6 +625,17 @@ func (a *AddressableEndpointState) IsInGroup(group tcpip.Address) bool {\nreturn ok\n}\n+// JoinedGroups returns a list of groups the endpoint is a member of.\n+func (a *AddressableEndpointState) JoinedGroups() []tcpip.Address {\n+ a.mu.RLock()\n+ defer a.mu.RUnlock()\n+ groups := make([]tcpip.Address, 0, len(a.mu.groups))\n+ for g := range a.mu.groups {\n+ groups = append(groups, g)\n+ }\n+ return groups\n+}\n+\n// Cleanup forcefully leaves all groups and removes all permanent addresses.\nfunc (a *AddressableEndpointState) Cleanup() {\na.mu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/addressable_endpoint_state_test.go", "new_path": "pkg/tcpip/stack/addressable_endpoint_state_test.go", "diff": "package stack_test\nimport (\n+ \"sort\"\n\"testing\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n+func TestJoinedGroups(t *testing.T) {\n+ const addr1 = tcpip.Address(\"\\x01\")\n+ const addr2 = tcpip.Address(\"\\x02\")\n+\n+ var ep fakeNetworkEndpoint\n+ var s stack.AddressableEndpointState\n+ s.Init(&ep)\n+\n+ if joined, err := s.JoinGroup(addr1); err != nil {\n+ t.Fatalf(\"JoinGroup(%s): %s\", addr1, err)\n+ } else if !joined {\n+ t.Errorf(\"got JoinGroup(%s) = false, want = true\", addr1)\n+ }\n+ if joined, err := s.JoinGroup(addr2); err != nil {\n+ t.Fatalf(\"JoinGroup(%s): %s\", addr2, err)\n+ } else if !joined {\n+ t.Errorf(\"got JoinGroup(%s) = false, want = true\", addr2)\n+ }\n+\n+ joinedGroups := s.JoinedGroups()\n+ sort.Slice(joinedGroups, func(i, j int) bool { return joinedGroups[i][0] < joinedGroups[j][0] })\n+ if diff := cmp.Diff([]tcpip.Address{addr1, addr2}, joinedGroups); diff != \"\" {\n+ t.Errorf(\"joined groups mismatch (-want +got):\\n%s\", diff)\n+ }\n+}\n+\n// TestAddressableEndpointStateCleanup tests that cleaning up an addressable\n// endpoint state removes permanent addresses and leaves groups.\nfunc TestAddressableEndpointStateCleanup(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Perform IGMP/MLD when the NIC is enabled/disabled Test: ip_test.TestMGPWithNICLifecycle Bug #4682, #4861 PiperOrigin-RevId: 344888091
259,964
30.11.2020 16:34:33
28,800
54ad145f2eb6d16a3a18b69e1c2adfa558639b72
Add more fragment reassembly tests These tests check if a maximum-sized (64k) packet is reassembled without receiving a fragment with MF flag set to zero.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -2424,6 +2424,28 @@ func TestReceiveFragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload4Addr1ToAddr2},\n},\n+ {\n+ name: \"Two fragments with MF flag reassembled into a maximum UDP packet\",\n+ fragments: []fragmentData{\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload4Addr1ToAddr2[:65512],\n+ },\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 65512,\n+ payload: ipv4Payload4Addr1ToAddr2[65512:],\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n}\nfor _, test := range tests {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -1009,6 +1009,7 @@ func TestReceiveIPv6Fragments(t *testing.T) {\n// the fragment block size of 8 (RFC 8200 section 4.5).\nudpPayload3Length = 127\nudpPayload4Length = header.IPv6MaximumPayloadSize - header.UDPMinimumSize\n+ udpMaximumSizeMinus15 = header.UDPMaximumSize - 15\nfragmentExtHdrLen = 8\n// Note, not all routing extension headers will be 8 bytes but this test\n// uses 8 byte routing extension headers for most sub tests.\n@@ -1353,14 +1354,14 @@ func TestReceiveIPv6Fragments(t *testing.T) {\ndstAddr: addr2,\nnextHdr: fragmentExtHdrID,\ndata: buffer.NewVectorisedView(\n- fragmentExtHdrLen+65520,\n+ fragmentExtHdrLen+udpMaximumSizeMinus15,\n[]buffer.View{\n// Fragment extension header.\n//\n// Fragment offset = 0, More = true, ID = 1\nbuffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 1}),\n- ipv6Payload4Addr1ToAddr2[:65520],\n+ ipv6Payload4Addr1ToAddr2[:udpMaximumSizeMinus15],\n},\n),\n},\n@@ -1369,20 +1370,64 @@ func TestReceiveIPv6Fragments(t *testing.T) {\ndstAddr: addr2,\nnextHdr: fragmentExtHdrID,\ndata: buffer.NewVectorisedView(\n- fragmentExtHdrLen+len(ipv6Payload4Addr1ToAddr2)-65520,\n+ fragmentExtHdrLen+len(ipv6Payload4Addr1ToAddr2)-udpMaximumSizeMinus15,\n[]buffer.View{\n// Fragment extension header.\n//\n- // Fragment offset = 8190, More = false, ID = 1\n- buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 255, 240, 0, 0, 0, 1}),\n+ // Fragment offset = udpMaximumSizeMinus15/8, More = false, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0,\n+ udpMaximumSizeMinus15 >> 8,\n+ udpMaximumSizeMinus15 & 0xff,\n+ 0, 0, 0, 1}),\n- ipv6Payload4Addr1ToAddr2[65520:],\n+ ipv6Payload4Addr1ToAddr2[udpMaximumSizeMinus15:],\n},\n),\n},\n},\nexpectedPayloads: [][]byte{udpPayload4Addr1ToAddr2},\n},\n+ {\n+ name: \"Two fragments with MF flag reassembled into a maximum UDP packet\",\n+ fragments: []fragmentData{\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+udpMaximumSizeMinus15,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 0, More = true, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 1}),\n+\n+ ipv6Payload4Addr1ToAddr2[:udpMaximumSizeMinus15],\n+ },\n+ ),\n+ },\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+len(ipv6Payload4Addr1ToAddr2)-udpMaximumSizeMinus15,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = udpMaximumSizeMinus15/8, More = true, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0,\n+ udpMaximumSizeMinus15 >> 8,\n+ (udpMaximumSizeMinus15 & 0xff) + 1,\n+ 0, 0, 0, 1}),\n+\n+ ipv6Payload4Addr1ToAddr2[udpMaximumSizeMinus15:],\n+ },\n+ ),\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n{\nname: \"Two fragments with per-fragment routing header with zero segments left\",\nfragments: []fragmentData{\n" } ]
Go
Apache License 2.0
google/gvisor
Add more fragment reassembly tests These tests check if a maximum-sized (64k) packet is reassembled without receiving a fragment with MF flag set to zero. PiperOrigin-RevId: 344913172
259,898
30.11.2020 21:21:21
28,800
59a2c785bfba56e2ffb04083c213fa2ad23a36a2
Do not start a ContainerExec twice ContainerExecStart and ContainerExecAttach both call the /exec/id/start API endpoint.
[ { "change_type": "MODIFY", "old_path": "pkg/test/dockerutil/exec.go", "new_path": "pkg/test/dockerutil/exec.go", "diff": "@@ -77,11 +77,6 @@ func (c *Container) doExec(ctx context.Context, r ExecOpts, args []string) (Proc\nreturn Process{}, fmt.Errorf(\"exec attach failed with err: %v\", err)\n}\n- if err := c.client.ContainerExecStart(ctx, resp.ID, types.ExecStartCheck{}); err != nil {\n- hijack.Close()\n- return Process{}, fmt.Errorf(\"exec start failed with err: %v\", err)\n- }\n-\nreturn Process{\ncontainer: c,\nexecid: resp.ID,\n" } ]
Go
Apache License 2.0
google/gvisor
Do not start a ContainerExec twice ContainerExecStart and ContainerExecAttach both call the /exec/id/start API endpoint. PiperOrigin-RevId: 344946627
259,860
30.11.2020 23:14:35
28,800
6b1dbbbdc8ec0b5d04e0961a216bd7323dbc45fb
Fix typo in ptrace documentation.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/ptrace.go", "new_path": "pkg/sentry/platform/ptrace/ptrace.go", "diff": "//\n// In a nutshell, it works as follows:\n//\n-// The creation of a new address space creates a new child processes with a\n-// single thread which is traced by a single goroutine.\n+// The creation of a new address space creates a new child process with a single\n+// thread which is traced by a single goroutine.\n//\n// A context is just a collection of temporary variables. Calling Switch on a\n// context does the following:\n" } ]
Go
Apache License 2.0
google/gvisor
Fix typo in ptrace documentation. PiperOrigin-RevId: 344958513
259,898
01.12.2020 18:52:02
28,800
aa419cef4b0189d0dbe739e65553482a135cd5d1
Avoid wrong error messages Stop showing wrong timeout values in packetimpact test error messages. e.g. "got frames ... want ... during -123ms"
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -598,7 +598,7 @@ func (conn *Connection) ExpectFrame(t *testing.T, layers Layers, timeout time.Du\nvar errs error\nfor {\nvar gotLayers Layers\n- if timeout = time.Until(deadline); timeout > 0 {\n+ if timeout := time.Until(deadline); timeout > 0 {\ngotLayers = conn.recvFrame(t, timeout)\n}\nif gotLayers == nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid wrong error messages Stop showing wrong timeout values in packetimpact test error messages. e.g. "got frames ... want ... during -123ms" PiperOrigin-RevId: 345144938
260,004
01.12.2020 21:32:36
28,800
0c497394226b762dfd31b83bb33043d19073b0a4
Correctly lock when listing neighbor entries
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -182,14 +182,15 @@ func (n *neighborCache) removeWaker(addr tcpip.Address, waker *sleep.Waker) {\n// entries returns all entries in the neighbor cache.\nfunc (n *neighborCache) entries() []NeighborEntry {\n- entries := make([]NeighborEntry, 0, len(n.cache))\nn.mu.RLock()\n+ defer n.mu.RUnlock()\n+\n+ entries := make([]NeighborEntry, 0, len(n.cache))\nfor _, entry := range n.cache {\nentry.mu.RLock()\nentries = append(entries, entry.neigh)\nentry.mu.RUnlock()\n}\n- n.mu.RUnlock()\nreturn entries\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Correctly lock when listing neighbor entries PiperOrigin-RevId: 345162450
260,004
01.12.2020 21:56:09
28,800
41675ebc6308bef2f227339d075b3af8b4062eec
Deflake stack_test.TestRouterSolicitation ...by using the fake clock. TestRouterSolicitation no longer runs its sub-tests in parallel now that the sub-tests are not long-running - the fake clock simulates time moving forward.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -120,6 +120,7 @@ go_test(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/checker\",\n+ \"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/link/loopback\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n@@ -5174,20 +5175,9 @@ func TestRouterSolicitation(t *testing.T) {\n},\n}\n- // This Run will not return until the parallel tests finish.\n- //\n- // We need this because we need to do some teardown work after the\n- // parallel tests complete.\n- //\n- // See https://godoc.org/testing#hdr-Subtests_and_Sub_benchmarks for\n- // more details.\n- t.Run(\"group\", func(t *testing.T) {\nfor _, test := range tests {\n- test := test\n-\nt.Run(test.name, func(t *testing.T) {\n- t.Parallel()\n-\n+ clock := faketime.NewManualClock()\ne := channelLinkWithHeaderLength{\nEndpoint: channel.New(int(test.maxRtrSolicit), 1280, test.linkAddr),\nheaderLength: test.linkHeaderLen,\n@@ -5195,12 +5185,11 @@ func TestRouterSolicitation(t *testing.T) {\ne.Endpoint.LinkEPCapabilities |= stack.CapabilityResolutionRequired\nwaitForPkt := func(timeout time.Duration) {\nt.Helper()\n- ctx, cancel := context.WithTimeout(context.Background(), timeout)\n- defer cancel()\n- p, ok := e.ReadContext(ctx)\n+\n+ clock.Advance(timeout)\n+ p, ok := e.Read()\nif !ok {\n- t.Fatal(\"timed out waiting for packet\")\n- return\n+ t.Fatal(\"expected router solicitation packet\")\n}\nif p.Proto != header.IPv6ProtocolNumber {\n@@ -5225,10 +5214,10 @@ func TestRouterSolicitation(t *testing.T) {\n}\nwaitForNothing := func(timeout time.Duration) {\nt.Helper()\n- ctx, cancel := context.WithTimeout(context.Background(), timeout)\n- defer cancel()\n- if _, ok := e.ReadContext(ctx); ok {\n- t.Fatal(\"unexpectedly got a packet\")\n+\n+ clock.Advance(timeout)\n+ if p, ok := e.Read(); ok {\n+ t.Fatalf(\"unexpectedly got a packet = %#v\", p)\n}\n}\ns := stack.New(stack.Options{\n@@ -5239,6 +5228,7 @@ func TestRouterSolicitation(t *testing.T) {\nMaxRtrSolicitationDelay: test.maxRtrSolicitDelay,\n},\n})},\n+ Clock: clock,\n})\nif err := s.CreateNIC(nicID, &e); err != nil {\nt.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n@@ -5253,34 +5243,31 @@ func TestRouterSolicitation(t *testing.T) {\n// Make sure each RS is sent at the right time.\nremaining := test.maxRtrSolicit\nif remaining > 0 {\n- waitForPkt(test.effectiveMaxRtrSolicitDelay + defaultAsyncPositiveEventTimeout)\n+ waitForPkt(test.effectiveMaxRtrSolicitDelay)\nremaining--\n}\nfor ; remaining > 0; remaining-- {\nif test.effectiveRtrSolicitInt > defaultAsyncPositiveEventTimeout {\n- waitForNothing(test.effectiveRtrSolicitInt - defaultAsyncNegativeEventTimeout)\n- waitForPkt(defaultAsyncPositiveEventTimeout)\n+ waitForNothing(test.effectiveRtrSolicitInt - time.Nanosecond)\n+ waitForPkt(time.Nanosecond)\n} else {\n- waitForPkt(test.effectiveRtrSolicitInt + defaultAsyncPositiveEventTimeout)\n+ waitForPkt(test.effectiveRtrSolicitInt)\n}\n}\n// Make sure no more RS.\nif test.effectiveRtrSolicitInt > test.effectiveMaxRtrSolicitDelay {\n- waitForNothing(test.effectiveRtrSolicitInt + defaultAsyncNegativeEventTimeout)\n+ waitForNothing(test.effectiveRtrSolicitInt)\n} else {\n- waitForNothing(test.effectiveMaxRtrSolicitDelay + defaultAsyncNegativeEventTimeout)\n+ waitForNothing(test.effectiveMaxRtrSolicitDelay)\n}\n- // Make sure the counter got properly\n- // incremented.\nif got, want := s.Stats().ICMP.V6PacketsSent.RouterSolicit.Value(), uint64(test.maxRtrSolicit); got != want {\nt.Fatalf(\"got sent RouterSolicit = %d, want = %d\", got, want)\n}\n})\n}\n- })\n}\nfunc TestStopStartSolicitingRouters(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Deflake stack_test.TestRouterSolicitation ...by using the fake clock. TestRouterSolicitation no longer runs its sub-tests in parallel now that the sub-tests are not long-running - the fake clock simulates time moving forward. PiperOrigin-RevId: 345165794
259,875
02.12.2020 00:11:17
28,800
b26dd6d9b78b2703a8a726376e6935011657123a
Add /proc/sys/kernel/sem.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/sem.go", "new_path": "pkg/abi/linux/sem.go", "diff": "@@ -32,6 +32,17 @@ const (\nSEM_STAT_ANY = 20\n)\n+// Information about system-wide sempahore limits and parameters.\n+//\n+// Source: include/uapi/linux/sem.h\n+const (\n+ SEMMNI = 32000\n+ SEMMSL = 32000\n+ SEMMNS = SEMMNI * SEMMSL\n+ SEMOPM = 500\n+ SEMVMX = 32767\n+)\n+\nconst SEM_UNDO = 0x1000\n// Sembuf is equivalent to struct sembuf.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/sys.go", "new_path": "pkg/sentry/fs/proc/sys.go", "diff": "@@ -84,6 +84,7 @@ func (p *proc) newKernelDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode\nchildren := map[string]*fs.Inode{\n\"hostname\": newProcInode(ctx, &h, msrc, fs.SpecialFile, nil),\n+ \"sem\": newStaticProcInode(ctx, msrc, []byte(fmt.Sprintf(\"%d\\t%d\\t%d\\t%d\\n\", linux.SEMMSL, linux.SEMMNS, linux.SEMOPM, linux.SEMMNI))),\n\"shmall\": newStaticProcInode(ctx, msrc, []byte(strconv.FormatUint(linux.SHMALL, 10))),\n\"shmmax\": newStaticProcInode(ctx, msrc, []byte(strconv.FormatUint(linux.SHMMAX, 10))),\n\"shmmni\": newStaticProcInode(ctx, msrc, []byte(strconv.FormatUint(linux.SHMMNI, 10))),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "diff": "@@ -44,6 +44,7 @@ func (fs *filesystem) newSysDir(ctx context.Context, root *auth.Credentials, k *\nreturn fs.newStaticDir(ctx, root, map[string]kernfs.Inode{\n\"kernel\": fs.newStaticDir(ctx, root, map[string]kernfs.Inode{\n\"hostname\": fs.newInode(ctx, root, 0444, &hostnameData{}),\n+ \"sem\": fs.newInode(ctx, root, 0444, newStaticFile(fmt.Sprintf(\"%d\\t%d\\t%d\\t%d\\n\", linux.SEMMSL, linux.SEMMNS, linux.SEMOPM, linux.SEMMNI))),\n\"shmall\": fs.newInode(ctx, root, 0444, shmData(linux.SHMALL)),\n\"shmmax\": fs.newInode(ctx, root, 0444, shmData(linux.SHMMAX)),\n\"shmmni\": fs.newInode(ctx, root, 0444, shmData(linux.SHMMNI)),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore.go", "diff": "@@ -29,17 +29,17 @@ import (\n)\nconst (\n- valueMax = 32767 // SEMVMX\n+ // Maximum semaphore value.\n+ valueMax = linux.SEMVMX\n- // semaphoresMax is \"maximum number of semaphores per semaphore ID\" (SEMMSL).\n- semaphoresMax = 32000\n+ // Maximum number of semaphore sets.\n+ setsMax = linux.SEMMNI\n- // setMax is \"system-wide limit on the number of semaphore sets\" (SEMMNI).\n- setsMax = 32000\n+ // Maximum number of semaphroes in a semaphore set.\n+ semsMax = linux.SEMMSL\n- // semaphoresTotalMax is \"system-wide limit on the number of semaphores\"\n- // (SEMMNS = SEMMNI*SEMMSL).\n- semaphoresTotalMax = 1024000000\n+ // Maximum number of semaphores in all semaphroe sets.\n+ semsTotalMax = linux.SEMMNS\n)\n// Registry maintains a set of semaphores that can be found by key or ID.\n@@ -122,7 +122,7 @@ func NewRegistry(userNS *auth.UserNamespace) *Registry {\n// be found. If exclusive is true, it fails if a set with the same key already\n// exists.\nfunc (r *Registry) FindOrCreate(ctx context.Context, key, nsems int32, mode linux.FileMode, private, create, exclusive bool) (*Set, error) {\n- if nsems < 0 || nsems > semaphoresMax {\n+ if nsems < 0 || nsems > semsMax {\nreturn nil, syserror.EINVAL\n}\n@@ -166,7 +166,7 @@ func (r *Registry) FindOrCreate(ctx context.Context, key, nsems int32, mode linu\nif len(r.semaphores) >= setsMax {\nreturn nil, syserror.EINVAL\n}\n- if r.totalSems() > int(semaphoresTotalMax-nsems) {\n+ if r.totalSems() > int(semsTotalMax-nsems) {\nreturn nil, syserror.EINVAL\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "#include <fcntl.h>\n#include <limits.h>\n#include <linux/magic.h>\n+#include <linux/sem.h>\n#include <sched.h>\n#include <signal.h>\n#include <stddef.h>\n@@ -2409,6 +2410,28 @@ TEST(ProcFilesystems, PresenceOfShmMaxMniAll) {\nASSERT_LE(shmall, ULONG_MAX - (1UL << 24));\n}\n+TEST(ProcFilesystems, PresenceOfSem) {\n+ uint32_t semmsl = 0;\n+ uint32_t semmns = 0;\n+ uint32_t semopm = 0;\n+ uint32_t semmni = 0;\n+ std::string proc_file;\n+ proc_file = ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/sys/kernel/sem\"));\n+ ASSERT_FALSE(proc_file.empty());\n+ std::vector<absl::string_view> sem_limits =\n+ absl::StrSplit(proc_file, absl::ByAnyChar(\"\\t\"), absl::SkipWhitespace());\n+ ASSERT_EQ(sem_limits.size(), 4);\n+ ASSERT_TRUE(absl::SimpleAtoi(sem_limits[0], &semmsl));\n+ ASSERT_TRUE(absl::SimpleAtoi(sem_limits[1], &semmns));\n+ ASSERT_TRUE(absl::SimpleAtoi(sem_limits[2], &semopm));\n+ ASSERT_TRUE(absl::SimpleAtoi(sem_limits[3], &semmni));\n+\n+ ASSERT_EQ(semmsl, SEMMSL);\n+ ASSERT_EQ(semmns, SEMMNS);\n+ ASSERT_EQ(semopm, SEMOPM);\n+ ASSERT_EQ(semmni, SEMMNI);\n+}\n+\n// Check that /proc/mounts is a symlink to self/mounts.\nTEST(ProcMounts, IsSymlink) {\nauto link = ASSERT_NO_ERRNO_AND_VALUE(ReadLink(\"/proc/mounts\"));\n" } ]
Go
Apache License 2.0
google/gvisor
Add /proc/sys/kernel/sem. PiperOrigin-RevId: 345178956
259,858
02.12.2020 09:13:59
28,800
9f02d2653bb790e8403b1c8b54656e06eb908802
Fix containerd.sh for later Ubuntu and Debian-based distributions.
[ { "change_type": "MODIFY", "old_path": "tools/installers/containerd.sh", "new_path": "tools/installers/containerd.sh", "diff": "@@ -49,10 +49,10 @@ install_helper() {\n# and later versions no longer have the transitional package.\nsource /etc/os-release\ndeclare BTRFS_DEV\n-if [[ \"${ID}\" == \"ubuntu\" ]] && [[ \"${VERSION_ID%.*}\" -le \"18\" ]]; then\n+if [[ \"${VERSION_ID%.*}\" -le \"18\" ]]; then\nBTRFS_DEV=\"btrfs-tools\"\nelse\n- BTRFS_DEV=\"btrfs-dev\"\n+ BTRFS_DEV=\"libbtrfs-dev\"\nfi\nreadonly BTRFS_DEV\n" } ]
Go
Apache License 2.0
google/gvisor
Fix containerd.sh for later Ubuntu and Debian-based distributions. PiperOrigin-RevId: 345245285
259,907
02.12.2020 09:19:02
28,800
f156fb6531918f62c1a14363af97240588948202
[netstack] Add back EndpointInfo struct in tcp. This was removed in an earlier commit. This should remain as it allows to add tcp-only state to be exposed.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -309,6 +309,19 @@ type Stats struct {\n// marker interface.\nfunc (*Stats) IsEndpointStats() {}\n+// EndpointInfo holds useful information about a transport endpoint which\n+// can be queried by monitoring tools. This exists to allow tcp-only state to\n+// be exposed.\n+//\n+// +stateify savable\n+type EndpointInfo struct {\n+ stack.TransportEndpointInfo\n+}\n+\n+// IsEndpointInfo is an empty method to implement the tcpip.EndpointInfo\n+// marker interface.\n+func (*EndpointInfo) IsEndpointInfo() {}\n+\n// endpoint represents a TCP endpoint. This struct serves as the interface\n// between users of the endpoint and the protocol implementation; it is legal to\n// have concurrent goroutines make calls into the endpoint, they are properly\n@@ -349,7 +362,7 @@ func (*Stats) IsEndpointStats() {}\n//\n// +stateify savable\ntype endpoint struct {\n- stack.TransportEndpointInfo\n+ EndpointInfo\ntcpip.DefaultSocketOptionsHandler\n// endpointEntry is used to queue endpoints for processing to the\n@@ -837,10 +850,12 @@ type keepalive struct {\nfunc newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) *endpoint {\ne := &endpoint{\nstack: s,\n+ EndpointInfo: EndpointInfo{\nTransportEndpointInfo: stack.TransportEndpointInfo{\nNetProto: netProto,\nTransProto: header.TCPProtocolNumber,\n},\n+ },\nwaiterQueue: waiterQueue,\nstate: StateInitial,\nrcvBufSize: DefaultReceiveBufferSize,\n" } ]
Go
Apache License 2.0
google/gvisor
[netstack] Add back EndpointInfo struct in tcp. This was removed in an earlier commit. This should remain as it allows to add tcp-only state to be exposed. PiperOrigin-RevId: 345246155
259,858
02.12.2020 09:24:52
28,800
496851d27b58bbb15ee863de0d8a106dd23b8050
Skip CanKillAllPIDs when running natively. This is quite disruptive to run in some environments.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/kill.cc", "new_path": "test/syscalls/linux/kill.cc", "diff": "@@ -58,6 +58,12 @@ void SigHandler(int sig, siginfo_t* info, void* context) { _exit(0); }\n// If pid equals -1, then sig is sent to every process for which the calling\n// process has permission to send signals, except for process 1 (init).\nTEST(KillTest, CanKillAllPIDs) {\n+ // If we're not running inside the sandbox, then we skip this test\n+ // as our namespace may contain may more processes that cannot tolerate\n+ // the signal below. We also cannot reliably create a new pid namespace\n+ // for ourselves and test the same functionality.\n+ SKIP_IF(!IsRunningOnGvisor());\n+\nint pipe_fds[2];\nASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\nFileDescriptor read_fd(pipe_fds[0]);\n" } ]
Go
Apache License 2.0
google/gvisor
Skip CanKillAllPIDs when running natively. This is quite disruptive to run in some environments. PiperOrigin-RevId: 345247206
259,860
02.12.2020 09:28:08
28,800
b11f40db1ec2afed67d7227fd5b79e9897ffbf1d
Clean up verity tests. Refactor some utilities and rename some others for clarity.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity_test.go", "new_path": "pkg/sentry/fsimpl/verity/verity_test.go", "diff": "@@ -35,14 +35,16 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n+const (\n// rootMerkleFilename is the name of the root Merkle tree file.\n-const rootMerkleFilename = \"root.verity\"\n+ rootMerkleFilename = \"root.verity\"\n+ // maxDataSize is the maximum data size of a test file.\n+ maxDataSize = 100000\n+)\n-// maxDataSize is the maximum data size written to the file for test.\n-const maxDataSize = 100000\n+var hashAlgs = []HashAlgorithm{SHA256, SHA512}\n-// getD returns a *dentry corresponding to VD.\n-func getD(t *testing.T, vd vfs.VirtualDentry) *dentry {\n+func dentryFromVD(t *testing.T, vd vfs.VirtualDentry) *dentry {\nt.Helper()\nd, ok := vd.Dentry().Impl().(*dentry)\nif !ok {\n@@ -51,10 +53,21 @@ func getD(t *testing.T, vd vfs.VirtualDentry) *dentry {\nreturn d\n}\n+// dentryFromFD returns the dentry corresponding to fd.\n+func dentryFromFD(t *testing.T, fd *vfs.FileDescription) *dentry {\n+ t.Helper()\n+ f, ok := fd.Impl().(*fileDescription)\n+ if !ok {\n+ t.Fatalf(\"can't assert %T as a *fileDescription\", fd)\n+ }\n+ return f.d\n+}\n+\n// newVerityRoot creates a new verity mount, and returns the root. The\n// underlying file system is tmpfs. If the error is not nil, then cleanup\n// should be called when the root is no longer needed.\nfunc newVerityRoot(t *testing.T, hashAlg HashAlgorithm) (*vfs.VirtualFilesystem, vfs.VirtualDentry, *kernel.Task, error) {\n+ t.Helper()\nk, err := testutil.Boot()\nif err != nil {\nt.Fatalf(\"testutil.Boot: %v\", err)\n@@ -102,7 +115,6 @@ func newVerityRoot(t *testing.T, hashAlg HashAlgorithm) (*vfs.VirtualFilesystem,\nt.Fatalf(\"testutil.CreateTask: %v\", err)\n}\n- t.Helper()\nt.Cleanup(func() {\nroot.DecRef(ctx)\nmntns.DecRef(ctx)\n@@ -111,6 +123,8 @@ func newVerityRoot(t *testing.T, hashAlg HashAlgorithm) (*vfs.VirtualFilesystem,\n}\n// openVerityAt opens a verity file.\n+//\n+// TODO(chongc): release reference from opening the file when done.\nfunc openVerityAt(ctx context.Context, vfsObj *vfs.VirtualFilesystem, vd vfs.VirtualDentry, path string, flags uint32, mode linux.FileMode) (*vfs.FileDescription, error) {\nreturn vfsObj.OpenAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\nRoot: vd,\n@@ -123,6 +137,8 @@ func openVerityAt(ctx context.Context, vfsObj *vfs.VirtualFilesystem, vd vfs.Vir\n}\n// openLowerAt opens the file in the underlying file system.\n+//\n+// TODO(chongc): release reference from opening the file when done.\nfunc (d *dentry) openLowerAt(ctx context.Context, vfsObj *vfs.VirtualFilesystem, path string, flags uint32, mode linux.FileMode) (*vfs.FileDescription, error) {\nreturn vfsObj.OpenAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\nRoot: d.lowerVD,\n@@ -135,6 +151,8 @@ func (d *dentry) openLowerAt(ctx context.Context, vfsObj *vfs.VirtualFilesystem,\n}\n// openLowerMerkleAt opens the Merkle file in the underlying file system.\n+//\n+// TODO(chongc): release reference from opening the file when done.\nfunc (d *dentry) openLowerMerkleAt(ctx context.Context, vfsObj *vfs.VirtualFilesystem, flags uint32, mode linux.FileMode) (*vfs.FileDescription, error) {\nreturn vfsObj.OpenAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\nRoot: d.lowerMerkleVD,\n@@ -190,21 +208,11 @@ func (d *dentry) renameLowerMerkleAt(ctx context.Context, vfsObj *vfs.VirtualFil\n}, &vfs.RenameOptions{})\n}\n-// getDentry returns a *dentry corresponds to fd.\n-func getDentry(t *testing.T, fd *vfs.FileDescription) *dentry {\n- t.Helper()\n- f, ok := fd.Impl().(*fileDescription)\n- if !ok {\n- t.Fatalf(\"can't assert %T as a *fileDescription\", fd)\n- }\n- return f.d\n-}\n-\n// newFileFD creates a new file in the verity mount, and returns the FD. The FD\n// points to a file that has random data generated.\nfunc newFileFD(ctx context.Context, t *testing.T, vfsObj *vfs.VirtualFilesystem, root vfs.VirtualDentry, filePath string, mode linux.FileMode) (*vfs.FileDescription, int, error) {\n// Create the file in the underlying file system.\n- lowerFD, err := getD(t, root).openLowerAt(ctx, vfsObj, filePath, linux.O_RDWR|linux.O_CREAT|linux.O_EXCL, linux.ModeRegular|mode)\n+ lowerFD, err := dentryFromVD(t, root).openLowerAt(ctx, vfsObj, filePath, linux.O_RDWR|linux.O_CREAT|linux.O_EXCL, linux.ModeRegular|mode)\nif err != nil {\nreturn nil, 0, err\n}\n@@ -231,9 +239,8 @@ func newFileFD(ctx context.Context, t *testing.T, vfsObj *vfs.VirtualFilesystem,\nreturn fd, dataSize, err\n}\n-// corruptRandomBit randomly flips a bit in the file represented by fd.\n-func corruptRandomBit(ctx context.Context, fd *vfs.FileDescription, size int) error {\n- // Flip a random bit in the underlying file.\n+// flipRandomBit randomly flips a bit in the file represented by fd.\n+func flipRandomBit(ctx context.Context, fd *vfs.FileDescription, size int) error {\nrandomPos := int64(rand.Intn(size))\nbyteToModify := make([]byte, 1)\nif _, err := fd.PRead(ctx, usermem.BytesIOSequence(byteToModify), randomPos, vfs.ReadOptions{}); err != nil {\n@@ -246,7 +253,14 @@ func corruptRandomBit(ctx context.Context, fd *vfs.FileDescription, size int) er\nreturn nil\n}\n-var hashAlgs = []HashAlgorithm{SHA256, SHA512}\n+func enableVerity(ctx context.Context, t *testing.T, fd *vfs.FileDescription) {\n+ t.Helper()\n+ var args arch.SyscallArguments\n+ args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n+ if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n+ t.Fatalf(\"enable verity: %v\", err)\n+ }\n+}\n// TestOpen ensures that when a file is created, the corresponding Merkle tree\n// file and the root Merkle tree file exist.\n@@ -264,12 +278,12 @@ func TestOpen(t *testing.T) {\n}\n// Ensure that the corresponding Merkle tree file is created.\n- if _, err = getDentry(t, fd).openLowerMerkleAt(ctx, vfsObj, linux.O_RDONLY, linux.ModeRegular); err != nil {\n+ if _, err = dentryFromFD(t, fd).openLowerMerkleAt(ctx, vfsObj, linux.O_RDONLY, linux.ModeRegular); err != nil {\nt.Errorf(\"OpenAt Merkle tree file %s: %v\", merklePrefix+filename, err)\n}\n// Ensure the root merkle tree file is created.\n- if _, err = getD(t, root).openLowerMerkleAt(ctx, vfsObj, linux.O_RDONLY, linux.ModeRegular); err != nil {\n+ if _, err = dentryFromVD(t, root).openLowerMerkleAt(ctx, vfsObj, linux.O_RDONLY, linux.ModeRegular); err != nil {\nt.Errorf(\"OpenAt root Merkle tree file %s: %v\", merklePrefix+rootMerkleFilename, err)\n}\n}\n@@ -291,11 +305,7 @@ func TestPReadUnmodifiedFileSucceeds(t *testing.T) {\n}\n// Enable verity on the file and confirm a normal read succeeds.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\nbuf := make([]byte, size)\nn, err := fd.PRead(ctx, usermem.BytesIOSequence(buf), 0 /* offset */, vfs.ReadOptions{})\n@@ -325,11 +335,7 @@ func TestReadUnmodifiedFileSucceeds(t *testing.T) {\n}\n// Enable verity on the file and confirm a normal read succeeds.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\nbuf := make([]byte, size)\nn, err := fd.Read(ctx, usermem.BytesIOSequence(buf), vfs.ReadOptions{})\n@@ -359,11 +365,7 @@ func TestReopenUnmodifiedFileSucceeds(t *testing.T) {\n}\n// Enable verity on the file and confirms a normal read succeeds.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\n// Ensure reopening the verity enabled file succeeds.\nif _, err = openVerityAt(ctx, vfsObj, root, filename, linux.O_RDONLY, linux.ModeRegular); err != nil {\n@@ -387,21 +389,14 @@ func TestOpenNonexistentFile(t *testing.T) {\n}\n// Enable verity on the file and confirms a normal read succeeds.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\n// Enable verity on the parent directory.\nparentFD, err := openVerityAt(ctx, vfsObj, root, \"\", linux.O_RDONLY, linux.ModeRegular)\nif err != nil {\nt.Fatalf(\"OpenAt: %v\", err)\n}\n-\n- if _, err := parentFD.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, parentFD)\n// Ensure open an unexpected file in the parent directory fails with\n// ENOENT rather than verification failure.\n@@ -426,20 +421,16 @@ func TestPReadModifiedFileFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\n// Open a new lowerFD that's read/writable.\n- lowerFD, err := getDentry(t, fd).openLowerAt(ctx, vfsObj, \"\", linux.O_RDWR, linux.ModeRegular)\n+ lowerFD, err := dentryFromFD(t, fd).openLowerAt(ctx, vfsObj, \"\", linux.O_RDWR, linux.ModeRegular)\nif err != nil {\nt.Fatalf(\"OpenAt: %v\", err)\n}\n- if err := corruptRandomBit(ctx, lowerFD, size); err != nil {\n- t.Fatalf(\"corruptRandomBit: %v\", err)\n+ if err := flipRandomBit(ctx, lowerFD, size); err != nil {\n+ t.Fatalf(\"flipRandomBit: %v\", err)\n}\n// Confirm that read from the modified file fails.\n@@ -466,20 +457,16 @@ func TestReadModifiedFileFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\n// Open a new lowerFD that's read/writable.\n- lowerFD, err := getDentry(t, fd).openLowerAt(ctx, vfsObj, \"\", linux.O_RDWR, linux.ModeRegular)\n+ lowerFD, err := dentryFromFD(t, fd).openLowerAt(ctx, vfsObj, \"\", linux.O_RDWR, linux.ModeRegular)\nif err != nil {\nt.Fatalf(\"OpenAt: %v\", err)\n}\n- if err := corruptRandomBit(ctx, lowerFD, size); err != nil {\n- t.Fatalf(\"corruptRandomBit: %v\", err)\n+ if err := flipRandomBit(ctx, lowerFD, size); err != nil {\n+ t.Fatalf(\"flipRandomBit: %v\", err)\n}\n// Confirm that read from the modified file fails.\n@@ -506,14 +493,10 @@ func TestModifiedMerkleFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\n// Open a new lowerMerkleFD that's read/writable.\n- lowerMerkleFD, err := getDentry(t, fd).openLowerMerkleAt(ctx, vfsObj, linux.O_RDWR, linux.ModeRegular)\n+ lowerMerkleFD, err := dentryFromFD(t, fd).openLowerMerkleAt(ctx, vfsObj, linux.O_RDWR, linux.ModeRegular)\nif err != nil {\nt.Fatalf(\"OpenAt: %v\", err)\n}\n@@ -524,14 +507,13 @@ func TestModifiedMerkleFails(t *testing.T) {\nt.Errorf(\"lowerMerkleFD.Stat: %v\", err)\n}\n- if err := corruptRandomBit(ctx, lowerMerkleFD, int(stat.Size)); err != nil {\n- t.Fatalf(\"corruptRandomBit: %v\", err)\n+ if err := flipRandomBit(ctx, lowerMerkleFD, int(stat.Size)); err != nil {\n+ t.Fatalf(\"flipRandomBit: %v\", err)\n}\n// Confirm that read from a file with modified Merkle tree fails.\nbuf := make([]byte, size)\nif _, err := fd.PRead(ctx, usermem.BytesIOSequence(buf), 0 /* offset */, vfs.ReadOptions{}); err == nil {\n- fmt.Println(buf)\nt.Fatalf(\"fd.PRead succeeded with modified Merkle file\")\n}\n}\n@@ -554,24 +536,17 @@ func TestModifiedParentMerkleFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\n// Enable verity on the parent directory.\nparentFD, err := openVerityAt(ctx, vfsObj, root, \"\", linux.O_RDONLY, linux.ModeRegular)\nif err != nil {\nt.Fatalf(\"OpenAt: %v\", err)\n}\n-\n- if _, err := parentFD.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, parentFD)\n// Open a new lowerMerkleFD that's read/writable.\n- parentLowerMerkleFD, err := getDentry(t, fd).parent.openLowerMerkleAt(ctx, vfsObj, linux.O_RDWR, linux.ModeRegular)\n+ parentLowerMerkleFD, err := dentryFromFD(t, fd).parent.openLowerMerkleAt(ctx, vfsObj, linux.O_RDWR, linux.ModeRegular)\nif err != nil {\nt.Fatalf(\"OpenAt: %v\", err)\n}\n@@ -591,8 +566,8 @@ func TestModifiedParentMerkleFails(t *testing.T) {\nif err != nil {\nt.Fatalf(\"Failed convert size to int: %v\", err)\n}\n- if err := corruptRandomBit(ctx, parentLowerMerkleFD, parentMerkleSize); err != nil {\n- t.Fatalf(\"corruptRandomBit: %v\", err)\n+ if err := flipRandomBit(ctx, parentLowerMerkleFD, parentMerkleSize); err != nil {\n+ t.Fatalf(\"flipRandomBit: %v\", err)\n}\nparentLowerMerkleFD.DecRef(ctx)\n@@ -619,13 +594,8 @@ func TestUnmodifiedStatSucceeds(t *testing.T) {\nt.Fatalf(\"newFileFD: %v\", err)\n}\n- // Enable verity on the file and confirms stat succeeds.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"fd.Ioctl: %v\", err)\n- }\n-\n+ // Enable verity on the file and confirm that stat succeeds.\n+ enableVerity(ctx, t, fd)\nif _, err := fd.Stat(ctx, vfs.StatOptions{}); err != nil {\nt.Errorf(\"fd.Stat: %v\", err)\n}\n@@ -648,11 +618,7 @@ func TestModifiedStatFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"fd.Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\nlowerFD := fd.Impl().(*fileDescription).lowerFD\n// Change the stat of the underlying file, and check that stat fails.\n@@ -711,19 +677,15 @@ func TestOpenDeletedFileFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\nif tc.changeFile {\n- if err := getD(t, root).unlinkLowerAt(ctx, vfsObj, filename); err != nil {\n+ if err := dentryFromVD(t, root).unlinkLowerAt(ctx, vfsObj, filename); err != nil {\nt.Fatalf(\"UnlinkAt: %v\", err)\n}\n}\nif tc.changeMerkleFile {\n- if err := getD(t, root).unlinkLowerMerkleAt(ctx, vfsObj, filename); err != nil {\n+ if err := dentryFromVD(t, root).unlinkLowerMerkleAt(ctx, vfsObj, filename); err != nil {\nt.Fatalf(\"UnlinkAt: %v\", err)\n}\n}\n@@ -776,20 +738,16 @@ func TestOpenRenamedFileFails(t *testing.T) {\n}\n// Enable verity on the file.\n- var args arch.SyscallArguments\n- args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n- if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n- t.Fatalf(\"Ioctl: %v\", err)\n- }\n+ enableVerity(ctx, t, fd)\nnewFilename := \"renamed-test-file\"\nif tc.changeFile {\n- if err := getD(t, root).renameLowerAt(ctx, vfsObj, filename, newFilename); err != nil {\n+ if err := dentryFromVD(t, root).renameLowerAt(ctx, vfsObj, filename, newFilename); err != nil {\nt.Fatalf(\"RenameAt: %v\", err)\n}\n}\nif tc.changeMerkleFile {\n- if err := getD(t, root).renameLowerMerkleAt(ctx, vfsObj, filename, newFilename); err != nil {\n+ if err := dentryFromVD(t, root).renameLowerMerkleAt(ctx, vfsObj, filename, newFilename); err != nil {\nt.Fatalf(\"UnlinkAt: %v\", err)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Clean up verity tests. Refactor some utilities and rename some others for clarity. PiperOrigin-RevId: 345247836
259,858
02.12.2020 10:46:10
28,800
7ccb0b6a7cd7fa33f2d58484aed5cfe1709018ca
Fix chown test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/chown.cc", "new_path": "test/syscalls/linux/chown.cc", "diff": "@@ -75,7 +75,16 @@ TEST_P(ChownParamTest, ChownFileSucceeds) {\nif (num_groups > 0) {\nstd::vector<gid_t> list(num_groups);\nEXPECT_THAT(getgroups(list.size(), list.data()), SyscallSucceeds());\n- gid = list[0];\n+ // Scan the list of groups for a valid gid. Note that if a group is not\n+ // defined in this local user namespace, then we will see 65534, and the\n+ // group will not chown below as expected. So only change if we find a\n+ // valid group in this list.\n+ for (const gid_t other_gid : list) {\n+ if (other_gid != 65534) {\n+ gid = other_gid;\n+ break;\n+ }\n+ }\n}\nEXPECT_NO_ERRNO(GetParam()(file.path(), geteuid(), gid));\n" } ]
Go
Apache License 2.0
google/gvisor
Fix chown test. PiperOrigin-RevId: 345265342
259,858
02.12.2020 11:26:03
28,800
dbd4a6e3e581cc081f686096226873f3a39c0369
Add BuildKite agent. This has no effect on the continuous integration system, and simply publishes a cached container image containing the agent and metrics agent with known provenance.
[ { "change_type": "ADD", "old_path": null, "new_path": "images/agent/Dockerfile", "diff": "+FROM golang:1.15 as build-agent\n+RUN git clone --depth=1 --branch=v3.25.0 https://github.com/buildkite/agent\n+RUN cd agent && go build -i -o /buildkite-agent .\n+\n+FROM golang:1.15 as build-agent-metrics\n+RUN git clone --depth=1 --branch=v5.2.0 https://github.com/buildkite/buildkite-agent-metrics\n+RUN cd buildkite-agent-metrics && go build -i -o /buildkite-agent-metrics .\n+\n+FROM gcr.io/distroless/base-debian10\n+COPY --from=build-agent /buildkite-agent /\n+COPY --from=build-agent-metrics /buildkite-agent-metrics /\n+CMD [\"/buildkite-agent\"]\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/agent/README.md", "diff": "+# Build Agent\n+\n+This is the image used by the build agent. It is built and bundled via a\n+separate packaging mechanism in order to provide local caching and to ensure\n+that there is better build provenance. Note that continuous integration system\n+will generally deploy new agents from the primary branch, and will only deploy\n+as instances are recycled. Updates to this image should be made carefully.\n" } ]
Go
Apache License 2.0
google/gvisor
Add BuildKite agent. This has no effect on the continuous integration system, and simply publishes a cached container image containing the agent and metrics agent with known provenance. PiperOrigin-RevId: 345274375
259,907
02.12.2020 11:31:38
28,800
1375a87a209ef1a2523ada84254e3a0101afb4f5
[netstack] Refactor common utils out of netstack to socket package. Moved AddressAndFamily() and ConvertAddress() to socket package from netstack. This helps because these utilities are used by sibling netstack packages. Such sibling dependencies can later cause circular dependencies. Common utils shared between siblings should be moved up to the parent.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/BUILD", "new_path": "pkg/sentry/socket/BUILD", "diff": "@@ -20,6 +20,7 @@ go_library(\n\"//pkg/sentry/vfs\",\n\"//pkg/syserr\",\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/header\",\n\"//pkg/usermem\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -209,18 +209,6 @@ const sizeOfInt32 int = 4\nvar errStackType = syserr.New(\"expected but did not receive a netstack.Stack\", linux.EINVAL)\n-// ntohs converts a 16-bit number from network byte order to host byte order. It\n-// assumes that the host is little endian.\n-func ntohs(v uint16) uint16 {\n- return v<<8 | v>>8\n-}\n-\n-// htons converts a 16-bit number from host byte order to network byte order. It\n-// assumes that the host is little endian.\n-func htons(v uint16) uint16 {\n- return ntohs(v)\n-}\n-\n// commonEndpoint represents the intersection of a tcpip.Endpoint and a\n// transport.Endpoint.\ntype commonEndpoint interface {\n@@ -359,88 +347,6 @@ func bytesToIPAddress(addr []byte) tcpip.Address {\nreturn tcpip.Address(addr)\n}\n-// AddressAndFamily reads an sockaddr struct from the given address and\n-// converts it to the FullAddress format. It supports AF_UNIX, AF_INET,\n-// AF_INET6, and AF_PACKET addresses.\n-//\n-// AddressAndFamily returns an address and its family.\n-func AddressAndFamily(addr []byte) (tcpip.FullAddress, uint16, *syserr.Error) {\n- // Make sure we have at least 2 bytes for the address family.\n- if len(addr) < 2 {\n- return tcpip.FullAddress{}, 0, syserr.ErrInvalidArgument\n- }\n-\n- // Get the rest of the fields based on the address family.\n- switch family := usermem.ByteOrder.Uint16(addr); family {\n- case linux.AF_UNIX:\n- path := addr[2:]\n- if len(path) > linux.UnixPathMax {\n- return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n- }\n- // Drop the terminating NUL (if one exists) and everything after\n- // it for filesystem (non-abstract) addresses.\n- if len(path) > 0 && path[0] != 0 {\n- if n := bytes.IndexByte(path[1:], 0); n >= 0 {\n- path = path[:n+1]\n- }\n- }\n- return tcpip.FullAddress{\n- Addr: tcpip.Address(path),\n- }, family, nil\n-\n- case linux.AF_INET:\n- var a linux.SockAddrInet\n- if len(addr) < sockAddrInetSize {\n- return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n- }\n- binary.Unmarshal(addr[:sockAddrInetSize], usermem.ByteOrder, &a)\n-\n- out := tcpip.FullAddress{\n- Addr: bytesToIPAddress(a.Addr[:]),\n- Port: ntohs(a.Port),\n- }\n- return out, family, nil\n-\n- case linux.AF_INET6:\n- var a linux.SockAddrInet6\n- if len(addr) < sockAddrInet6Size {\n- return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n- }\n- binary.Unmarshal(addr[:sockAddrInet6Size], usermem.ByteOrder, &a)\n-\n- out := tcpip.FullAddress{\n- Addr: bytesToIPAddress(a.Addr[:]),\n- Port: ntohs(a.Port),\n- }\n- if isLinkLocal(out.Addr) {\n- out.NIC = tcpip.NICID(a.Scope_id)\n- }\n- return out, family, nil\n-\n- case linux.AF_PACKET:\n- var a linux.SockAddrLink\n- if len(addr) < sockAddrLinkSize {\n- return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n- }\n- binary.Unmarshal(addr[:sockAddrLinkSize], usermem.ByteOrder, &a)\n- if a.Family != linux.AF_PACKET || a.HardwareAddrLen != header.EthernetAddressSize {\n- return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n- }\n-\n- // TODO(gvisor.dev/issue/173): Return protocol too.\n- return tcpip.FullAddress{\n- NIC: tcpip.NICID(a.InterfaceIndex),\n- Addr: tcpip.Address(a.HardwareAddr[:header.EthernetAddressSize]),\n- }, family, nil\n-\n- case linux.AF_UNSPEC:\n- return tcpip.FullAddress{}, family, nil\n-\n- default:\n- return tcpip.FullAddress{}, 0, syserr.ErrAddressFamilyNotSupported\n- }\n-}\n-\nfunc (s *socketOpsCommon) isPacketBased() bool {\nreturn s.skType == linux.SOCK_DGRAM || s.skType == linux.SOCK_SEQPACKET || s.skType == linux.SOCK_RDM || s.skType == linux.SOCK_RAW\n}\n@@ -741,7 +647,7 @@ func (s *socketOpsCommon) mapFamily(addr tcpip.FullAddress, family uint16) tcpip\n// Connect implements the linux syscall connect(2) for sockets backed by\n// tpcip.Endpoint.\nfunc (s *socketOpsCommon) Connect(t *kernel.Task, sockaddr []byte, blocking bool) *syserr.Error {\n- addr, family, err := AddressAndFamily(sockaddr)\n+ addr, family, err := socket.AddressAndFamily(sockaddr)\nif err != nil {\nreturn err\n}\n@@ -822,7 +728,7 @@ func (s *socketOpsCommon) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n}\n} else {\nvar err *syserr.Error\n- addr, family, err = AddressAndFamily(sockaddr)\n+ addr, family, err = socket.AddressAndFamily(sockaddr)\nif err != nil {\nreturn err\n}\n@@ -913,7 +819,7 @@ func (s *SocketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\nvar addr linux.SockAddr\nvar addrLen uint32\nif peerAddr != nil {\n- addr, addrLen = ConvertAddress(s.family, *peerAddr)\n+ addr, addrLen = socket.ConvertAddress(s.family, *peerAddr)\n}\nfd, e := t.NewFDFrom(0, ns, kernel.FDFlags{\n@@ -1496,7 +1402,7 @@ func getSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nreturn nil, syserr.TranslateNetstackError(err)\n}\n- a, _ := ConvertAddress(linux.AF_INET6, tcpip.FullAddress(v))\n+ a, _ := socket.ConvertAddress(linux.AF_INET6, tcpip.FullAddress(v))\nreturn a.(*linux.SockAddrInet6), nil\ncase linux.IP6T_SO_GET_INFO:\n@@ -1614,7 +1520,7 @@ func getSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nreturn nil, syserr.TranslateNetstackError(err)\n}\n- a, _ := ConvertAddress(linux.AF_INET, tcpip.FullAddress{Addr: v.InterfaceAddr})\n+ a, _ := socket.ConvertAddress(linux.AF_INET, tcpip.FullAddress{Addr: v.InterfaceAddr})\nreturn &a.(*linux.SockAddrInet).Addr, nil\n@@ -1677,7 +1583,7 @@ func getSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nreturn nil, syserr.TranslateNetstackError(err)\n}\n- a, _ := ConvertAddress(linux.AF_INET, tcpip.FullAddress(v))\n+ a, _ := socket.ConvertAddress(linux.AF_INET, tcpip.FullAddress(v))\nreturn a.(*linux.SockAddrInet), nil\ncase linux.IPT_SO_GET_INFO:\n@@ -2322,7 +2228,7 @@ func setSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(&tcpip.MulticastInterfaceOption{\nNIC: tcpip.NICID(req.InterfaceIndex),\n- InterfaceAddr: bytesToIPAddress(req.InterfaceAddr[:]),\n+ InterfaceAddr: socket.BytesToIPAddress(req.InterfaceAddr[:]),\n}))\ncase linux.IP_MULTICAST_LOOP:\n@@ -2579,72 +2485,6 @@ func emitUnimplementedEventIP(t *kernel.Task, name int) {\n}\n}\n-// isLinkLocal determines if the given IPv6 address is link-local. This is the\n-// case when it has the fe80::/10 prefix. This check is used to determine when\n-// the NICID is relevant for a given IPv6 address.\n-func isLinkLocal(addr tcpip.Address) bool {\n- return len(addr) >= 2 && addr[0] == 0xfe && addr[1]&0xc0 == 0x80\n-}\n-\n-// ConvertAddress converts the given address to a native format.\n-func ConvertAddress(family int, addr tcpip.FullAddress) (linux.SockAddr, uint32) {\n- switch family {\n- case linux.AF_UNIX:\n- var out linux.SockAddrUnix\n- out.Family = linux.AF_UNIX\n- l := len([]byte(addr.Addr))\n- for i := 0; i < l; i++ {\n- out.Path[i] = int8(addr.Addr[i])\n- }\n-\n- // Linux returns the used length of the address struct (including the\n- // null terminator) for filesystem paths. The Family field is 2 bytes.\n- // It is sometimes allowed to exclude the null terminator if the\n- // address length is the max. Abstract and empty paths always return\n- // the full exact length.\n- if l == 0 || out.Path[0] == 0 || l == len(out.Path) {\n- return &out, uint32(2 + l)\n- }\n- return &out, uint32(3 + l)\n-\n- case linux.AF_INET:\n- var out linux.SockAddrInet\n- copy(out.Addr[:], addr.Addr)\n- out.Family = linux.AF_INET\n- out.Port = htons(addr.Port)\n- return &out, uint32(sockAddrInetSize)\n-\n- case linux.AF_INET6:\n- var out linux.SockAddrInet6\n- if len(addr.Addr) == header.IPv4AddressSize {\n- // Copy address in v4-mapped format.\n- copy(out.Addr[12:], addr.Addr)\n- out.Addr[10] = 0xff\n- out.Addr[11] = 0xff\n- } else {\n- copy(out.Addr[:], addr.Addr)\n- }\n- out.Family = linux.AF_INET6\n- out.Port = htons(addr.Port)\n- if isLinkLocal(addr.Addr) {\n- out.Scope_id = uint32(addr.NIC)\n- }\n- return &out, uint32(sockAddrInet6Size)\n-\n- case linux.AF_PACKET:\n- // TODO(gvisor.dev/issue/173): Return protocol too.\n- var out linux.SockAddrLink\n- out.Family = linux.AF_PACKET\n- out.InterfaceIndex = int32(addr.NIC)\n- out.HardwareAddrLen = header.EthernetAddressSize\n- copy(out.HardwareAddr[:], addr.Addr)\n- return &out, uint32(sockAddrLinkSize)\n-\n- default:\n- return nil, 0\n- }\n-}\n-\n// GetSockName implements the linux syscall getsockname(2) for sockets backed by\n// tcpip.Endpoint.\nfunc (s *socketOpsCommon) GetSockName(t *kernel.Task) (linux.SockAddr, uint32, *syserr.Error) {\n@@ -2653,7 +2493,7 @@ func (s *socketOpsCommon) GetSockName(t *kernel.Task) (linux.SockAddr, uint32, *\nreturn nil, 0, syserr.TranslateNetstackError(err)\n}\n- a, l := ConvertAddress(s.family, addr)\n+ a, l := socket.ConvertAddress(s.family, addr)\nreturn a, l, nil\n}\n@@ -2665,7 +2505,7 @@ func (s *socketOpsCommon) GetPeerName(t *kernel.Task) (linux.SockAddr, uint32, *\nreturn nil, 0, syserr.TranslateNetstackError(err)\n}\n- a, l := ConvertAddress(s.family, addr)\n+ a, l := socket.ConvertAddress(s.family, addr)\nreturn a, l, nil\n}\n@@ -2814,10 +2654,10 @@ func (s *socketOpsCommon) nonBlockingRead(ctx context.Context, dst usermem.IOSeq\nvar addr linux.SockAddr\nvar addrLen uint32\nif isPacket && senderRequested {\n- addr, addrLen = ConvertAddress(s.family, s.sender)\n+ addr, addrLen = socket.ConvertAddress(s.family, s.sender)\nswitch v := addr.(type) {\ncase *linux.SockAddrLink:\n- v.Protocol = htons(uint16(s.linkPacketInfo.Protocol))\n+ v.Protocol = socket.Htons(uint16(s.linkPacketInfo.Protocol))\nv.PacketType = toLinuxPacketType(s.linkPacketInfo.PktType)\n}\n}\n@@ -2982,7 +2822,7 @@ func (s *socketOpsCommon) SendMsg(t *kernel.Task, src usermem.IOSequence, to []b\nvar addr *tcpip.FullAddress\nif len(to) > 0 {\n- addrBuf, family, err := AddressAndFamily(to)\n+ addrBuf, family, err := socket.AddressAndFamily(to)\nif err != nil {\nreturn 0, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "new_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "diff": "@@ -189,7 +189,7 @@ func (s *SocketVFS2) Accept(t *kernel.Task, peerRequested bool, flags int, block\nvar addrLen uint32\nif peerAddr != nil {\n// Get address of the peer and write it to peer slice.\n- addr, addrLen = ConvertAddress(s.family, *peerAddr)\n+ addr, addrLen = socket.ConvertAddress(s.family, *peerAddr)\n}\nfd, e := t.NewFDFromVFS2(0, ns, kernel.FDFlags{\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/provider.go", "new_path": "pkg/sentry/socket/netstack/provider.go", "diff": "@@ -158,7 +158,7 @@ func packetSocket(t *kernel.Task, epStack *Stack, stype linux.SockType, protocol\n// protocol is passed in network byte order, but netstack wants it in\n// host order.\n- netProto := tcpip.NetworkProtocolNumber(ntohs(uint16(protocol)))\n+ netProto := tcpip.NetworkProtocolNumber(socket.Ntohs(uint16(protocol)))\nwq := &waiter.Queue{}\nep, err := epStack.Stack.NewPacketEndpoint(cooked, netProto, wq)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/provider_vfs2.go", "new_path": "pkg/sentry/socket/netstack/provider_vfs2.go", "diff": "@@ -102,7 +102,7 @@ func packetSocketVFS2(t *kernel.Task, epStack *Stack, stype linux.SockType, prot\n// protocol is passed in network byte order, but netstack wants it in\n// host order.\n- netProto := tcpip.NetworkProtocolNumber(ntohs(uint16(protocol)))\n+ netProto := tcpip.NetworkProtocolNumber(socket.Ntohs(uint16(protocol)))\nwq := &waiter.Queue{}\nep, err := epStack.Stack.NewPacketEndpoint(cooked, netProto, wq)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/socket.go", "new_path": "pkg/sentry/socket/socket.go", "diff": "package socket\nimport (\n+ \"bytes\"\n\"fmt\"\n\"sync/atomic\"\n\"syscall\"\n@@ -35,6 +36,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -460,3 +462,176 @@ func UnmarshalSockAddr(family int, data []byte) linux.SockAddr {\npanic(fmt.Sprintf(\"Unsupported socket family %v\", family))\n}\n}\n+\n+var sockAddrLinkSize = (&linux.SockAddrLink{}).SizeBytes()\n+var sockAddrInetSize = (&linux.SockAddrInet{}).SizeBytes()\n+var sockAddrInet6Size = (&linux.SockAddrInet6{}).SizeBytes()\n+\n+// Ntohs converts a 16-bit number from network byte order to host byte order. It\n+// assumes that the host is little endian.\n+func Ntohs(v uint16) uint16 {\n+ return v<<8 | v>>8\n+}\n+\n+// Htons converts a 16-bit number from host byte order to network byte order. It\n+// assumes that the host is little endian.\n+func Htons(v uint16) uint16 {\n+ return Ntohs(v)\n+}\n+\n+// isLinkLocal determines if the given IPv6 address is link-local. This is the\n+// case when it has the fe80::/10 prefix. This check is used to determine when\n+// the NICID is relevant for a given IPv6 address.\n+func isLinkLocal(addr tcpip.Address) bool {\n+ return len(addr) >= 2 && addr[0] == 0xfe && addr[1]&0xc0 == 0x80\n+}\n+\n+// ConvertAddress converts the given address to a native format.\n+func ConvertAddress(family int, addr tcpip.FullAddress) (linux.SockAddr, uint32) {\n+ switch family {\n+ case linux.AF_UNIX:\n+ var out linux.SockAddrUnix\n+ out.Family = linux.AF_UNIX\n+ l := len([]byte(addr.Addr))\n+ for i := 0; i < l; i++ {\n+ out.Path[i] = int8(addr.Addr[i])\n+ }\n+\n+ // Linux returns the used length of the address struct (including the\n+ // null terminator) for filesystem paths. The Family field is 2 bytes.\n+ // It is sometimes allowed to exclude the null terminator if the\n+ // address length is the max. Abstract and empty paths always return\n+ // the full exact length.\n+ if l == 0 || out.Path[0] == 0 || l == len(out.Path) {\n+ return &out, uint32(2 + l)\n+ }\n+ return &out, uint32(3 + l)\n+\n+ case linux.AF_INET:\n+ var out linux.SockAddrInet\n+ copy(out.Addr[:], addr.Addr)\n+ out.Family = linux.AF_INET\n+ out.Port = Htons(addr.Port)\n+ return &out, uint32(sockAddrInetSize)\n+\n+ case linux.AF_INET6:\n+ var out linux.SockAddrInet6\n+ if len(addr.Addr) == header.IPv4AddressSize {\n+ // Copy address in v4-mapped format.\n+ copy(out.Addr[12:], addr.Addr)\n+ out.Addr[10] = 0xff\n+ out.Addr[11] = 0xff\n+ } else {\n+ copy(out.Addr[:], addr.Addr)\n+ }\n+ out.Family = linux.AF_INET6\n+ out.Port = Htons(addr.Port)\n+ if isLinkLocal(addr.Addr) {\n+ out.Scope_id = uint32(addr.NIC)\n+ }\n+ return &out, uint32(sockAddrInet6Size)\n+\n+ case linux.AF_PACKET:\n+ // TODO(gvisor.dev/issue/173): Return protocol too.\n+ var out linux.SockAddrLink\n+ out.Family = linux.AF_PACKET\n+ out.InterfaceIndex = int32(addr.NIC)\n+ out.HardwareAddrLen = header.EthernetAddressSize\n+ copy(out.HardwareAddr[:], addr.Addr)\n+ return &out, uint32(sockAddrLinkSize)\n+\n+ default:\n+ return nil, 0\n+ }\n+}\n+\n+// BytesToIPAddress converts an IPv4 or IPv6 address from the user to the\n+// netstack representation taking any addresses into account.\n+func BytesToIPAddress(addr []byte) tcpip.Address {\n+ if bytes.Equal(addr, make([]byte, 4)) || bytes.Equal(addr, make([]byte, 16)) {\n+ return \"\"\n+ }\n+ return tcpip.Address(addr)\n+}\n+\n+// AddressAndFamily reads an sockaddr struct from the given address and\n+// converts it to the FullAddress format. It supports AF_UNIX, AF_INET,\n+// AF_INET6, and AF_PACKET addresses.\n+//\n+// AddressAndFamily returns an address and its family.\n+func AddressAndFamily(addr []byte) (tcpip.FullAddress, uint16, *syserr.Error) {\n+ // Make sure we have at least 2 bytes for the address family.\n+ if len(addr) < 2 {\n+ return tcpip.FullAddress{}, 0, syserr.ErrInvalidArgument\n+ }\n+\n+ // Get the rest of the fields based on the address family.\n+ switch family := usermem.ByteOrder.Uint16(addr); family {\n+ case linux.AF_UNIX:\n+ path := addr[2:]\n+ if len(path) > linux.UnixPathMax {\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n+ }\n+ // Drop the terminating NUL (if one exists) and everything after\n+ // it for filesystem (non-abstract) addresses.\n+ if len(path) > 0 && path[0] != 0 {\n+ if n := bytes.IndexByte(path[1:], 0); n >= 0 {\n+ path = path[:n+1]\n+ }\n+ }\n+ return tcpip.FullAddress{\n+ Addr: tcpip.Address(path),\n+ }, family, nil\n+\n+ case linux.AF_INET:\n+ var a linux.SockAddrInet\n+ if len(addr) < sockAddrInetSize {\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n+ }\n+ binary.Unmarshal(addr[:sockAddrInetSize], usermem.ByteOrder, &a)\n+\n+ out := tcpip.FullAddress{\n+ Addr: BytesToIPAddress(a.Addr[:]),\n+ Port: Ntohs(a.Port),\n+ }\n+ return out, family, nil\n+\n+ case linux.AF_INET6:\n+ var a linux.SockAddrInet6\n+ if len(addr) < sockAddrInet6Size {\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n+ }\n+ binary.Unmarshal(addr[:sockAddrInet6Size], usermem.ByteOrder, &a)\n+\n+ out := tcpip.FullAddress{\n+ Addr: BytesToIPAddress(a.Addr[:]),\n+ Port: Ntohs(a.Port),\n+ }\n+ if isLinkLocal(out.Addr) {\n+ out.NIC = tcpip.NICID(a.Scope_id)\n+ }\n+ return out, family, nil\n+\n+ case linux.AF_PACKET:\n+ var a linux.SockAddrLink\n+ if len(addr) < sockAddrLinkSize {\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n+ }\n+ binary.Unmarshal(addr[:sockAddrLinkSize], usermem.ByteOrder, &a)\n+ if a.Family != linux.AF_PACKET || a.HardwareAddrLen != header.EthernetAddressSize {\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n+ }\n+\n+ // TODO(gvisor.dev/issue/173): Return protocol too.\n+ return tcpip.FullAddress{\n+ NIC: tcpip.NICID(a.InterfaceIndex),\n+ Addr: tcpip.Address(a.HardwareAddr[:header.EthernetAddressSize]),\n+ }, family, nil\n+\n+ case linux.AF_UNSPEC:\n+ return tcpip.FullAddress{}, family, nil\n+\n+ default:\n+ return tcpip.FullAddress{}, 0, syserr.ErrAddressFamilyNotSupported\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix.go", "new_path": "pkg/sentry/socket/unix/unix.go", "diff": "@@ -136,7 +136,7 @@ func (s *socketOpsCommon) Endpoint() transport.Endpoint {\n// extractPath extracts and validates the address.\nfunc extractPath(sockaddr []byte) (string, *syserr.Error) {\n- addr, family, err := netstack.AddressAndFamily(sockaddr)\n+ addr, family, err := socket.AddressAndFamily(sockaddr)\nif err != nil {\nif err == syserr.ErrAddressFamilyNotSupported {\nerr = syserr.ErrInvalidArgument\n@@ -169,7 +169,7 @@ func (s *socketOpsCommon) GetPeerName(t *kernel.Task) (linux.SockAddr, uint32, *\nreturn nil, 0, syserr.TranslateNetstackError(err)\n}\n- a, l := netstack.ConvertAddress(linux.AF_UNIX, addr)\n+ a, l := socket.ConvertAddress(linux.AF_UNIX, addr)\nreturn a, l, nil\n}\n@@ -181,7 +181,7 @@ func (s *socketOpsCommon) GetSockName(t *kernel.Task) (linux.SockAddr, uint32, *\nreturn nil, 0, syserr.TranslateNetstackError(err)\n}\n- a, l := netstack.ConvertAddress(linux.AF_UNIX, addr)\n+ a, l := socket.ConvertAddress(linux.AF_UNIX, addr)\nreturn a, l, nil\n}\n@@ -255,7 +255,7 @@ func (s *SocketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\nvar addr linux.SockAddr\nvar addrLen uint32\nif peerAddr != nil {\n- addr, addrLen = netstack.ConvertAddress(linux.AF_UNIX, *peerAddr)\n+ addr, addrLen = socket.ConvertAddress(linux.AF_UNIX, *peerAddr)\n}\nfd, e := t.NewFDFrom(0, ns, kernel.FDFlags{\n@@ -647,7 +647,7 @@ func (s *socketOpsCommon) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nvar from linux.SockAddr\nvar fromLen uint32\nif r.From != nil && len([]byte(r.From.Addr)) != 0 {\n- from, fromLen = netstack.ConvertAddress(linux.AF_UNIX, *r.From)\n+ from, fromLen = socket.ConvertAddress(linux.AF_UNIX, *r.From)\n}\nif r.ControlTrunc {\n@@ -682,7 +682,7 @@ func (s *socketOpsCommon) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nvar from linux.SockAddr\nvar fromLen uint32\nif r.From != nil {\n- from, fromLen = netstack.ConvertAddress(linux.AF_UNIX, *r.From)\n+ from, fromLen = socket.ConvertAddress(linux.AF_UNIX, *r.From)\n}\nif r.ControlTrunc {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix_vfs2.go", "new_path": "pkg/sentry/socket/unix/unix_vfs2.go", "diff": "@@ -172,7 +172,7 @@ func (s *SocketVFS2) Accept(t *kernel.Task, peerRequested bool, flags int, block\nvar addr linux.SockAddr\nvar addrLen uint32\nif peerAddr != nil {\n- addr, addrLen = netstack.ConvertAddress(linux.AF_UNIX, *peerAddr)\n+ addr, addrLen = socket.ConvertAddress(linux.AF_UNIX, *peerAddr)\n}\nfd, e := t.NewFDFromVFS2(0, ns, kernel.FDFlags{\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/BUILD", "new_path": "pkg/sentry/strace/BUILD", "diff": "@@ -32,8 +32,8 @@ go_library(\n\"//pkg/seccomp\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/socket\",\n\"//pkg/sentry/socket/netlink\",\n- \"//pkg/sentry/socket/netstack\",\n\"//pkg/sentry/syscalls/linux\",\n\"//pkg/usermem\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/socket.go", "new_path": "pkg/sentry/strace/socket.go", "diff": "@@ -23,8 +23,8 @@ import (\n\"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/marshal/primitive\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netlink\"\n- \"gvisor.dev/gvisor/pkg/sentry/socket/netstack\"\nslinux \"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -341,7 +341,7 @@ func sockAddr(t *kernel.Task, addr usermem.Addr, length uint32) string {\nswitch family {\ncase linux.AF_INET, linux.AF_INET6, linux.AF_UNIX:\n- fa, _, err := netstack.AddressAndFamily(b)\n+ fa, _, err := socket.AddressAndFamily(b)\nif err != nil {\nreturn fmt.Sprintf(\"%#x {Family: %s, error extracting address: %v}\", addr, familyStr, err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[netstack] Refactor common utils out of netstack to socket package. Moved AddressAndFamily() and ConvertAddress() to socket package from netstack. This helps because these utilities are used by sibling netstack packages. Such sibling dependencies can later cause circular dependencies. Common utils shared between siblings should be moved up to the parent. PiperOrigin-RevId: 345275571
259,858
02.12.2020 11:35:54
28,800
24d6eb58e51be706ae66db31d027e2400307152f
Skip generating an empty (broken) test case. It's possible that all the cases in a given batch are excluded if the offsets line up just right, which will cause the test to fail. Don't generate an invalid test in this case.
[ { "change_type": "MODIFY", "old_path": "test/runtimes/runner/lib/lib.go", "new_path": "test/runtimes/runner/lib/lib.go", "diff": "@@ -122,6 +122,10 @@ func getTests(ctx context.Context, d *dockerutil.Container, lang, image string,\n}\ntcs = append(tcs, tests[tc])\n}\n+ if len(tcs) == 0 {\n+ // No tests to add to this batch.\n+ continue\n+ }\nitests = append(itests, testing.InternalTest{\nName: strings.Join(tcs, \", \"),\nF: func(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Skip generating an empty (broken) test case. It's possible that all the cases in a given batch are excluded if the offsets line up just right, which will cause the test to fail. Don't generate an invalid test in this case. PiperOrigin-RevId: 345276588
259,951
02.12.2020 14:09:40
28,800
6a26930eeb717f758ea7ba555df06d9028b24ec8
Abandon reassembly of a packet if fragments overlap However, receiving duplicated fragments will not cause reassembly to fail. This is what Linux does too:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/fragmentation/fragmentation.go", "new_path": "pkg/tcpip/network/fragmentation/fragmentation.go", "diff": "@@ -46,9 +46,13 @@ const (\n)\nvar (\n- // ErrInvalidArgs indicates to the caller that that an invalid argument was\n+ // ErrInvalidArgs indicates to the caller that an invalid argument was\n// provided.\nErrInvalidArgs = errors.New(\"invalid args\")\n+\n+ // ErrFragmentOverlap indicates that, during reassembly, a fragment overlaps\n+ // with another one.\n+ ErrFragmentOverlap = errors.New(\"overlapping fragments\")\n)\n// FragmentID is the identifier for a fragment.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/fragmentation/reassembler.go", "new_path": "pkg/tcpip/network/fragmentation/reassembler.go", "diff": "@@ -28,7 +28,7 @@ import (\ntype hole struct {\nfirst uint16\nlast uint16\n- deleted bool\n+ filled bool\n}\ntype reassembler struct {\n@@ -38,7 +38,7 @@ type reassembler struct {\nproto uint8\nmu sync.Mutex\nholes []hole\n- deleted int\n+ filled int\nheap fragHeap\ndone bool\ncreationTime int64\n@@ -55,42 +55,84 @@ func newReassembler(id FragmentID, clock tcpip.Clock) *reassembler {\nr.holes = append(r.holes, hole{\nfirst: 0,\nlast: math.MaxUint16,\n- deleted: false})\n+ filled: false,\n+ })\nreturn r\n}\n-// updateHoles updates the list of holes for an incoming fragment and\n-// returns true iff the fragment filled at least part of an existing hole.\n-func (r *reassembler) updateHoles(first, last uint16, more bool) bool {\n- used := false\n+// updateHoles updates the list of holes for an incoming fragment. It returns\n+// true if the fragment fits, it is not a duplicate and it does not overlap with\n+// another fragment.\n+//\n+// For IPv6, overlaps with an existing fragment are explicitly forbidden by\n+// RFC 8200 section 4.5:\n+// If any of the fragments being reassembled overlap with any other fragments\n+// being reassembled for the same packet, reassembly of that packet must be\n+// abandoned and all the fragments that have been received for that packet\n+// must be discarded, and no ICMP error messages should be sent.\n+//\n+// It is not explicitly forbidden for IPv4, but to keep parity with Linux we\n+// disallow it as well:\n+// https://github.com/torvalds/linux/blob/38525c6/net/ipv4/inet_fragment.c#L349\n+func (r *reassembler) updateHoles(first, last uint16, more bool) (bool, error) {\nfor i := range r.holes {\n- if r.holes[i].deleted || first > r.holes[i].last || last < r.holes[i].first {\n+ currentHole := &r.holes[i]\n+\n+ if currentHole.filled || last < currentHole.first || currentHole.last < first {\ncontinue\n}\n- used = true\n- r.deleted++\n- r.holes[i].deleted = true\n- if first > r.holes[i].first {\n- r.holes = append(r.holes, hole{r.holes[i].first, first - 1, false})\n+\n+ if first < currentHole.first || currentHole.last < last {\n+ // Incoming fragment only partially fits in the free hole.\n+ return false, ErrFragmentOverlap\n+ }\n+\n+ r.filled++\n+ if first > currentHole.first {\n+ r.holes = append(r.holes, hole{\n+ first: currentHole.first,\n+ last: first - 1,\n+ filled: false,\n+ })\n+ }\n+ if last < currentHole.last && more {\n+ r.holes = append(r.holes, hole{\n+ first: last + 1,\n+ last: currentHole.last,\n+ filled: false,\n+ })\n}\n- if last < r.holes[i].last && more {\n- r.holes = append(r.holes, hole{last + 1, r.holes[i].last, false})\n+ // Update the current hole to precisely match the incoming fragment.\n+ r.holes[i] = hole{\n+ first: first,\n+ last: last,\n+ filled: true,\n}\n+ return true, nil\n}\n- return used\n+\n+ // Incoming fragment is a duplicate/subset, or its offset comes after the end\n+ // of the reassembled payload.\n+ return false, nil\n}\nfunc (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *stack.PacketBuffer) (buffer.VectorisedView, uint8, bool, int, error) {\nr.mu.Lock()\ndefer r.mu.Unlock()\n- consumed := 0\nif r.done {\n// A concurrent goroutine might have already reassembled\n// the packet and emptied the heap while this goroutine\n// was waiting on the mutex. We don't have to do anything in this case.\n- return buffer.VectorisedView{}, 0, false, consumed, nil\n+ return buffer.VectorisedView{}, 0, false, 0, nil\n+ }\n+\n+ used, err := r.updateHoles(first, last, more)\n+ if err != nil {\n+ return buffer.VectorisedView{}, 0, false, 0, fmt.Errorf(\"fragment reassembly failed: %w\", err)\n}\n- if r.updateHoles(first, last, more) {\n+\n+ var consumed int\n+ if used {\n// For IPv6, it is possible to have different Protocol values between\n// fragments of a packet (because, unlike IPv4, the Protocol is not used to\n// identify a fragment). In this case, only the Protocol of the first\n@@ -109,13 +151,14 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *s\nconsumed = vv.Size()\nr.size += consumed\n}\n- // Check if all the holes have been deleted and we are ready to reassamble.\n- if r.deleted < len(r.holes) {\n+\n+ // Check if all the holes have been filled and we are ready to reassemble.\n+ if r.filled < len(r.holes) {\nreturn buffer.VectorisedView{}, 0, false, consumed, nil\n}\nres, err := r.heap.reassemble()\nif err != nil {\n- return buffer.VectorisedView{}, 0, false, consumed, fmt.Errorf(\"fragment reassembly failed: %w\", err)\n+ return buffer.VectorisedView{}, 0, false, 0, fmt.Errorf(\"fragment reassembly failed: %w\", err)\n}\nreturn res, r.proto, true, consumed, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/fragmentation/reassembler_test.go", "new_path": "pkg/tcpip/network/fragmentation/reassembler_test.go", "diff": "@@ -16,92 +16,124 @@ package fragmentation\nimport (\n\"math\"\n- \"reflect\"\n\"testing\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n)\n-type updateHolesInput struct {\n+type updateHolesParams struct {\nfirst uint16\nlast uint16\nmore bool\n+ wantUsed bool\n+ wantError error\n}\n-var holesTestCases = []struct {\n- comment string\n- in []updateHolesInput\n+func TestUpdateHoles(t *testing.T) {\n+ var tests = []struct {\n+ name string\n+ params []updateHolesParams\nwant []hole\n}{\n{\n- comment: \"No fragments. Expected holes: {[0 -> inf]}.\",\n- in: []updateHolesInput{},\n- want: []hole{{first: 0, last: math.MaxUint16, deleted: false}},\n+ name: \"No fragments\",\n+ params: nil,\n+ want: []hole{{first: 0, last: math.MaxUint16, filled: false}},\n},\n{\n- comment: \"One fragment at beginning. Expected holes: {[2, inf]}.\",\n- in: []updateHolesInput{{first: 0, last: 1, more: true}},\n+ name: \"One fragment at beginning\",\n+ params: []updateHolesParams{{first: 0, last: 1, more: true, wantUsed: true, wantError: nil}},\nwant: []hole{\n- {first: 0, last: math.MaxUint16, deleted: true},\n- {first: 2, last: math.MaxUint16, deleted: false},\n+ {first: 0, last: 1, filled: true},\n+ {first: 2, last: math.MaxUint16, filled: false},\n},\n},\n{\n- comment: \"One fragment in the middle. Expected holes: {[0, 0], [3, inf]}.\",\n- in: []updateHolesInput{{first: 1, last: 2, more: true}},\n+ name: \"One fragment in the middle\",\n+ params: []updateHolesParams{{first: 1, last: 2, more: true, wantUsed: true, wantError: nil}},\nwant: []hole{\n- {first: 0, last: math.MaxUint16, deleted: true},\n- {first: 0, last: 0, deleted: false},\n- {first: 3, last: math.MaxUint16, deleted: false},\n+ {first: 1, last: 2, filled: true},\n+ {first: 0, last: 0, filled: false},\n+ {first: 3, last: math.MaxUint16, filled: false},\n},\n},\n{\n- comment: \"One fragment at the end. Expected holes: {[0, 0]}.\",\n- in: []updateHolesInput{{first: 1, last: 2, more: false}},\n+ name: \"One fragment at the end\",\n+ params: []updateHolesParams{{first: 1, last: 2, more: false, wantUsed: true, wantError: nil}},\nwant: []hole{\n- {first: 0, last: math.MaxUint16, deleted: true},\n- {first: 0, last: 0, deleted: false},\n+ {first: 1, last: 2, filled: true},\n+ {first: 0, last: 0, filled: false},\n},\n},\n{\n- comment: \"One fragment completing a packet. Expected holes: {}.\",\n- in: []updateHolesInput{{first: 0, last: 1, more: false}},\n+ name: \"One fragment completing a packet\",\n+ params: []updateHolesParams{{first: 0, last: 1, more: false, wantUsed: true, wantError: nil}},\nwant: []hole{\n- {first: 0, last: math.MaxUint16, deleted: true},\n+ {first: 0, last: 1, filled: true},\n},\n},\n{\n- comment: \"Two non-overlapping fragments completing a packet. Expected holes: {}.\",\n- in: []updateHolesInput{\n- {first: 0, last: 1, more: true},\n- {first: 2, last: 3, more: false},\n+ name: \"Two fragments completing a packet\",\n+ params: []updateHolesParams{\n+ {first: 0, last: 1, more: true, wantUsed: true, wantError: nil},\n+ {first: 2, last: 3, more: false, wantUsed: true, wantError: nil},\n},\nwant: []hole{\n- {first: 0, last: math.MaxUint16, deleted: true},\n- {first: 2, last: math.MaxUint16, deleted: true},\n+ {first: 0, last: 1, filled: true},\n+ {first: 2, last: 3, filled: true},\n},\n},\n{\n- comment: \"Two overlapping fragments completing a packet. Expected holes: {}.\",\n- in: []updateHolesInput{\n- {first: 0, last: 2, more: true},\n- {first: 2, last: 3, more: false},\n+ name: \"Two fragments completing a packet with a duplicate\",\n+ params: []updateHolesParams{\n+ {first: 0, last: 1, more: true, wantUsed: true, wantError: nil},\n+ {first: 0, last: 1, more: true, wantUsed: false, wantError: nil},\n+ {first: 2, last: 3, more: false, wantUsed: true, wantError: nil},\n},\nwant: []hole{\n- {first: 0, last: math.MaxUint16, deleted: true},\n- {first: 3, last: math.MaxUint16, deleted: true},\n+ {first: 0, last: 1, filled: true},\n+ {first: 2, last: 3, filled: true},\n+ },\n+ },\n+ {\n+ name: \"Two overlapping fragments\",\n+ params: []updateHolesParams{\n+ {first: 0, last: 10, more: true, wantUsed: true, wantError: nil},\n+ {first: 5, last: 15, more: false, wantUsed: false, wantError: ErrFragmentOverlap},\n+ {first: 11, last: 15, more: false, wantUsed: true, wantError: nil},\n+ },\n+ want: []hole{\n+ {first: 0, last: 10, filled: true},\n+ {first: 11, last: 15, filled: true},\n+ },\n+ },\n+ {\n+ name: \"Out of bounds fragment\",\n+ params: []updateHolesParams{\n+ {first: 0, last: 10, more: true, wantUsed: true, wantError: nil},\n+ {first: 11, last: 15, more: false, wantUsed: true, wantError: nil},\n+ {first: 16, last: 20, more: false, wantUsed: false, wantError: nil},\n+ },\n+ want: []hole{\n+ {first: 0, last: 10, filled: true},\n+ {first: 11, last: 15, filled: true},\n},\n},\n}\n-func TestUpdateHoles(t *testing.T) {\n- for _, c := range holesTestCases {\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\nr := newReassembler(FragmentID{}, &faketime.NullClock{})\n- for _, i := range c.in {\n- r.updateHoles(i.first, i.last, i.more)\n+ for _, param := range test.params {\n+ used, err := r.updateHoles(param.first, param.last, param.more)\n+ if used != param.wantUsed || err != param.wantError {\n+ t.Errorf(\"got r.updateHoles(%d, %d, %t) = (%t, %v), want = (%t, %v)\", param.first, param.last, param.more, used, err, param.wantUsed, param.wantError)\n+ }\n}\n- if !reflect.DeepEqual(r.holes, c.want) {\n- t.Errorf(\"Test \\\"%s\\\" produced unexepetced holes. Got %v. Want %v\", c.comment, r.holes, c.want)\n+ if diff := cmp.Diff(test.want, r.holes, cmp.AllowUnexported(hole{})); diff != \"\" {\n+ t.Errorf(\"r.holes mismatch (-want +got):\\n%s\", diff)\n}\n+ })\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/ipv4_fragment_reassembly_test.go", "new_path": "test/packetimpact/tests/ipv4_fragment_reassembly_test.go", "diff": "@@ -34,10 +34,10 @@ type fragmentInfo struct {\noffset uint16\nsize uint16\nmore uint8\n+ id uint16\n}\nfunc TestIPv4FragmentReassembly(t *testing.T) {\n- const fragmentID = 42\nicmpv4ProtoNum := uint8(header.ICMPv4ProtocolNumber)\ntests := []struct {\n@@ -45,28 +45,75 @@ func TestIPv4FragmentReassembly(t *testing.T) {\nipPayloadLen int\nfragments []fragmentInfo\nexpectReply bool\n+ skip bool\n+ skipReason string\n}{\n{\ndescription: \"basic reassembly\",\n- ipPayloadLen: 2000,\n+ ipPayloadLen: 3000,\nfragments: []fragmentInfo{\n- {offset: 0, size: 1000, more: header.IPv4FlagMoreFragments},\n- {offset: 1000, size: 1000, more: 0},\n+ {offset: 0, size: 1000, id: 5, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, id: 5, more: header.IPv4FlagMoreFragments},\n+ {offset: 2000, size: 1000, id: 5, more: 0},\n},\nexpectReply: true,\n},\n{\ndescription: \"out of order fragments\",\n- ipPayloadLen: 2000,\n+ ipPayloadLen: 3000,\nfragments: []fragmentInfo{\n- {offset: 1000, size: 1000, more: 0},\n- {offset: 0, size: 1000, more: header.IPv4FlagMoreFragments},\n+ {offset: 2000, size: 1000, id: 6, more: 0},\n+ {offset: 0, size: 1000, id: 6, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, id: 6, more: header.IPv4FlagMoreFragments},\n},\nexpectReply: true,\n},\n+ {\n+ description: \"duplicated fragments\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, id: 7, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, id: 7, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, id: 7, more: header.IPv4FlagMoreFragments},\n+ {offset: 2000, size: 1000, id: 7, more: 0},\n+ },\n+ expectReply: true,\n+ skip: true,\n+ skipReason: \"gvisor.dev/issues/4971\",\n+ },\n+ {\n+ description: \"fragment subset\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, id: 8, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, id: 8, more: header.IPv4FlagMoreFragments},\n+ {offset: 512, size: 256, id: 8, more: header.IPv4FlagMoreFragments},\n+ {offset: 2000, size: 1000, id: 8, more: 0},\n+ },\n+ expectReply: true,\n+ skip: true,\n+ skipReason: \"gvisor.dev/issues/4971\",\n+ },\n+ {\n+ description: \"fragment overlap\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, id: 9, more: header.IPv4FlagMoreFragments},\n+ {offset: 1512, size: 1000, id: 9, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, id: 9, more: header.IPv4FlagMoreFragments},\n+ {offset: 2000, size: 1000, id: 9, more: 0},\n+ },\n+ expectReply: false,\n+ skip: true,\n+ skipReason: \"gvisor.dev/issues/4971\",\n+ },\n}\nfor _, test := range tests {\n+ if test.skip {\n+ t.Skip(\"%s test skipped: %s\", test.description, test.skipReason)\n+ continue\n+ }\nt.Run(test.description, func(t *testing.T) {\ndut := testbench.NewDUT(t)\nconn := dut.Net.NewIPv4Conn(t, testbench.IPv4{}, testbench.IPv4{})\n@@ -95,7 +142,7 @@ func TestIPv4FragmentReassembly(t *testing.T) {\nProtocol: &icmpv4ProtoNum,\nFragmentOffset: testbench.Uint16(fragment.offset),\nFlags: testbench.Uint8(fragment.more),\n- ID: testbench.Uint16(fragmentID),\n+ ID: testbench.Uint16(fragment.id),\n},\n&testbench.Payload{\nBytes: data[fragment.offset:][:fragment.size],\n@@ -114,7 +161,7 @@ func TestIPv4FragmentReassembly(t *testing.T) {\n}, time.Second)\nif err != nil {\n// Either an unexpected frame was received, or none at all.\n- if bytesReceived < test.ipPayloadLen {\n+ if test.expectReply && bytesReceived < test.ipPayloadLen {\nt.Fatalf(\"received %d bytes out of %d, then conn.ExpectFrame(_, _, time.Second) failed with %s\", bytesReceived, test.ipPayloadLen, err)\n}\nbreak\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go", "new_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go", "diff": "@@ -35,10 +35,10 @@ type fragmentInfo struct {\noffset uint16\nsize uint16\nmore bool\n+ id uint32\n}\nfunc TestIPv6FragmentReassembly(t *testing.T) {\n- const fragmentID = 42\nicmpv6ProtoNum := header.IPv6ExtensionHeaderIdentifier(header.ICMPv6ProtocolNumber)\ntests := []struct {\n@@ -49,10 +49,11 @@ func TestIPv6FragmentReassembly(t *testing.T) {\n}{\n{\ndescription: \"basic reassembly\",\n- ipPayloadLen: 1500,\n+ ipPayloadLen: 3000,\nfragments: []fragmentInfo{\n- {offset: 0, size: 760, more: true},\n- {offset: 760, size: 740, more: false},\n+ {offset: 0, size: 1000, id: 100, more: true},\n+ {offset: 1000, size: 1000, id: 100, more: true},\n+ {offset: 2000, size: 1000, id: 100, more: false},\n},\nexpectReply: true,\n},\n@@ -60,12 +61,45 @@ func TestIPv6FragmentReassembly(t *testing.T) {\ndescription: \"out of order fragments\",\nipPayloadLen: 3000,\nfragments: []fragmentInfo{\n- {offset: 0, size: 1024, more: true},\n- {offset: 2048, size: 952, more: false},\n- {offset: 1024, size: 1024, more: true},\n+ {offset: 0, size: 1000, id: 101, more: true},\n+ {offset: 2000, size: 1000, id: 101, more: false},\n+ {offset: 1000, size: 1000, id: 101, more: true},\n+ },\n+ expectReply: true,\n+ },\n+ {\n+ description: \"duplicated fragments\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, id: 102, more: true},\n+ {offset: 1000, size: 1000, id: 102, more: true},\n+ {offset: 1000, size: 1000, id: 102, more: true},\n+ {offset: 2000, size: 1000, id: 102, more: false},\n+ },\n+ expectReply: true,\n+ },\n+ {\n+ description: \"fragment subset\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, id: 103, more: true},\n+ {offset: 1000, size: 1000, id: 103, more: true},\n+ {offset: 512, size: 256, id: 103, more: true},\n+ {offset: 2000, size: 1000, id: 103, more: false},\n},\nexpectReply: true,\n},\n+ {\n+ description: \"fragment overlap\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, id: 104, more: true},\n+ {offset: 1512, size: 1000, id: 104, more: true},\n+ {offset: 1000, size: 1000, id: 104, more: true},\n+ {offset: 2000, size: 1000, id: 104, more: false},\n+ },\n+ expectReply: false,\n+ },\n}\nfor _, test := range tests {\n@@ -101,7 +135,7 @@ func TestIPv6FragmentReassembly(t *testing.T) {\nNextHeader: &icmpv6ProtoNum,\nFragmentOffset: testbench.Uint16(fragment.offset / header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit),\nMoreFragments: testbench.Bool(fragment.more),\n- Identification: testbench.Uint32(fragmentID),\n+ Identification: testbench.Uint32(fragment.id),\n},\n&testbench.Payload{\nBytes: data[fragment.offset:][:fragment.size],\n@@ -118,7 +152,7 @@ func TestIPv6FragmentReassembly(t *testing.T) {\n}, time.Second)\nif err != nil {\n// Either an unexpected frame was received, or none at all.\n- if bytesReceived < test.ipPayloadLen {\n+ if test.expectReply && bytesReceived < test.ipPayloadLen {\nt.Fatalf(\"received %d bytes out of %d, then conn.ExpectFrame(_, _, time.Second) failed with %s\", bytesReceived, test.ipPayloadLen, err)\n}\nbreak\n" } ]
Go
Apache License 2.0
google/gvisor
Abandon reassembly of a packet if fragments overlap However, receiving duplicated fragments will not cause reassembly to fail. This is what Linux does too: https://github.com/torvalds/linux/blob/38525c6/net/ipv4/inet_fragment.c#L355 PiperOrigin-RevId: 345309546
259,951
02.12.2020 15:14:52
28,800
bdaae08ee2b4834422d46cdfd292161e974e4d26
Extract ICMPv4/v6 specific stats to their own types This change lets us split the v4 stats from the v6 stats, which will be useful when adding stats for each network endpoint.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -84,7 +84,8 @@ var Metrics = tcpip.Stats{\nMalformedRcvdPackets: mustCreateMetric(\"/netstack/malformed_received_packets\", \"Number of packets received by netstack that were deemed malformed.\"),\nDroppedPackets: mustCreateMetric(\"/netstack/dropped_packets\", \"Number of packets dropped by netstack due to full queues.\"),\nICMP: tcpip.ICMPStats{\n- V4PacketsSent: tcpip.ICMPv4SentPacketStats{\n+ V4: tcpip.ICMPv4Stats{\n+ PacketsSent: tcpip.ICMPv4SentPacketStats{\nICMPv4PacketStats: tcpip.ICMPv4PacketStats{\nEcho: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/echo\", \"Total number of ICMPv4 echo packets sent by netstack.\"),\nEchoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/echo_reply\", \"Total number of ICMPv4 echo reply packets sent by netstack.\"),\n@@ -100,7 +101,7 @@ var Metrics = tcpip.Stats{\n},\nDropped: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/dropped\", \"Total number of ICMPv4 packets dropped by netstack due to link layer errors.\"),\n},\n- V4PacketsReceived: tcpip.ICMPv4ReceivedPacketStats{\n+ PacketsReceived: tcpip.ICMPv4ReceivedPacketStats{\nICMPv4PacketStats: tcpip.ICMPv4PacketStats{\nEcho: mustCreateMetric(\"/netstack/icmp/v4/packets_received/echo\", \"Total number of ICMPv4 echo packets received by netstack.\"),\nEchoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/echo_reply\", \"Total number of ICMPv4 echo reply packets received by netstack.\"),\n@@ -116,7 +117,9 @@ var Metrics = tcpip.Stats{\n},\nInvalid: mustCreateMetric(\"/netstack/icmp/v4/packets_received/invalid\", \"Total number of ICMPv4 packets received that the transport layer could not parse.\"),\n},\n- V6PacketsSent: tcpip.ICMPv6SentPacketStats{\n+ },\n+ V6: tcpip.ICMPv6Stats{\n+ PacketsSent: tcpip.ICMPv6SentPacketStats{\nICMPv6PacketStats: tcpip.ICMPv6PacketStats{\nEchoRequest: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/echo_request\", \"Total number of ICMPv6 echo request packets sent by netstack.\"),\nEchoReply: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/echo_reply\", \"Total number of ICMPv6 echo reply packets sent by netstack.\"),\n@@ -132,7 +135,7 @@ var Metrics = tcpip.Stats{\n},\nDropped: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/dropped\", \"Total number of ICMPv6 packets dropped by netstack due to link layer errors.\"),\n},\n- V6PacketsReceived: tcpip.ICMPv6ReceivedPacketStats{\n+ PacketsReceived: tcpip.ICMPv6ReceivedPacketStats{\nICMPv6PacketStats: tcpip.ICMPv6PacketStats{\nEchoRequest: mustCreateMetric(\"/netstack/icmp/v6/packets_received/echo_request\", \"Total number of ICMPv6 echo request packets received by netstack.\"),\nEchoReply: mustCreateMetric(\"/netstack/icmp/v6/packets_received/echo_reply\", \"Total number of ICMPv6 echo reply packets received by netstack.\"),\n@@ -149,6 +152,7 @@ var Metrics = tcpip.Stats{\nInvalid: mustCreateMetric(\"/netstack/icmp/v6/packets_received/invalid\", \"Total number of ICMPv6 packets received that the transport layer could not parse.\"),\n},\n},\n+ },\nIP: tcpip.IPStats{\nPacketsReceived: mustCreateMetric(\"/netstack/ip/packets_received\", \"Total number of IP packets received from the link layer in nic.DeliverNetworkPacket.\"),\nInvalidDestinationAddressesReceived: mustCreateMetric(\"/netstack/ip/invalid_addresses_received\", \"Total number of IP packets received with an unknown or invalid destination address.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/stack.go", "new_path": "pkg/sentry/socket/netstack/stack.go", "diff": "@@ -324,12 +324,12 @@ func (s *Stack) Statistics(stat interface{}, arg string) error {\n0, // Support Ip/FragCreates.\n}\ncase *inet.StatSNMPICMP:\n- in := Metrics.ICMP.V4PacketsReceived.ICMPv4PacketStats\n- out := Metrics.ICMP.V4PacketsSent.ICMPv4PacketStats\n+ in := Metrics.ICMP.V4.PacketsReceived.ICMPv4PacketStats\n+ out := Metrics.ICMP.V4.PacketsSent.ICMPv4PacketStats\n// TODO(gvisor.dev/issue/969) Support stubbed stats.\n*stats = inet.StatSNMPICMP{\n0, // Icmp/InMsgs.\n- Metrics.ICMP.V4PacketsSent.Dropped.Value(), // InErrors.\n+ Metrics.ICMP.V4.PacketsSent.Dropped.Value(), // InErrors.\n0, // Icmp/InCsumErrors.\nin.DstUnreachable.Value(), // InDestUnreachs.\nin.TimeExceeded.Value(), // InTimeExcds.\n@@ -343,7 +343,7 @@ func (s *Stack) Statistics(stat interface{}, arg string) error {\nin.InfoRequest.Value(), // InAddrMasks.\nin.InfoReply.Value(), // InAddrMaskReps.\n0, // Icmp/OutMsgs.\n- Metrics.ICMP.V4PacketsReceived.Invalid.Value(), // OutErrors.\n+ Metrics.ICMP.V4.PacketsReceived.Invalid.Value(), // OutErrors.\nout.DstUnreachable.Value(), // OutDestUnreachs.\nout.TimeExceeded.Value(), // OutTimeExcds.\nout.ParamProblem.Value(), // OutParmProbs.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/icmp.go", "new_path": "pkg/tcpip/network/ipv4/icmp.go", "diff": "@@ -63,7 +63,7 @@ func (e *endpoint) handleControl(typ stack.ControlType, extra uint32, pkt *stack\nfunc (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\nstats := e.protocol.stack.Stats()\n- received := stats.ICMP.V4PacketsReceived\n+ received := stats.ICMP.V4.PacketsReceived\n// TODO(gvisor.dev/issue/170): ICMP packets don't have their\n// TransportHeader fields set. See icmp/protocol.go:protocol.Parse for a\n// full explanation.\n@@ -130,7 +130,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\ncase header.ICMPv4Echo:\nreceived.Echo.Increment()\n- sent := stats.ICMP.V4PacketsSent\n+ sent := stats.ICMP.V4.PacketsSent\nif !e.protocol.stack.AllowICMPMessage() {\nsent.RateLimited.Increment()\nreturn\n@@ -379,7 +379,7 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\n}\ndefer route.Release()\n- sent := p.stack.Stats().ICMP.V4PacketsSent\n+ sent := p.stack.Stats().ICMP.V4.PacketsSent\nif !p.stack.AllowICMPMessage() {\nsent.RateLimited.Increment()\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -126,8 +126,8 @@ func getTargetLinkAddr(it header.NDPOptionIterator) (tcpip.LinkAddress, bool) {\nfunc (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool) {\nstats := e.protocol.stack.Stats().ICMP\n- sent := stats.V6PacketsSent\n- received := stats.V6PacketsReceived\n+ sent := stats.V6.PacketsSent\n+ received := stats.V6.PacketsReceived\n// TODO(gvisor.dev/issue/170): ICMP packets don't have their\n// TransportHeader fields set. See icmp/protocol.go:protocol.Parse for a\n// full explanation.\n@@ -709,7 +709,7 @@ func (p *protocol) LinkAddressRequest(targetAddr, localAddr tcpip.Address, remot\nns.Options().Serialize(optsSerializer)\npacket.SetChecksum(header.ICMPv6Checksum(packet, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n- stat := p.stack.Stats().ICMP.V6PacketsSent\n+ stat := p.stack.Stats().ICMP.V6.PacketsSent\nif err := r.WritePacket(nil /* gso */, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n@@ -856,7 +856,7 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\ndefer route.Release()\nstats := p.stack.Stats().ICMP\n- sent := stats.V6PacketsSent\n+ sent := stats.V6.PacketsSent\nif !p.stack.AllowICMPMessage() {\nsent.RateLimited.Increment()\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -317,7 +317,7 @@ func TestICMPCounts(t *testing.T) {\n// Stats().ICMP.ICMPv6ReceivedPacketStats.Invalid is incremented.\nhandleIPv6Payload(header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\n- icmpv6Stats := s.Stats().ICMP.V6PacketsReceived\n+ icmpv6Stats := s.Stats().ICMP.V6.PacketsReceived\nvisitStats(reflect.ValueOf(&icmpv6Stats).Elem(), func(name string, s *tcpip.StatCounter) {\nif got, want := s.Value(), uint64(1); got != want {\nt.Errorf(\"got %s = %d, want = %d\", name, got, want)\n@@ -475,7 +475,7 @@ func TestICMPCountsWithNeighborCache(t *testing.T) {\n// Stats().ICMP.ICMPv6ReceivedPacketStats.Invalid is incremented.\nhandleIPv6Payload(header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\n- icmpv6Stats := s.Stats().ICMP.V6PacketsReceived\n+ icmpv6Stats := s.Stats().ICMP.V6.PacketsReceived\nvisitStats(reflect.ValueOf(&icmpv6Stats).Elem(), func(name string, s *tcpip.StatCounter) {\nif got, want := s.Value(), uint64(1); got != want {\nt.Errorf(\"got %s = %d, want = %d\", name, got, want)\n@@ -865,7 +865,7 @@ func TestICMPChecksumValidationSimple(t *testing.T) {\ne.InjectInbound(ProtocolNumber, pkt)\n}\n- stats := s.Stats().ICMP.V6PacketsReceived\n+ stats := s.Stats().ICMP.V6.PacketsReceived\ninvalid := stats.Invalid\nrouterOnly := stats.RouterOnlyPacketsDroppedByHost\ntypStat := typ.statCounter(stats)\n@@ -1060,7 +1060,7 @@ func TestICMPChecksumValidationWithPayload(t *testing.T) {\ne.InjectInbound(ProtocolNumber, pkt)\n}\n- stats := s.Stats().ICMP.V6PacketsReceived\n+ stats := s.Stats().ICMP.V6.PacketsReceived\ninvalid := stats.Invalid\ntypStat := typ.statCounter(stats)\n@@ -1239,7 +1239,7 @@ func TestICMPChecksumValidationWithPayloadMultipleViews(t *testing.T) {\ne.InjectInbound(ProtocolNumber, pkt)\n}\n- stats := s.Stats().ICMP.V6PacketsReceived\n+ stats := s.Stats().ICMP.V6.PacketsReceived\ninvalid := stats.Invalid\ntypStat := typ.statCounter(stats)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -80,7 +80,7 @@ func testReceiveICMP(t *testing.T, s *stack.Stack, e *channel.Endpoint, src, dst\nData: hdr.View().ToVectorisedView(),\n}))\n- stats := s.Stats().ICMP.V6PacketsReceived\n+ stats := s.Stats().ICMP.V6.PacketsReceived\nif got := stats.NeighborAdvert.Value(); got != want {\nt.Fatalf(\"got NeighborAdvert = %d, want = %d\", got, want)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/mld.go", "new_path": "pkg/tcpip/network/ipv6/mld.go", "diff": "@@ -125,7 +125,7 @@ func (mld *mldState) initializeAll() {\n}\nfunc (mld *mldState) writePacket(destAddress, groupAddress tcpip.Address, mldType header.ICMPv6Type) *tcpip.Error {\n- sentStats := mld.ep.protocol.stack.Stats().ICMP.V6PacketsSent\n+ sentStats := mld.ep.protocol.stack.Stats().ICMP.V6.PacketsSent\nvar mldStat *tcpip.StatCounter\nswitch mldType {\ncase header.ICMPv6MulticastListenerReport:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp.go", "new_path": "pkg/tcpip/network/ipv6/ndp.go", "diff": "@@ -724,7 +724,7 @@ func (ndp *ndpState) sendDADPacket(addr tcpip.Address, addressEndpoint stack.Add\nData: buffer.View(icmp).ToVectorisedView(),\n})\n- sent := ndp.ep.protocol.stack.Stats().ICMP.V6PacketsSent\n+ sent := ndp.ep.protocol.stack.Stats().ICMP.V6.PacketsSent\nndp.ep.addIPHeader(header.IPv6Any, snmc, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n@@ -1846,7 +1846,7 @@ func (ndp *ndpState) startSolicitingRouters() {\nData: buffer.View(icmpData).ToVectorisedView(),\n})\n- sent := ndp.ep.protocol.stack.Stats().ICMP.V6PacketsSent\n+ sent := ndp.ep.protocol.stack.Stats().ICMP.V6.PacketsSent\nndp.ep.addIPHeader(localAddr, header.IPv6AllRoutersMulticastAddress, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -220,7 +220,7 @@ func TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\nDstAddr: lladdr0,\n})\n- invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+ invalid := s.Stats().ICMP.V6.PacketsReceived.Invalid\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n@@ -326,7 +326,7 @@ func TestNeighorSolicitationWithSourceLinkLayerOptionUsingNeighborCache(t *testi\nDstAddr: lladdr0,\n})\n- invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+ invalid := s.Stats().ICMP.V6.PacketsReceived.Invalid\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n@@ -606,7 +606,7 @@ func TestNeighorSolicitationResponse(t *testing.T) {\nDstAddr: test.nsDst,\n})\n- invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+ invalid := s.Stats().ICMP.V6.PacketsReceived.Invalid\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n@@ -792,7 +792,7 @@ func TestNeighorAdvertisementWithTargetLinkLayerOption(t *testing.T) {\nDstAddr: lladdr0,\n})\n- invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+ invalid := s.Stats().ICMP.V6.PacketsReceived.Invalid\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n@@ -905,7 +905,7 @@ func TestNeighorAdvertisementWithTargetLinkLayerOptionUsingNeighborCache(t *test\nDstAddr: lladdr0,\n})\n- invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+ invalid := s.Stats().ICMP.V6.PacketsReceived.Invalid\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n@@ -1122,7 +1122,7 @@ func TestNDPValidation(t *testing.T) {\ns.SetForwarding(ProtocolNumber, true)\n}\n- stats := s.Stats().ICMP.V6PacketsReceived\n+ stats := s.Stats().ICMP.V6.PacketsReceived\ninvalid := stats.Invalid\nrouterOnly := stats.RouterOnlyPacketsDroppedByHost\ntypStat := typ.statCounter(stats)\n@@ -1358,7 +1358,7 @@ func TestRouterAdvertValidation(t *testing.T) {\nDstAddr: header.IPv6AllNodesMulticastAddress,\n})\n- stats := s.Stats().ICMP.V6PacketsReceived\n+ stats := s.Stats().ICMP.V6.PacketsReceived\ninvalid := stats.Invalid\nrxRA := stats.RouterAdvert\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/multicast_group_test.go", "new_path": "pkg/tcpip/network/multicast_group_test.go", "diff": "@@ -218,10 +218,10 @@ func TestMGPDisabled(t *testing.T) {\nprotoNum: ipv6.ProtocolNumber,\nmulticastAddr: ipv6MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n},\nreceivedQueryStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsReceived.MulticastListenerQuery\n+ return s.Stats().ICMP.V6.PacketsReceived.MulticastListenerQuery\n},\nrxQuery: func(e *channel.Endpoint) {\ncreateAndInjectMLDPacket(e, mldQuery, 0, header.IPv6Any)\n@@ -326,7 +326,7 @@ func TestMGPReceiveCounters(t *testing.T) {\nmaxRespTime: 0,\ngroupAddress: header.IPv6Any,\nstatCounter: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsReceived.MulticastListenerQuery\n+ return s.Stats().ICMP.V6.PacketsReceived.MulticastListenerQuery\n},\nrxMGPkt: createAndInjectMLDPacket,\n},\n@@ -336,7 +336,7 @@ func TestMGPReceiveCounters(t *testing.T) {\nmaxRespTime: 0,\ngroupAddress: header.IPv6Any,\nstatCounter: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsReceived.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsReceived.MulticastListenerReport\n},\nrxMGPkt: createAndInjectMLDPacket,\n},\n@@ -346,7 +346,7 @@ func TestMGPReceiveCounters(t *testing.T) {\nmaxRespTime: 0,\ngroupAddress: header.IPv6Any,\nstatCounter: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsReceived.MulticastListenerDone\n+ return s.Stats().ICMP.V6.PacketsReceived.MulticastListenerDone\n},\nrxMGPkt: createAndInjectMLDPacket,\n},\n@@ -399,10 +399,10 @@ func TestMGPJoinGroup(t *testing.T) {\nmulticastAddr: ipv6MulticastAddr1,\nmaxUnsolicitedResponseDelay: ipv6.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n},\nreceivedQueryStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsReceived.MulticastListenerQuery\n+ return s.Stats().ICMP.V6.PacketsReceived.MulticastListenerQuery\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\nt.Helper()\n@@ -497,10 +497,10 @@ func TestMGPLeaveGroup(t *testing.T) {\nprotoNum: ipv6.ProtocolNumber,\nmulticastAddr: ipv6MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n},\nsentLeaveStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerDone\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerDone\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo) {\nt.Helper()\n@@ -597,10 +597,10 @@ func TestMGPQueryMessages(t *testing.T) {\nmulticastAddr: ipv6MulticastAddr1,\nmaxUnsolicitedResponseDelay: ipv6.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n},\nreceivedQueryStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsReceived.MulticastListenerQuery\n+ return s.Stats().ICMP.V6.PacketsReceived.MulticastListenerQuery\n},\nrxQuery: func(e *channel.Endpoint, maxRespTime uint8, groupAddress tcpip.Address) {\ncreateAndInjectMLDPacket(e, mldQuery, maxRespTime, groupAddress)\n@@ -744,10 +744,10 @@ func TestMGPReportMessages(t *testing.T) {\nprotoNum: ipv6.ProtocolNumber,\nmulticastAddr: ipv6MulticastAddr1,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n},\nsentLeaveStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerDone\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerDone\n},\nrxReport: func(e *channel.Endpoint) {\ncreateAndInjectMLDPacket(e, mldReport, 0, ipv6MulticastAddr1)\n@@ -877,10 +877,10 @@ func TestMGPWithNICLifecycle(t *testing.T) {\nfinalMulticastAddr: ipv6MulticastAddr3,\nmaxUnsolicitedResponseDelay: ipv6.UnsolicitedReportIntervalMax,\nsentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerReport\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n},\nsentLeaveStat: func(s *stack.Stack) *tcpip.StatCounter {\n- return s.Stats().ICMP.V6PacketsSent.MulticastListenerDone\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerDone\n},\nvalidateReport: func(t *testing.T, p channel.PacketInfo, addr tcpip.Address) {\nt.Helper()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -353,7 +353,7 @@ func TestDADDisabled(t *testing.T) {\n}\n// We should not have sent any NDP NS messages.\n- if got := s.Stats().ICMP.V6PacketsSent.NeighborSolicit.Value(); got != 0 {\n+ if got := s.Stats().ICMP.V6.PacketsSent.NeighborSolicit.Value(); got != 0 {\nt.Fatalf(\"got NeighborSolicit = %d, want = 0\", got)\n}\n}\n@@ -525,7 +525,7 @@ func TestDADResolve(t *testing.T) {\n}\n// Should not have sent any more NS messages.\n- if got := s.Stats().ICMP.V6PacketsSent.NeighborSolicit.Value(); got != uint64(test.dupAddrDetectTransmits) {\n+ if got := s.Stats().ICMP.V6.PacketsSent.NeighborSolicit.Value(); got != uint64(test.dupAddrDetectTransmits) {\nt.Fatalf(\"got NeighborSolicit = %d, want = %d\", got, test.dupAddrDetectTransmits)\n}\n@@ -673,7 +673,7 @@ func TestDADFail(t *testing.T) {\n// Receive a packet to simulate an address conflict.\ntest.rxPkt(e, addr1)\n- stat := test.getStat(s.Stats().ICMP.V6PacketsReceived)\n+ stat := test.getStat(s.Stats().ICMP.V6.PacketsReceived)\nif got := stat.Value(); got != 1 {\nt.Fatalf(\"got stat = %d, want = 1\", got)\n}\n@@ -810,7 +810,7 @@ func TestDADStop(t *testing.T) {\n}\n// Should not have sent more than 1 NS message.\n- if got := s.Stats().ICMP.V6PacketsSent.NeighborSolicit.Value(); got > 1 {\n+ if got := s.Stats().ICMP.V6.PacketsSent.NeighborSolicit.Value(); got > 1 {\nt.Errorf(\"got NeighborSolicit = %d, want <= 1\", got)\n}\n})\n@@ -5263,7 +5263,7 @@ func TestRouterSolicitation(t *testing.T) {\nwaitForNothing(test.effectiveMaxRtrSolicitDelay)\n}\n- if got, want := s.Stats().ICMP.V6PacketsSent.RouterSolicit.Value(), uint64(test.maxRtrSolicit); got != want {\n+ if got, want := s.Stats().ICMP.V6.PacketsSent.RouterSolicit.Value(), uint64(test.maxRtrSolicit); got != want {\nt.Fatalf(\"got sent RouterSolicit = %d, want = %d\", got, want)\n}\n})\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1384,25 +1384,37 @@ type ICMPv6ReceivedPacketStats struct {\nRouterOnlyPacketsDroppedByHost *StatCounter\n}\n-// ICMPStats collects ICMP-specific stats (both v4 and v6).\n-type ICMPStats struct {\n+// ICMPv4Stats collects ICMPv4-specific stats.\n+type ICMPv4Stats struct {\n// ICMPv4SentPacketStats contains counts of sent packets by ICMPv4 packet type\n// and a single count of packets which failed to write to the link\n// layer.\n- V4PacketsSent ICMPv4SentPacketStats\n+ PacketsSent ICMPv4SentPacketStats\n// ICMPv4ReceivedPacketStats contains counts of received packets by ICMPv4\n// packet type and a single count of invalid packets received.\n- V4PacketsReceived ICMPv4ReceivedPacketStats\n+ PacketsReceived ICMPv4ReceivedPacketStats\n+}\n+// ICMPv6Stats collects ICMPv6-specific stats.\n+type ICMPv6Stats struct {\n// ICMPv6SentPacketStats contains counts of sent packets by ICMPv6 packet type\n// and a single count of packets which failed to write to the link\n// layer.\n- V6PacketsSent ICMPv6SentPacketStats\n+ PacketsSent ICMPv6SentPacketStats\n// ICMPv6ReceivedPacketStats contains counts of received packets by ICMPv6\n// packet type and a single count of invalid packets received.\n- V6PacketsReceived ICMPv6ReceivedPacketStats\n+ PacketsReceived ICMPv6ReceivedPacketStats\n+}\n+\n+// ICMPStats collects ICMP-specific stats (both v4 and v6).\n+type ICMPStats struct {\n+ // V4 contains the ICMPv4-specifics stats.\n+ V4 ICMPv4Stats\n+\n+ // V6 contains the ICMPv4-specifics stats.\n+ V6 ICMPv6Stats\n}\n// IGMPPacketStats enumerates counts for all IGMP packet types.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -264,7 +264,7 @@ func TestTCPResetsSentNoICMP(t *testing.T) {\n}\n// Read outgoing ICMP stats and check no ICMP DstUnreachable was recorded.\n- sent := stats.ICMP.V4PacketsSent\n+ sent := stats.ICMP.V4.PacketsSent\nif got, want := sent.DstUnreachable.Value(), uint64(0); got != want {\nt.Errorf(\"got ICMP DstUnreachable.Value() = %d, want = %d\", got, want)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Extract ICMPv4/v6 specific stats to their own types This change lets us split the v4 stats from the v6 stats, which will be useful when adding stats for each network endpoint. PiperOrigin-RevId: 345322615
259,898
02.12.2020 19:09:17
28,800
8b692f593103d24d1de0d85ef89ec5b3f3e9cd5a
Make testutil.RandomID safe for concurrent uses testutil.RandomID was using Rand.Read which is not safe for concurrent use. It caused name conflicts in packetimpact tests when they are run in parallel. Adding a mutex to protect the Rand.Read operation.
[ { "change_type": "MODIFY", "old_path": "pkg/test/testutil/testutil.go", "new_path": "pkg/test/testutil/testutil.go", "diff": "@@ -248,14 +248,25 @@ func writeSpec(dir string, spec *specs.Spec) error {\n// idRandomSrc is a pseudo random generator used to in RandomID.\nvar idRandomSrc = rand.New(rand.NewSource(time.Now().UnixNano()))\n+// idRandomSrcMtx is the mutex protecting idRandomSrc.Read from being used\n+// concurrently in differnt goroutines.\n+var idRandomSrcMtx sync.Mutex\n+\n// RandomID returns 20 random bytes following the given prefix.\nfunc RandomID(prefix string) string {\n// Read 20 random bytes.\nb := make([]byte, 20)\n+ // Rand.Read is not safe for concurrent use. Packetimpact tests can be run in\n+ // parallel now, so we have to protect the Read with a mutex. Otherwise we'll\n+ // run into name conflicts.\n+ // https://golang.org/pkg/math/rand/#Rand.Read\n+ idRandomSrcMtx.Lock()\n// \"[Read] always returns len(p) and a nil error.\" --godoc\nif _, err := idRandomSrc.Read(b); err != nil {\n+ idRandomSrcMtx.Unlock()\npanic(\"rand.Read failed: \" + err.Error())\n}\n+ idRandomSrcMtx.Unlock()\nif prefix != \"\" {\nprefix = prefix + \"-\"\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Make testutil.RandomID safe for concurrent uses testutil.RandomID was using Rand.Read which is not safe for concurrent use. It caused name conflicts in packetimpact tests when they are run in parallel. Adding a mutex to protect the Rand.Read operation. PiperOrigin-RevId: 345360062
259,858
03.12.2020 00:58:36
28,800
80552b936d06e43ea77df09a6b6c5ce2600a6f6a
Support partitions for other tests.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -123,6 +123,7 @@ list-images: ## List all available images.\n##\nPARTITION ?= 1\nTOTAL_PARTITIONS ?= 1\n+PARTITIONS := --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\nrunsc: ## Builds the runsc binary.\n@$(call submake,build OPTIONS=\"-c opt\" TARGETS=\"//runsc\")\n@@ -137,7 +138,7 @@ smoke-tests: ## Runs a simple smoke test after build runsc.\n.PHONY: smoke-tests\nfuse-tests:\n- @$(call submake,test OPTIONS=\"--test_tag_filters fuse\" TARGETS=\"test/fuse/...\")\n+ @$(call submake,test OPTIONS=\"--test_tag_filters fuse $(PARTITIONS)\" TARGETS=\"test/fuse/...\")\n.PHONY: fuse-tests\nunit-tests: ## Local package unit tests in pkg/..., runsc/, tools/.., etc.\n@@ -161,28 +162,22 @@ network-tests: iptables-tests packetdrill-tests packetimpact-tests\nINTEGRATION_TARGETS := //test/image:image_test //test/e2e:integration_test\nsyscall-%-tests:\n- @$(call submake,test OPTIONS=\"--test_tag_filters runsc_$*\" TARGETS=\"test/syscalls/...\")\n+ @$(call submake,test OPTIONS=\"--test_tag_filters runsc_$* $(PARTITIONS)\" TARGETS=\"test/syscalls/...\")\nsyscall-native-tests:\n- @$(call submake,test OPTIONS=\"--test_tag_filters native\" TARGETS=\"test/syscalls/...\")\n+ @$(call submake,test OPTIONS=\"--test_tag_filters native $(PARTITIONS)\" TARGETS=\"test/syscalls/...\")\n.PHONY: syscall-native-tests\nsyscall-tests: ## Run all system call tests.\n- @$(call submake,test TARGETS=\"test/syscalls/...\")\n+ @$(call submake,test OPTIONS=\"$(PARTITIONS)\" TARGETS=\"test/syscalls/...\")\n%-runtime-tests: load-runtimes_%\n@$(call submake,install-runtime)\n- @$(call submake,test-runtime OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\n+ @$(call submake,test-runtime OPTIONS=\"--test_timeout=10800\" TARGETS=\"//test/runtimes:$*\")\n%-runtime-tests_vfs2: load-runtimes_%\n-ifeq ($(PARTITION),)\n- @$(eval PARTITION := 1)\n-endif\n-ifeq ($(TOTAL_PARTITIONS),)\n- @$(eval TOTAL_PARTITIONS := 1)\n-endif\n@$(call submake,install-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n- @$(call submake,test-runtime RUNTIME=\"vfs2\" OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\n+ @$(call submake,test-runtime RUNTIME=\"vfs2\" OPTIONS=\"--test_timeout=10800\" TARGETS=\"//test/runtimes:$*\")\ndo-tests: runsc\n@$(call submake,run TARGETS=\"//runsc\" ARGS=\"--rootless do true\")\n@@ -464,7 +459,7 @@ configure: ## Configures a single runtime. Requires sudo. Typically called from\n.PHONY: configure\ntest-runtime: ## A convenient wrapper around test that provides the runtime argument. Target must still be provided.\n- @$(call submake,test OPTIONS=\"$(OPTIONS) --test_arg=--runtime=$(RUNTIME)\")\n+ @$(call submake,test OPTIONS=\"$(OPTIONS) --test_arg=--runtime=$(RUNTIME) $(PARTITIONS)\")\n.PHONY: test-runtime\nnogo: ## Surfaces all nogo findings.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\", \"most_shards\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\npackage(licenses = [\"notice\"])\n@@ -112,7 +112,7 @@ go_test(\n\"transport_demuxer_test.go\",\n\"transport_test.go\",\n],\n- shard_count = 20,\n+ shard_count = most_shards,\ndeps = [\n\":stack\",\n\"//pkg/rand\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/BUILD", "new_path": "pkg/tcpip/transport/tcp/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\", \"more_shards\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\npackage(licenses = [\"notice\"])\n@@ -93,7 +93,7 @@ go_test(\n\"tcp_test.go\",\n\"tcp_timestamp_test.go\",\n],\n- shard_count = 10,\n+ shard_count = more_shards,\ndeps = [\n\":tcp\",\n\"//pkg/rand\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/test/testutil/testutil.go", "new_path": "pkg/test/testutil/testutil.go", "diff": "@@ -49,6 +49,8 @@ import (\nvar (\ncheckpoint = flag.Bool(\"checkpoint\", true, \"control checkpoint/restore support\")\n+ partition = flag.Int(\"partition\", 1, \"partition number, this is 1-indexed\")\n+ totalPartitions = flag.Int(\"total_partitions\", 1, \"total number of partitions\")\n)\n// IsCheckpointSupported returns the relevant command line flag.\n@@ -521,7 +523,8 @@ func TouchShardStatusFile() error {\n}\n// TestIndicesForShard returns indices for this test shard based on the\n-// TEST_SHARD_INDEX and TEST_TOTAL_SHARDS environment vars.\n+// TEST_SHARD_INDEX and TEST_TOTAL_SHARDS environment vars, as well as\n+// the passed partition flags.\n//\n// If either of the env vars are not present, then the function will return all\n// tests. If there are more shards than there are tests, then the returned list\n@@ -546,6 +549,11 @@ func TestIndicesForShard(numTests int) ([]int, error) {\n}\n}\n+ // Combine with the partitions.\n+ partitionSize := shardTotal\n+ shardTotal = (*totalPartitions) * shardTotal\n+ shardIndex = partitionSize*(*partition-1) + shardIndex\n+\n// Calculate!\nvar indices []int\nnumBlocks := int(math.Ceil(float64(numTests) / float64(shardTotal)))\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/BUILD", "new_path": "runsc/container/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\", \"more_shards\")\npackage(licenses = [\"notice\"])\n@@ -49,7 +49,7 @@ go_test(\n\"//test/cmd/test_app\",\n],\nlibrary = \":container\",\n- shard_count = 10,\n+ shard_count = more_shards,\ntags = [\n\"requires-kvm\",\n],\n" }, { "change_type": "MODIFY", "old_path": "test/packetdrill/defs.bzl", "new_path": "test/packetdrill/defs.bzl", "diff": "@@ -15,7 +15,7 @@ def _packetdrill_test_impl(ctx):\n# Make sure that everything is readable here.\n\"find . -type f -exec chmod a+rx {} \\\\;\",\n\"find . -type d -exec chmod a+rx {} \\\\;\",\n- \"%s %s --init_script %s $@ -- %s\\n\" % (\n+ \"%s %s --init_script %s \\\"$@\\\" -- %s\\n\" % (\ntest_runner.short_path,\n\" \".join(ctx.attr.flags),\nctx.files._init_script[0].short_path,\n@@ -80,9 +80,7 @@ def packetdrill_netstack_test(name, **kwargs):\nkwargs[\"tags\"] = PACKETDRILL_TAGS\n_packetdrill_test(\nname = name,\n- # This is the default runtime unless\n- # \"--test_arg=--runtime=OTHER_RUNTIME\" is used to override the value.\n- flags = [\"--dut_platform\", \"netstack\", \"--runtime\", \"runsc-d\"],\n+ flags = [\"--dut_platform\", \"netstack\"],\n**kwargs\n)\n" }, { "change_type": "MODIFY", "old_path": "test/packetdrill/packetdrill_test.sh", "new_path": "test/packetdrill/packetdrill_test.sh", "diff": "@@ -29,7 +29,7 @@ function failure() {\n}\ntrap 'failure ${LINENO} \"$BASH_COMMAND\"' ERR\n-declare -r LONGOPTS=\"dut_platform:,init_script:,runtime:\"\n+declare -r LONGOPTS=\"dut_platform:,init_script:,runtime:,partition:,total_partitions:\"\n# Don't use declare below so that the error from getopt will end the script.\nPARSED=$(getopt --options \"\" --longoptions=$LONGOPTS --name \"$0\" -- \"$@\")\n@@ -48,12 +48,17 @@ while true; do\nshift 2\n;;\n--runtime)\n- # Not readonly because there might be multiple --runtime arguments and we\n- # want to use just the last one. Only used if --dut_platform is\n- # \"netstack\".\ndeclare RUNTIME=\"$2\"\nshift 2\n;;\n+ --partition)\n+ # Ignored.\n+ shift 2\n+ ;;\n+ --total_partitions)\n+ # Ignored.\n+ shift 2\n+ ;;\n--)\nshift\nbreak\n" }, { "change_type": "MODIFY", "old_path": "test/perf/BUILD", "new_path": "test/perf/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"more_shards\")\nload(\"//test/runner:defs.bzl\", \"syscall_test\")\npackage(licenses = [\"notice\"])\n@@ -37,7 +38,7 @@ syscall_test(\nsyscall_test(\nsize = \"enormous\",\ndebug = False,\n- shard_count = 10,\n+ shard_count = more_shards,\ntags = [\"nogotsan\"],\ntest = \"//test/perf/linux:getdents_benchmark\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/runner/defs.bzl", "new_path": "test/runner/defs.bzl", "diff": "@@ -12,7 +12,7 @@ def _runner_test_impl(ctx):\n\" mkdir -p \\\"${TEST_UNDECLARED_OUTPUTS_DIR}\\\"\",\n\" chmod a+rwx \\\"${TEST_UNDECLARED_OUTPUTS_DIR}\\\"\",\n\"fi\",\n- \"exec %s %s %s\\n\" % (\n+ \"exec %s %s \\\"$@\\\" %s\\n\" % (\nctx.files.runner[0].short_path,\n\" \".join(ctx.attr.runner_args),\nctx.files.test[0].short_path,\n@@ -52,8 +52,6 @@ _runner_test = rule(\ndef _syscall_test(\ntest,\n- shard_count,\n- size,\nplatform,\nuse_tmpfs,\ntags,\n@@ -63,7 +61,8 @@ def _syscall_test(\noverlay = False,\nadd_uds_tree = False,\nvfs2 = False,\n- fuse = False):\n+ fuse = False,\n+ **kwargs):\n# Prepend \"runsc\" to non-native platform names.\nfull_platform = platform if platform == \"native\" else \"runsc_\" + platform\n@@ -126,15 +125,12 @@ def _syscall_test(\nname = name,\ntest = test,\nrunner_args = runner_args,\n- size = size,\ntags = tags,\n- shard_count = shard_count,\n+ **kwargs\n)\ndef syscall_test(\ntest,\n- shard_count = 5,\n- size = \"small\",\nuse_tmpfs = False,\nadd_overlay = False,\nadd_uds_tree = False,\n@@ -142,18 +138,21 @@ def syscall_test(\nvfs2 = True,\nfuse = False,\ndebug = True,\n- tags = None):\n+ tags = None,\n+ **kwargs):\n\"\"\"syscall_test is a macro that will create targets for all platforms.\nArgs:\ntest: the test target.\n- shard_count: shards for defined tests.\n- size: the defined test size.\nuse_tmpfs: use tmpfs in the defined tests.\nadd_overlay: add an overlay test.\nadd_uds_tree: add a UDS test.\nadd_hostinet: add a hostinet test.\n+ vfs2: enable VFS2 support.\n+ fuse: enable FUSE support.\n+ debug: enable debug output.\ntags: starting test tags.\n+ **kwargs: additional test arguments.\n\"\"\"\nif not tags:\ntags = []\n@@ -173,8 +172,6 @@ def syscall_test(\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n@@ -182,6 +179,7 @@ def syscall_test(\ndebug = debug,\nvfs2 = True,\nfuse = fuse,\n+ **kwargs\n)\nif fuse:\n# Only generate *_vfs2_fuse target if fuse parameter is enabled.\n@@ -189,38 +187,35 @@ def syscall_test(\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = \"native\",\nuse_tmpfs = False,\nadd_uds_tree = add_uds_tree,\ntags = list(tags),\ndebug = debug,\n+ **kwargs\n)\nfor (platform, platform_tags) in platforms.items():\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\ntags = platform_tags + tags,\ndebug = debug,\n+ **kwargs\n)\nif add_overlay:\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\ntags = platforms[default_platform] + tags,\ndebug = debug,\noverlay = True,\n+ **kwargs\n)\n# TODO(gvisor.dev/issue/4407): Remove tags to enable VFS2 overlay tests.\n@@ -230,8 +225,6 @@ def syscall_test(\noverlay_vfs2_tags.append(\"notap\")\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n@@ -239,38 +232,35 @@ def syscall_test(\ndebug = debug,\noverlay = True,\nvfs2 = True,\n+ **kwargs\n)\nif add_hostinet:\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nnetwork = \"host\",\nadd_uds_tree = add_uds_tree,\ntags = platforms[default_platform] + tags,\ndebug = debug,\n+ **kwargs\n)\nif not use_tmpfs:\n# Also test shared gofer access.\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\ntags = platforms[default_platform] + tags,\ndebug = debug,\nfile_access = \"shared\",\n+ **kwargs\n)\n_syscall_test(\ntest = test,\n- shard_count = shard_count,\n- size = size,\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n@@ -278,4 +268,5 @@ def syscall_test(\ndebug = debug,\nfile_access = \"shared\",\nvfs2 = True,\n+ **kwargs\n)\n" }, { "change_type": "MODIFY", "old_path": "test/runtimes/BUILD", "new_path": "test/runtimes/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"bzl_library\")\n+load(\"//tools:defs.bzl\", \"bzl_library\", \"more_shards\", \"most_shards\")\nload(\"//test/runtimes:defs.bzl\", \"runtime_test\")\npackage(licenses = [\"notice\"])\n@@ -7,7 +7,7 @@ runtime_test(\nname = \"go1.12\",\nexclude_file = \"exclude/go1.12.csv\",\nlang = \"go\",\n- shard_count = 8,\n+ shard_count = more_shards,\n)\nruntime_test(\n@@ -15,28 +15,28 @@ runtime_test(\nbatch = 100,\nexclude_file = \"exclude/java11.csv\",\nlang = \"java\",\n- shard_count = 16,\n+ shard_count = most_shards,\n)\nruntime_test(\nname = \"nodejs12.4.0\",\nexclude_file = \"exclude/nodejs12.4.0.csv\",\nlang = \"nodejs\",\n- shard_count = 8,\n+ shard_count = most_shards,\n)\nruntime_test(\nname = \"php7.3.6\",\nexclude_file = \"exclude/php7.3.6.csv\",\nlang = \"php\",\n- shard_count = 8,\n+ shard_count = more_shards,\n)\nruntime_test(\nname = \"python3.7.3\",\nexclude_file = \"exclude/python3.7.3.csv\",\nlang = \"python\",\n- shard_count = 8,\n+ shard_count = more_shards,\n)\nbzl_library(\n" }, { "change_type": "MODIFY", "old_path": "test/runtimes/runner/lib/lib.go", "new_path": "test/runtimes/runner/lib/lib.go", "diff": "@@ -34,12 +34,7 @@ import (\n// RunTests is a helper that is called by main. It exists so that we can run\n// defered functions before exiting. It returns an exit code that should be\n// passed to os.Exit.\n-func RunTests(lang, image, excludeFile string, partitionNum, totalPartitions, batchSize int, timeout time.Duration) int {\n- if partitionNum <= 0 || totalPartitions <= 0 || partitionNum > totalPartitions {\n- fmt.Fprintf(os.Stderr, \"invalid partition %d of %d\", partitionNum, totalPartitions)\n- return 1\n- }\n-\n+func RunTests(lang, image, excludeFile string, batchSize int, timeout time.Duration) int {\n// TODO(gvisor.dev/issue/1624): Remove those tests from all exclude lists\n// that only fail with VFS1.\n@@ -63,7 +58,7 @@ func RunTests(lang, image, excludeFile string, partitionNum, totalPartitions, ba\n// Get a slice of tests to run. This will also start a single Docker\n// container that will be used to run each test. The final test will\n// stop the Docker container.\n- tests, err := getTests(ctx, d, lang, image, partitionNum, totalPartitions, batchSize, timeout, excludes)\n+ tests, err := getTests(ctx, d, lang, image, batchSize, timeout, excludes)\nif err != nil {\nfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\nreturn 1\n@@ -74,7 +69,7 @@ func RunTests(lang, image, excludeFile string, partitionNum, totalPartitions, ba\n}\n// getTests executes all tests as table tests.\n-func getTests(ctx context.Context, d *dockerutil.Container, lang, image string, partitionNum, totalPartitions, batchSize int, timeout time.Duration, excludes map[string]struct{}) ([]testing.InternalTest, error) {\n+func getTests(ctx context.Context, d *dockerutil.Container, lang, image string, batchSize int, timeout time.Duration, excludes map[string]struct{}) ([]testing.InternalTest, error) {\n// Start the container.\nopts := dockerutil.RunOpts{\nImage: fmt.Sprintf(\"runtimes/%s\", image),\n@@ -90,18 +85,9 @@ func getTests(ctx context.Context, d *dockerutil.Container, lang, image string,\nreturn nil, fmt.Errorf(\"docker exec failed: %v\", err)\n}\n- // Calculate a subset of tests to run corresponding to the current\n- // shard.\n+ // Calculate a subset of tests.\ntests := strings.Fields(list)\nsort.Strings(tests)\n-\n- partitionSize := len(tests) / totalPartitions\n- if partitionNum == totalPartitions {\n- tests = tests[(partitionNum-1)*partitionSize:]\n- } else {\n- tests = tests[(partitionNum-1)*partitionSize : partitionNum*partitionSize]\n- }\n-\nindices, err := testutil.TestIndicesForShard(len(tests))\nif err != nil {\nreturn nil, fmt.Errorf(\"TestsForShard() failed: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "test/runtimes/runner/main.go", "new_path": "test/runtimes/runner/main.go", "diff": "@@ -28,8 +28,6 @@ var (\nlang = flag.String(\"lang\", \"\", \"language runtime to test\")\nimage = flag.String(\"image\", \"\", \"docker image with runtime tests\")\nexcludeFile = flag.String(\"exclude_file\", \"\", \"file containing list of tests to exclude, in CSV format with fields: test name, bug id, comment\")\n- partition = flag.Int(\"partition\", 1, \"partition number, this is 1-indexed\")\n- totalPartitions = flag.Int(\"total_partitions\", 1, \"total number of partitions\")\nbatchSize = flag.Int(\"batch\", 50, \"number of test cases run in one command\")\ntimeout = flag.Duration(\"timeout\", 90*time.Minute, \"batch timeout\")\n)\n@@ -40,5 +38,5 @@ func main() {\nfmt.Fprintf(os.Stderr, \"lang and image flags must not be empty\\n\")\nos.Exit(1)\n}\n- os.Exit(lib.RunTests(*lang, *image, *excludeFile, *partition, *totalPartitions, *batchSize, *timeout))\n+ os.Exit(lib.RunTests(*lang, *image, *excludeFile, *batchSize, *timeout))\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"more_shards\", \"most_shards\")\nload(\"//test/runner:defs.bzl\", \"syscall_test\")\npackage(licenses = [\"notice\"])\n@@ -12,7 +13,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:accept_bind_test\",\n)\n@@ -32,7 +33,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:alarm_test\",\n)\n@@ -66,7 +67,7 @@ syscall_test(\nsize = \"large\",\n# Produce too many logs in the debug mode.\ndebug = False,\n- shard_count = 50,\n+ shard_count = most_shards,\n# Takes too long for TSAN. Since this is kind of a stress test that doesn't\n# involve much concurrency, TSAN's usefulness here is limited anyway.\ntags = [\"nogotsan\"],\n@@ -211,7 +212,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:futex_test\",\n)\n@@ -258,7 +259,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:itimer_test\",\n)\n@@ -313,7 +314,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:mmap_test\",\n)\n@@ -347,6 +348,7 @@ syscall_test(\nsyscall_test(\nadd_overlay = True,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:open_test\",\n)\n@@ -376,7 +378,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\nadd_overlay = True,\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:pipe_test\",\n)\n@@ -448,7 +450,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:pty_test\",\n)\n@@ -475,6 +477,7 @@ syscall_test(\n)\nsyscall_test(\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:raw_socket_test\",\n)\n@@ -490,7 +493,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:readv_socket_test\",\n)\n@@ -539,7 +542,7 @@ syscall_test(\n)\nsyscall_test(\n- shard_count = 20,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:semaphore_test\",\n)\n@@ -594,7 +597,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_abstract_test\",\n)\n@@ -605,7 +608,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_domain_test\",\n)\n@@ -618,19 +621,19 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\nadd_overlay = True,\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_filesystem_test\",\n)\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_inet_loopback_test\",\n)\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\n# Takes too long for TSAN. Creates a lot of TCP sockets.\ntags = [\"nogotsan\"],\ntest = \"//test/syscalls/linux:socket_inet_loopback_nogotsan_test\",\n@@ -638,7 +641,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_ip_tcp_generic_loopback_test\",\n)\n@@ -649,13 +652,13 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_ip_tcp_loopback_test\",\n)\nsyscall_test(\nsize = \"medium\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_ip_tcp_udp_generic_loopback_test\",\n)\n@@ -666,7 +669,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_ip_udp_loopback_test\",\n)\n@@ -677,6 +680,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n+ shard_count = more_shards,\n# Takes too long under gotsan to run.\ntags = [\"nogotsan\"],\ntest = \"//test/syscalls/linux:socket_ipv4_udp_unbound_loopback_nogotsan_test\",\n@@ -691,6 +695,7 @@ syscall_test(\n)\nsyscall_test(\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:socket_ip_unbound_test\",\n)\n@@ -753,7 +758,7 @@ syscall_test(\nsyscall_test(\n# NOTE(b/116636318): Large sendmsg may stall a long time.\nsize = \"enormous\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:socket_unix_dgram_local_test\",\n)\n@@ -765,14 +770,14 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\nadd_overlay = True,\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_unix_pair_test\",\n)\nsyscall_test(\n# NOTE(b/116636318): Large sendmsg may stall a long time.\nsize = \"enormous\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:socket_unix_seqpacket_local_test\",\n)\n@@ -798,13 +803,13 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 10,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:socket_unix_unbound_seqpacket_test\",\n)\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_unix_unbound_stream_test\",\n)\n@@ -858,7 +863,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 10,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:tcp_socket_test\",\n)\n@@ -867,6 +872,7 @@ syscall_test(\n)\nsyscall_test(\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:timerfd_test\",\n)\n@@ -903,7 +909,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\nadd_hostinet = True,\n- shard_count = 10,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:udp_socket_test\",\n)\n@@ -947,7 +953,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 5,\n+ shard_count = more_shards,\ntest = \"//test/syscalls/linux:wait_test\",\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/bazel.mk", "new_path": "tools/bazel.mk", "diff": "@@ -41,6 +41,9 @@ DOCKER_CONFIG := /etc/docker\n# Bazel flags.\nBAZEL := bazel $(STARTUP_OPTIONS)\nBASE_OPTIONS := --color=no --curses=no\n+ifneq (,$(BAZEL_CONFIG))\n+BASE_OPTIONS += --config=$(BAZEL_CONFIG)\n+endif\n# Basic options.\nUID := $(shell id -u ${USER})\n@@ -103,11 +106,6 @@ FULL_DOCKER_RUN_OPTIONS += --group-add $(KVM_GROUP)\nendif\nendif\n-# Load the appropriate config.\n-ifneq (,$(BAZEL_CONFIG))\n-OPTIONS += --config=$(BAZEL_CONFIG)\n-endif\n-\nbazel-image: load-default\n@if docker ps --all | grep $(BUILDER_NAME); then docker rm -f $(BUILDER_NAME); fi\ndocker run --user 0:0 --entrypoint \"\" --name $(BUILDER_NAME) \\\n" }, { "change_type": "MODIFY", "old_path": "tools/bazeldefs/defs.bzl", "new_path": "tools/bazeldefs/defs.bzl", "diff": "@@ -7,6 +7,8 @@ build_test = _build_test\nbzl_library = _bzl_library\nrbe_platform = native.platform\nrbe_toolchain = native.toolchain\n+more_shards = 4\n+most_shards = 8\ndef short_path(path):\nreturn path\n" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -8,7 +8,7 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\nload(\"//tools/nogo:defs.bzl\", \"nogo_test\")\n-load(\"//tools/bazeldefs:defs.bzl\", _build_test = \"build_test\", _bzl_library = \"bzl_library\", _coreutil = \"coreutil\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _proto_library = \"proto_library\", _rbe_platform = \"rbe_platform\", _rbe_toolchain = \"rbe_toolchain\", _select_arch = \"select_arch\", _select_system = \"select_system\", _short_path = \"short_path\")\n+load(\"//tools/bazeldefs:defs.bzl\", _build_test = \"build_test\", _bzl_library = \"bzl_library\", _coreutil = \"coreutil\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _more_shards = \"more_shards\", _most_shards = \"most_shards\", _proto_library = \"proto_library\", _rbe_platform = \"rbe_platform\", _rbe_toolchain = \"rbe_toolchain\", _select_arch = \"select_arch\", _select_system = \"select_system\", _short_path = \"short_path\")\nload(\"//tools/bazeldefs:cc.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_grpc_library = \"cc_grpc_library\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _gbenchmark = \"gbenchmark\", _grpcpp = \"grpcpp\", _gtest = \"gtest\", _vdso_linker_option = \"vdso_linker_option\")\nload(\"//tools/bazeldefs:go.bzl\", _gazelle = \"gazelle\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_grpc_and_proto_libraries = \"go_grpc_and_proto_libraries\", _go_library = \"go_library\", _go_path = \"go_path\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _select_goarch = \"select_goarch\", _select_goos = \"select_goos\")\nload(\"//tools/bazeldefs:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\n@@ -26,6 +26,8 @@ short_path = _short_path\nrbe_platform = _rbe_platform\nrbe_toolchain = _rbe_toolchain\ncoreutil = _coreutil\n+more_shards = _more_shards\n+most_shards = _most_shards\n# C++ rules.\ncc_binary = _cc_binary\n" } ]
Go
Apache License 2.0
google/gvisor
Support partitions for other tests. PiperOrigin-RevId: 345399936
259,858
03.12.2020 11:04:34
28,800
3186b50dffc196755a3ce7ce0ab44253f78a2495
Add BuildKite pipeline.
[ { "change_type": "ADD", "old_path": null, "new_path": ".buildkite/pipeline.yaml", "diff": "+_templates:\n+ common: &common\n+ retry:\n+ automatic:\n+ - exit_status: -1\n+ limit: 10\n+ - exit_status: \"*\"\n+ limit: 2\n+\n+steps:\n+ # Run basic smoke tests before preceding to other tests.\n+ - label: \":fire: Smoke tests\"\n+ command: make smoke-tests\n+ - wait\n+\n+ # Check that the Go branch builds.\n+ - <<: *common\n+ label: \":golang: Go branch\"\n+ commands:\n+ - rm -rf bazel-bin/gopath\n+ - make build TARGETS=\"//:gopath\"\n+ - tools/go_branch.sh\n+ - git checkout go && git clean -f\n+ - go build ./...\n+\n+ # Basic unit tests.\n+ - <<: *common\n+ label: \":test_tube: Unit tests\"\n+ command: make unit-tests\n+\n+ # All system call tests.\n+ - <<: *common\n+ label: \":toolbox: System call tests\"\n+ command: make syscall-tests\n+ parallelism: 20\n+\n+ # Integration tests.\n+ - <<: *common\n+ label: \":parachute: FUSE tests\"\n+ command: make fuse-tests\n+ - <<: *common\n+ label: \":docker: Docker tests\"\n+ command: make docker-tests\n+ - <<: *common\n+ label: \":goggles: Overlay tests\"\n+ command: make overlay-tests\n+ - <<: *common\n+ label: \":safety_pin: Host network tests\"\n+ command: make hostnet-tests\n+ - <<: *common\n+ label: \":satellite: SWGSO tests\"\n+ command: make swgso-tests\n+ - <<: *common\n+ label: \":coffee: Do tests\"\n+ command: make do-tests\n+ - <<: *common\n+ label: \":person_in_lotus_position: KVM tests\"\n+ command: make kvm-tests\n+ - <<: *common\n+ label: \":docker: Containerd 1.3.4 tests\"\n+ command: make containerd-test-1.3.4\n+ - <<: *common\n+ label: \":docker: Containerd 1.4.1 tests\"\n+ command: make containerd-test-1.4.1\n+\n+ # Check the website builds.\n+ - <<: *common\n+ label: \":earth_americas: Website tests\"\n+ command: make website-build\n+\n+ # Networking tests.\n+ - <<: *common\n+ label: \":table_tennis_paddle_and_ball: IPTables tests\"\n+ command: make iptables-tests\n+ - <<: *common\n+ label: \":construction_worker: Packetdrill tests\"\n+ command: make packetdrill-tests\n+ - <<: *common\n+ label: \":hammer: Packetimpact tests\"\n+ command: make packetimpact-tests\n+\n+ # Start heavy runtime tests.\n+ - wait\n+ - <<: *common\n+ label: \":php: PHP runtime tests\"\n+ command: make php7.3.6-runtime-tests\n+ parallelism: 10\n+ - <<: *common\n+ label: \":java: Java runtime tests\"\n+ command: make java11-runtime-tests\n+ parallelism: 40\n+ - <<: *common\n+ label: \":golang: Go runtime tests\"\n+ command: make go1.12-runtime-tests\n+ parallelism: 10\n+ - <<: *common\n+ label: \":node: NodeJS runtime tests\"\n+ command: make nodejs12.4.0-runtime-tests\n+ parallelism: 10\n+ - <<: *common\n+ label: \":node: Python runtime tests\"\n+ command: make python3.7.3-runtime-tests\n+ parallelism: 10\n" } ]
Go
Apache License 2.0
google/gvisor
Add BuildKite pipeline. PiperOrigin-RevId: 345490319
259,860
03.12.2020 11:44:53
28,800
bec8cea6513beaf6c2348ed0b71cb40e417beb68
Surface usage message for `runsc do`. c.Usage() only returns a string; f.Usage() will print the usage message.
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/do.go", "new_path": "runsc/cmd/do.go", "diff": "@@ -81,7 +81,7 @@ func (c *Do) SetFlags(f *flag.FlagSet) {\n// Execute implements subcommands.Command.Execute.\nfunc (c *Do) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\nif len(f.Args()) == 0 {\n- c.Usage()\n+ f.Usage()\nreturn subcommands.ExitUsageError\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Surface usage message for `runsc do`. c.Usage() only returns a string; f.Usage() will print the usage message. PiperOrigin-RevId: 345500123
259,992
03.12.2020 16:53:22
28,800
9eb77281c4fe1c1f252a0df67ca2c1fee8867b80
Update containerd to 1.3.9
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -57,8 +57,8 @@ steps:\nlabel: \":person_in_lotus_position: KVM tests\"\ncommand: make kvm-tests\n- <<: *common\n- label: \":docker: Containerd 1.3.4 tests\"\n- command: make containerd-test-1.3.4\n+ label: \":docker: Containerd 1.3.9 tests\"\n+ command: make containerd-test-1.3.9\n- <<: *common\nlabel: \":docker: Containerd 1.4.1 tests\"\ncommand: make containerd-test-1.4.1\n" }, { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -151,7 +151,7 @@ tests: unit-tests syscall-tests\nintegration-tests: ## Run all standard integration tests.\nintegration-tests: docker-tests overlay-tests hostnet-tests swgso-tests\n-integration-tests: do-tests kvm-tests containerd-test-1.3.4\n+integration-tests: do-tests kvm-tests containerd-test-1.3.9\n.PHONY: integration-tests\nnetwork-tests: ## Run all networking integration tests.\n@@ -261,7 +261,7 @@ containerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-b\n# actually drive the tests. The v1 API is tested exclusively through 1.2.13.\ncontainerd-tests: ## Runs all supported containerd version tests.\ncontainerd-tests: containerd-test-1.2.13\n-containerd-tests: containerd-test-1.3.4\n+containerd-tests: containerd-test-1.3.9\ncontainerd-tests: containerd-test-1.4.0-beta.0\n##\n" }, { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -193,8 +193,8 @@ go_repository(\nname = \"com_github_containerd_containerd\",\nbuild_file_proto_mode = \"disable\",\nimportpath = \"github.com/containerd/containerd\",\n- sum = \"h1:3o0smo5SKY7H6AJCmJhsnCjR2/V2T8VmiHt7seN2/kI=\",\n- version = \"v1.3.4\",\n+ sum = \"h1:K2U/F4jGAMBqeUssfgJRbFuomLcS2Fxo1vR3UM/Mbh8=\",\n+ version = \"v1.3.9\",\n)\ngo_repository(\n" }, { "change_type": "MODIFY", "old_path": "go.mod", "new_path": "go.mod", "diff": "@@ -11,7 +11,7 @@ require (\ngithub.com/cenkalti/backoff v1.1.1-0.20190506075156-2146c9339422 // indirect\ngithub.com/cilium/ebpf v0.0.0-20200110133405-4032b1d8aae3 // indirect\ngithub.com/containerd/cgroups v0.0.0-20181219155423-39b18af02c41 // indirect\n- github.com/containerd/containerd v1.3.4 // indirect\n+ github.com/containerd/containerd v1.3.9 // indirect\ngithub.com/containerd/continuity v0.0.0-20200928162600-f2cc35102c2a // indirect\ngithub.com/containerd/fifo v0.0.0-20191213151349-ff969a566b00 // indirect\ngithub.com/containerd/go-runc v0.0.0-20200220073739-7016d3ce2328 // indirect\n" }, { "change_type": "MODIFY", "old_path": "go.sum", "new_path": "go.sum", "diff": "@@ -54,9 +54,7 @@ github.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59/go.mod h1:pA0z1\ngithub.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw=\ngithub.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e h1:GdiIYd8ZDOrT++e1NjhSD4rGt9zaJukHm4rt5F4mRQc=\ngithub.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e/go.mod h1:8Pf4gM6VEbTNRIT26AyyU7hxdQU3MvAvxVI0sc00XBE=\n-github.com/containerd/containerd v1.3.2/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=\n-github.com/containerd/containerd v1.3.4 h1:3o0smo5SKY7H6AJCmJhsnCjR2/V2T8VmiHt7seN2/kI=\n-github.com/containerd/containerd v1.3.4/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=\n+github.com/containerd/containerd v1.3.9/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=\ngithub.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=\ngithub.com/containerd/continuity v0.0.0-20200928162600-f2cc35102c2a h1:jEIoR0aA5GogXZ8pP3DUzE+zrhaF6/1rYZy+7KkYEWM=\ngithub.com/containerd/continuity v0.0.0-20200928162600-f2cc35102c2a/go.mod h1:W0qIOTD7mp2He++YVq+kgfXezRYqzP1uDuMVH1bITDY=\n" }, { "change_type": "MODIFY", "old_path": "pkg/shim/v2/service.go", "new_path": "pkg/shim/v2/service.go", "diff": "@@ -67,9 +67,15 @@ var (\nvar _ = (taskAPI.TaskService)(&service{})\n+const (\n// configFile is the default config file name. For containerd 1.2,\n// we assume that a config.toml should exist in the runtime root.\n-const configFile = \"config.toml\"\n+ configFile = \"config.toml\"\n+\n+ // shimAddressPath is the relative path to a file that contains the address\n+ // to the shim UDS. See service.shimAddress.\n+ shimAddressPath = \"address\"\n+)\n// New returns a new shim service that can be used via GRPC.\nfunc New(ctx context.Context, id string, publisher shim.Publisher, cancel func()) (shim.Shim, error) {\n@@ -101,6 +107,11 @@ func New(ctx context.Context, id string, publisher shim.Publisher, cancel func()\nreturn nil, fmt.Errorf(\"failed to initialized platform behavior: %w\", err)\n}\ngo s.forward(ctx, publisher)\n+\n+ if address, err := shim.ReadAddress(shimAddressPath); err == nil {\n+ s.shimAddress = address\n+ }\n+\nreturn s, nil\n}\n@@ -152,6 +163,9 @@ type service struct {\n// cancel is a function that needs to be called before the shim stops. The\n// function is provided by the caller to New().\ncancel func()\n+\n+ // shimAddress is the location of the UDS used to communicate to containerd.\n+ shimAddress string\n}\nfunc (s *service) newCommand(ctx context.Context, containerdBinary, containerdAddress string) (*exec.Cmd, error) {\n@@ -191,38 +205,58 @@ func (s *service) StartShim(ctx context.Context, id, containerdBinary, container\nif err != nil {\nreturn \"\", err\n}\n- address, err := shim.SocketAddress(ctx, id)\n+ address, err := shim.SocketAddress(ctx, containerdAddress, id)\nif err != nil {\nreturn \"\", err\n}\nsocket, err := shim.NewSocket(address)\nif err != nil {\n- return \"\", err\n+ // The only time where this would happen is if there is a bug and the socket\n+ // was not cleaned up in the cleanup method of the shim or we are using the\n+ // grouping functionality where the new process should be run with the same\n+ // shim as an existing container.\n+ if !shim.SocketEaddrinuse(err) {\n+ return \"\", fmt.Errorf(\"create new shim socket: %w\", err)\n+ }\n+ if shim.CanConnect(address) {\n+ if err := shim.WriteAddress(shimAddressPath, address); err != nil {\n+ return \"\", fmt.Errorf(\"write existing socket for shim: %w\", err)\n+ }\n+ return address, nil\n+ }\n+ if err := shim.RemoveSocket(address); err != nil {\n+ return \"\", fmt.Errorf(\"remove pre-existing socket: %w\", err)\n+ }\n+ if socket, err = shim.NewSocket(address); err != nil {\n+ return \"\", fmt.Errorf(\"try create new shim socket 2x: %w\", err)\n}\n- defer socket.Close()\n+ }\n+ cu := cleanup.Make(func() {\n+ socket.Close()\n+ _ = shim.RemoveSocket(address)\n+ })\n+ defer cu.Clean()\n+\nf, err := socket.File()\nif err != nil {\nreturn \"\", err\n}\n- defer f.Close()\ncmd.ExtraFiles = append(cmd.ExtraFiles, f)\nlog.L.Debugf(\"Executing: %q %s\", cmd.Path, cmd.Args)\nif err := cmd.Start(); err != nil {\n+ f.Close()\nreturn \"\", err\n}\n- cu := cleanup.Make(func() {\n- cmd.Process.Kill()\n- })\n- defer cu.Clean()\n+ cu.Add(func() { cmd.Process.Kill() })\n// make sure to wait after start\ngo cmd.Wait()\nif err := shim.WritePidFile(\"shim.pid\", cmd.Process.Pid); err != nil {\nreturn \"\", err\n}\n- if err := shim.WriteAddress(\"address\", address); err != nil {\n+ if err := shim.WriteAddress(shimAddressPath, address); err != nil {\nreturn \"\", err\n}\nif err := shim.SetScore(cmd.Process.Pid); err != nil {\n@@ -675,8 +709,11 @@ func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*task\nfunc (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Shutdown, id: %s\", r.ID)\ns.cancel()\n+ if s.shimAddress != \"\" {\n+ _ = shim.RemoveSocket(s.shimAddress)\n+ }\nos.Exit(0)\n- return empty, nil\n+ panic(\"Should not get here\")\n}\nfunc (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) {\n@@ -843,9 +880,7 @@ func (s *service) getContainerPids(ctx context.Context, id string) ([]uint32, er\nfunc (s *service) forward(ctx context.Context, publisher shim.Publisher) {\nfor e := range s.events {\n- ctx, cancel := context.WithTimeout(ctx, 5*time.Second)\nerr := publisher.Publish(ctx, getTopic(e), e)\n- cancel()\nif err != nil {\n// Should not happen.\npanic(fmt.Errorf(\"post event: %w\", err))\n" } ]
Go
Apache License 2.0
google/gvisor
Update containerd to 1.3.9 PiperOrigin-RevId: 345564927
259,875
03.12.2020 19:55:20
28,800
a78cef0ed7ce15583424f5873f0aa6fdad1d5c2f
Implement command IPC_INFO for semctl.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/sem.go", "new_path": "pkg/abi/linux/sem.go", "diff": "@@ -41,6 +41,12 @@ const (\nSEMMNS = SEMMNI * SEMMSL\nSEMOPM = 500\nSEMVMX = 32767\n+ SEMAEM = SEMVMX\n+\n+ // followings are unused in kernel\n+ SEMUME = SEMOPM\n+ SEMMNU = SEMMNS\n+ SEMMAP = SEMMNS\n)\nconst SEM_UNDO = 0x1000\n@@ -53,3 +59,21 @@ type Sembuf struct {\nSemOp int16\nSemFlg int16\n}\n+\n+// SemInfo is equivalent to struct seminfo.\n+//\n+// Source: include/uapi/linux/sem.h\n+//\n+// +marshal\n+type SemInfo struct {\n+ SemMap uint32\n+ SemMni uint32\n+ SemMns uint32\n+ SemMnu uint32\n+ SemMsl uint32\n+ SemOpm uint32\n+ SemUme uint32\n+ SemUsz uint32\n+ SemVmx uint32\n+ SemAem uint32\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore.go", "diff": "@@ -176,6 +176,22 @@ func (r *Registry) FindOrCreate(ctx context.Context, key, nsems int32, mode linu\nreturn r.newSet(ctx, key, owner, owner, perms, nsems)\n}\n+// IPCInfo returns information about system-wide semaphore limits and parameters.\n+func (r *Registry) IPCInfo() *linux.SemInfo {\n+ return &linux.SemInfo{\n+ SemMap: linux.SEMMAP,\n+ SemMni: linux.SEMMNI,\n+ SemMns: linux.SEMMNS,\n+ SemMnu: linux.SEMMNU,\n+ SemMsl: linux.SEMMSL,\n+ SemOpm: linux.SEMOPM,\n+ SemUme: linux.SEMUME,\n+ SemUsz: 0, // SemUsz not supported.\n+ SemVmx: linux.SEMVMX,\n+ SemAem: linux.SEMAEM,\n+ }\n+}\n+\n// RemoveID removes set with give 'id' from the registry and marks the set as\n// dead. All waiters will be awakened and fail.\nfunc (r *Registry) RemoveID(id int32, creds *auth.Credentials) error {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64.go", "new_path": "pkg/sentry/syscalls/linux/linux64.go", "diff": "@@ -118,7 +118,7 @@ var AMD64 = &kernel.SyscallTable{\n63: syscalls.Supported(\"uname\", Uname),\n64: syscalls.Supported(\"semget\", Semget),\n65: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n- 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n+ 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n67: syscalls.Supported(\"shmdt\", Shmdt),\n68: syscalls.ErrorWithEvent(\"msgget\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n69: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n@@ -619,7 +619,7 @@ var ARM64 = &kernel.SyscallTable{\n188: syscalls.ErrorWithEvent(\"msgrcv\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n- 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n+ 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_sem.go", "new_path": "pkg/sentry/syscalls/linux/sys_sem.go", "diff": "@@ -146,8 +146,15 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nv, err := getNCnt(t, id, num)\nreturn uintptr(v), nil, err\n- case linux.IPC_INFO,\n- linux.SEM_INFO,\n+ case linux.IPC_INFO:\n+ buf := args[3].Pointer()\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ info := r.IPCInfo()\n+ _, err := info.CopyOut(t, buf)\n+ // TODO(gvisor.dev/issue/137): Return the index of the highest used entry.\n+ return 0, nil, err\n+\n+ case linux.SEM_INFO,\nlinux.SEM_STAT,\nlinux.SEM_STAT_ANY:\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/semaphore.cc", "new_path": "test/syscalls/linux/semaphore.cc", "diff": "@@ -773,6 +773,21 @@ TEST(SemaphoreTest, SemopGetncntOnSignal_NoRandomSave) {\nEXPECT_EQ(semctl(sem.get(), 0, GETNCNT), 0);\n}\n+TEST(SemaphoreTest, IpcInfo) {\n+ struct seminfo info;\n+ ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceeds());\n+\n+ EXPECT_EQ(info.semmap, 1024000000);\n+ EXPECT_EQ(info.semmni, 32000);\n+ EXPECT_EQ(info.semmns, 1024000000);\n+ EXPECT_EQ(info.semmnu, 1024000000);\n+ EXPECT_EQ(info.semmsl, 32000);\n+ EXPECT_EQ(info.semopm, 500);\n+ EXPECT_EQ(info.semume, 500);\n+ EXPECT_EQ(info.semvmx, 32767);\n+ EXPECT_EQ(info.semaem, 32767);\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement command IPC_INFO for semctl. PiperOrigin-RevId: 345589628
259,881
04.12.2020 08:17:39
28,800
6708c8c97e4ede29935c8d3e809c7bb76309112c
Require sync.RWMutex to lock and unlock from the same goroutine This is the RWMutex equivalent to the preceding sync.Mutex CL. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/fs.go", "new_path": "pkg/sentry/fs/fs.go", "diff": "@@ -65,7 +65,7 @@ var (\n// runs with the lock held for reading. AsyncBarrier will take the lock\n// for writing, thus ensuring that all Async work completes before\n// AsyncBarrier returns.\n- workMu sync.RWMutex\n+ workMu sync.CrossGoroutineRWMutex\n// asyncError is used to store up to one asynchronous execution error.\nasyncError = make(chan error, 1)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/rwmutex_unsafe.go", "new_path": "pkg/sync/rwmutex_unsafe.go", "diff": "@@ -18,10 +18,10 @@ import (\n\"unsafe\"\n)\n-// RWMutex is identical to sync.RWMutex, but adds the DowngradeLock,\n-// TryLock and TryRLock methods.\n-type RWMutex struct {\n- // w is held by writers.\n+// CrossGoroutineRWMutex is equivalent to RWMutex, but it need not be unlocked\n+// by a the same goroutine that locked the mutex.\n+type CrossGoroutineRWMutex struct {\n+ // w is held if there are pending writers\n//\n// We use CrossGoroutineMutex rather than Mutex because the lock\n// annotation instrumentation in Mutex will trigger false positives in\n@@ -37,7 +37,7 @@ const rwmutexMaxReaders = 1 << 30\n// TryRLock locks rw for reading. It returns true if it succeeds and false\n// otherwise. It does not block.\n-func (rw *RWMutex) TryRLock() bool {\n+func (rw *CrossGoroutineRWMutex) TryRLock() bool {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -61,7 +61,11 @@ func (rw *RWMutex) TryRLock() bool {\n}\n// RLock locks rw for reading.\n-func (rw *RWMutex) RLock() {\n+//\n+// It should not be used for recursive read locking; a blocked Lock call\n+// excludes new readers from acquiring the lock. See the documentation on the\n+// RWMutex type.\n+func (rw *CrossGoroutineRWMutex) RLock() {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -76,7 +80,10 @@ func (rw *RWMutex) RLock() {\n}\n// RUnlock undoes a single RLock call.\n-func (rw *RWMutex) RUnlock() {\n+//\n+// Preconditions:\n+// * rw is locked for reading.\n+func (rw *CrossGoroutineRWMutex) RUnlock() {\nif RaceEnabled {\nRaceReleaseMerge(unsafe.Pointer(&rw.writerSem))\nRaceDisable()\n@@ -98,7 +105,7 @@ func (rw *RWMutex) RUnlock() {\n// TryLock locks rw for writing. It returns true if it succeeds and false\n// otherwise. It does not block.\n-func (rw *RWMutex) TryLock() bool {\n+func (rw *CrossGoroutineRWMutex) TryLock() bool {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -124,8 +131,9 @@ func (rw *RWMutex) TryLock() bool {\nreturn true\n}\n-// Lock locks rw for writing.\n-func (rw *RWMutex) Lock() {\n+// Lock locks rw for writing. If the lock is already locked for reading or\n+// writing, Lock blocks until the lock is available.\n+func (rw *CrossGoroutineRWMutex) Lock() {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -144,7 +152,10 @@ func (rw *RWMutex) Lock() {\n}\n// Unlock unlocks rw for writing.\n-func (rw *RWMutex) Unlock() {\n+//\n+// Preconditions:\n+// * rw is locked for writing.\n+func (rw *CrossGoroutineRWMutex) Unlock() {\nif RaceEnabled {\nRaceRelease(unsafe.Pointer(&rw.writerSem))\nRaceRelease(unsafe.Pointer(&rw.readerSem))\n@@ -167,7 +178,10 @@ func (rw *RWMutex) Unlock() {\n}\n// DowngradeLock atomically unlocks rw for writing and locks it for reading.\n-func (rw *RWMutex) DowngradeLock() {\n+//\n+// Preconditions:\n+// * rw is locked for writing.\n+func (rw *CrossGoroutineRWMutex) DowngradeLock() {\nif RaceEnabled {\nRaceRelease(unsafe.Pointer(&rw.readerSem))\nRaceDisable()\n@@ -190,3 +204,91 @@ func (rw *RWMutex) DowngradeLock() {\nRaceEnable()\n}\n}\n+\n+// A RWMutex is a reader/writer mutual exclusion lock. The lock can be held by\n+// an arbitrary number of readers or a single writer. The zero value for a\n+// RWMutex is an unlocked mutex.\n+//\n+// A RWMutex must not be copied after first use.\n+//\n+// If a goroutine holds a RWMutex for reading and another goroutine might call\n+// Lock, no goroutine should expect to be able to acquire a read lock until the\n+// initial read lock is released. In particular, this prohibits recursive read\n+// locking. This is to ensure that the lock eventually becomes available; a\n+// blocked Lock call excludes new readers from acquiring the lock.\n+//\n+// A Mutex must be unlocked by the same goroutine that locked it. This\n+// invariant is enforced with the 'checklocks' build tag.\n+type RWMutex struct {\n+ m CrossGoroutineRWMutex\n+}\n+\n+// TryRLock locks rw for reading. It returns true if it succeeds and false\n+// otherwise. It does not block.\n+func (rw *RWMutex) TryRLock() bool {\n+ // Note lock first to enforce proper locking even if unsuccessful.\n+ noteLock(unsafe.Pointer(rw))\n+ locked := rw.m.TryRLock()\n+ if !locked {\n+ noteUnlock(unsafe.Pointer(rw))\n+ }\n+ return locked\n+}\n+\n+// RLock locks rw for reading.\n+//\n+// It should not be used for recursive read locking; a blocked Lock call\n+// excludes new readers from acquiring the lock. See the documentation on the\n+// RWMutex type.\n+func (rw *RWMutex) RLock() {\n+ noteLock(unsafe.Pointer(rw))\n+ rw.m.RLock()\n+}\n+\n+// RUnlock undoes a single RLock call.\n+//\n+// Preconditions:\n+// * rw is locked for reading.\n+// * rw was locked by this goroutine.\n+func (rw *RWMutex) RUnlock() {\n+ rw.m.RUnlock()\n+ noteUnlock(unsafe.Pointer(rw))\n+}\n+\n+// TryLock locks rw for writing. It returns true if it succeeds and false\n+// otherwise. It does not block.\n+func (rw *RWMutex) TryLock() bool {\n+ // Note lock first to enforce proper locking even if unsuccessful.\n+ noteLock(unsafe.Pointer(rw))\n+ locked := rw.m.TryLock()\n+ if !locked {\n+ noteUnlock(unsafe.Pointer(rw))\n+ }\n+ return locked\n+}\n+\n+// Lock locks rw for writing. If the lock is already locked for reading or\n+// writing, Lock blocks until the lock is available.\n+func (rw *RWMutex) Lock() {\n+ noteLock(unsafe.Pointer(rw))\n+ rw.m.Lock()\n+}\n+\n+// Unlock unlocks rw for writing.\n+//\n+// Preconditions:\n+// * rw is locked for writing.\n+// * rw was locked by this goroutine.\n+func (rw *RWMutex) Unlock() {\n+ rw.m.Unlock()\n+ noteUnlock(unsafe.Pointer(rw))\n+}\n+\n+// DowngradeLock atomically unlocks rw for writing and locks it for reading.\n+//\n+// Preconditions:\n+// * rw is locked for writing.\n+func (rw *RWMutex) DowngradeLock() {\n+ // No note change for DowngradeLock.\n+ rw.m.DowngradeLock()\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Require sync.RWMutex to lock and unlock from the same goroutine This is the RWMutex equivalent to the preceding sync.Mutex CL. Updates #4804 PiperOrigin-RevId: 345681051
259,885
04.12.2020 09:44:25
28,800
5c16707568cafad1f86543c06a70285b86636aa0
Avoid fallocate(FALLOC_FL_PUNCH_HOLE) when ManualZeroing is in effect.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/pgalloc/pgalloc.go", "new_path": "pkg/sentry/pgalloc/pgalloc.go", "diff": "@@ -423,11 +423,7 @@ func (f *MemoryFile) Allocate(length uint64, kind usage.MemoryKind) (memmap.File\n}\nif f.opts.ManualZeroing {\n- if err := f.forEachMappingSlice(fr, func(bs []byte) {\n- for i := range bs {\n- bs[i] = 0\n- }\n- }); err != nil {\n+ if err := f.manuallyZero(fr); err != nil {\nreturn memmap.FileRange{}, err\n}\n}\n@@ -560,19 +556,39 @@ func (f *MemoryFile) Decommit(fr memmap.FileRange) error {\npanic(fmt.Sprintf(\"invalid range: %v\", fr))\n}\n+ if f.opts.ManualZeroing {\n+ // FALLOC_FL_PUNCH_HOLE may not zero pages if ManualZeroing is in\n+ // effect.\n+ if err := f.manuallyZero(fr); err != nil {\n+ return err\n+ }\n+ } else {\n+ if err := f.decommitFile(fr); err != nil {\n+ return err\n+ }\n+ }\n+\n+ f.markDecommitted(fr)\n+ return nil\n+}\n+\n+func (f *MemoryFile) manuallyZero(fr memmap.FileRange) error {\n+ return f.forEachMappingSlice(fr, func(bs []byte) {\n+ for i := range bs {\n+ bs[i] = 0\n+ }\n+ })\n+}\n+\n+func (f *MemoryFile) decommitFile(fr memmap.FileRange) error {\n// \"After a successful call, subsequent reads from this range will\n// return zeroes. The FALLOC_FL_PUNCH_HOLE flag must be ORed with\n// FALLOC_FL_KEEP_SIZE in mode ...\" - fallocate(2)\n- err := syscall.Fallocate(\n+ return syscall.Fallocate(\nint(f.file.Fd()),\n_FALLOC_FL_PUNCH_HOLE|_FALLOC_FL_KEEP_SIZE,\nint64(fr.Start),\nint64(fr.Length()))\n- if err != nil {\n- return err\n- }\n- f.markDecommitted(fr)\n- return nil\n}\nfunc (f *MemoryFile) markDecommitted(fr memmap.FileRange) {\n@@ -1044,20 +1060,20 @@ func (f *MemoryFile) runReclaim() {\nbreak\n}\n- if err := f.Decommit(fr); err != nil {\n+ // If ManualZeroing is in effect, pages will be zeroed on allocation\n+ // and may not be freed by decommitFile, so calling decommitFile is\n+ // unnecessary.\n+ if !f.opts.ManualZeroing {\n+ if err := f.decommitFile(fr); err != nil {\nlog.Warningf(\"Reclaim failed to decommit %v: %v\", fr, err)\n// Zero the pages manually. This won't reduce memory usage, but at\n// least ensures that the pages will be zero when reallocated.\n- f.forEachMappingSlice(fr, func(bs []byte) {\n- for i := range bs {\n- bs[i] = 0\n+ if err := f.manuallyZero(fr); err != nil {\n+ panic(fmt.Sprintf(\"Reclaim failed to decommit or zero %v: %v\", fr, err))\n}\n- })\n- // Pretend the pages were decommitted even though they weren't,\n- // since the memory accounting implementation has no idea how to\n- // deal with this.\n- f.markDecommitted(fr)\n}\n+ }\n+ f.markDecommitted(fr)\nf.markReclaimed(fr)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid fallocate(FALLOC_FL_PUNCH_HOLE) when ManualZeroing is in effect. PiperOrigin-RevId: 345696124
259,858
04.12.2020 15:03:21
28,800
216abfb6dfa437166627cf7e2d2a66ae95aad07e
Update containerd tests for 1.4+ to 1.4.3.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -60,8 +60,8 @@ steps:\nlabel: \":docker: Containerd 1.3.9 tests\"\ncommand: make containerd-test-1.3.9\n- <<: *common\n- label: \":docker: Containerd 1.4.1 tests\"\n- command: make containerd-test-1.4.1\n+ label: \":docker: Containerd 1.4.3 tests\"\n+ command: make containerd-test-1.4.3\n# Check the website builds.\n- <<: *common\n@@ -98,6 +98,6 @@ steps:\ncommand: make nodejs12.4.0-runtime-tests\nparallelism: 10\n- <<: *common\n- label: \":node: Python runtime tests\"\n+ label: \":python: Python runtime tests\"\ncommand: make python3.7.3-runtime-tests\nparallelism: 10\n" }, { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -262,7 +262,7 @@ containerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-b\ncontainerd-tests: ## Runs all supported containerd version tests.\ncontainerd-tests: containerd-test-1.2.13\ncontainerd-tests: containerd-test-1.3.9\n-containerd-tests: containerd-test-1.4.0-beta.0\n+containerd-tests: containerd-test-1.4.3\n##\n## Benchmarks.\n" } ]
Go
Apache License 2.0
google/gvisor
Update containerd tests for 1.4+ to 1.4.3. PiperOrigin-RevId: 345764404
259,885
04.12.2020 19:05:08
28,800
8a45c8161601e62faa0d448ff6d5bc0604ea406f
Allow use of SeqAtomic with pointer-containing types. Per runtime.memmove, pointers are always copied atomically, as this is required by the GC. (Also, the init() safety check doesn't work because it gets renamed to <prefix>init() by template instantiation.)
[ { "change_type": "MODIFY", "old_path": "pkg/sync/seqatomic_unsafe.go", "new_path": "pkg/sync/seqatomic_unsafe.go", "diff": "package template\nimport (\n- \"fmt\"\n- \"reflect\"\n- \"strings\"\n\"unsafe\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n// Value is a required type parameter.\n-//\n-// Value must not contain any pointers, including interface objects, function\n-// objects, slices, maps, channels, unsafe.Pointer, and arrays or structs\n-// containing any of the above. An init() function will panic if this property\n-// does not hold.\ntype Value struct{}\n// SeqAtomicLoad returns a copy of *ptr, ensuring that the read does not race\n@@ -55,12 +47,3 @@ func SeqAtomicTryLoad(seq *sync.SeqCount, epoch sync.SeqCountEpoch, ptr *Value)\nok = seq.ReadOk(epoch)\nreturn\n}\n-\n-func init() {\n- var val Value\n- typ := reflect.TypeOf(val)\n- name := typ.Name()\n- if ptrs := sync.PointersInType(typ, name); len(ptrs) != 0 {\n- panic(fmt.Sprintf(\"SeqAtomicLoad<%s> is invalid since values %s of type %s contain pointers:\\n%s\", typ, name, typ, strings.Join(ptrs, \"\\n\")))\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/seqcount.go", "new_path": "pkg/sync/seqcount.go", "diff": "package sync\nimport (\n- \"fmt\"\n- \"reflect\"\n\"sync/atomic\"\n)\n@@ -27,9 +25,6 @@ import (\n// - SeqCount may be more flexible: correct use of SeqCount.ReadOk allows other\n// operations to be made atomic with reads of SeqCount-protected data.\n//\n-// - SeqCount may be less flexible: as of this writing, SeqCount-protected data\n-// cannot include pointers.\n-//\n// - SeqCount is more cumbersome to use; atomic reads of SeqCount-protected\n// data require instantiating function templates using go_generics (see\n// seqatomic.go).\n@@ -128,32 +123,3 @@ func (s *SeqCount) EndWrite() {\npanic(\"SeqCount.EndWrite outside writer critical section\")\n}\n}\n-\n-// PointersInType returns a list of pointers reachable from values named\n-// valName of the given type.\n-//\n-// PointersInType is not exhaustive, but it is guaranteed that if typ contains\n-// at least one pointer, then PointersInTypeOf returns a non-empty list.\n-func PointersInType(typ reflect.Type, valName string) []string {\n- switch kind := typ.Kind(); kind {\n- case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:\n- return nil\n-\n- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.String, reflect.UnsafePointer:\n- return []string{valName}\n-\n- case reflect.Array:\n- return PointersInType(typ.Elem(), valName+\"[]\")\n-\n- case reflect.Struct:\n- var ptrs []string\n- for i, n := 0, typ.NumField(); i < n; i++ {\n- field := typ.Field(i)\n- ptrs = append(ptrs, PointersInType(field.Type, fmt.Sprintf(\"%s.%s\", valName, field.Name))...)\n- }\n- return ptrs\n-\n- default:\n- return []string{fmt.Sprintf(\"%s (of type %s with unknown kind %s)\", valName, typ, kind)}\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/seqcount_test.go", "new_path": "pkg/sync/seqcount_test.go", "diff": "package sync\nimport (\n- \"reflect\"\n\"testing\"\n\"time\"\n)\n@@ -99,55 +98,3 @@ func BenchmarkSeqCountReadUncontended(b *testing.B) {\n}\n})\n}\n-\n-func TestPointersInType(t *testing.T) {\n- for _, test := range []struct {\n- name string // used for both test and value name\n- val interface{}\n- ptrs []string\n- }{\n- {\n- name: \"EmptyStruct\",\n- val: struct{}{},\n- },\n- {\n- name: \"Int\",\n- val: int(0),\n- },\n- {\n- name: \"MixedStruct\",\n- val: struct {\n- b bool\n- I int\n- ExportedPtr *struct{}\n- unexportedPtr *struct{}\n- arr [2]int\n- ptrArr [2]*int\n- nestedStruct struct {\n- nestedNonptr int\n- nestedPtr *int\n- }\n- structArr [1]struct {\n- nonptr int\n- ptr *int\n- }\n- }{},\n- ptrs: []string{\n- \"MixedStruct.ExportedPtr\",\n- \"MixedStruct.unexportedPtr\",\n- \"MixedStruct.ptrArr[]\",\n- \"MixedStruct.nestedStruct.nestedPtr\",\n- \"MixedStruct.structArr[].ptr\",\n- },\n- },\n- } {\n- t.Run(test.name, func(t *testing.T) {\n- typ := reflect.TypeOf(test.val)\n- ptrs := PointersInType(typ, test.name)\n- t.Logf(\"Found pointers: %v\", ptrs)\n- if (len(ptrs) != 0 || len(test.ptrs) != 0) && !reflect.DeepEqual(ptrs, test.ptrs) {\n- t.Errorf(\"Got %v, wanted %v\", ptrs, test.ptrs)\n- }\n- })\n- }\n-}\n" } ]
Go
Apache License 2.0
google/gvisor
Allow use of SeqAtomic with pointer-containing types. Per runtime.memmove, pointers are always copied atomically, as this is required by the GC. (Also, the init() safety check doesn't work because it gets renamed to <prefix>init() by template instantiation.) PiperOrigin-RevId: 345800302
259,885
04.12.2020 19:05:26
28,800
b80021afd2395fd40464ebbeac8f4c8034dee06e
Overlay runsc regular file mounts with regular files. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/copy_up.go", "new_path": "pkg/sentry/fsimpl/overlay/copy_up.go", "diff": "@@ -16,7 +16,6 @@ package overlay\nimport (\n\"fmt\"\n- \"io\"\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -129,25 +128,9 @@ func (d *dentry) copyUpLocked(ctx context.Context) error {\nreturn err\n}\ndefer newFD.DecRef(ctx)\n- bufIOSeq := usermem.BytesIOSequence(make([]byte, 32*1024)) // arbitrary buffer size\n- for {\n- readN, readErr := oldFD.Read(ctx, bufIOSeq, vfs.ReadOptions{})\n- if readErr != nil && readErr != io.EOF {\n+ if _, err := vfs.CopyRegularFileData(ctx, newFD, oldFD); err != nil {\ncleanupUndoCopyUp()\n- return readErr\n- }\n- total := int64(0)\n- for total < readN {\n- writeN, writeErr := newFD.Write(ctx, bufIOSeq.DropFirst64(total), vfs.WriteOptions{})\n- total += writeN\n- if writeErr != nil {\n- cleanupUndoCopyUp()\n- return writeErr\n- }\n- }\n- if readErr == io.EOF {\n- break\n- }\n+ return err\n}\nd.mapsMu.Lock()\ndefer d.mapsMu.Unlock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "package vfs\nimport (\n+ \"io\"\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -838,3 +839,28 @@ func (fd *FileDescription) SetAsyncHandler(newHandler func() FileAsync) FileAsyn\n}\nreturn fd.asyncHandler\n}\n+\n+// CopyRegularFileData copies data from srcFD to dstFD until reading from srcFD\n+// returns EOF or an error. It returns the number of bytes copied.\n+func CopyRegularFileData(ctx context.Context, dstFD, srcFD *FileDescription) (int64, error) {\n+ done := int64(0)\n+ buf := usermem.BytesIOSequence(make([]byte, 32*1024)) // arbitrary buffer size\n+ for {\n+ readN, readErr := srcFD.Read(ctx, buf, ReadOptions{})\n+ if readErr != nil && readErr != io.EOF {\n+ return done, readErr\n+ }\n+ src := buf.TakeFirst64(readN)\n+ for src.NumBytes() != 0 {\n+ writeN, writeErr := dstFD.Write(ctx, src, WriteOptions{})\n+ done += writeN\n+ src = src.DropFirst64(writeN)\n+ if writeErr != nil {\n+ return done, writeErr\n+ }\n+ }\n+ if readErr == io.EOF {\n+ return done, nil\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/vfs.go", "new_path": "runsc/boot/vfs.go", "diff": "@@ -250,36 +250,76 @@ func (c *containerMounter) configureOverlay(ctx context.Context, creds *auth.Cre\noverlayOpts := *lowerOpts\noverlayOpts.GetFilesystemOptions = vfs.GetFilesystemOptions{}\n- // Next mount upper and lower. Upper is a tmpfs mount to keep all\n- // modifications inside the sandbox.\n- upper, err := c.k.VFS().MountDisconnected(ctx, creds, \"\" /* source */, tmpfs.Name, &upperOpts)\n- if err != nil {\n- return nil, nil, fmt.Errorf(\"failed to create upper layer for overlay, opts: %+v: %v\", upperOpts, err)\n- }\n- cu := cleanup.Make(func() { upper.DecRef(ctx) })\n- defer cu.Clean()\n-\n// All writes go to the upper layer, be paranoid and make lower readonly.\nlowerOpts.ReadOnly = true\nlower, err := c.k.VFS().MountDisconnected(ctx, creds, \"\" /* source */, lowerFSName, lowerOpts)\nif err != nil {\nreturn nil, nil, err\n}\n- cu.Add(func() { lower.DecRef(ctx) })\n+ cu := cleanup.Make(func() { lower.DecRef(ctx) })\n+ defer cu.Clean()\n- // Propagate the lower layer's root's owner, group, and mode to the upper\n- // layer's root for consistency with VFS1.\n- upperRootVD := vfs.MakeVirtualDentry(upper, upper.Root())\n+ // Determine the lower layer's root's type.\nlowerRootVD := vfs.MakeVirtualDentry(lower, lower.Root())\nstat, err := c.k.VFS().StatAt(ctx, creds, &vfs.PathOperation{\nRoot: lowerRootVD,\nStart: lowerRootVD,\n}, &vfs.StatOptions{\n- Mask: linux.STATX_UID | linux.STATX_GID | linux.STATX_MODE,\n+ Mask: linux.STATX_UID | linux.STATX_GID | linux.STATX_MODE | linux.STATX_TYPE,\n})\nif err != nil {\n- return nil, nil, err\n+ return nil, nil, fmt.Errorf(\"failed to stat lower layer's root: %v\", err)\n+ }\n+ if stat.Mask&linux.STATX_TYPE == 0 {\n+ return nil, nil, fmt.Errorf(\"failed to get file type of lower layer's root\")\n+ }\n+ rootType := stat.Mode & linux.S_IFMT\n+ if rootType != linux.S_IFDIR && rootType != linux.S_IFREG {\n+ return nil, nil, fmt.Errorf(\"lower layer's root has unsupported file type %v\", rootType)\n+ }\n+\n+ // Upper is a tmpfs mount to keep all modifications inside the sandbox.\n+ upperOpts.GetFilesystemOptions.InternalData = tmpfs.FilesystemOpts{\n+ RootFileType: uint16(rootType),\n+ }\n+ upper, err := c.k.VFS().MountDisconnected(ctx, creds, \"\" /* source */, tmpfs.Name, &upperOpts)\n+ if err != nil {\n+ return nil, nil, fmt.Errorf(\"failed to create upper layer for overlay, opts: %+v: %v\", upperOpts, err)\n+ }\n+ cu.Add(func() { upper.DecRef(ctx) })\n+\n+ // If the overlay mount consists of a regular file, copy up its contents\n+ // from the lower layer, since in the overlay the otherwise-empty upper\n+ // layer file will take precedence.\n+ upperRootVD := vfs.MakeVirtualDentry(upper, upper.Root())\n+ if rootType == linux.S_IFREG {\n+ lowerFD, err := c.k.VFS().OpenAt(ctx, creds, &vfs.PathOperation{\n+ Root: lowerRootVD,\n+ Start: lowerRootVD,\n+ }, &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ })\n+ if err != nil {\n+ return nil, nil, fmt.Errorf(\"failed to open lower layer root for copying: %v\", err)\n+ }\n+ defer lowerFD.DecRef(ctx)\n+ upperFD, err := c.k.VFS().OpenAt(ctx, creds, &vfs.PathOperation{\n+ Root: upperRootVD,\n+ Start: upperRootVD,\n+ }, &vfs.OpenOptions{\n+ Flags: linux.O_WRONLY,\n+ })\n+ if err != nil {\n+ return nil, nil, fmt.Errorf(\"failed to open upper layer root for copying: %v\", err)\n+ }\n+ defer upperFD.DecRef(ctx)\n+ if _, err := vfs.CopyRegularFileData(ctx, upperFD, lowerFD); err != nil {\n+ return nil, nil, fmt.Errorf(\"failed to copy up overlay file: %v\", err)\n}\n+ }\n+\n+ // Propagate the lower layer's root's owner, group, and mode to the upper\n+ // layer's root for consistency with VFS1.\nerr = c.k.VFS().SetStatAt(ctx, creds, &vfs.PathOperation{\nRoot: upperRootVD,\nStart: upperRootVD,\n" } ]
Go
Apache License 2.0
google/gvisor
Overlay runsc regular file mounts with regular files. Fixes #4991 PiperOrigin-RevId: 345800333
260,004
04.12.2020 22:02:09
28,800
df2dbe3e38aac73926a51d8045dbb419c6167cf5
Remove stack.ReadOnlyAddressableEndpointState Startblock: has LGTM from asfez and then add reviewer tamird
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -799,28 +799,12 @@ func (e *endpoint) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp boo\ndefer e.mu.Unlock()\nloopback := e.nic.IsLoopback()\n- addressEndpoint := e.mu.addressableEndpointState.ReadOnly().AddrOrMatching(localAddr, allowTemp, func(addressEndpoint stack.AddressEndpoint) bool {\n+ return e.mu.addressableEndpointState.AcquireAssignedAddressOrMatching(localAddr, func(addressEndpoint stack.AddressEndpoint) bool {\nsubnet := addressEndpoint.Subnet()\n// IPv4 has a notion of a subnet broadcast address and considers the\n// loopback interface bound to an address's whole subnet (on linux).\nreturn subnet.IsBroadcast(localAddr) || (loopback && subnet.Contains(localAddr))\n- })\n- if addressEndpoint != nil {\n- return addressEndpoint\n- }\n-\n- if !allowTemp {\n- return nil\n- }\n-\n- addr := localAddr.WithPrefix()\n- addressEndpoint, err := e.mu.addressableEndpointState.AddAndAcquireTemporaryAddress(addr, tempPEB)\n- if err != nil {\n- // AddAddress only returns an error if the address is already assigned,\n- // but we just checked above if the address exists so we expect no error.\n- panic(fmt.Sprintf(\"e.mu.addressableEndpointState.AddAndAcquireTemporaryAddress(%s, %d): %s\", addr, tempPEB, err))\n- }\n- return addressEndpoint\n+ }, allowTemp, tempPEB)\n}\n// AcquireOutgoingPrimaryAddress implements stack.AddressableEndpoint.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -263,7 +263,7 @@ func (e *endpoint) Enable() *tcpip.Error {\n// Addresses may have aleady completed DAD but in the time since the endpoint\n// was last enabled, other devices may have acquired the same addresses.\nvar err *tcpip.Error\n- e.mu.addressableEndpointState.ReadOnly().ForEach(func(addressEndpoint stack.AddressEndpoint) bool {\n+ e.mu.addressableEndpointState.ForEachEndpoint(func(addressEndpoint stack.AddressEndpoint) bool {\naddr := addressEndpoint.AddressWithPrefix().Address\nif !header.IsV6UnicastAddress(addr) {\nreturn true\n@@ -357,7 +357,7 @@ func (e *endpoint) disableLocked() {\n// Precondition: e.mu must be write locked.\nfunc (e *endpoint) stopDADForPermanentAddressesLocked() {\n// Stop DAD for all the tentative unicast addresses.\n- e.mu.addressableEndpointState.ReadOnly().ForEach(func(addressEndpoint stack.AddressEndpoint) bool {\n+ e.mu.addressableEndpointState.ForEachEndpoint(func(addressEndpoint stack.AddressEndpoint) bool {\nif addressEndpoint.GetKind() != stack.PermanentTentative {\nreturn true\n}\n@@ -1261,7 +1261,7 @@ func (e *endpoint) hasPermanentAddressRLocked(addr tcpip.Address) bool {\n//\n// Precondition: e.mu must be read or write locked.\nfunc (e *endpoint) getAddressRLocked(localAddr tcpip.Address) stack.AddressEndpoint {\n- return e.mu.addressableEndpointState.ReadOnly().Lookup(localAddr)\n+ return e.mu.addressableEndpointState.GetAddress(localAddr)\n}\n// MainAddress implements stack.AddressableEndpoint.\n@@ -1312,7 +1312,7 @@ func (e *endpoint) acquireOutgoingPrimaryAddressRLocked(remoteAddr tcpip.Address\n// Create a candidate set of available addresses we can potentially use as a\n// source address.\nvar cs []addrCandidate\n- e.mu.addressableEndpointState.ReadOnly().ForEachPrimaryEndpoint(func(addressEndpoint stack.AddressEndpoint) {\n+ e.mu.addressableEndpointState.ForEachPrimaryEndpoint(func(addressEndpoint stack.AddressEndpoint) {\n// If r is not valid for outgoing connections, it is not a valid endpoint.\nif !addressEndpoint.IsAssigned(allowExpired) {\nreturn\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/addressable_endpoint_state.go", "new_path": "pkg/tcpip/stack/addressable_endpoint_state.go", "diff": "@@ -50,62 +50,31 @@ func (a *AddressableEndpointState) Init(networkEndpoint NetworkEndpoint) {\na.mu.endpoints = make(map[tcpip.Address]*addressState)\n}\n-// ReadOnlyAddressableEndpointState provides read-only access to an\n-// AddressableEndpointState.\n-type ReadOnlyAddressableEndpointState struct {\n- inner *AddressableEndpointState\n-}\n-\n-// AddrOrMatching returns an endpoint for the passed address that is consisdered\n-// bound to the wrapped AddressableEndpointState.\n+// GetAddress returns the AddressEndpoint for the passed address.\n//\n-// If addr is an exact match with an existing address, that address is returned.\n-// Otherwise, f is called with each address and the address that f returns true\n-// for is returned.\n+// GetAddress does not increment the address's reference count or check if the\n+// address is considered bound to the endpoint.\n//\n-// Returns nil of no address matches.\n-func (m ReadOnlyAddressableEndpointState) AddrOrMatching(addr tcpip.Address, spoofingOrPrimiscuous bool, f func(AddressEndpoint) bool) AddressEndpoint {\n- m.inner.mu.RLock()\n- defer m.inner.mu.RUnlock()\n-\n- if ep, ok := m.inner.mu.endpoints[addr]; ok {\n- if ep.IsAssigned(spoofingOrPrimiscuous) && ep.IncRef() {\n- return ep\n- }\n- }\n-\n- for _, ep := range m.inner.mu.endpoints {\n- if ep.IsAssigned(spoofingOrPrimiscuous) && f(ep) && ep.IncRef() {\n- return ep\n- }\n- }\n-\n- return nil\n-}\n-\n-// Lookup returns the AddressEndpoint for the passed address.\n-//\n-// Returns nil if the passed address is not associated with the\n-// AddressableEndpointState.\n-func (m ReadOnlyAddressableEndpointState) Lookup(addr tcpip.Address) AddressEndpoint {\n- m.inner.mu.RLock()\n- defer m.inner.mu.RUnlock()\n+// Returns nil if the passed address is not associated with the endpoint.\n+func (a *AddressableEndpointState) GetAddress(addr tcpip.Address) AddressEndpoint {\n+ a.mu.RLock()\n+ defer a.mu.RUnlock()\n- ep, ok := m.inner.mu.endpoints[addr]\n+ ep, ok := a.mu.endpoints[addr]\nif !ok {\nreturn nil\n}\nreturn ep\n}\n-// ForEach calls f for each address pair.\n+// ForEachEndpoint calls f for each address.\n//\n-// If f returns false, f is no longer be called.\n-func (m ReadOnlyAddressableEndpointState) ForEach(f func(AddressEndpoint) bool) {\n- m.inner.mu.RLock()\n- defer m.inner.mu.RUnlock()\n+// Once f returns false, f will no longer be called.\n+func (a *AddressableEndpointState) ForEachEndpoint(f func(AddressEndpoint) bool) {\n+ a.mu.RLock()\n+ defer a.mu.RUnlock()\n- for _, ep := range m.inner.mu.endpoints {\n+ for _, ep := range a.mu.endpoints {\nif !f(ep) {\nreturn\n}\n@@ -113,21 +82,15 @@ func (m ReadOnlyAddressableEndpointState) ForEach(f func(AddressEndpoint) bool)\n}\n// ForEachPrimaryEndpoint calls f for each primary address.\n-//\n-// If f returns false, f is no longer be called.\n-func (m ReadOnlyAddressableEndpointState) ForEachPrimaryEndpoint(f func(AddressEndpoint)) {\n- m.inner.mu.RLock()\n- defer m.inner.mu.RUnlock()\n- for _, ep := range m.inner.mu.primary {\n+func (a *AddressableEndpointState) ForEachPrimaryEndpoint(f func(AddressEndpoint)) {\n+ a.mu.RLock()\n+ defer a.mu.RUnlock()\n+\n+ for _, ep := range a.mu.primary {\nf(ep)\n}\n}\n-// ReadOnly returns a readonly reference to a.\n-func (a *AddressableEndpointState) ReadOnly() ReadOnlyAddressableEndpointState {\n- return ReadOnlyAddressableEndpointState{inner: a}\n-}\n-\nfunc (a *AddressableEndpointState) releaseAddressState(addrState *addressState) {\na.mu.Lock()\ndefer a.mu.Unlock()\n@@ -460,8 +423,19 @@ func (a *AddressableEndpointState) acquirePrimaryAddressRLocked(isValid func(*ad\nreturn deprecatedEndpoint\n}\n-// AcquireAssignedAddress implements AddressableEndpoint.\n-func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {\n+// AcquireAssignedAddressOrMatching returns an address endpoint that is\n+// considered assigned to the addressable endpoint.\n+//\n+// If the address is an exact match with an existing address, that address is\n+// returned. Otherwise, if f is provided, f is called with each address and\n+// the address that f returns true for is returned.\n+//\n+// If there is no matching address, a temporary address will be returned if\n+// allowTemp is true.\n+//\n+// Regardless how the address was obtained, it will be acquired before it is\n+// returned.\n+func (a *AddressableEndpointState) AcquireAssignedAddressOrMatching(localAddr tcpip.Address, f func(AddressEndpoint) bool, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {\na.mu.Lock()\ndefer a.mu.Unlock()\n@@ -477,6 +451,14 @@ func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Addres\nreturn addrState\n}\n+ if f != nil {\n+ for _, addrState := range a.mu.endpoints {\n+ if addrState.IsAssigned(allowTemp) && f(addrState) && addrState.IncRef() {\n+ return addrState\n+ }\n+ }\n+ }\n+\nif !allowTemp {\nreturn nil\n}\n@@ -509,6 +491,11 @@ func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Addres\nreturn ep\n}\n+// AcquireAssignedAddress implements AddressableEndpoint.\n+func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {\n+ return a.AcquireAssignedAddressOrMatching(localAddr, nil, allowTemp, tempPEB)\n+}\n+\n// AcquireOutgoingPrimaryAddress implements AddressableEndpoint.\nfunc (a *AddressableEndpointState) AcquireOutgoingPrimaryAddress(remoteAddr tcpip.Address, allowExpired bool) AddressEndpoint {\na.mu.RLock()\n" } ]
Go
Apache License 2.0
google/gvisor
Remove stack.ReadOnlyAddressableEndpointState Startblock: has LGTM from asfez and then add reviewer tamird PiperOrigin-RevId: 345815146
259,986
07.12.2020 08:42:09
28,800
eeb23531ebef4fc44af317b4e4a8834c8b069dd9
Support icmpv6 transport protocol
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -207,7 +207,7 @@ swgso-tests: load-basic-images\nhostnet-tests: load-basic-images\n@$(call submake,install-runtime RUNTIME=\"hostnet\" ARGS=\"--network=host\")\n- @$(call submake,test-runtime RUNTIME=\"hostnet\" OPTIONS=\"--test_arg=-checkpoint=false\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n+ @$(call submake,test-runtime RUNTIME=\"hostnet\" OPTIONS=\"--test_arg=-checkpoint=false --test_arg=-hostnet=true\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: hostnet-tests\nkvm-tests: load-basic-images\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/basic/ping4test/Dockerfile", "diff": "+FROM ubuntu:bionic\n+\n+WORKDIR /root\n+COPY ping4.sh .\n+RUN chmod +x ping4.sh\n+\n+RUN apt-get update && apt-get install -y iputils-ping\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/basic/ping4test/ping4.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2020 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -euo pipefail\n+\n+# The docker API doesn't provide for starting a container, running a command,\n+# and getting the exit status of the command in one go. The most straightforward\n+# way to do this is to verify the output of the command, so we output nothing on\n+# success and an error message on failure.\n+if ! out=$(ping -c 10 127.0.0.1); then\n+ echo \"$out\"\n+fi\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/basic/ping6test/Dockerfile", "diff": "+FROM ubuntu:bionic\n+\n+WORKDIR /root\n+COPY ping6.sh .\n+RUN chmod +x ping6.sh\n+\n+RUN apt-get update && apt-get install -y iputils-ping iproute2\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/basic/ping6test/ping6.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2020 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -euo pipefail\n+\n+# Enable ipv6 on loopback if it's not already enabled. Runsc doesn't enable ipv6\n+# loopback unless an ipv6 address was assigned to the container, which docker\n+# does not do by default.\n+if ! [[ $(ip -6 addr show dev lo) ]]; then\n+ ip addr add ::1 dev lo\n+fi\n+\n+# The docker API doesn't provide for starting a container, running a command,\n+# and getting the exit status of the command in one go. The most straightforward\n+# way to do this is to verify the output of the command, so we output nothing on\n+# success and an error message on failure.\n+if ! out=$(/bin/ping6 -c 10 ::1); then\n+ echo \"$out\"\n+fi\n" }, { "change_type": "MODIFY", "old_path": "pkg/test/testutil/testutil.go", "new_path": "pkg/test/testutil/testutil.go", "diff": "@@ -51,6 +51,7 @@ var (\ncheckpoint = flag.Bool(\"checkpoint\", true, \"control checkpoint/restore support\")\npartition = flag.Int(\"partition\", 1, \"partition number, this is 1-indexed\")\ntotalPartitions = flag.Int(\"total_partitions\", 1, \"total number of partitions\")\n+ isRunningWithHostNet = flag.Bool(\"hostnet\", false, \"whether test is running with hostnet\")\n)\n// IsCheckpointSupported returns the relevant command line flag.\n@@ -58,6 +59,11 @@ func IsCheckpointSupported() bool {\nreturn *checkpoint\n}\n+// IsRunningWithHostNet returns the relevant command line flag.\n+func IsRunningWithHostNet() bool {\n+ return *isRunningWithHostNet\n+}\n+\n// ImageByName mangles the image name used locally. This depends on the image\n// build infrastructure in images/ and tools/vm.\nfunc ImageByName(name string) string {\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -1082,7 +1082,12 @@ func newRootNetworkNamespace(conf *config.Config, clock tcpip.Clock, uniqueID st\nfunc newEmptySandboxNetworkStack(clock tcpip.Clock, uniqueID stack.UniqueID) (inet.Stack, error) {\nnetProtos := []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol, arp.NewProtocol}\n- transProtos := []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4}\n+ transProtos := []stack.TransportProtocolFactory{\n+ tcp.NewProtocol,\n+ udp.NewProtocol,\n+ icmp.NewProtocol4,\n+ icmp.NewProtocol6,\n+ }\ns := netstack.Stack{stack.New(stack.Options{\nNetworkProtocols: netProtos,\nTransportProtocols: transProtos,\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/integration_test.go", "new_path": "test/e2e/integration_test.go", "diff": "@@ -494,6 +494,55 @@ func TestLink(t *testing.T) {\n}\n}\n+// This test ensures we can run ping without errors.\n+func TestPing4Loopback(t *testing.T) {\n+ if testutil.IsRunningWithHostNet() {\n+ // TODO(gvisor.dev/issue/5011): support ICMP sockets in hostnet and enable\n+ // this test.\n+ t.Skip(\"hostnet only supports TCP/UDP sockets, so ping is not supported.\")\n+ }\n+\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+\n+ if got, err := d.Run(ctx, dockerutil.RunOpts{\n+ Image: \"basic/ping4test\",\n+ }, \"/root/ping4.sh\"); err != nil {\n+ t.Fatalf(\"docker run failed: %s\", err)\n+ } else if got != \"\" {\n+ t.Errorf(\"test failed:\\n%s\", got)\n+ }\n+}\n+\n+// This test ensures we can enable ipv6 on loopback and run ping6 without\n+// errors.\n+func TestPing6Loopback(t *testing.T) {\n+ if testutil.IsRunningWithHostNet() {\n+ // TODO(gvisor.dev/issue/5011): support ICMP sockets in hostnet and enable\n+ // this test.\n+ t.Skip(\"hostnet only supports TCP/UDP sockets, so ping6 is not supported.\")\n+ }\n+\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+\n+ if got, err := d.Run(ctx, dockerutil.RunOpts{\n+ Image: \"basic/ping6test\",\n+ // The CAP_NET_ADMIN capability is required to use the `ip` utility, which\n+ // we use to enable ipv6 on loopback.\n+ //\n+ // By default, ipv6 loopback is not enabled by runsc, because docker does\n+ // not assign an ipv6 address to the test container.\n+ CapAdd: []string{\"NET_ADMIN\"},\n+ }, \"/root/ping6.sh\"); err != nil {\n+ t.Fatalf(\"docker run failed: %s\", err)\n+ } else if got != \"\" {\n+ t.Errorf(\"test failed:\\n%s\", got)\n+ }\n+}\n+\nfunc TestMain(m *testing.M) {\ndockerutil.EnsureSupportedDockerVersion()\nflag.Parse()\n" } ]
Go
Apache License 2.0
google/gvisor
Support icmpv6 transport protocol PiperOrigin-RevId: 346101076
259,967
07.12.2020 14:49:26
28,800
0e5ba13b331d4e85548b6f095b28ae88df95a89a
Remove stale comment Removes comment lines about MaxUnsolicitedReportDelay. This is already documented in the comment for GenericMulticastProtocolOptions.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "new_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "diff": "@@ -152,9 +152,6 @@ type GenericMulticastProtocolState struct {\n}\n// Init initializes the Generic Multicast Protocol state.\n-//\n-// maxUnsolicitedReportDelay is the maximum time between sending unsolicited\n-// reports after joining a group.\nfunc (g *GenericMulticastProtocolState) Init(opts GenericMulticastProtocolOptions) {\ng.mu.Lock()\ndefer g.mu.Unlock()\n" } ]
Go
Apache License 2.0
google/gvisor
Remove stale comment Removes comment lines about MaxUnsolicitedReportDelay. This is already documented in the comment for GenericMulticastProtocolOptions. PiperOrigin-RevId: 346185053
259,951
07.12.2020 15:50:23
28,800
615c3380d297ee3c61e47fb48a4cca87f7c99ba0
Export IGMP stats
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -153,6 +153,28 @@ var Metrics = tcpip.Stats{\n},\n},\n},\n+ IGMP: tcpip.IGMPStats{\n+ PacketsSent: tcpip.IGMPSentPacketStats{\n+ IGMPPacketStats: tcpip.IGMPPacketStats{\n+ MembershipQuery: mustCreateMetric(\"/netstack/igmp/packets_sent/membership_query\", \"Total number of IGMP Membership Query messages sent by netstack.\"),\n+ V1MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_sent/v1_membership_report\", \"Total number of IGMPv1 Membership Report messages sent by netstack.\"),\n+ V2MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_sent/v2_membership_report\", \"Total number of IGMPv2 Membership Report messages sent by netstack.\"),\n+ LeaveGroup: mustCreateMetric(\"/netstack/igmp/packets_sent/leave_group\", \"Total number of IGMP Leave Group messages sent by netstack.\"),\n+ },\n+ Dropped: mustCreateMetric(\"/netstack/igmp/packets_sent/dropped\", \"Total number of IGMP packets dropped by netstack due to link layer errors.\"),\n+ },\n+ PacketsReceived: tcpip.IGMPReceivedPacketStats{\n+ IGMPPacketStats: tcpip.IGMPPacketStats{\n+ MembershipQuery: mustCreateMetric(\"/netstack/igmp/packets_received/membership_query\", \"Total number of IGMP Membership Query messages received by netstack.\"),\n+ V1MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_received/v1_membership_report\", \"Total number of IGMPv1 Membership Report messages received by netstack.\"),\n+ V2MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_received/v2_membership_report\", \"Total number of IGMPv2 Membership Report messages received by netstack.\"),\n+ LeaveGroup: mustCreateMetric(\"/netstack/igmp/packets_received/leave_group\", \"Total number of IGMP Leave Group messages received by netstack.\"),\n+ },\n+ Invalid: mustCreateMetric(\"/netstack/igmp/packets_received/invalid\", \"Total number of IGMP packets received by netstack that could not be parsed.\"),\n+ ChecksumErrors: mustCreateMetric(\"/netstack/igmp/packets_received/checksum_errors\", \"Total number of received IGMP packets with bad checksums.\"),\n+ Unrecognized: mustCreateMetric(\"/netstack/igmp/packets_received/unrecognized\", \"Total number of unrecognized IGMP packets received by netstack.\"),\n+ },\n+ },\nIP: tcpip.IPStats{\nPacketsReceived: mustCreateMetric(\"/netstack/ip/packets_received\", \"Total number of IP packets received from the link layer in nic.DeliverNetworkPacket.\"),\nInvalidDestinationAddressesReceived: mustCreateMetric(\"/netstack/ip/invalid_addresses_received\", \"Total number of IP packets received with an unknown or invalid destination address.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1438,8 +1438,7 @@ type IGMPPacketStats struct {\ntype IGMPSentPacketStats struct {\nIGMPPacketStats\n- // Dropped is the total number of IGMP packets dropped due to link layer\n- // errors.\n+ // Dropped is the total number of IGMP packets dropped.\nDropped *StatCounter\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Export IGMP stats PiperOrigin-RevId: 346197760
259,975
07.12.2020 16:17:14
28,800
6d30688bd70370fd9327cd3fca178bb85342cc2a
Fix tags on benchmark targets.
[ { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"bzl_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+bzl_library(\n+ name = \"defs_bzl\",\n+ srcs = [\"defs.bzl\"],\n+ visibility = [\n+ \"//:sandbox\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/BUILD", "new_path": "test/benchmarks/base/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//test/benchmarks:defs.bzl\", \"benchmark_test\")\npackage(licenses = [\"notice\"])\n@@ -14,7 +15,7 @@ go_library(\n],\n)\n-go_test(\n+benchmark_test(\nname = \"startup_test\",\nsize = \"enormous\",\nsrcs = [\"startup_test.go\"],\n@@ -26,7 +27,7 @@ go_test(\n],\n)\n-go_test(\n+benchmark_test(\nname = \"size_test\",\nsize = \"enormous\",\nsrcs = [\"size_test.go\"],\n@@ -39,7 +40,7 @@ go_test(\n],\n)\n-go_test(\n+benchmark_test(\nname = \"sysbench_test\",\nsize = \"enormous\",\nsrcs = [\"sysbench_test.go\"],\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/database/BUILD", "new_path": "test/benchmarks/database/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//test/benchmarks:defs.bzl\", \"benchmark_test\")\npackage(licenses = [\"notice\"])\n@@ -9,16 +10,11 @@ go_library(\ndeps = [\"//test/benchmarks/harness\"],\n)\n-go_test(\n+benchmark_test(\nname = \"database_test\",\nsize = \"enormous\",\nsrcs = [\"redis_test.go\"],\nlibrary = \":database\",\n- tags = [\n- # Requires docker and runsc to be configured before test runs.\n- \"manual\",\n- \"local\",\n- ],\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/defs.bzl", "diff": "+\"\"\"Defines a rule for benchmark test targets.\"\"\"\n+\n+load(\"//tools:defs.bzl\", \"go_test\")\n+\n+def benchmark_test(name, tags = [], **kwargs):\n+ go_test(\n+ name,\n+ tags = [\n+ # Requires docker and runsc to be configured before the test runs.\n+ \"local\",\n+ \"manual\",\n+ ],\n+ **kwargs\n+ )\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/BUILD", "new_path": "test/benchmarks/fs/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_test\")\n+load(\"//test/benchmarks:defs.bzl\", \"benchmark_test\")\npackage(licenses = [\"notice\"])\n-go_test(\n+benchmark_test(\nname = \"bazel_test\",\nsize = \"enormous\",\nsrcs = [\"bazel_test.go\"],\n@@ -14,7 +14,7 @@ go_test(\n],\n)\n-go_test(\n+benchmark_test(\nname = \"fio_test\",\nsize = \"enormous\",\nsrcs = [\"fio_test.go\"],\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/media/BUILD", "new_path": "test/benchmarks/media/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//test/benchmarks:defs.bzl\", \"benchmark_test\")\npackage(licenses = [\"notice\"])\n@@ -9,7 +10,7 @@ go_library(\ndeps = [\"//test/benchmarks/harness\"],\n)\n-go_test(\n+benchmark_test(\nname = \"media_test\",\nsize = \"large\",\nsrcs = [\"ffmpeg_test.go\"],\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/BUILD", "new_path": "test/benchmarks/ml/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//test/benchmarks:defs.bzl\", \"benchmark_test\")\npackage(licenses = [\"notice\"])\n@@ -9,7 +10,7 @@ go_library(\ndeps = [\"//test/benchmarks/harness\"],\n)\n-go_test(\n+benchmark_test(\nname = \"ml_test\",\nsize = \"large\",\nsrcs = [\"tensorflow_test.go\"],\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/BUILD", "new_path": "test/benchmarks/network/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//test/benchmarks:defs.bzl\", \"benchmark_test\")\npackage(licenses = [\"notice\"])\n@@ -16,7 +17,7 @@ go_library(\n],\n)\n-go_test(\n+benchmark_test(\nname = \"network_test\",\nsize = \"large\",\nsrcs = [\n@@ -27,11 +28,6 @@ go_test(\n\"ruby_test.go\",\n],\nlibrary = \":network\",\n- tags = [\n- # Requires docker and runsc to be configured before test runs.\n- \"manual\",\n- \"local\",\n- ],\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n" } ]
Go
Apache License 2.0
google/gvisor
Fix tags on benchmark targets. PiperOrigin-RevId: 346203209
259,985
07.12.2020 17:58:56
28,800
9c198e5df4216feb5ebbf144e3b616888dfe3c27
Fix error handling on fusefs mount. Don't propagate arbitrary golang errors up from fusefs because errors that don't map to an errno result in a sentry panic. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "new_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "diff": "@@ -84,11 +84,7 @@ func (conn *connection) InitSend(creds *auth.Credentials, pid uint32) error {\nFlags: fuseDefaultInitFlags,\n}\n- req, err := conn.NewRequest(creds, pid, 0, linux.FUSE_INIT, &in)\n- if err != nil {\n- return err\n- }\n-\n+ req := conn.NewRequest(creds, pid, 0, linux.FUSE_INIT, &in)\n// Since there is no task to block on and FUSE_INIT is the request\n// to unblock other requests, use nil.\nreturn conn.CallAsync(nil, req)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection_test.go", "new_path": "pkg/sentry/fsimpl/fuse/connection_test.go", "diff": "@@ -76,10 +76,7 @@ func TestConnectionAbort(t *testing.T) {\nvar futNormal []*futureResponse\nfor i := 0; i < int(numRequests); i++ {\n- req, err := conn.NewRequest(creds, uint32(i), uint64(i), 0, testObj)\n- if err != nil {\n- t.Fatalf(\"NewRequest creation failed: %v\", err)\n- }\n+ req := conn.NewRequest(creds, uint32(i), uint64(i), 0, testObj)\nfut, err := conn.callFutureLocked(task, req)\nif err != nil {\nt.Fatalf(\"callFutureLocked failed: %v\", err)\n@@ -105,10 +102,7 @@ func TestConnectionAbort(t *testing.T) {\n}\n// After abort, Call() should return directly with ENOTCONN.\n- req, err := conn.NewRequest(creds, 0, 0, 0, testObj)\n- if err != nil {\n- t.Fatalf(\"NewRequest creation failed: %v\", err)\n- }\n+ req := conn.NewRequest(creds, 0, 0, 0, testObj)\n_, err = conn.Call(task, req)\nif err != syserror.ENOTCONN {\nt.Fatalf(\"Incorrect error code received for Call() after connection aborted\")\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev_test.go", "new_path": "pkg/sentry/fsimpl/fuse/dev_test.go", "diff": "@@ -219,10 +219,7 @@ func fuseClientRun(t *testing.T, s *testutil.System, k *kernel.Kernel, conn *con\ndata: rand.Uint32(),\n}\n- req, err := conn.NewRequest(creds, pid, inode, echoTestOpcode, testObj)\n- if err != nil {\n- t.Fatalf(\"NewRequest creation failed: %v\", err)\n- }\n+ req := conn.NewRequest(creds, pid, inode, echoTestOpcode, testObj)\n// Queue up a request.\n// Analogous to Call except it doesn't block on the task.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/directory.go", "new_path": "pkg/sentry/fsimpl/fuse/directory.go", "diff": "@@ -68,11 +68,7 @@ func (dir *directoryFD) IterDirents(ctx context.Context, callback vfs.IterDirent\n}\n// TODO(gVisor.dev/issue/3404): Support FUSE_READDIRPLUS.\n- req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), dir.inode().nodeID, linux.FUSE_READDIR, &in)\n- if err != nil {\n- return err\n- }\n-\n+ req := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), dir.inode().nodeID, linux.FUSE_READDIR, &in)\nres, err := fusefs.conn.Call(task, req)\nif err != nil {\nreturn err\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -83,12 +83,8 @@ func (fd *fileDescription) Release(ctx context.Context) {\nopcode = linux.FUSE_RELEASE\n}\nkernelTask := kernel.TaskFromContext(ctx)\n- // ignoring errors and FUSE server reply is analogous to Linux's behavior.\n- req, err := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().nodeID, opcode, &in)\n- if err != nil {\n- // No way to invoke Call() with an errored request.\n- return\n- }\n+ // Ignoring errors and FUSE server reply is analogous to Linux's behavior.\n+ req := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().nodeID, opcode, &in)\n// The reply will be ignored since no callback is defined in asyncCallBack().\nconn.CallAsync(kernelTask, req)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -119,7 +119,8 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ndeviceDescriptor, err := strconv.ParseInt(deviceDescriptorStr, 10 /* base */, 32 /* bitSize */)\nif err != nil {\n- return nil, nil, err\n+ log.Debugf(\"%s.GetFilesystem: device FD '%v' not parsable: %v\", fsType.Name(), deviceDescriptorStr, err)\n+ return nil, nil, syserror.EINVAL\n}\nkernelTask := kernel.TaskFromContext(ctx)\n@@ -360,12 +361,8 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kernfs.Dentr\nin.Flags &= ^uint32(linux.O_TRUNC)\n}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, opcode, &in)\n- if err != nil {\n- return nil, err\n- }\n-\n// Send the request and receive the reply.\n+ req := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, opcode, &in)\nres, err := i.fs.conn.Call(kernelTask, req)\nif err != nil {\nreturn nil, err\n@@ -485,10 +482,7 @@ func (i *inode) Unlink(ctx context.Context, name string, child kernfs.Inode) err\nreturn syserror.EINVAL\n}\nin := linux.FUSEUnlinkIn{Name: name}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, linux.FUSE_UNLINK, &in)\n- if err != nil {\n- return err\n- }\n+ req := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, linux.FUSE_UNLINK, &in)\nres, err := i.fs.conn.Call(kernelTask, req)\nif err != nil {\nreturn err\n@@ -515,11 +509,7 @@ func (i *inode) RmDir(ctx context.Context, name string, child kernfs.Inode) erro\ntask, creds := kernel.TaskFromContext(ctx), auth.CredentialsFromContext(ctx)\nin := linux.FUSERmDirIn{Name: name}\n- req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_RMDIR, &in)\n- if err != nil {\n- return err\n- }\n-\n+ req := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_RMDIR, &in)\nres, err := i.fs.conn.Call(task, req)\nif err != nil {\nreturn err\n@@ -535,10 +525,7 @@ func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMo\nlog.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.nodeID)\nreturn nil, syserror.EINVAL\n}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, opcode, payload)\n- if err != nil {\n- return nil, err\n- }\n+ req := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, opcode, payload)\nres, err := i.fs.conn.Call(kernelTask, req)\nif err != nil {\nreturn nil, err\n@@ -574,10 +561,7 @@ func (i *inode) Readlink(ctx context.Context, mnt *vfs.Mount) (string, error) {\nlog.Warningf(\"fusefs.Inode.Readlink: couldn't get kernel task from context\")\nreturn \"\", syserror.EINVAL\n}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, linux.FUSE_READLINK, &linux.FUSEEmptyIn{})\n- if err != nil {\n- return \"\", err\n- }\n+ req := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, linux.FUSE_READLINK, &linux.FUSEEmptyIn{})\nres, err := i.fs.conn.Call(kernelTask, req)\nif err != nil {\nreturn \"\", err\n@@ -680,11 +664,7 @@ func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOp\nGetAttrFlags: flags,\nFh: fh,\n}\n- req, err := i.fs.conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_GETATTR, &in)\n- if err != nil {\n- return linux.FUSEAttr{}, err\n- }\n-\n+ req := i.fs.conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_GETATTR, &in)\nres, err := i.fs.conn.Call(task, req)\nif err != nil {\nreturn linux.FUSEAttr{}, err\n@@ -803,11 +783,7 @@ func (i *inode) setAttr(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nUID: opts.Stat.UID,\nGID: opts.Stat.GID,\n}\n- req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_SETATTR, &in)\n- if err != nil {\n- return err\n- }\n-\n+ req := conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_SETATTR, &in)\nres, err := conn.Call(task, req)\nif err != nil {\nreturn err\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/read_write.go", "new_path": "pkg/sentry/fsimpl/fuse/read_write.go", "diff": "@@ -79,13 +79,9 @@ func (fs *filesystem) ReadInPages(ctx context.Context, fd *regularFileFD, off ui\nin.Offset = off + (uint64(pagesRead) << usermem.PageShift)\nin.Size = pagesCanRead << usermem.PageShift\n- req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().nodeID, linux.FUSE_READ, &in)\n- if err != nil {\n- return nil, 0, err\n- }\n-\n// TODO(gvisor.dev/issue/3247): support async read.\n+ req := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().nodeID, linux.FUSE_READ, &in)\nres, err := fs.conn.Call(t, req)\nif err != nil {\nreturn nil, 0, err\n@@ -204,11 +200,7 @@ func (fs *filesystem) Write(ctx context.Context, fd *regularFileFD, off uint64,\nin.Offset = off + uint64(written)\nin.Size = toWrite\n- req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), inode.nodeID, linux.FUSE_WRITE, &in)\n- if err != nil {\n- return 0, err\n- }\n-\n+ req := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), inode.nodeID, linux.FUSE_WRITE, &in)\nreq.payload = data[written : written+toWrite]\n// TODO(gvisor.dev/issue/3247): support async write.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/request_response.go", "new_path": "pkg/sentry/fsimpl/fuse/request_response.go", "diff": "@@ -104,7 +104,7 @@ type Request struct {\n}\n// NewRequest creates a new request that can be sent to the FUSE server.\n-func (conn *connection) NewRequest(creds *auth.Credentials, pid uint32, ino uint64, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*Request, error) {\n+func (conn *connection) NewRequest(creds *auth.Credentials, pid uint32, ino uint64, opcode linux.FUSEOpcode, payload marshal.Marshallable) *Request {\nconn.fd.mu.Lock()\ndefer conn.fd.mu.Unlock()\nconn.fd.nextOpID += linux.FUSEOpID(reqIDStep)\n@@ -130,7 +130,7 @@ func (conn *connection) NewRequest(creds *auth.Credentials, pid uint32, ino uint\nid: hdr.Unique,\nhdr: &hdr,\ndata: buf,\n- }, nil\n+ }\n}\n// futureResponse represents an in-flight request, that may or may not have\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -71,3 +71,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:setstat_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:mount_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -228,3 +228,15 @@ cc_binary(\n\"//test/util:test_util\",\n],\n)\n+\n+cc_binary(\n+ name = \"mount_test\",\n+ testonly = 1,\n+ srcs = [\"mount_test.cc\"],\n+ deps = [\n+ gtest,\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/mount_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <sys/mount.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+TEST(FuseMount, FDNotParsable) {\n+ int devfd;\n+ EXPECT_THAT(devfd = open(\"/dev/fuse\", O_RDWR), SyscallSucceeds());\n+ std::string mount_opts = \"fd=thiscantbeparsed\";\n+ TempPath mount_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_THAT(mount(\"fuse\", mount_dir.path().c_str(), \"fuse\",\n+ MS_NODEV | MS_NOSUID, mount_opts.c_str()),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Fix error handling on fusefs mount. Don't propagate arbitrary golang errors up from fusefs because errors that don't map to an errno result in a sentry panic. Reported-by: [email protected] PiperOrigin-RevId: 346220306
259,853
09.12.2020 00:42:53
28,800
658f874b94ad83d9b4abed47d9aba856fe5f617c
Prepare for supporting cross compilation.
[ { "change_type": "MODIFY", "old_path": "pkg/flipcall/BUILD", "new_path": "pkg/flipcall/BUILD", "diff": "@@ -11,7 +11,8 @@ go_library(\n\"futex_linux.go\",\n\"io.go\",\n\"packet_window_allocator.go\",\n- \"packet_window_mmap.go\",\n+ \"packet_window_mmap_amd64.go\",\n+ \"packet_window_mmap_arm64.go\",\n],\nvisibility = [\"//visibility:public\"],\ndeps = [\n" }, { "change_type": "RENAME", "old_path": "pkg/flipcall/packet_window_mmap.go", "new_path": "pkg/flipcall/packet_window_mmap_amd64.go", "diff": "" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/flipcall/packet_window_mmap_arm64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package flipcall\n+\n+import (\n+ \"syscall\"\n+)\n+\n+// Return a memory mapping of the pwd in memory that can be shared outside the sandbox.\n+func packetWindowMmap(pwd PacketWindowDescriptor) (uintptr, syscall.Errno) {\n+ m, _, err := syscall.RawSyscall6(syscall.SYS_MMAP, 0, uintptr(pwd.Length), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED, uintptr(pwd.FD), uintptr(pwd.Offset))\n+ return m, err\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/BUILD", "new_path": "pkg/sentry/platform/ring0/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools:defs.bzl\", \"arch_genrule\", \"go_library\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template\", \"go_template_instance\")\npackage(licenses = [\"notice\"])\n@@ -39,19 +39,19 @@ go_template_instance(\ntemplate = \":defs_arm64\",\n)\n-genrule(\n+arch_genrule(\nname = \"entry_impl_amd64\",\nsrcs = [\"entry_amd64.s\"],\nouts = [\"entry_impl_amd64.s\"],\n- cmd = \"(echo -e '// build +amd64\\\\n' && $(location //pkg/sentry/platform/ring0/gen_offsets) && cat $(SRCS)) > $@\",\n+ cmd = \"(echo -e '// build +amd64\\\\n' && QEMU $(location //pkg/sentry/platform/ring0/gen_offsets) && cat $(location entry_amd64.s)) > $@\",\ntools = [\"//pkg/sentry/platform/ring0/gen_offsets\"],\n)\n-genrule(\n+arch_genrule(\nname = \"entry_impl_arm64\",\nsrcs = [\"entry_arm64.s\"],\nouts = [\"entry_impl_arm64.s\"],\n- cmd = \"(echo -e '// build +arm64\\\\n' && $(location //pkg/sentry/platform/ring0/gen_offsets) && cat $(SRCS)) > $@\",\n+ cmd = \"(echo -e '// build +arm64\\\\n' && QEMU $(location //pkg/sentry/platform/ring0/gen_offsets) && cat $(location entry_arm64.s)) > $@\",\ntools = [\"//pkg/sentry/platform/ring0/gen_offsets\"],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/gen_offsets/BUILD", "new_path": "pkg/sentry/platform/ring0/gen_offsets/BUILD", "diff": "@@ -24,6 +24,9 @@ go_binary(\n\"defs_impl_arm64.go\",\n\"main.go\",\n],\n+ # Use the libc malloc to avoid any extra dependencies. This is required to\n+ # pass the sentry deps test.\n+ system_malloc = True,\nvisibility = [\n\"//pkg/sentry/platform/kvm:__pkg__\",\n\"//pkg/sentry/platform/ring0:__pkg__\",\n" }, { "change_type": "MODIFY", "old_path": "tools/bazeldefs/BUILD", "new_path": "tools/bazeldefs/BUILD", "diff": "@@ -58,3 +58,21 @@ bzl_library(\nsrcs = [\"defs.bzl\"],\nvisibility = [\"//visibility:private\"],\n)\n+\n+config_setting(\n+ name = \"linux_arm64_cross\",\n+ values = {\n+ \"cpu\": \"aarch64\",\n+ \"host_cpu\": \"k8\",\n+ },\n+ visibility = [\"//visibility:private\"],\n+)\n+\n+config_setting(\n+ name = \"linux_amd64_cross\",\n+ values = {\n+ \"cpu\": \"k8\",\n+ \"host_cpu\": \"aarch64\",\n+ },\n+ visibility = [\"//visibility:private\"],\n+)\n" }, { "change_type": "MODIFY", "old_path": "tools/bazeldefs/defs.bzl", "new_path": "tools/bazeldefs/defs.bzl", "diff": "@@ -39,3 +39,44 @@ def default_net_util():\ndef coreutil():\nreturn [] # Nothing needed.\n+\n+def select_native_vs_cross(native = [], amd64 = [], arm64 = [], cross = []):\n+ values = {\n+ \"//tools/bazeldefs:linux_arm64_cross\": arm64 + cross,\n+ \"//tools/bazeldefs:linux_amd64_cross\": amd64 + cross,\n+ \"//conditions:default\": native,\n+ }\n+ return select(values)\n+\n+def arch_genrule(name, srcs, outs, cmd, tools):\n+ \"\"\"Runs a gen command on the target architecture.\n+\n+ If the target architecture isn't match the host architecture, it will build\n+ a command for the target architecture and run it via qemu.\n+\n+ The native genrule runs the command on the host architecture.\n+\n+ Args:\n+ name: name of generated target.\n+ srcs: A list of inputs for this rule.\n+ cmd: The command to run. It has to contain \" QEMU \" before executed binaries.\n+ outs: A list of files generated by this rule.\n+ tools: A list of tool dependencies for this rule.\n+ \"\"\"\n+ qemu_arm64 = \"qemu-aarch64-static\"\n+ qemu_amd64 = \"qemu-x86_64-static\"\n+ srcs = select_native_vs_cross(\n+ cross = srcs + tools,\n+ native = srcs,\n+ )\n+ tools = select_native_vs_cross(\n+ cross = [],\n+ native = tools,\n+ )\n+ cmd = select_native_vs_cross(\n+ arm64 = cmd.replace(\"QEMU\", qemu_arm64),\n+ amd64 = cmd.replace(\"QEMU\", qemu_amd64),\n+ native = cmd.replace(\"QEMU\", \"\"),\n+ cross = \"\",\n+ )\n+ native.genrule(name = name, srcs = srcs, outs = outs, cmd = cmd, tools = tools)\n" }, { "change_type": "MODIFY", "old_path": "tools/bazeldefs/go.bzl", "new_path": "tools/bazeldefs/go.bzl", "diff": "@@ -28,7 +28,7 @@ def go_proto_library(name, **kwargs):\ndef go_grpc_and_proto_libraries(name, **kwargs):\n_go_proto_or_grpc_library(_go_grpc_library, name, **kwargs)\n-def go_binary(name, static = False, pure = False, x_defs = None, **kwargs):\n+def go_binary(name, static = False, pure = False, x_defs = None, system_malloc = False, **kwargs):\n\"\"\"Build a go binary.\nArgs:\n@@ -52,7 +52,7 @@ def go_importpath(target):\n\"\"\"Returns the importpath for the target.\"\"\"\nreturn target[GoLibrary].importpath\n-def go_library(name, **kwargs):\n+def go_library(name, arch_deps = [], **kwargs):\n_go_library(\nname = name,\nimportpath = \"gvisor.dev/gvisor/\" + native.package_name(),\n" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -8,7 +8,7 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\nload(\"//tools/nogo:defs.bzl\", \"nogo_test\")\n-load(\"//tools/bazeldefs:defs.bzl\", _build_test = \"build_test\", _bzl_library = \"bzl_library\", _coreutil = \"coreutil\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _more_shards = \"more_shards\", _most_shards = \"most_shards\", _proto_library = \"proto_library\", _rbe_platform = \"rbe_platform\", _rbe_toolchain = \"rbe_toolchain\", _select_arch = \"select_arch\", _select_system = \"select_system\", _short_path = \"short_path\")\n+load(\"//tools/bazeldefs:defs.bzl\", _arch_genrule = \"arch_genrule\", _build_test = \"build_test\", _bzl_library = \"bzl_library\", _coreutil = \"coreutil\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _more_shards = \"more_shards\", _most_shards = \"most_shards\", _proto_library = \"proto_library\", _rbe_platform = \"rbe_platform\", _rbe_toolchain = \"rbe_toolchain\", _select_arch = \"select_arch\", _select_system = \"select_system\", _short_path = \"short_path\")\nload(\"//tools/bazeldefs:cc.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_grpc_library = \"cc_grpc_library\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _gbenchmark = \"gbenchmark\", _grpcpp = \"grpcpp\", _gtest = \"gtest\", _vdso_linker_option = \"vdso_linker_option\")\nload(\"//tools/bazeldefs:go.bzl\", _gazelle = \"gazelle\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_grpc_and_proto_libraries = \"go_grpc_and_proto_libraries\", _go_library = \"go_library\", _go_path = \"go_path\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _select_goarch = \"select_goarch\", _select_goos = \"select_goos\")\nload(\"//tools/bazeldefs:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\n@@ -16,6 +16,7 @@ load(\"//tools/bazeldefs:platforms.bzl\", _default_platform = \"default_platform\",\nload(\"//tools/bazeldefs:tags.bzl\", \"go_suffixes\")\n# Core rules.\n+arch_genrule = _arch_genrule\nbuild_test = _build_test\nbzl_library = _bzl_library\ndefault_installer = _default_installer\n@@ -184,6 +185,7 @@ def go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = F\nname + suffix + \"_state_autogen.go\"\nfor suffix in state_sets.keys()\n]\n+\nif \"//pkg/state\" not in all_deps:\nall_deps = all_deps + [\"//pkg/state\"]\n" } ]
Go
Apache License 2.0
google/gvisor
Prepare for supporting cross compilation. PiperOrigin-RevId: 346496532
259,927
09.12.2020 09:14:45
28,800
f6cb96bd57dec4e3baa8c57ccdeb0f1d8706b682
Cap UDP payload size to length informed in UDP header startblock: has LGTM from peterjohnston and then add reviewer ghanan,tamird
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/udp.go", "new_path": "pkg/tcpip/header/udp.go", "diff": "@@ -36,10 +36,10 @@ const (\n// UDPFields contains the fields of a UDP packet. It is used to describe the\n// fields of a packet that needs to be encoded.\ntype UDPFields struct {\n- // SrcPort is the \"source port\" field of a UDP packet.\n+ // SrcPort is the \"Source Port\" field of a UDP packet.\nSrcPort uint16\n- // DstPort is the \"destination port\" field of a UDP packet.\n+ // DstPort is the \"Destination Port\" field of a UDP packet.\nDstPort uint16\n// Length is the \"length\" field of a UDP packet.\n@@ -64,52 +64,57 @@ const (\nUDPProtocolNumber tcpip.TransportProtocolNumber = 17\n)\n-// SourcePort returns the \"source port\" field of the udp header.\n+// SourcePort returns the \"Source Port\" field of the UDP header.\nfunc (b UDP) SourcePort() uint16 {\nreturn binary.BigEndian.Uint16(b[udpSrcPort:])\n}\n-// DestinationPort returns the \"destination port\" field of the udp header.\n+// DestinationPort returns the \"Destination Port\" field of the UDP header.\nfunc (b UDP) DestinationPort() uint16 {\nreturn binary.BigEndian.Uint16(b[udpDstPort:])\n}\n-// Length returns the \"length\" field of the udp header.\n+// Length returns the \"Length\" field of the UDP header.\nfunc (b UDP) Length() uint16 {\nreturn binary.BigEndian.Uint16(b[udpLength:])\n}\n// Payload returns the data contained in the UDP datagram.\nfunc (b UDP) Payload() []byte {\n- return b[UDPMinimumSize:]\n+ return b[:b.Length()][UDPMinimumSize:]\n}\n-// Checksum returns the \"checksum\" field of the udp header.\n+// Checksum returns the \"checksum\" field of the UDP header.\nfunc (b UDP) Checksum() uint16 {\nreturn binary.BigEndian.Uint16(b[udpChecksum:])\n}\n-// SetSourcePort sets the \"source port\" field of the udp header.\n+// SetSourcePort sets the \"source port\" field of the UDP header.\nfunc (b UDP) SetSourcePort(port uint16) {\nbinary.BigEndian.PutUint16(b[udpSrcPort:], port)\n}\n-// SetDestinationPort sets the \"destination port\" field of the udp header.\n+// SetDestinationPort sets the \"destination port\" field of the UDP header.\nfunc (b UDP) SetDestinationPort(port uint16) {\nbinary.BigEndian.PutUint16(b[udpDstPort:], port)\n}\n-// SetChecksum sets the \"checksum\" field of the udp header.\n+// SetChecksum sets the \"checksum\" field of the UDP header.\nfunc (b UDP) SetChecksum(checksum uint16) {\nbinary.BigEndian.PutUint16(b[udpChecksum:], checksum)\n}\n-// SetLength sets the \"length\" field of the udp header.\n+// SetLength sets the \"length\" field of the UDP header.\nfunc (b UDP) SetLength(length uint16) {\nbinary.BigEndian.PutUint16(b[udpLength:], length)\n}\n-// CalculateChecksum calculates the checksum of the udp packet, given the\n+// PayloadLength returns the length of the payload following the UDP header.\n+func (b UDP) PayloadLength() uint16 {\n+ return b.Length() - UDPMinimumSize\n+}\n+\n+// CalculateChecksum calculates the checksum of the UDP packet, given the\n// checksum of the network-layer pseudo-header and the checksum of the payload.\nfunc (b UDP) CalculateChecksum(partialChecksum uint16) uint16 {\n// Calculate the rest of the checksum.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/BUILD", "new_path": "pkg/tcpip/transport/udp/BUILD", "diff": "@@ -58,5 +58,6 @@ go_test(\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/transport/icmp\",\n\"//pkg/waiter\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -1267,7 +1267,6 @@ func verifyChecksum(hdr header.UDP, pkt *stack.PacketBuffer) bool {\n// HandlePacket is called by the stack when new packets arrive to this transport\n// endpoint.\nfunc (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketBuffer) {\n- // Get the header then trim it from the view.\nhdr := header.UDP(pkt.TransportHeader().View())\nif int(hdr.Length()) > pkt.Data.Size()+header.UDPMinimumSize {\n// Malformed packet.\n@@ -1276,6 +1275,10 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\nreturn\n}\n+ // TODO(gvisor.dev/issues/5033): We should mirror the Network layer and cap\n+ // packets at \"Parse\" instead of when handling a packet.\n+ pkt.Data.CapLength(int(hdr.PayloadLength()))\n+\nif !verifyChecksum(hdr, pkt) {\n// Checksum Error.\ne.stack.Stats().UDP.ChecksumErrors.Increment()\n@@ -1309,7 +1312,7 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\nsenderAddress: tcpip.FullAddress{\nNIC: pkt.NICID,\nAddr: id.RemoteAddress,\n- Port: header.UDP(hdr).SourcePort(),\n+ Port: hdr.SourcePort(),\n},\n}\npacket.data = pkt.Data\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"testing\"\n\"time\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n@@ -1827,27 +1828,31 @@ func TestV4UnknownDestination(t *testing.T) {\nicmpPkt := header.ICMPv4(hdr.Payload())\npayloadIPHeader := header.IPv4(icmpPkt.Payload())\nincomingHeaderLength := header.IPv4MinimumSize + header.UDPMinimumSize\n- wantLen := len(payload)\n+ wantPayloadLen := len(payload)\nif tc.largePayload {\n// To work out the data size we need to simulate what the sender would\n// have done. The wanted size is the total available minus the sum of\n// the headers in the UDP AND ICMP packets, given that we know the test\n// had only a minimal IP header but the ICMP sender will have allowed\n// for a maximally sized packet header.\n- wantLen = header.IPv4MinimumProcessableDatagramSize - header.IPv4MaximumHeaderSize - header.ICMPv4MinimumSize - incomingHeaderLength\n+ wantPayloadLen = header.IPv4MinimumProcessableDatagramSize - header.IPv4MaximumHeaderSize - header.ICMPv4MinimumSize - incomingHeaderLength\n}\n// In the case of large payloads the IP packet may be truncated. Update\n// the length field before retrieving the udp datagram payload.\n// Add back the two headers within the payload.\n- payloadIPHeader.SetTotalLength(uint16(wantLen + incomingHeaderLength))\n-\n+ payloadIPHeader.SetTotalLength(uint16(wantPayloadLen + incomingHeaderLength))\norigDgram := header.UDP(payloadIPHeader.Payload())\n- if got, want := len(origDgram.Payload()), wantLen; got != want {\n- t.Fatalf(\"unexpected payload length got: %d, want: %d\", got, want)\n+ wantDgramLen := wantPayloadLen + header.UDPMinimumSize\n+\n+ if got, want := len(origDgram), wantDgramLen; got != want {\n+ t.Fatalf(\"got len(origDgram) = %d, want = %d\", got, want)\n}\n- if got, want := origDgram.Payload(), payload[:wantLen]; !bytes.Equal(got, want) {\n- t.Fatalf(\"unexpected payload got: %d, want: %d\", got, want)\n+ // Correct UDP length to access payload.\n+ origDgram.SetLength(uint16(wantDgramLen))\n+\n+ if got, want := origDgram.Payload(), payload[:wantPayloadLen]; !bytes.Equal(got, want) {\n+ t.Fatalf(\"got origDgram.Payload() = %x, want = %x\", got, want)\n}\n})\n}\n@@ -1922,20 +1927,23 @@ func TestV6UnknownDestination(t *testing.T) {\nicmpPkt := header.ICMPv6(hdr.Payload())\npayloadIPHeader := header.IPv6(icmpPkt.Payload())\n- wantLen := len(payload)\n+ wantPayloadLen := len(payload)\nif tc.largePayload {\n- wantLen = header.IPv6MinimumMTU - header.IPv6MinimumSize*2 - header.ICMPv6MinimumSize - header.UDPMinimumSize\n+ wantPayloadLen = header.IPv6MinimumMTU - header.IPv6MinimumSize*2 - header.ICMPv6MinimumSize - header.UDPMinimumSize\n}\n+ wantDgramLen := wantPayloadLen + header.UDPMinimumSize\n// In case of large payloads the IP packet may be truncated. Update\n// the length field before retrieving the udp datagram payload.\n- payloadIPHeader.SetPayloadLength(uint16(wantLen + header.UDPMinimumSize))\n+ payloadIPHeader.SetPayloadLength(uint16(wantDgramLen))\norigDgram := header.UDP(payloadIPHeader.Payload())\n- if got, want := len(origDgram.Payload()), wantLen; got != want {\n- t.Fatalf(\"unexpected payload length got: %d, want: %d\", got, want)\n+ if got, want := len(origDgram), wantPayloadLen+header.UDPMinimumSize; got != want {\n+ t.Fatalf(\"got len(origDgram) = %d, want = %d\", got, want)\n}\n- if got, want := origDgram.Payload(), payload[:wantLen]; !bytes.Equal(got, want) {\n- t.Fatalf(\"unexpected payload got: %v, want: %v\", got, want)\n+ // Correct UDP length to access payload.\n+ origDgram.SetLength(uint16(wantPayloadLen + header.UDPMinimumSize))\n+ if got, want := origDgram.Payload(), payload[:wantPayloadLen]; !bytes.Equal(got, want) {\n+ t.Fatalf(\"got origDgram.Payload() = %x, want = %x\", got, want)\n}\n})\n}\n@@ -2448,3 +2456,67 @@ func TestOutgoingSubnetBroadcast(t *testing.T) {\n})\n}\n}\n+\n+func TestReceiveShortLength(t *testing.T) {\n+ flows := []testFlow{unicastV4, unicastV6}\n+ for _, flow := range flows {\n+ t.Run(flow.String(), func(t *testing.T) {\n+ c := newDualTestContext(t, defaultMTU)\n+ defer c.cleanup()\n+\n+ c.createEndpointForFlow(flow)\n+\n+ // Bind to wildcard.\n+ bindAddr := tcpip.FullAddress{Port: stackPort}\n+ if err := c.ep.Bind(bindAddr); err != nil {\n+ c.t.Fatalf(\"c.ep.Bind(%#v): %s\", bindAddr, err)\n+ }\n+\n+ payload := newPayload()\n+ extraBytes := []byte{1, 2, 3, 4}\n+ h := flow.header4Tuple(incoming)\n+ var buf buffer.View\n+ var proto tcpip.NetworkProtocolNumber\n+\n+ // Build packets with extra bytes not accounted for in the UDP length\n+ // field.\n+ var udp header.UDP\n+ if flow.isV4() {\n+ buf = c.buildV4Packet(payload, &h)\n+ buf = append(buf, extraBytes...)\n+ ip := header.IPv4(buf)\n+ ip.SetTotalLength(ip.TotalLength() + uint16(len(extraBytes)))\n+ ip.SetChecksum(0)\n+ ip.SetChecksum(^ip.CalculateChecksum())\n+ proto = ipv4.ProtocolNumber\n+ udp = ip.Payload()\n+ } else {\n+ buf = c.buildV6Packet(payload, &h)\n+ buf = append(buf, extraBytes...)\n+ ip := header.IPv6(buf)\n+ ip.SetPayloadLength(ip.PayloadLength() + uint16(len(extraBytes)))\n+ proto = ipv6.ProtocolNumber\n+ udp = ip.Payload()\n+ }\n+\n+ if diff := cmp.Diff(payload, udp.Payload()); diff != \"\" {\n+ t.Errorf(\"udp.Payload() mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ c.linkEP.InjectInbound(proto, stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: buf.ToVectorisedView(),\n+ }))\n+\n+ // Try to receive the data.\n+ v, _, err := c.ep.Read(nil)\n+ if err != nil {\n+ t.Fatalf(\"c.ep.Read(..): %s\", err)\n+ }\n+\n+ // Check the payload is read back without extra bytes.\n+ if diff := cmp.Diff(buffer.View(payload), v); diff != \"\" {\n+ t.Errorf(\"c.ep.Read(..) mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Cap UDP payload size to length informed in UDP header startblock: has LGTM from peterjohnston and then add reviewer ghanan,tamird PiperOrigin-RevId: 346565589
260,004
09.12.2020 10:50:42
28,800
50189b0d6f2401f842f63ae149de13b89b4c30f9
Do not perform IGMP/MLD on loopback interfaces The loopback interface will never have any neighbouring nodes so advertising its interest in multicast groups is unnecessary. Bug Startblock: has LGTM from asfez and then add reviewer tamird
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "new_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "diff": "@@ -161,7 +161,8 @@ type GenericMulticastProtocolState struct {\n// Init initializes the Generic Multicast Protocol state.\n//\n-// Must only be called once for the lifetime of g.\n+// Must only be called once for the lifetime of g; Init will panic if it is\n+// called twice.\n//\n// The GenericMulticastProtocolState will only grab the lock when timers/jobs\n// fire.\n@@ -170,9 +171,11 @@ func (g *GenericMulticastProtocolState) Init(protocolMU *sync.RWMutex, opts Gene\npanic(\"attempted to initialize generic membership protocol state twice\")\n}\n- g.opts = opts\n- g.memberships = make(map[tcpip.Address]multicastGroupState)\n- g.protocolMU = protocolMU\n+ *g = GenericMulticastProtocolState{\n+ opts: opts,\n+ memberships: make(map[tcpip.Address]multicastGroupState),\n+ protocolMU: protocolMU,\n+ }\n}\n// MakeAllNonMemberLocked transitions all groups to the non-member state.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/igmp.go", "new_path": "pkg/tcpip/network/ipv4/igmp.go", "diff": "@@ -57,6 +57,9 @@ type IGMPOptions struct {\n// When enabled, IGMP may transmit IGMP report and leave messages when\n// joining and leaving multicast groups respectively, and handle incoming\n// IGMP packets.\n+ //\n+ // This field is ignored and is always assumed to be false for interfaces\n+ // without neighbouring nodes (e.g. loopback).\nEnabled bool\n}\n@@ -69,6 +72,8 @@ type igmpState struct {\n// The IPv4 endpoint this igmpState is for.\nep *endpoint\n+ enabled bool\n+\ngenericMulticastProtocol ip.GenericMulticastProtocolState\n// igmpV1Present is for maintaining compatibility with IGMPv1 Routers, from\n@@ -117,8 +122,11 @@ func (igmp *igmpState) SendLeave(groupAddress tcpip.Address) *tcpip.Error {\n// Must only be called once for the lifetime of igmp.\nfunc (igmp *igmpState) init(ep *endpoint) {\nigmp.ep = ep\n+ // No need to perform IGMP on loopback interfaces since they don't have\n+ // neighbouring nodes.\n+ igmp.enabled = ep.protocol.options.IGMP.Enabled && !igmp.ep.nic.IsLoopback()\nigmp.genericMulticastProtocol.Init(&ep.mu.RWMutex, ip.GenericMulticastProtocolOptions{\n- Enabled: ep.protocol.options.IGMP.Enabled,\n+ Enabled: igmp.enabled,\nRand: ep.protocol.stack.Rand(),\nClock: ep.protocol.stack.Clock(),\nProtocol: igmp,\n@@ -210,7 +218,7 @@ func (igmp *igmpState) handleMembershipQuery(groupAddress tcpip.Address, maxResp\n// As per RFC 2236 Section 6, Page 10: If the maximum response time is zero\n// then change the state to note that an IGMPv1 router is present and\n// schedule the query received Job.\n- if maxRespTime == 0 && igmp.ep.protocol.options.IGMP.Enabled {\n+ if igmp.enabled && maxRespTime == 0 {\nigmp.igmpV1Job.Cancel()\nigmp.igmpV1Job.Schedule(v1RouterPresentTimeout)\nigmp.setV1Present(true)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/mld.go", "new_path": "pkg/tcpip/network/ipv6/mld.go", "diff": "@@ -40,6 +40,9 @@ type MLDOptions struct {\n// When enabled, MLD may transmit MLD report and done messages when\n// joining and leaving multicast groups respectively, and handle incoming\n// MLD packets.\n+ //\n+ // This field is ignored and is always assumed to be false for interfaces\n+ // without neighbouring nodes (e.g. loopback).\nEnabled bool\n}\n@@ -72,7 +75,9 @@ func (mld *mldState) SendLeave(groupAddress tcpip.Address) *tcpip.Error {\nfunc (mld *mldState) init(ep *endpoint) {\nmld.ep = ep\nmld.genericMulticastProtocol.Init(&ep.mu.RWMutex, ip.GenericMulticastProtocolOptions{\n- Enabled: ep.protocol.options.MLD.Enabled,\n+ // No need to perform MLD on loopback interfaces since they don't have\n+ // neighbouring nodes.\n+ Enabled: ep.protocol.options.MLD.Enabled && !mld.ep.nic.IsLoopback(),\nRand: ep.protocol.stack.Rand(),\nClock: ep.protocol.stack.Clock(),\nProtocol: mld,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/multicast_group_test.go", "new_path": "pkg/tcpip/network/multicast_group_test.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -104,7 +105,14 @@ func createStack(t *testing.T, mgpEnabled bool) (*channel.Endpoint, *stack.Stack\n// Create an endpoint of queue size 2, since no more than 2 packets are ever\n// queued in the tests in this file.\n- e := channel.New(2, 1280, linkAddr)\n+ e := channel.New(2, header.IPv6MinimumMTU, linkAddr)\n+ s, clock := createStackWithLinkEndpoint(t, mgpEnabled, e)\n+ return e, s, clock\n+}\n+\n+func createStackWithLinkEndpoint(t *testing.T, mgpEnabled bool, e stack.LinkEndpoint) (*stack.Stack, *faketime.ManualClock) {\n+ t.Helper()\n+\nclock := faketime.NewManualClock()\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{\n@@ -125,7 +133,7 @@ func createStack(t *testing.T, mgpEnabled bool) (*channel.Endpoint, *stack.Stack\nt.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n}\n- return e, s, clock\n+ return s, clock\n}\n// createAndInjectIGMPPacket creates and injects an IGMP packet with the\n@@ -1067,3 +1075,59 @@ func TestMGPWithNICLifecycle(t *testing.T) {\n})\n}\n}\n+\n+// TestMGPDisabledOnLoopback tests that the multicast group protocol is not\n+// performed on loopback interfaces since they have no neighbours.\n+func TestMGPDisabledOnLoopback(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ protoNum tcpip.NetworkProtocolNumber\n+ multicastAddr tcpip.Address\n+ sentReportStat func(*stack.Stack) *tcpip.StatCounter\n+ }{\n+ {\n+ name: \"IGMP\",\n+ protoNum: ipv4.ProtocolNumber,\n+ multicastAddr: ipv4MulticastAddr1,\n+ sentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n+ return s.Stats().IGMP.PacketsSent.V2MembershipReport\n+ },\n+ },\n+ {\n+ name: \"MLD\",\n+ protoNum: ipv6.ProtocolNumber,\n+ multicastAddr: ipv6MulticastAddr1,\n+ sentReportStat: func(s *stack.Stack) *tcpip.StatCounter {\n+ return s.Stats().ICMP.V6.PacketsSent.MulticastListenerReport\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s, clock := createStackWithLinkEndpoint(t, true /* mgpEnabled */, loopback.New())\n+\n+ sentReportStat := test.sentReportStat(s)\n+ if got := sentReportStat.Value(); got != 0 {\n+ t.Fatalf(\"got sentReportStat.Value() = %d, want = 0\", got)\n+ }\n+ clock.Advance(time.Hour)\n+ if got := sentReportStat.Value(); got != 0 {\n+ t.Fatalf(\"got sentReportStat.Value() = %d, want = 0\", got)\n+ }\n+\n+ // Test joining a specific group explicitly and verify that no reports are\n+ // sent.\n+ if err := s.JoinGroup(test.protoNum, nicID, test.multicastAddr); err != nil {\n+ t.Fatalf(\"JoinGroup(%d, %d, %s): %s\", test.protoNum, nicID, test.multicastAddr, err)\n+ }\n+ if got := sentReportStat.Value(); got != 0 {\n+ t.Fatalf(\"got sentReportStat.Value() = %d, want = 0\", got)\n+ }\n+ clock.Advance(time.Hour)\n+ if got := sentReportStat.Value(); got != 0 {\n+ t.Fatalf(\"got sentReportStat.Value() = %d, want = 0\", got)\n+ }\n+ })\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Do not perform IGMP/MLD on loopback interfaces The loopback interface will never have any neighbouring nodes so advertising its interest in multicast groups is unnecessary. Bug #4682, #4861 Startblock: has LGTM from asfez and then add reviewer tamird PiperOrigin-RevId: 346587604
259,975
09.12.2020 11:55:06
28,800
992769c7748d886e7ee1580f0c6cfdfa7ce0eb75
Add tensorflow, ffmpeg, and redis jobs.
[ { "change_type": "MODIFY", "old_path": "BUILD", "new_path": "BUILD", "diff": "@@ -67,11 +67,11 @@ build_test(\n\"//test/benchmarks/base:startup_test\",\n\"//test/benchmarks/base:size_test\",\n\"//test/benchmarks/base:sysbench_test\",\n- \"//test/benchmarks/database:database_test\",\n+ \"//test/benchmarks/database:redis_test\",\n\"//test/benchmarks/fs:bazel_test\",\n\"//test/benchmarks/fs:fio_test\",\n- \"//test/benchmarks/media:media_test\",\n- \"//test/benchmarks/ml:ml_test\",\n+ \"//test/benchmarks/media:ffmpeg_test\",\n+ \"//test/benchmarks/ml:tensorflow_test\",\n\"//test/benchmarks/network:network_test\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/database/BUILD", "new_path": "test/benchmarks/database/BUILD", "diff": "@@ -7,11 +7,10 @@ go_library(\nname = \"database\",\ntestonly = 1,\nsrcs = [\"database.go\"],\n- deps = [\"//test/benchmarks/harness\"],\n)\nbenchmark_test(\n- name = \"database_test\",\n+ name = \"redis_test\",\nsize = \"enormous\",\nsrcs = [\"redis_test.go\"],\nlibrary = \":database\",\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/database/database.go", "new_path": "test/benchmarks/database/database.go", "diff": "// Package database holds benchmarks around database applications.\npackage database\n-\n-import (\n- \"os\"\n- \"testing\"\n-\n- \"gvisor.dev/gvisor/test/benchmarks/harness\"\n-)\n-\n-var h harness.Harness\n-\n-// TestMain is the main method for package database.\n-func TestMain(m *testing.M) {\n- h.Init()\n- os.Exit(m.Run())\n-}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/database/redis_test.go", "new_path": "test/benchmarks/database/redis_test.go", "diff": "@@ -16,6 +16,7 @@ package database\nimport (\n\"context\"\n+ \"os\"\n\"testing\"\n\"time\"\n@@ -24,6 +25,8 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// All possible operations from redis. Note: \"ping\" will\n// run both PING_INLINE and PING_BUILD.\nvar operations []string = []string{\n@@ -111,12 +114,11 @@ func BenchmarkRedis(b *testing.B) {\n// Reset profiles and timer to begin the measurement.\nserver.RestartProfiles()\nb.ResetTimer()\n- for i := 0; i < b.N; i++ {\nclient := clientMachine.GetNativeContainer(ctx, b)\ndefer client.CleanUp(ctx)\nout, err := client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/redis\",\n- }, redis.MakeCmd(ip, serverPort)...)\n+ }, redis.MakeCmd(ip, serverPort, b.N /*requests*/)...)\nif err != nil {\nb.Fatalf(\"redis-benchmark failed with: %v\", err)\n}\n@@ -124,8 +126,11 @@ func BenchmarkRedis(b *testing.B) {\n// Stop time while we parse results.\nb.StopTimer()\nredis.Report(b, out)\n- b.StartTimer()\n- }\n})\n}\n}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/media/BUILD", "new_path": "test/benchmarks/media/BUILD", "diff": "@@ -7,12 +7,11 @@ go_library(\nname = \"media\",\ntestonly = 1,\nsrcs = [\"media.go\"],\n- deps = [\"//test/benchmarks/harness\"],\n)\nbenchmark_test(\n- name = \"media_test\",\n- size = \"large\",\n+ name = \"ffmpeg_test\",\n+ size = \"enormous\",\nsrcs = [\"ffmpeg_test.go\"],\nlibrary = \":media\",\nvisibility = [\"//:sandbox\"],\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/media/ffmpeg_test.go", "new_path": "test/benchmarks/media/ffmpeg_test.go", "diff": "@@ -15,6 +15,7 @@ package media\nimport (\n\"context\"\n+ \"os\"\n\"strings\"\n\"testing\"\n@@ -22,6 +23,8 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n)\n+var h harness.Harness\n+\n// BenchmarkFfmpeg runs ffmpeg in a container and records runtime.\n// BenchmarkFfmpeg should run as root to drop caches.\nfunc BenchmarkFfmpeg(b *testing.B) {\n@@ -32,13 +35,13 @@ func BenchmarkFfmpeg(b *testing.B) {\ndefer machine.CleanUp()\nctx := context.Background()\n- container := machine.GetContainer(ctx, b)\n- defer container.CleanUp(ctx)\ncmd := strings.Split(\"ffmpeg -i video.mp4 -c:v libx264 -preset veryslow output.mp4\", \" \")\nb.ResetTimer()\nfor i := 0; i < b.N; i++ {\nb.StopTimer()\n+ container := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\nif err := harness.DropCaches(machine); err != nil {\nb.Skipf(\"failed to drop caches: %v. You probably need root.\", err)\n}\n@@ -51,3 +54,8 @@ func BenchmarkFfmpeg(b *testing.B) {\n}\n}\n}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/media/media.go", "new_path": "test/benchmarks/media/media.go", "diff": "// Package media holds benchmarks around media processing applications.\npackage media\n-\n-import (\n- \"os\"\n- \"testing\"\n-\n- \"gvisor.dev/gvisor/test/benchmarks/harness\"\n-)\n-\n-var h harness.Harness\n-\n-// TestMain is the main method for package media.\n-func TestMain(m *testing.M) {\n- h.Init()\n- os.Exit(m.Run())\n-}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/BUILD", "new_path": "test/benchmarks/ml/BUILD", "diff": "@@ -7,12 +7,11 @@ go_library(\nname = \"ml\",\ntestonly = 1,\nsrcs = [\"ml.go\"],\n- deps = [\"//test/benchmarks/harness\"],\n)\nbenchmark_test(\n- name = \"ml_test\",\n- size = \"large\",\n+ name = \"tensorflow_test\",\n+ size = \"enormous\",\nsrcs = [\"tensorflow_test.go\"],\nlibrary = \":ml\",\nvisibility = [\"//:sandbox\"],\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/ml.go", "new_path": "test/benchmarks/ml/ml.go", "diff": "// Package ml holds benchmarks around machine learning performance.\npackage ml\n-\n-import (\n- \"os\"\n- \"testing\"\n-\n- \"gvisor.dev/gvisor/test/benchmarks/harness\"\n-)\n-\n-var h harness.Harness\n-\n-// TestMain is the main method for package ml.\n-func TestMain(m *testing.M) {\n- h.Init()\n- os.Exit(m.Run())\n-}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/tensorflow_test.go", "new_path": "test/benchmarks/ml/tensorflow_test.go", "diff": "@@ -15,12 +15,15 @@ package ml\nimport (\n\"context\"\n+ \"os\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n)\n+var h harness.Harness\n+\n// BenchmarkTensorflow runs workloads from a TensorFlow tutorial.\n// See: https://github.com/aymericdamien/TensorFlow-Examples\nfunc BenchmarkTensorflow(b *testing.B) {\n@@ -44,12 +47,12 @@ func BenchmarkTensorflow(b *testing.B) {\nfor name, workload := range workloads {\nb.Run(name, func(b *testing.B) {\nctx := context.Background()\n- container := machine.GetContainer(ctx, b)\n- defer container.CleanUp(ctx)\nb.ResetTimer()\nfor i := 0; i < b.N; i++ {\nb.StopTimer()\n+ container := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\nif err := harness.DropCaches(machine); err != nil {\nb.Skipf(\"failed to drop caches: %v. You probably need root.\", err)\n}\n@@ -67,3 +70,8 @@ func BenchmarkTensorflow(b *testing.B) {\n}\n}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/redis.go", "new_path": "test/benchmarks/tools/redis.go", "diff": "@@ -29,17 +29,17 @@ type Redis struct {\n}\n// MakeCmd returns a redis-benchmark client command.\n-func (r *Redis) MakeCmd(ip net.IP, port int) []string {\n+func (r *Redis) MakeCmd(ip net.IP, port, requests int) []string {\n// There is no -t PING_BULK for redis-benchmark, so adjust the command in that case.\n// Note that \"ping\" will run both PING_INLINE and PING_BULK.\nif r.Operation == \"PING_BULK\" {\nreturn strings.Split(\n- fmt.Sprintf(\"redis-benchmark --csv -t ping -h %s -p %d\", ip, port), \" \")\n+ fmt.Sprintf(\"redis-benchmark --csv -t ping -h %s -p %d -n %d\", ip, port, requests), \" \")\n}\n// runs redis-benchmark -t operation for 100K requests against server.\nreturn strings.Split(\n- fmt.Sprintf(\"redis-benchmark --csv -t %s -h %s -p %d\", r.Operation, ip, port), \" \")\n+ fmt.Sprintf(\"redis-benchmark --csv -t %s -h %s -p %d -n %d\", r.Operation, ip, port, requests), \" \")\n}\n// Report parses output from redis-benchmark client and reports metrics.\n" } ]
Go
Apache License 2.0
google/gvisor
Add tensorflow, ffmpeg, and redis jobs. PiperOrigin-RevId: 346603153
259,975
09.12.2020 13:49:41
28,800
b4af9d4572707718514e66b7e537bc51216b60f6
Add network benchmarks jobs Add httpd, nginx, node, and ruby benchmarks to continuous jobs.
[ { "change_type": "MODIFY", "old_path": "BUILD", "new_path": "BUILD", "diff": "@@ -72,7 +72,10 @@ build_test(\n\"//test/benchmarks/fs:fio_test\",\n\"//test/benchmarks/media:ffmpeg_test\",\n\"//test/benchmarks/ml:tensorflow_test\",\n- \"//test/benchmarks/network:network_test\",\n+ \"//test/benchmarks/network:httpd_test\",\n+ \"//test/benchmarks/network:nginx_test\",\n+ \"//test/benchmarks/network:node_test\",\n+ \"//test/benchmarks/network:ruby_test\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/BUILD", "new_path": "test/benchmarks/network/BUILD", "diff": "@@ -8,7 +8,6 @@ go_library(\ntestonly = 1,\nsrcs = [\n\"network.go\",\n- \"static_server.go\",\n],\ndeps = [\n\"//pkg/test/dockerutil\",\n@@ -18,17 +17,74 @@ go_library(\n)\nbenchmark_test(\n- name = \"network_test\",\n- size = \"large\",\n+ name = \"iperf_test\",\n+ size = \"enormous\",\nsrcs = [\n- \"httpd_test.go\",\n\"iperf_test.go\",\n- \"nginx_test.go\",\n+ ],\n+ library = \":network\",\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//pkg/test/testutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n+\n+benchmark_test(\n+ name = \"node_test\",\n+ size = \"enormous\",\n+ srcs = [\n\"node_test.go\",\n+ ],\n+ library = \":network\",\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n+\n+benchmark_test(\n+ name = \"ruby_test\",\n+ size = \"enormous\",\n+ srcs = [\n\"ruby_test.go\",\n],\nlibrary = \":network\",\nvisibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n+\n+benchmark_test(\n+ name = \"nginx_test\",\n+ size = \"enormous\",\n+ srcs = [\n+ \"nginx_test.go\",\n+ ],\n+ library = \":network\",\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n+\n+benchmark_test(\n+ name = \"httpd_test\",\n+ size = \"enormous\",\n+ srcs = [\n+ \"httpd_test.go\",\n+ ],\n+ library = \":network\",\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//pkg/test/testutil\",\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/httpd_test.go", "new_path": "test/benchmarks/network/httpd_test.go", "diff": "package network\nimport (\n+ \"os\"\n\"strconv\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// see Dockerfile '//images/benchmarks/httpd'.\nvar httpdDocs = map[string]string{\n\"notfound\": \"notfound\",\n@@ -43,6 +47,22 @@ func BenchmarkReverseHttpd(b *testing.B) {\nbenchmarkHttpdDocSize(b, true /* reverse */)\n}\n+// BenchmarkContinuousHttpd runs specific benchmarks for continous jobs.\n+// The runtime under test is the server serving a runc client.\n+func BenchmarkContinuousHttpd(b *testing.B) {\n+ sizes := []string{\"10Kb\", \"100Kb\", \"1Mb\"}\n+ threads := []int{1, 25, 100, 1000}\n+ benchmarkHttpdContinuous(b, threads, sizes, false /*reverse*/)\n+}\n+\n+// BenchmarkContinuousHttpdReverse runs specific benchmarks for continous jobs.\n+// The runtime under test is the client downloading from a runc server.\n+func BenchmarkContinuousHttpdReverse(b *testing.B) {\n+ sizes := []string{\"10Kb\", \"100Kb\", \"1Mb\"}\n+ threads := []int{1, 25, 100, 1000}\n+ benchmarkHttpdContinuous(b, threads, sizes, true /*reverse*/)\n+}\n+\n// benchmarkHttpdDocSize iterates through all doc sizes, running subbenchmarks\n// for each size.\nfunc benchmarkHttpdDocSize(b *testing.B, reverse bool) {\n@@ -74,6 +94,42 @@ func benchmarkHttpdDocSize(b *testing.B, reverse bool) {\n}\n}\n+// benchmarkHttpdContinuous iterates through given sizes and concurrencies.\n+func benchmarkHttpdContinuous(b *testing.B, concurrency []int, sizes []string, reverse bool) {\n+ for _, size := range sizes {\n+ filename := httpdDocs[size]\n+ for _, c := range concurrency {\n+ fsize := tools.Parameter{\n+ Name: \"filesize\",\n+ Value: size,\n+ }\n+\n+ threads := tools.Parameter{\n+ Name: \"concurrency\",\n+ Value: strconv.Itoa(c),\n+ }\n+\n+ name, err := tools.ParametersToName(fsize, threads)\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse parameters: %v\", err)\n+ }\n+\n+ requests := b.N\n+ if requests < c {\n+ requests = c\n+ }\n+ b.Run(name, func(b *testing.B) {\n+ hey := &tools.Hey{\n+ Requests: requests,\n+ Concurrency: c,\n+ Doc: filename,\n+ }\n+ runHttpd(b, hey, reverse)\n+ })\n+ }\n+ }\n+}\n+\n// runHttpd configures the static serving methods to run httpd.\nfunc runHttpd(b *testing.B, hey *tools.Hey, reverse bool) {\n// httpd runs on port 80.\n@@ -91,5 +147,10 @@ func runHttpd(b *testing.B, hey *tools.Hey, reverse bool) {\n},\n}\nhttpdCmd := []string{\"sh\", \"-c\", \"mkdir -p /tmp/html; cp -r /local/* /tmp/html/.; apache2 -X\"}\n- runStaticServer(b, httpdRunOpts, httpdCmd, port, hey, reverse)\n+ runStaticServer(b, h, httpdRunOpts, httpdCmd, port, hey, reverse)\n+}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/iperf_test.go", "new_path": "test/benchmarks/network/iperf_test.go", "diff": "@@ -15,6 +15,7 @@ package network\nimport (\n\"context\"\n+ \"os\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n@@ -23,9 +24,11 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\nfunc BenchmarkIperf(b *testing.B) {\niperf := tools.Iperf{\n- Time: 10, // time in seconds to run client.\n+ Time: b.N, // time in seconds to run client.\n}\nclientMachine, err := h.GetMachine()\n@@ -97,7 +100,6 @@ func BenchmarkIperf(b *testing.B) {\n// Restart the server profiles. If the server isn't being profiled\n// this does nothing.\nserver.RestartProfiles()\n- for i := 0; i < b.N; i++ {\nout, err := client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/iperf\",\n}, iperf.MakeCmd(ip, servingPort)...)\n@@ -106,8 +108,11 @@ func BenchmarkIperf(b *testing.B) {\n}\nb.StopTimer()\niperf.Report(b, out)\n- b.StartTimer()\n- }\n})\n}\n}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/network.go", "new_path": "test/benchmarks/network/network.go", "diff": "package network\nimport (\n- \"os\"\n+ \"context\"\n\"testing\"\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n+ \"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n-var h harness.Harness\n+// runStaticServer runs static serving workloads (httpd, nginx).\n+func runStaticServer(b *testing.B, h harness.Harness, serverOpts dockerutil.RunOpts, serverCmd []string, port int, hey *tools.Hey, reverse bool) {\n+ ctx := context.Background()\n-// TestMain is the main method for package network.\n-func TestMain(m *testing.M) {\n- h.Init()\n- os.Exit(m.Run())\n+ // Get two machines: a client and server.\n+ clientMachine, err := h.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer clientMachine.CleanUp()\n+\n+ serverMachine, err := h.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer serverMachine.CleanUp()\n+\n+ // Make the containers. 'reverse=true' specifies that the client should use the\n+ // runtime under test.\n+ var client, server *dockerutil.Container\n+ if reverse {\n+ client = clientMachine.GetContainer(ctx, b)\n+ server = serverMachine.GetNativeContainer(ctx, b)\n+ } else {\n+ client = clientMachine.GetNativeContainer(ctx, b)\n+ server = serverMachine.GetContainer(ctx, b)\n+ }\n+ defer client.CleanUp(ctx)\n+ defer server.CleanUp(ctx)\n+\n+ // Start the server.\n+ if err := server.Spawn(ctx, serverOpts, serverCmd...); err != nil {\n+ b.Fatalf(\"failed to start server: %v\", err)\n+ }\n+\n+ // Get its IP.\n+ ip, err := serverMachine.IPAddress()\n+ if err != nil {\n+ b.Fatalf(\"failed to find server ip: %v\", err)\n+ }\n+\n+ // Get the published port.\n+ servingPort, err := server.FindPort(ctx, port)\n+ if err != nil {\n+ b.Fatalf(\"failed to find server port %d: %v\", port, err)\n+ }\n+\n+ // Make sure the server is serving.\n+ harness.WaitUntilServing(ctx, clientMachine, ip, servingPort)\n+ b.ResetTimer()\n+ server.RestartProfiles()\n+ out, err := client.Run(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/hey\",\n+ }, hey.MakeCmd(ip, servingPort)...)\n+ if err != nil {\n+ b.Fatalf(\"run failed with: %v\", err)\n+ }\n+\n+ b.StopTimer()\n+ hey.Report(b, out)\n+ b.StartTimer()\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/nginx_test.go", "new_path": "test/benchmarks/network/nginx_test.go", "diff": "package network\nimport (\n+ \"os\"\n\"strconv\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// see Dockerfile '//images/benchmarks/nginx'.\nvar nginxDocs = map[string]string{\n\"notfound\": \"notfound\",\n@@ -44,6 +48,22 @@ func BenchmarkReverseNginxDocSize(b *testing.B) {\nbenchmarkNginxDocSize(b, true /* reverse */, true /* tmpfs */)\n}\n+// BenchmarkContinuousNginx runs specific benchmarks for continous jobs.\n+// The runtime under test is the sever serving a runc client.\n+func BenchmarkContinuousNginx(b *testing.B) {\n+ sizes := []string{\"10Kb\", \"100Kb\", \"1Mb\"}\n+ threads := []int{1, 25, 100, 1000}\n+ benchmarkNginxContinuous(b, threads, sizes, false /*reverse*/)\n+}\n+\n+// BenchmarkContinuousNginxReverse runs specific benchmarks for continous jobs.\n+// The runtime under test is the client downloading from a runc server.\n+func BenchmarkContinuousNginxReverse(b *testing.B) {\n+ sizes := []string{\"10Kb\", \"100Kb\", \"1Mb\"}\n+ threads := []int{1, 25, 100, 1000}\n+ benchmarkNginxContinuous(b, threads, sizes, true /*reverse*/)\n+}\n+\n// benchmarkNginxDocSize iterates through all doc sizes, running subbenchmarks\n// for each size.\nfunc benchmarkNginxDocSize(b *testing.B, reverse, tmpfs bool) {\n@@ -84,6 +104,47 @@ func benchmarkNginxDocSize(b *testing.B, reverse, tmpfs bool) {\n}\n}\n+// benchmarkNginxContinuous iterates through given sizes and concurrencies on a tmpfs mount.\n+func benchmarkNginxContinuous(b *testing.B, concurrency []int, sizes []string, reverse bool) {\n+ for _, size := range sizes {\n+ filename := nginxDocs[size]\n+ for _, c := range concurrency {\n+ fsize := tools.Parameter{\n+ Name: \"filesize\",\n+ Value: size,\n+ }\n+\n+ threads := tools.Parameter{\n+ Name: \"concurrency\",\n+ Value: strconv.Itoa(c),\n+ }\n+\n+ fs := tools.Parameter{\n+ Name: \"filesystem\",\n+ Value: \"tmpfs\",\n+ }\n+\n+ name, err := tools.ParametersToName(fsize, threads, fs)\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse parameters: %v\", err)\n+ }\n+\n+ requests := b.N\n+ if requests < c {\n+ requests = c\n+ }\n+ b.Run(name, func(b *testing.B) {\n+ hey := &tools.Hey{\n+ Requests: requests,\n+ Concurrency: c,\n+ Doc: filename,\n+ }\n+ runNginx(b, hey, reverse, true /*tmpfs*/)\n+ })\n+ }\n+ }\n+}\n+\n// runNginx configures the static serving methods to run httpd.\nfunc runNginx(b *testing.B, hey *tools.Hey, reverse, tmpfs bool) {\n// nginx runs on port 80.\n@@ -99,5 +160,10 @@ func runNginx(b *testing.B, hey *tools.Hey, reverse, tmpfs bool) {\n}\n// Command copies nginxDocs to tmpfs serving directory and runs nginx.\n- runStaticServer(b, nginxRunOpts, nginxCmd, port, hey, reverse)\n+ runStaticServer(b, h, nginxRunOpts, nginxCmd, port, hey, reverse)\n+}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/node_test.go", "new_path": "test/benchmarks/network/node_test.go", "diff": "@@ -15,6 +15,7 @@ package network\nimport (\n\"context\"\n+ \"os\"\n\"strconv\"\n\"testing\"\n\"time\"\n@@ -24,6 +25,8 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// BenchmarkNode runs requests using 'hey' against a Node server run on\n// 'runtime'. The server responds to requests by grabbing some data in a\n// redis instance and returns the data in its reponse. The test loops through\n@@ -131,5 +134,9 @@ func runNode(b *testing.B, hey *tools.Hey) {\n// Stop the timer to parse the data and report stats.\nb.StopTimer()\nhey.Report(b, out)\n- b.StartTimer()\n+}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/ruby_test.go", "new_path": "test/benchmarks/network/ruby_test.go", "diff": "@@ -16,6 +16,7 @@ package network\nimport (\n\"context\"\n\"fmt\"\n+ \"os\"\n\"strconv\"\n\"testing\"\n\"time\"\n@@ -25,6 +26,8 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// BenchmarkRuby runs requests using 'hey' against a ruby application server.\n// On start, ruby app generates some random data and pushes it to a redis\n// instance. On a request, the app grabs for random entries from the redis\n@@ -52,7 +55,6 @@ func BenchmarkRuby(b *testing.B) {\n// runRuby runs the test for a given # of requests and concurrency.\nfunc runRuby(b *testing.B, hey *tools.Hey) {\n- b.Helper()\n// The machine to hold Redis and the Ruby Server.\nserverMachine, err := h.GetMachine()\nif err != nil {\n@@ -141,3 +143,8 @@ func runRuby(b *testing.B, hey *tools.Hey) {\nhey.Report(b, out)\nb.StartTimer()\n}\n+\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n" }, { "change_type": "DELETE", "old_path": "test/benchmarks/network/static_server.go", "new_path": null, "diff": "-// Copyright 2020 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package network\n-\n-import (\n- \"context\"\n- \"testing\"\n-\n- \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n- \"gvisor.dev/gvisor/test/benchmarks/harness\"\n- \"gvisor.dev/gvisor/test/benchmarks/tools\"\n-)\n-\n-// runStaticServer runs static serving workloads (httpd, nginx).\n-func runStaticServer(b *testing.B, serverOpts dockerutil.RunOpts, serverCmd []string, port int, hey *tools.Hey, reverse bool) {\n- ctx := context.Background()\n-\n- // Get two machines: a client and server.\n- clientMachine, err := h.GetMachine()\n- if err != nil {\n- b.Fatalf(\"failed to get machine: %v\", err)\n- }\n- defer clientMachine.CleanUp()\n-\n- serverMachine, err := h.GetMachine()\n- if err != nil {\n- b.Fatalf(\"failed to get machine: %v\", err)\n- }\n- defer serverMachine.CleanUp()\n-\n- // Make the containers. 'reverse=true' specifies that the client should use the\n- // runtime under test.\n- var client, server *dockerutil.Container\n- if reverse {\n- client = clientMachine.GetContainer(ctx, b)\n- server = serverMachine.GetNativeContainer(ctx, b)\n- } else {\n- client = clientMachine.GetNativeContainer(ctx, b)\n- server = serverMachine.GetContainer(ctx, b)\n- }\n- defer client.CleanUp(ctx)\n- defer server.CleanUp(ctx)\n-\n- // Start the server.\n- if err := server.Spawn(ctx, serverOpts, serverCmd...); err != nil {\n- b.Fatalf(\"failed to start server: %v\", err)\n- }\n-\n- // Get its IP.\n- ip, err := serverMachine.IPAddress()\n- if err != nil {\n- b.Fatalf(\"failed to find server ip: %v\", err)\n- }\n-\n- // Get the published port.\n- servingPort, err := server.FindPort(ctx, port)\n- if err != nil {\n- b.Fatalf(\"failed to find server port %d: %v\", port, err)\n- }\n-\n- // Make sure the server is serving.\n- harness.WaitUntilServing(ctx, clientMachine, ip, servingPort)\n- b.ResetTimer()\n- server.RestartProfiles()\n- out, err := client.Run(ctx, dockerutil.RunOpts{\n- Image: \"benchmarks/hey\",\n- }, hey.MakeCmd(ip, servingPort)...)\n- if err != nil {\n- b.Fatalf(\"run failed with: %v\", err)\n- }\n-\n- b.StopTimer()\n- hey.Report(b, out)\n- b.StartTimer()\n-}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/iperf.go", "new_path": "test/benchmarks/tools/iperf.go", "diff": "@@ -31,7 +31,7 @@ type Iperf struct {\n// MakeCmd returns a iperf client command.\nfunc (i *Iperf) MakeCmd(ip net.IP, port int) []string {\n// iperf report in Kb realtime\n- return strings.Split(fmt.Sprintf(\"iperf -f K --realtime --time %d -c %s -p %d\", i.Time, ip, port), \" \")\n+ return strings.Split(fmt.Sprintf(\"iperf -f K --realtime --time %d --client %s --port %d\", i.Time, ip, port), \" \")\n}\n// Report parses output from iperf client and reports metrics.\n" } ]
Go
Apache License 2.0
google/gvisor
Add network benchmarks jobs Add httpd, nginx, node, and ruby benchmarks to continuous jobs. PiperOrigin-RevId: 346629115
259,962
09.12.2020 14:54:43
28,800
92ca72ecb73d91e9def31e7f9835adf7a50b3d65
Add support for IP_RECVORIGDSTADDR IP option. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/control/control.go", "new_path": "pkg/sentry/socket/control/control.go", "diff": "@@ -359,13 +359,26 @@ func PackIPPacketInfo(t *kernel.Task, packetInfo tcpip.IPPacketInfo, buf []byte)\n)\n}\n+// PackOriginalDstAddress packs an IP_RECVORIGINALDSTADDR socket control message.\n+func PackOriginalDstAddress(t *kernel.Task, family int, originalDstAddress tcpip.FullAddress, buf []byte) []byte {\n+ p, _ := socket.ConvertAddress(family, originalDstAddress)\n+ level := uint32(linux.SOL_IP)\n+ optType := uint32(linux.IP_RECVORIGDSTADDR)\n+ if family == linux.AF_INET6 {\n+ level = linux.SOL_IPV6\n+ optType = linux.IPV6_RECVORIGDSTADDR\n+ }\n+ return putCmsgStruct(\n+ buf, level, optType, t.Arch().Width(), p)\n+}\n+\n// PackControlMessages packs control messages into the given buffer.\n//\n// We skip control messages specific to Unix domain sockets.\n//\n// Note that some control messages may be truncated if they do not fit under\n// the capacity of buf.\n-func PackControlMessages(t *kernel.Task, cmsgs socket.ControlMessages, buf []byte) []byte {\n+func PackControlMessages(t *kernel.Task, family int, cmsgs socket.ControlMessages, buf []byte) []byte {\nif cmsgs.IP.HasTimestamp {\nbuf = PackTimestamp(t, cmsgs.IP.Timestamp, buf)\n}\n@@ -387,6 +400,10 @@ func PackControlMessages(t *kernel.Task, cmsgs socket.ControlMessages, buf []byt\nbuf = PackIPPacketInfo(t, cmsgs.IP.PacketInfo, buf)\n}\n+ if cmsgs.IP.HasOriginalDstAddress {\n+ buf = PackOriginalDstAddress(t, family, cmsgs.IP.OriginalDstAddress, buf)\n+ }\n+\nreturn buf\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket.go", "new_path": "pkg/sentry/socket/hostinet/socket.go", "diff": "@@ -551,7 +551,7 @@ func (s *socketOpsCommon) SendMsg(t *kernel.Task, src usermem.IOSequence, to []b\n}\ncontrolBuf := make([]byte, 0, space)\n// PackControlMessages will append up to space bytes to controlBuf.\n- controlBuf = control.PackControlMessages(t, controlMessages, controlBuf)\n+ controlBuf = control.PackControlMessages(t, s.family, controlMessages, controlBuf)\nsendmsgFromBlocks := safemem.WriterFunc(func(srcs safemem.BlockSeq) (uint64, error) {\n// Refuse to do anything if any part of src.Addrs was unusable.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1418,6 +1418,14 @@ func getSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nv := primitive.Int32(boolToInt32(ep.SocketOptions().GetReceiveTClass()))\nreturn &v, nil\n+ case linux.IPV6_RECVORIGDSTADDR:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetReceiveOriginalDstAddress()))\n+ return &v, nil\n+\ncase linux.IP6T_ORIGINAL_DST:\nif outLen < int(binary.Size(linux.SockAddrInet6{})) {\nreturn nil, syserr.ErrInvalidArgument\n@@ -1599,6 +1607,14 @@ func getSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nv := primitive.Int32(boolToInt32(ep.SocketOptions().GetHeaderIncluded()))\nreturn &v, nil\n+ case linux.IP_RECVORIGDSTADDR:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetReceiveOriginalDstAddress()))\n+ return &v, nil\n+\ncase linux.SO_ORIGINAL_DST:\nif outLen < int(binary.Size(linux.SockAddrInet{})) {\nreturn nil, syserr.ErrInvalidArgument\n@@ -2094,6 +2110,15 @@ func setSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nt.Kernel().EmitUnimplementedEvent(t)\n+ case linux.IPV6_RECVORIGDSTADDR:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ v := int32(usermem.ByteOrder.Uint32(optVal))\n+\n+ ep.SocketOptions().SetReceiveOriginalDstAddress(v != 0)\n+ return nil\n+\ncase linux.IPV6_TCLASS:\nif len(optVal) < sizeOfInt32 {\nreturn syserr.ErrInvalidArgument\n@@ -2325,6 +2350,18 @@ func setSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nep.SocketOptions().SetHeaderIncluded(v != 0)\nreturn nil\n+ case linux.IP_RECVORIGDSTADDR:\n+ if len(optVal) == 0 {\n+ return nil\n+ }\n+ v, err := parseIntOrChar(optVal)\n+ if err != nil {\n+ return err\n+ }\n+\n+ ep.SocketOptions().SetReceiveOriginalDstAddress(v != 0)\n+ return nil\n+\ncase linux.IPT_SO_SET_REPLACE:\nif len(optVal) < linux.SizeOfIPTReplace {\nreturn syserr.ErrInvalidArgument\n@@ -2363,7 +2400,6 @@ func setSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nlinux.IP_RECVERR,\nlinux.IP_RECVFRAGSIZE,\nlinux.IP_RECVOPTS,\n- linux.IP_RECVORIGDSTADDR,\nlinux.IP_RECVTTL,\nlinux.IP_RETOPTS,\nlinux.IP_TRANSPARENT,\n@@ -2441,7 +2477,6 @@ func emitUnimplementedEventIPv6(t *kernel.Task, name int) {\nlinux.IPV6_RECVFRAGSIZE,\nlinux.IPV6_RECVHOPLIMIT,\nlinux.IPV6_RECVHOPOPTS,\n- linux.IPV6_RECVORIGDSTADDR,\nlinux.IPV6_RECVPATHMTU,\nlinux.IPV6_RECVPKTINFO,\nlinux.IPV6_RECVRTHDR,\n@@ -2754,6 +2789,8 @@ func (s *socketOpsCommon) controlMessages() socket.ControlMessages {\nTClass: s.readCM.TClass,\nHasIPPacketInfo: s.readCM.HasIPPacketInfo,\nPacketInfo: s.readCM.PacketInfo,\n+ HasOriginalDstAddress: s.readCM.HasOriginalDstAddress,\n+ OriginalDstAddress: s.readCM.OriginalDstAddress,\n},\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_socket.go", "new_path": "pkg/sentry/syscalls/linux/sys_socket.go", "diff": "@@ -784,8 +784,9 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\n}\ndefer cms.Release(t)\n+ family, _, _ := s.Type()\ncontrolData := make([]byte, 0, msg.ControlLen)\n- controlData = control.PackControlMessages(t, cms, controlData)\n+ controlData = control.PackControlMessages(t, family, cms, controlData)\nif cr, ok := s.(transport.Credentialer); ok && cr.Passcred() {\ncreds, _ := cms.Unix.Credentials.(control.SCMCredentials)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/socket.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/socket.go", "diff": "@@ -787,8 +787,9 @@ func recvSingleMsg(t *kernel.Task, s socket.SocketVFS2, msgPtr usermem.Addr, fla\n}\ndefer cms.Release(t)\n+ family, _, _ := s.Type()\ncontrolData := make([]byte, 0, msg.ControlLen)\n- controlData = control.PackControlMessages(t, cms, controlData)\n+ controlData = control.PackControlMessages(t, family, cms, controlData)\nif cr, ok := s.(transport.Credentialer); ok && cr.Passcred() {\ncreds, _ := cms.Unix.Credentials.(control.SCMCredentials)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/checker/checker.go", "new_path": "pkg/tcpip/checker/checker.go", "diff": "@@ -321,6 +321,19 @@ func ReceiveIPPacketInfo(want tcpip.IPPacketInfo) ControlMessagesChecker {\n}\n}\n+// ReceiveOriginalDstAddr creates a checker that checks the OriginalDstAddress\n+// field in ControlMessages.\n+func ReceiveOriginalDstAddr(want tcpip.FullAddress) ControlMessagesChecker {\n+ return func(t *testing.T, cm tcpip.ControlMessages) {\n+ t.Helper()\n+ if !cm.HasOriginalDstAddress {\n+ t.Errorf(\"got cm.HasOriginalDstAddress = %t, want = true\", cm.HasOriginalDstAddress)\n+ } else if diff := cmp.Diff(want, cm.OriginalDstAddress); diff != \"\" {\n+ t.Errorf(\"OriginalDstAddress mismatch (-want +got):\\n%s\", diff)\n+ }\n+ }\n+}\n+\n// TOS creates a checker that checks the TOS field.\nfunc TOS(tos uint8, label uint32) NetworkChecker {\nreturn func(t *testing.T, h []header.Network) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -130,6 +130,10 @@ type SocketOptions struct {\n// corkOptionEnabled is used to specify if data should be held until segments\n// are full by the TCP transport protocol.\ncorkOptionEnabled uint32\n+\n+ // receiveOriginalDstAddress is used to specify if the original destination of\n+ // the incoming packet should be returned as an ancillary message.\n+ receiveOriginalDstAddress uint32\n}\n// InitHandler initializes the handler. This must be called before using the\n@@ -302,3 +306,13 @@ func (so *SocketOptions) SetCorkOption(v bool) {\nstoreAtomicBool(&so.corkOptionEnabled, v)\nso.handler.OnCorkOptionSet(v)\n}\n+\n+// GetReceiveOriginalDstAddress gets value for IP(V6)_RECVORIGDSTADDR option.\n+func (so *SocketOptions) GetReceiveOriginalDstAddress() bool {\n+ return atomic.LoadUint32(&so.receiveOriginalDstAddress) != 0\n+}\n+\n+// SetReceiveOriginalDstAddress sets value for IP(V6)_RECVORIGDSTADDR option.\n+func (so *SocketOptions) SetReceiveOriginalDstAddress(v bool) {\n+ storeAtomicBool(&so.receiveOriginalDstAddress, v)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -492,6 +492,14 @@ type ControlMessages struct {\n// PacketInfo holds interface and address data on an incoming packet.\nPacketInfo IPPacketInfo\n+\n+ // HasOriginalDestinationAddress indicates whether OriginalDstAddress is\n+ // set.\n+ HasOriginalDstAddress bool\n+\n+ // OriginalDestinationAddress holds the original destination address\n+ // and port of the incoming packet.\n+ OriginalDstAddress FullAddress\n}\n// PacketOwner is used to get UID and GID of the packet.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -31,6 +31,7 @@ import (\ntype udpPacket struct {\nudpPacketEntry\nsenderAddress tcpip.FullAddress\n+ destinationAddress tcpip.FullAddress\npacketInfo tcpip.IPPacketInfo\ndata buffer.VectorisedView `state:\".(buffer.VectorisedView)\"`\ntimestamp int64\n@@ -323,6 +324,10 @@ func (e *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMess\ncm.HasIPPacketInfo = true\ncm.PacketInfo = p.packetInfo\n}\n+ if e.ops.GetReceiveOriginalDstAddress() {\n+ cm.HasOriginalDstAddress = true\n+ cm.OriginalDstAddress = p.destinationAddress\n+ }\nreturn p.data.ToView(), cm, nil\n}\n@@ -1314,6 +1319,11 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\nAddr: id.RemoteAddress,\nPort: hdr.SourcePort(),\n},\n+ destinationAddress: tcpip.FullAddress{\n+ NIC: pkt.NICID,\n+ Addr: id.LocalAddress,\n+ Port: header.UDP(hdr).DestinationPort(),\n+ },\n}\npacket.data = pkt.Data\ne.rcvList.PushBack(packet)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -1428,6 +1428,93 @@ func TestReadIPPacketInfo(t *testing.T) {\n}\n}\n+func TestReadRecvOriginalDstAddr(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ proto tcpip.NetworkProtocolNumber\n+ flow testFlow\n+ expectedOriginalDstAddr tcpip.FullAddress\n+ }{\n+ {\n+ name: \"IPv4 unicast\",\n+ proto: header.IPv4ProtocolNumber,\n+ flow: unicastV4,\n+ expectedOriginalDstAddr: tcpip.FullAddress{1, stackAddr, stackPort},\n+ },\n+ {\n+ name: \"IPv4 multicast\",\n+ proto: header.IPv4ProtocolNumber,\n+ flow: multicastV4,\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ expectedOriginalDstAddr: tcpip.FullAddress{1, multicastAddr, stackPort},\n+ },\n+ {\n+ name: \"IPv4 broadcast\",\n+ proto: header.IPv4ProtocolNumber,\n+ flow: broadcast,\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ expectedOriginalDstAddr: tcpip.FullAddress{1, broadcastAddr, stackPort},\n+ },\n+ {\n+ name: \"IPv6 unicast\",\n+ proto: header.IPv6ProtocolNumber,\n+ flow: unicastV6,\n+ expectedOriginalDstAddr: tcpip.FullAddress{1, stackV6Addr, stackPort},\n+ },\n+ {\n+ name: \"IPv6 multicast\",\n+ proto: header.IPv6ProtocolNumber,\n+ flow: multicastV6,\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ expectedOriginalDstAddr: tcpip.FullAddress{1, multicastV6Addr, stackPort},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ c := newDualTestContext(t, defaultMTU)\n+ defer c.cleanup()\n+\n+ c.createEndpoint(test.proto)\n+\n+ bindAddr := tcpip.FullAddress{Port: stackPort}\n+ if err := c.ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"Bind(%+v): %s\", bindAddr, err)\n+ }\n+\n+ if test.flow.isMulticast() {\n+ ifoptSet := tcpip.AddMembershipOption{NIC: 1, MulticastAddr: test.flow.getMcastAddr()}\n+ if err := c.ep.SetSockOpt(&ifoptSet); err != nil {\n+ c.t.Fatalf(\"SetSockOpt(&%#v): %s:\", ifoptSet, err)\n+ }\n+ }\n+\n+ c.ep.SocketOptions().SetReceiveOriginalDstAddress(true)\n+\n+ testRead(c, test.flow, checker.ReceiveOriginalDstAddr(test.expectedOriginalDstAddr))\n+\n+ if got := c.s.Stats().UDP.PacketsReceived.Value(); got != 1 {\n+ t.Fatalf(\"Read did not increment PacketsReceived: got = %d, want = 1\", got)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestWriteIncrementsPacketsSent(t *testing.T) {\nc := newDualTestContext(t, defaultMTU)\ndefer c.cleanup()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2450,6 +2450,27 @@ cc_library(\nalwayslink = 1,\n)\n+cc_library(\n+ name = \"socket_ipv6_udp_unbound_test_cases\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ipv6_udp_unbound.cc\",\n+ ],\n+ hdrs = [\n+ \"socket_ipv6_udp_unbound.h\",\n+ ],\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_test_util\",\n+ \"@com_google_absl//absl/memory\",\n+ gtest,\n+ \"//test/util:posix_error\",\n+ \"//test/util:save_util\",\n+ \"//test/util:test_util\",\n+ ],\n+ alwayslink = 1,\n+)\n+\ncc_library(\nname = \"socket_ipv4_udp_unbound_netlink_test_cases\",\ntestonly = 1,\n@@ -2789,6 +2810,22 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"socket_ipv6_udp_unbound_loopback_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ipv6_udp_unbound_loopback.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_ipv6_udp_unbound_test_cases\",\n+ \":socket_test_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"socket_ipv4_udp_unbound_loopback_nogotsan_test\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "diff": "#include \"test/syscalls/linux/socket_ip_udp_generic.h\"\n#include <errno.h>\n+#ifdef __linux__\n+#include <linux/in6.h>\n+#endif // __linux__\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <poll.h>\n@@ -356,6 +359,58 @@ TEST_P(UDPSocketPairTest, SetAndGetIPPKTINFO) {\nEXPECT_EQ(get_len, sizeof(get));\n}\n+// Test getsockopt for a socket which is not set with IP_RECVORIGDSTADDR option.\n+TEST_P(UDPSocketPairTest, ReceiveOrigDstAddrDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ int level = SOL_IP;\n+ int type = IP_RECVORIGDSTADDR;\n+ if (sockets->first_addr()->sa_family == AF_INET6) {\n+ level = SOL_IPV6;\n+ type = IPV6_RECVORIGDSTADDR;\n+ }\n+ ASSERT_THAT(getsockopt(sockets->first_fd(), level, type, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOff);\n+}\n+\n+// Test setsockopt and getsockopt for a socket with IP_RECVORIGDSTADDR option.\n+TEST_P(UDPSocketPairTest, SetAndGetReceiveOrigDstAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int level = SOL_IP;\n+ int type = IP_RECVORIGDSTADDR;\n+ if (sockets->first_addr()->sa_family == AF_INET6) {\n+ level = SOL_IPV6;\n+ type = IPV6_RECVORIGDSTADDR;\n+ }\n+\n+ // Check getsockopt before IP_PKTINFO is set.\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), level, type, &kSockOptOn,\n+ sizeof(kSockOptOn)),\n+ SyscallSucceedsWithValue(0));\n+\n+ ASSERT_THAT(getsockopt(sockets->first_fd(), level, type, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get, kSockOptOn);\n+ EXPECT_EQ(get_len, sizeof(get));\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), level, type, &kSockOptOff,\n+ sizeof(kSockOptOff)),\n+ SyscallSucceedsWithValue(0));\n+\n+ ASSERT_THAT(getsockopt(sockets->first_fd(), level, type, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get, kSockOptOff);\n+ EXPECT_EQ(get_len, sizeof(get));\n+}\n+\n// Holds TOS or TClass information for IPv4 or IPv6 respectively.\nstruct RecvTosOption {\nint level;\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "diff": "@@ -2222,6 +2222,90 @@ TEST_P(IPv4UDPUnboundSocketTest, SetAndReceiveIPPKTINFO) {\nEXPECT_EQ(received_pktinfo.ipi_addr.s_addr, htonl(INADDR_LOOPBACK));\n}\n+// Test that socket will receive IP_RECVORIGDSTADDR control message.\n+TEST_P(IPv4UDPUnboundSocketTest, SetAndReceiveIPReceiveOrigDstAddr) {\n+ auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver_addr = V4Loopback();\n+ int level = SOL_IP;\n+ int type = IP_RECVORIGDSTADDR;\n+\n+ ASSERT_THAT(\n+ bind(receiver->get(), reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ // Retrieve the port bound by the receiver.\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ ASSERT_THAT(getsockname(receiver->get(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ ASSERT_THAT(\n+ connect(sender->get(), reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ // Get address and port bound by the sender.\n+ sockaddr_storage sender_addr_storage;\n+ socklen_t sender_addr_len = sizeof(sender_addr_storage);\n+ ASSERT_THAT(getsockname(sender->get(),\n+ reinterpret_cast<sockaddr*>(&sender_addr_storage),\n+ &sender_addr_len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(sender_addr_len, sizeof(struct sockaddr_in));\n+\n+ // Enable IP_RECVORIGDSTADDR on socket so that we get the original destination\n+ // address of the datagram as auxiliary information in the control message.\n+ ASSERT_THAT(\n+ setsockopt(receiver->get(), level, type, &kSockOptOn, sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+\n+ // Prepare message to send.\n+ constexpr size_t kDataLength = 1024;\n+ msghdr sent_msg = {};\n+ iovec sent_iov = {};\n+ char sent_data[kDataLength];\n+ sent_iov.iov_base = sent_data;\n+ sent_iov.iov_len = kDataLength;\n+ sent_msg.msg_iov = &sent_iov;\n+ sent_msg.msg_iovlen = 1;\n+ sent_msg.msg_flags = 0;\n+\n+ ASSERT_THAT(RetryEINTR(sendmsg)(sender->get(), &sent_msg, 0),\n+ SyscallSucceedsWithValue(kDataLength));\n+\n+ msghdr received_msg = {};\n+ iovec received_iov = {};\n+ char received_data[kDataLength];\n+ char received_cmsg_buf[CMSG_SPACE(sizeof(sockaddr_in))] = {};\n+ size_t cmsg_data_len = sizeof(sockaddr_in);\n+ received_iov.iov_base = received_data;\n+ received_iov.iov_len = kDataLength;\n+ received_msg.msg_iov = &received_iov;\n+ received_msg.msg_iovlen = 1;\n+ received_msg.msg_controllen = CMSG_LEN(cmsg_data_len);\n+ received_msg.msg_control = received_cmsg_buf;\n+\n+ ASSERT_THAT(RecvMsgTimeout(receiver->get(), &received_msg, 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(kDataLength));\n+\n+ cmsghdr* cmsg = CMSG_FIRSTHDR(&received_msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));\n+ EXPECT_EQ(cmsg->cmsg_level, level);\n+ EXPECT_EQ(cmsg->cmsg_type, type);\n+\n+ // Check the data\n+ sockaddr_in received_addr = {};\n+ memcpy(&received_addr, CMSG_DATA(cmsg), sizeof(received_addr));\n+ auto orig_receiver_addr = reinterpret_cast<sockaddr_in*>(&receiver_addr.addr);\n+ EXPECT_EQ(received_addr.sin_addr.s_addr, orig_receiver_addr->sin_addr.s_addr);\n+ EXPECT_EQ(received_addr.sin_port, orig_receiver_addr->sin_port);\n+}\n+\n// Check that setting SO_RCVBUF below min is clamped to the minimum\n// receive buffer size.\nTEST_P(IPv4UDPUnboundSocketTest, SetSocketRecvBufBelowMin) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/socket_ipv6_udp_unbound.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/syscalls/linux/socket_ipv6_udp_unbound.h\"\n+\n+#include <arpa/inet.h>\n+#include <netinet/in.h>\n+#ifdef __linux__\n+#include <linux/in6.h>\n+#endif // __linux__\n+#include <net/if.h>\n+#include <sys/ioctl.h>\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <sys/un.h>\n+\n+#include <cstdio>\n+#include <cstring>\n+\n+#include \"gtest/gtest.h\"\n+#include \"absl/memory/memory.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/save_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test that socket will receive IP_RECVORIGDSTADDR control message.\n+TEST_P(IPv6UDPUnboundSocketTest, SetAndReceiveIPReceiveOrigDstAddr) {\n+ auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver_addr = V6Loopback();\n+ int level = SOL_IPV6;\n+ int type = IPV6_RECVORIGDSTADDR;\n+\n+ ASSERT_THAT(\n+ bind(receiver->get(), reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ // Retrieve the port bound by the receiver.\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ ASSERT_THAT(getsockname(receiver->get(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ ASSERT_THAT(\n+ connect(sender->get(), reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ // Get address and port bound by the sender.\n+ sockaddr_storage sender_addr_storage;\n+ socklen_t sender_addr_len = sizeof(sender_addr_storage);\n+ ASSERT_THAT(getsockname(sender->get(),\n+ reinterpret_cast<sockaddr*>(&sender_addr_storage),\n+ &sender_addr_len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(sender_addr_len, sizeof(struct sockaddr_in6));\n+\n+ // Enable IP_RECVORIGDSTADDR on socket so that we get the original destination\n+ // address of the datagram as auxiliary information in the control message.\n+ ASSERT_THAT(\n+ setsockopt(receiver->get(), level, type, &kSockOptOn, sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+\n+ // Prepare message to send.\n+ constexpr size_t kDataLength = 1024;\n+ msghdr sent_msg = {};\n+ iovec sent_iov = {};\n+ char sent_data[kDataLength];\n+ sent_iov.iov_base = sent_data;\n+ sent_iov.iov_len = kDataLength;\n+ sent_msg.msg_iov = &sent_iov;\n+ sent_msg.msg_iovlen = 1;\n+ sent_msg.msg_flags = 0;\n+\n+ ASSERT_THAT(RetryEINTR(sendmsg)(sender->get(), &sent_msg, 0),\n+ SyscallSucceedsWithValue(kDataLength));\n+\n+ msghdr received_msg = {};\n+ iovec received_iov = {};\n+ char received_data[kDataLength];\n+ char received_cmsg_buf[CMSG_SPACE(sizeof(sockaddr_in6))] = {};\n+ size_t cmsg_data_len = sizeof(sockaddr_in6);\n+ received_iov.iov_base = received_data;\n+ received_iov.iov_len = kDataLength;\n+ received_msg.msg_iov = &received_iov;\n+ received_msg.msg_iovlen = 1;\n+ received_msg.msg_controllen = CMSG_LEN(cmsg_data_len);\n+ received_msg.msg_control = received_cmsg_buf;\n+\n+ ASSERT_THAT(RecvMsgTimeout(receiver->get(), &received_msg, 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(kDataLength));\n+\n+ cmsghdr* cmsg = CMSG_FIRSTHDR(&received_msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));\n+ EXPECT_EQ(cmsg->cmsg_level, level);\n+ EXPECT_EQ(cmsg->cmsg_type, type);\n+\n+ // Check that the received address in the control message matches the expected\n+ // receiver's address.\n+ sockaddr_in6 received_addr = {};\n+ memcpy(&received_addr, CMSG_DATA(cmsg), sizeof(received_addr));\n+ auto orig_receiver_addr =\n+ reinterpret_cast<sockaddr_in6*>(&receiver_addr.addr);\n+ EXPECT_EQ(memcmp(&received_addr.sin6_addr, &orig_receiver_addr->sin6_addr,\n+ sizeof(in6_addr)),\n+ 0);\n+ EXPECT_EQ(received_addr.sin6_port, orig_receiver_addr->sin6_port);\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/socket_ipv6_udp_unbound.h", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_H_\n+#define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_H_\n+\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test fixture for tests that apply to IPv6 UDP sockets.\n+using IPv6UDPUnboundSocketTest = SimpleSocketTest;\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_H_\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/socket_ipv6_udp_unbound_loopback.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <vector>\n+\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_ipv6_udp_unbound.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+INSTANTIATE_TEST_SUITE_P(\n+ IPv6UDPSockets, IPv6UDPUnboundSocketTest,\n+ ::testing::ValuesIn(ApplyVec<SocketKind>(IPv6UDPUnboundSocket,\n+ AllBitwiseCombinations(List<int>{\n+ 0, SOCK_NONBLOCK}))));\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for IP_RECVORIGDSTADDR IP option. Fixes #5004 PiperOrigin-RevId: 346643745
259,858
09.12.2020 18:48:52
28,800
65a2242db409e7f4aeef04a01eb4f89699557866
Tweak aarch64 support. A few images were broken with respect to aarch64. We should now be able to run push-all-images with ARCH=aarch64 as part of the regular continuous integration builds, and add aarch64 smoke tests (via user emulation for now) to the regular test suite (future).
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -9,7 +9,8 @@ _templates:\nsteps:\n# Run basic smoke tests before preceding to other tests.\n- - label: \":fire: Smoke tests\"\n+ - <<: *common\n+ label: \":fire: Smoke tests\"\ncommand: make smoke-tests\n- wait\n@@ -77,25 +78,24 @@ steps:\nlabel: \":hammer: Packetimpact tests\"\ncommand: make packetimpact-tests\n- # Start heavy runtime tests.\n- - wait\n+ # Runtime tests.\n- <<: *common\nlabel: \":php: PHP runtime tests\"\n- command: make php7.3.6-runtime-tests\n+ command: make php7.3.6-runtime-tests_vfs2\nparallelism: 10\n- <<: *common\nlabel: \":java: Java runtime tests\"\n- command: make java11-runtime-tests\n+ command: make java11-runtime-tests_vfs2\nparallelism: 40\n- <<: *common\nlabel: \":golang: Go runtime tests\"\n- command: make go1.12-runtime-tests\n+ command: make go1.12-runtime-tests_vfs2\nparallelism: 10\n- <<: *common\nlabel: \":node: NodeJS runtime tests\"\n- command: make nodejs12.4.0-runtime-tests\n+ command: make nodejs12.4.0-runtime-tests_vfs2\nparallelism: 10\n- <<: *common\nlabel: \":python: Python runtime tests\"\n- command: make python3.7.3-runtime-tests\n+ command: make python3.7.3-runtime-tests_vfs2\nparallelism: 10\n" }, { "change_type": "RENAME", "old_path": "images/benchmarks/absl/Dockerfile", "new_path": "images/benchmarks/absl/Dockerfile.x86_64", "diff": "@@ -12,6 +12,7 @@ RUN set -x \\\nunzip \\\npython3 \\\n&& rm -rf /var/lib/apt/lists/*\n+\nRUN wget https://github.com/bazelbuild/bazel/releases/download/0.27.0/bazel-0.27.0-installer-linux-x86_64.sh\nRUN chmod +x bazel-0.27.0-installer-linux-x86_64.sh\nRUN ./bazel-0.27.0-installer-linux-x86_64.sh\n" }, { "change_type": "MODIFY", "old_path": "images/benchmarks/hey/Dockerfile", "new_path": "images/benchmarks/hey/Dockerfile", "diff": "-FROM ubuntu:18.04\n+FROM golang:1.15 as build\n+RUN go get github.com/rakyll/hey\n+WORKDIR /go/src/github.com/rakyll/hey\n+RUN go mod download\n+RUN CGO_ENABLED=0 go build -o /hey hey.go\n+FROM ubuntu:18.04\nRUN set -x \\\n&& apt-get update \\\n&& apt-get install -y \\\nwget \\\n&& rm -rf /var/lib/apt/lists/*\n-\n-RUN wget https://storage.googleapis.com/hey-release/hey_linux_amd64 \\\n- && chmod 777 hey_linux_amd64 \\\n- && cp hey_linux_amd64 /bin/hey \\\n- && rm hey_linux_amd64\n+COPY --from=build /hey /bin/hey\n" }, { "change_type": "RENAME", "old_path": "images/benchmarks/runsc/Dockerfile", "new_path": "images/benchmarks/runsc/Dockerfile.x86_64", "diff": "@@ -14,6 +14,7 @@ RUN set -x \\\npython3 \\\npython3-pip \\\n&& rm -rf /var/lib/apt/lists/*\n+\nRUN wget https://github.com/bazelbuild/bazel/releases/download/3.4.1/bazel-3.4.1-installer-linux-x86_64.sh\nRUN chmod +x bazel-3.4.1-installer-linux-x86_64.sh\nRUN ./bazel-3.4.1-installer-linux-x86_64.sh\n" }, { "change_type": "MODIFY", "old_path": "images/default/Dockerfile", "new_path": "images/default/Dockerfile", "diff": "FROM fedora:31\n+\n# Install bazel.\nRUN dnf install -y dnf-plugins-core && dnf copr enable -y vbatts/bazel\nRUN dnf install -y git gcc make golang gcc-c++ glibc-devel python3 which python3-pip python3-devel libffi-devel openssl-devel pkg-config glibc-static libstdc++-static patch diffutils\nRUN pip install --no-cache-dir pycparser\nRUN dnf install -y bazel3\n-# Install gcloud.\n+\n+# Install gcloud. Note that while this is \"x86_64\", it doesn't actually matter.\nRUN curl https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-289.0.0-linux-x86_64.tar.gz | \\\ntar zxf - google-cloud-sdk && \\\ngoogle-cloud-sdk/install.sh && \\\nln -s /google-cloud-sdk/bin/gcloud /usr/bin/gcloud\n+\n# Install Docker client for the website build.\nRUN dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo\nRUN dnf install -y docker-ce-cli\n+\nWORKDIR /workspace\nENTRYPOINT [\"/usr/bin/bazel\"]\n" }, { "change_type": "RENAME", "old_path": "images/runtimes/go1.12/Dockerfile", "new_path": "images/runtimes/go1.12/Dockerfile.x86_64", "diff": "" }, { "change_type": "MODIFY", "old_path": "runsc/cli/main.go", "new_path": "runsc/cli/main.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"io/ioutil\"\n\"os\"\n\"os/signal\"\n+ \"runtime\"\n\"syscall\"\n\"time\"\n@@ -207,6 +208,8 @@ func Main(version string) {\nlog.Infof(\"***************************\")\nlog.Infof(\"Args: %s\", os.Args)\nlog.Infof(\"Version %s\", version)\n+ log.Infof(\"GOOS: %s\", runtime.GOOS)\n+ log.Infof(\"GOARCH: %s\", runtime.GOARCH)\nlog.Infof(\"PID: %d\", os.Getpid())\nlog.Infof(\"UID: %d, GID: %d\", os.Getuid(), os.Getgid())\nlog.Infof(\"Configuration:\")\n" }, { "change_type": "MODIFY", "old_path": "tools/bazel.mk", "new_path": "tools/bazel.mk", "diff": "@@ -44,8 +44,8 @@ BUILD_ROOTS := bazel-bin/ bazel-out/\n# Bazel container configuration (see below).\nUSER := $(shell whoami)\nHASH := $(shell readlink -m $(CURDIR) | md5sum | cut -c1-8)\n-BUILDER_NAME := gvisor-builder-$(HASH)\n-DOCKER_NAME := gvisor-bazel-$(HASH)\n+BUILDER_NAME := gvisor-builder-$(HASH)-$(ARCH)\n+DOCKER_NAME := gvisor-bazel-$(HASH)-$(ARCH)\nDOCKER_PRIVILEGED := --privileged\nBAZEL_CACHE := $(shell readlink -m ~/.cache/bazel/)\nGCLOUD_CONFIG := $(shell readlink -m ~/.config/gcloud/)\n@@ -164,7 +164,7 @@ bazel-image: load-default ## Ensures that the local builder exists.\n@docker commit $(BUILDER_NAME) gvisor.dev/images/builder\n.PHONY: bazel-image\n-ifeq (,$(findstring $(DOCKER_NAME),$(shell docker ps 2>/dev/null)))\n+ifneq (true,$(shell $(wrapper echo true)))\nbazel-server: bazel-image ## Ensures that the server exists.\n@$(call header,DOCKER RUN)\n@docker rm -f $(DOCKER_NAME) 2>/dev/null || true\n@@ -208,6 +208,10 @@ run = $(call header,RUN $(1) $(2)) && $(call build_paths,$(1),{} $(2))\nsudo = $(call header,SUDO $(1) $(2)) && $(call build_paths,$(1),sudo -E {} $(2))\ntest = $(call header,TEST $(1)) && $(call wrapper,$(BAZEL) test $(TEST_OPTIONS) $(1))\n+clean: ## Cleans the bazel cache.\n+ @$(call clean)\n+.PHONY: clean\n+\ntestlogs: ## Returns the most recent set of test logs.\n@if test -f .build_events.json; then \\\ncat .build_events.json | jq -r \\\n" }, { "change_type": "MODIFY", "old_path": "tools/images.mk", "new_path": "tools/images.mk", "diff": "@@ -99,8 +99,8 @@ loaded1_$(1)=.PHONY: load-$$(1)\nendef\n$(foreach image, $(EXISTING_IMAGES), $(eval $(call existing_image_rule,$(image))))\ndefine tag_expand_rule =\n-$(eval $(loaded0_$(call local_image,$(1))_$(call tag,$(1))))\n-$(eval $(loaded1_$(call local_image,$(1))_$(call tag,$(1))))\n+$(eval $(loaded0_$(call remote_image,$(1))_$(call tag,$(1))))\n+$(eval $(loaded1_$(call remote_image,$(1))_$(call tag,$(1))))\nendef\n$(foreach image, $(ALL_IMAGES), $(eval $(call tag_expand_rule,$(image))))\n@@ -108,16 +108,19 @@ $(foreach image, $(ALL_IMAGES), $(eval $(call tag_expand_rule,$(image))))\n# ensure that caching works as expected, as well as the \"latest\" tag that is\n# used by the tests.\nlocal_tag = \\\n- docker tag $(call remote_image,$(1)):$(call tag,$(1)) $(call local_image,$(1)):$(call tag,$(1)) && \\\n- docker tag $(call remote_image,$(1)):$(call tag,$(1)) $(call local_image,$(1))\n+ docker tag $(call remote_image,$(1)):$(call tag,$(1)) $(call local_image,$(1)):$(call tag,$(1))\n+latest_tag = \\\n+ docker tag $(call local_image,$(1)):$(call tag,$(1)) $(call local_image,$(1))\ntag-%: ## Tag a local image.\n- @$(call local_tag,$*)\n+ @$(call header,TAG $*)\n+ @$(call local_tag,$*) && $(call latest_tag,$*)\n# pull forces the image to be pulled.\npull = \\\n$(call header,PULL $(1)) && \\\ndocker pull $(DOCKER_PLATFORM_ARGS) $(call remote_image,$(1)):$(call tag,$(1)) && \\\n- $(call local_tag,$(1))\n+ $(call local_tag,$(1)) && \\\n+ $(call latest_tag,$(1))\npull-%: register-cross ## Force a repull of the image.\n@$(call pull,$*)\n@@ -134,7 +137,8 @@ rebuild = \\\n-t \"$(call remote_image,$(1)):$(call tag,$(1))\" \\\n$$T && \\\nrm -rf $$T) && \\\n- $(call local_tag,$(1))\n+ $(call local_tag,$(1)) && \\\n+ $(call latest_tag,$(1))\nrebuild-%: register-cross ## Force rebuild an image locally.\n@$(call rebuild,$*)\n" } ]
Go
Apache License 2.0
google/gvisor
Tweak aarch64 support. A few images were broken with respect to aarch64. We should now be able to run push-all-images with ARCH=aarch64 as part of the regular continuous integration builds, and add aarch64 smoke tests (via user emulation for now) to the regular test suite (future). PiperOrigin-RevId: 346685462
259,885
10.12.2020 15:17:20
28,800
ed0c7be614eaf1ec19dae90d1516a5e90ec1f793
Proposal for runtime.DedicateOSThread(). Updates
[ { "change_type": "ADD", "old_path": null, "new_path": "g3doc/proposals/runtime_dedicate_os_thread.md", "diff": "+# `runtime.DedicateOSThread`\n+\n+Status as of 2020-09-18: Deprioritized; initial studies in #2180 suggest that\n+this may be difficult to support in the Go runtime due to issues with GC.\n+\n+## Summary\n+\n+Allow goroutines to bind to kernel threads in a way that allows their scheduling\n+to be kernel-managed rather than runtime-managed.\n+\n+## Objectives\n+\n+* Reduce Go runtime overhead in the gVisor sentry (#2184).\n+\n+* Minimize intrusiveness of changes to the Go runtime.\n+\n+## Background\n+\n+In Go, execution contexts are referred to as goroutines, which the runtime calls\n+Gs. The Go runtime maintains a variably-sized pool of threads (called Ms by the\n+runtime) on which Gs are executed, as well as a pool of \"virtual processors\"\n+(called Ps by the runtime) of size equal to `runtime.GOMAXPROCS()`. Usually,\n+each M requires a P in order to execute Gs, limiting the number of concurrently\n+executing goroutines to `runtime.GOMAXPROCS()`.\n+\n+The `runtime.LockOSThread` function temporarily locks the invoking goroutine to\n+its current thread. It is primarily useful for interacting with OS or non-Go\n+library facilities that are per-thread. It does not reduce interactions with the\n+Go runtime scheduler: locked Ms relinquish their P when they become blocked, and\n+only continue execution after another M \"chooses\" their locked G to run and\n+donates their P to the locked M instead.\n+\n+## Problems\n+\n+### Context Switch Overhead\n+\n+Most goroutines in the gVisor sentry are task goroutines, which back application\n+threads. Task goroutines spend large amounts of time blocked on syscalls that\n+execute untrusted application code. When invoking said syscall (which varies by\n+gVisor platform), the task goroutine may interact with the Go runtime in one of\n+three ways:\n+\n+* It can invoke the syscall without informing the runtime. In this case, the\n+ task goroutine will continue to hold its P during the syscall, limiting the\n+ number of application threads that can run concurrently to\n+ `runtime.GOMAXPROCS()`. This is problematic because the Go runtime scheduler\n+ is known to scale poorly with `GOMAXPROCS`; see #1942 and\n+ https://github.com/golang/go/issues/28808. It also means that preemption of\n+ application threads must be driven by sentry or runtime code, which is\n+ strictly slower than kernel-driven preemption (since the sentry must invoke\n+ another syscall to preempt the application thread).\n+\n+* It can call `runtime.entersyscallblock` before invoking the syscall, and\n+ `runtime.exitsyscall` after the syscall returns. In this case, the task\n+ goroutine will release its P while the syscall is executing. This allows the\n+ number of threads concurrently executing application code to exceed\n+ `GOMAXPROCS`. However, this incurs additional latency on syscall entry (to\n+ hand off the released P to another M, often requiring a `futex(FUTEX_WAKE)`\n+ syscall) and on syscall exit (to acquire a new P). It also drastically\n+ increases the number of threads that concurrently interact with the runtime\n+ scheduler, which is also problematic for performance (both in terms of CPU\n+ utilization and in terms of context switch latency); see #205.\n+\n+- It can call `runtime.entersyscall` before invoking the syscall, and\n+ `runtime.exitsyscall` after the syscall returns. In this case, the task\n+ goroutine \"lazily releases\" its P, allowing the runtime's \"sysmon\" thread to\n+ steal it on behalf of another M after a 20us delay. This mitigates the\n+ context switch latency problem when there are few task goroutines and the\n+ interval between switches to application code (i.e. the interval between\n+ application syscalls, page faults, or signal delivery) is short. (Cynically,\n+ this means that it's most effective in microbenchmarks). However, the delay\n+ before a P is stolen can also be problematic for performance when there are\n+ both many task goroutines switching to application code (lazily releasing\n+ their Ps) *and* many task goroutines switching to sentry code (contending\n+ for Ps), which is likely in larger heterogeneous workloads.\n+\n+### Blocking Overhead\n+\n+Task goroutines block on behalf of application syscalls like `futex` and\n+`epoll_wait` by receiving from a Go channel. (Future work may convert task\n+goroutine blocking to use the `syncevent` package to avoid overhead associated\n+with channels and `select`, but this does not change how blocking interacts with\n+the Go runtime scheduler.)\n+\n+If `runtime.LockOSThread()` is not in effect when a task goroutine blocks, then\n+when the task goroutine is unblocked (by e.g. an application `FUTEX_WAKE`,\n+signal delivery, or a timeout) by sending to the blocked channel,\n+`runtime.ready` migrates the unblocked G to the unblocking P. In most cases,\n+this implies that every application thread block/unblock cycle results in a\n+migration of the thread between Ps, and therefore Ms, and therefore cores,\n+resulting in reduced application performance due to loss of CPU caches.\n+Furthermore, in most cases, the unblocking P cannot immediately switch to the\n+unblocked G (instead resuming execution of its current application thread after\n+completing the application's `futex(FUTEX_WAKE)`, `tgkill`, etc. syscall), often\n+requiring that another P steal the unblocked G before it can resume execution.\n+\n+If `runtime.LockOSThread()` is in effect when a task goroutine blocks, then the\n+G will remain locked to its M, avoiding the core migration described above;\n+however, wakeup latency is significantly increased since, as described in\n+\"Background\", the G still needs to be selected by the scheduler before it can\n+run, and the M that selects the G then needs to transfer its P to the locked M,\n+incurring an additional `FUTEX_WAKE` syscall and round of kernel scheduling.\n+\n+## Proposal\n+\n+We propose to add a function, tentatively called `DedicateOSThread`, to the Go\n+`runtime` package, documented as follows:\n+\n+```go\n+// DedicateOSThread wires the calling goroutine to its current operating system\n+// thread, and exempts it from counting against GOMAXPROCS. The calling\n+// goroutine will always execute in that thread, and no other goroutine will\n+// execute in it, until the calling goroutine has made as many calls to\n+// UndedicateOSThread as to DedicateOSThread. If the calling goroutine exits\n+// without unlocking the thread, the thread will be terminated.\n+//\n+// DedicateOSThread should only be used by long-lived goroutines that usually\n+// block due to blocking system calls, rather than interaction with other\n+// goroutines.\n+func DedicateOSThread()\n+```\n+\n+Mechanically, `DedicateOSThread` implies `LockOSThread` (i.e. it locks the\n+invoking G to a M), but additionally locks the invoking M to a P. Ps locked by\n+`DedicateOSThread` are not counted against `GOMAXPROCS`; that is, the actual\n+number of Ps in the system (`len(runtime.allp)`) is `GOMAXPROCS` plus the number\n+of bound Ps (plus some slack to avoid frequent changes to `runtime.allp`).\n+Corollaries:\n+\n+* If `runtime.ready` observes that a readied G is locked to a M locked to a P,\n+ it immediately wakes the locked M without migrating the G to the readying P\n+ or waiting for a future call to `runtime.schedule` to select the readied G\n+ in `runtime.findrunnable`.\n+\n+* `runtime.stoplockedm` and `runtime.reentersyscall` skip the release of\n+ locked Ps; the latter also skips sysmon wakeup. `runtime.stoplockedm` and\n+ `runtime.exitsyscall` skip re-acquisition of Ps if one is locked.\n+\n+* sysmon does not attempt to preempt Gs that are locked to Ps, avoiding\n+ fruitless overhead from `tgkill` syscalls and signal delivery.\n+\n+* `runtime.findrunnable`'s work stealing skips locked Ps (suggesting that\n+ unlocked Ps be tracked in a separate array). `runtime.findrunnable` on\n+ locked Ps skip the global run queue, work stealing, and possibly netpoll.\n+\n+* New goroutines created by goroutines with locked Ps are enqueued on the\n+ global run queue rather than the invoking P's local run queue.\n+\n+While gVisor's use case does not strictly require that the association is\n+reversible (with `runtime.UndedicateOSThread`), such a feature is required to\n+allow reuse of locked Ms, which is likely to be critical for performance.\n+\n+## Alternatives Considered\n+\n+* Make the runtime scale well with `GOMAXPROCS`. While we are also\n+ concurrently investigating this problem, this would not address the issues\n+ of increased preemption cost or blocking overhead.\n+\n+* Make the runtime scale well with number of Ms. It is unclear if this is\n+ actually feasible, and would not address blocking overhead.\n+\n+* Make P-locking part of `LockOSThread`'s behavior. This would likely\n+ introduce performance regressions in existing uses of `LockOSThread` that do\n+ not fit this usage pattern. In particular, since `DedicateOSThread`\n+ transitions the invoker's P from \"counted against `GOMAXPROCS`\" to \"not\n+ counted against `GOMAXPROCS`\", it may need to wake another M to run a new P\n+ (that is counted against `GOMAXPROCS`), and the converse applies to\n+ `UndedicateOSThread`.\n+\n+* Rewrite the gVisor sentry in a language that does not force userspace\n+ scheduling. This is a last resort due to the amount of code involved.\n+\n+## Related Issues\n+\n+The proposed functionality is directly analogous to `spawn_blocking` in Rust\n+async runtimes\n+[`async_std`](https://docs.rs/async-std/1.8.0/async_std/task/fn.spawn_blocking.html)\n+and [`tokio`](https://docs.rs/tokio/0.3.5/tokio/task/fn.spawn_blocking.html).\n+\n+Outside of gVisor:\n+\n+* https://github.com/golang/go/issues/21827#issuecomment-595152452 describes a\n+ use case for this feature in go-delve, where the goroutine that would use\n+ this feature spends much of its time blocked in `ptrace` syscalls.\n+\n+* This feature may improve performance in the use case described in\n+ https://github.com/golang/go/issues/18237, given the prominence of\n+ syscall.Syscall in the profile given in that bug report.\n" } ]
Go
Apache License 2.0
google/gvisor
Proposal for runtime.DedicateOSThread(). Updates #2184 PiperOrigin-RevId: 346875966
259,860
10.12.2020 15:28:57
28,800
dbc86593db8f9d34dbe5098d38f6dc374d50280c
Fix typo in go template error messages.
[ { "change_type": "MODIFY", "old_path": "tools/go_generics/defs.bzl", "new_path": "tools/go_generics/defs.bzl", "diff": "@@ -67,7 +67,7 @@ def _go_template_instance_impl(ctx):\n# Check that all defined types are expected by the template.\nfor t in ctx.attr.types:\nif (t not in info.types) and (t not in info.opt_types):\n- fail(\"Type %s it not a parameter to %s\" % (t, ctx.attr.template.label))\n+ fail(\"Type %s is not a parameter to %s\" % (t, ctx.attr.template.label))\n# Check that all required consts are defined.\nfor t in info.consts:\n@@ -77,7 +77,7 @@ def _go_template_instance_impl(ctx):\n# Check that all defined consts are expected by the template.\nfor t in ctx.attr.consts:\nif (t not in info.consts) and (t not in info.opt_consts):\n- fail(\"Const %s it not a parameter to %s\" % (t, ctx.attr.template.label))\n+ fail(\"Const %s is not a parameter to %s\" % (t, ctx.attr.template.label))\n# Build the argument list.\nargs = [\"-i=%s\" % info.template.path, \"-o=%s\" % output.path]\n" } ]
Go
Apache License 2.0
google/gvisor
Fix typo in go template error messages. PiperOrigin-RevId: 346878344
259,884
10.12.2020 18:04:45
28,800
28c3260d74930a556febafdfaf9e2cecae1b9d3e
Add simple guidelines & instructions for blog contribution Modeled after knative's blog guidelines.
[ { "change_type": "MODIFY", "old_path": "website/blog/index.html", "new_path": "website/blog/index.html", "diff": "@@ -20,3 +20,8 @@ pagination:\n{% if paginator.total_pages > 1 %}\n{% include paginator.html %}\n{% endif %}\n+\n+<hr>\n+\n+If you would like to contribute to the gVisor blog check out the\n+<a href=\"https://github.com/google/gvisor/tree/master/website/blog\">instructions</a>.\n" } ]
Go
Apache License 2.0
google/gvisor
Add simple guidelines & instructions for blog contribution Modeled after knative's blog guidelines. https://github.com/knative/docs/blob/master/blog/README.md PiperOrigin-RevId: 346905713
260,001
10.12.2020 20:50:45
28,800
e7279936e8128c1ade57a26eb76726cabcb762a9
Change merkle root file name to avoid collision
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -64,6 +64,10 @@ const (\n// tree file for \"/foo\" is \"/.merkle.verity.foo\".\nmerklePrefix = \".merkle.verity.\"\n+ // merkleRootPrefix is the prefix of the Merkle tree root file. This\n+ // needs to be different from merklePrefix to avoid name collision.\n+ merkleRootPrefix = \".merkleroot.verity.\"\n+\n// merkleOffsetInParentXattr is the extended attribute name specifying the\n// offset of the child hash in its parent's Merkle tree.\nmerkleOffsetInParentXattr = \"user.merkle.offset\"\n@@ -255,7 +259,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nlowerVD.IncRef()\nd.lowerVD = lowerVD\n- rootMerkleName := merklePrefix + iopts.RootMerkleFileName\n+ rootMerkleName := merkleRootPrefix + iopts.RootMerkleFileName\nlowerMerkleVD, err := vfsObj.GetDentryAt(ctx, fs.creds, &vfs.PathOperation{\nRoot: lowerVD,\n" } ]
Go
Apache License 2.0
google/gvisor
Change merkle root file name to avoid collision PiperOrigin-RevId: 346923826
259,884
10.12.2020 21:47:38
28,800
0eb4acad37c448a298c77090b3475ce6903ecf18
Fix website build Fix 'run' function call so that parameters are passed properly to the function.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -371,7 +371,7 @@ WEBSITE_PROJECT := gvisordev\nWEBSITE_REGION := us-central1\nwebsite-build: load-jekyll ## Build the site image locally.\n- @$(call run,//website:website $(WEBSITE_IMAGE))\n+ @$(call run,//website:website,$(WEBSITE_IMAGE))\n.PHONY: website-build\nwebsite-server: website-build ## Run a local server for development.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix website build Fix 'run' function call so that parameters are passed properly to the function. PiperOrigin-RevId: 346929952
259,875
11.12.2020 04:19:58
28,800
73eccab91ec58aafd1ffdf038993b78a812ba30f
Make semctl IPC_INFO cmd return the index of highest used entry.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore.go", "diff": "@@ -52,6 +52,9 @@ type Registry struct {\nmu sync.Mutex `state:\"nosave\"`\nsemaphores map[int32]*Set\nlastIDUsed int32\n+ // indexes maintains a mapping between a set's index in virtual array and\n+ // its identifier.\n+ indexes map[int32]int32\n}\n// Set represents a set of semaphores that can be operated atomically.\n@@ -113,6 +116,7 @@ func NewRegistry(userNS *auth.UserNamespace) *Registry {\nreturn &Registry{\nuserNS: userNS,\nsemaphores: make(map[int32]*Set),\n+ indexes: make(map[int32]int32),\n}\n}\n@@ -163,6 +167,9 @@ func (r *Registry) FindOrCreate(ctx context.Context, key, nsems int32, mode linu\n}\n// Apply system limits.\n+ //\n+ // Map semaphores and map indexes in a registry are of the same size,\n+ // check map semaphores only here for the system limit.\nif len(r.semaphores) >= setsMax {\nreturn nil, syserror.EINVAL\n}\n@@ -192,6 +199,23 @@ func (r *Registry) IPCInfo() *linux.SemInfo {\n}\n}\n+// HighestIndex returns the index of the highest used entry in\n+// the kernel's array.\n+func (r *Registry) HighestIndex() int32 {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+\n+ // By default, highest used index is 0 even though\n+ // there is no semaphroe set.\n+ var highestIndex int32\n+ for index := range r.indexes {\n+ if index > highestIndex {\n+ highestIndex = index\n+ }\n+ }\n+ return highestIndex\n+}\n+\n// RemoveID removes set with give 'id' from the registry and marks the set as\n// dead. All waiters will be awakened and fail.\nfunc (r *Registry) RemoveID(id int32, creds *auth.Credentials) error {\n@@ -202,6 +226,11 @@ func (r *Registry) RemoveID(id int32, creds *auth.Credentials) error {\nif set == nil {\nreturn syserror.EINVAL\n}\n+ index, found := r.findIndexByID(id)\n+ if !found {\n+ // Inconsistent state.\n+ panic(fmt.Sprintf(\"unable to find an index for ID: %d\", id))\n+ }\nset.mu.Lock()\ndefer set.mu.Unlock()\n@@ -213,6 +242,7 @@ func (r *Registry) RemoveID(id int32, creds *auth.Credentials) error {\n}\ndelete(r.semaphores, set.ID)\n+ delete(r.indexes, index)\nset.destroy()\nreturn nil\n}\n@@ -236,6 +266,11 @@ func (r *Registry) newSet(ctx context.Context, key int32, owner, creator fs.File\ncontinue\n}\nif r.semaphores[id] == nil {\n+ index, found := r.findFirstAvailableIndex()\n+ if !found {\n+ panic(\"unable to find an available index\")\n+ }\n+ r.indexes[index] = id\nr.lastIDUsed = id\nr.semaphores[id] = set\nset.ID = id\n@@ -263,6 +298,24 @@ func (r *Registry) findByKey(key int32) *Set {\nreturn nil\n}\n+func (r *Registry) findIndexByID(id int32) (int32, bool) {\n+ for k, v := range r.indexes {\n+ if v == id {\n+ return k, true\n+ }\n+ }\n+ return 0, false\n+}\n+\n+func (r *Registry) findFirstAvailableIndex() (int32, bool) {\n+ for index := int32(0); index < setsMax; index++ {\n+ if _, present := r.indexes[index]; !present {\n+ return index, true\n+ }\n+ }\n+ return 0, false\n+}\n+\nfunc (r *Registry) totalSems() int {\ntotalSems := 0\nfor _, v := range r.semaphores {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_sem.go", "new_path": "pkg/sentry/syscalls/linux/sys_sem.go", "diff": "@@ -150,9 +150,10 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nbuf := args[3].Pointer()\nr := t.IPCNamespace().SemaphoreRegistry()\ninfo := r.IPCInfo()\n- _, err := info.CopyOut(t, buf)\n- // TODO(gvisor.dev/issue/137): Return the index of the highest used entry.\n+ if _, err := info.CopyOut(t, buf); err != nil {\nreturn 0, nil, err\n+ }\n+ return uintptr(r.HighestIndex()), nil, nil\ncase linux.SEM_INFO,\nlinux.SEM_STAT,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/semaphore.cc", "new_path": "test/syscalls/linux/semaphore.cc", "diff": "#include <atomic>\n#include <cerrno>\n#include <ctime>\n+#include <stack>\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n@@ -774,8 +775,32 @@ TEST(SemaphoreTest, SemopGetncntOnSignal_NoRandomSave) {\n}\nTEST(SemaphoreTest, IpcInfo) {\n+ std::stack<int> sem_ids;\n+ std::stack<int> max_used_indexes;\nstruct seminfo info;\n- ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceeds());\n+ for (int i = 0; i < 3; i++) {\n+ int sem_id = 0;\n+ ASSERT_THAT(sem_id = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT),\n+ SyscallSucceeds());\n+ sem_ids.push(sem_id);\n+ int max_used_index = 0;\n+ EXPECT_THAT(max_used_index = semctl(0, 0, IPC_INFO, &info),\n+ SyscallSucceeds());\n+ if (!max_used_indexes.empty()) {\n+ EXPECT_GT(max_used_index, max_used_indexes.top());\n+ }\n+ max_used_indexes.push(max_used_index);\n+ }\n+ while (!sem_ids.empty()) {\n+ int sem_id = sem_ids.top();\n+ sem_ids.pop();\n+ ASSERT_THAT(semctl(sem_id, 0, IPC_RMID), SyscallSucceeds());\n+ int max_index = max_used_indexes.top();\n+ EXPECT_THAT(max_index = semctl(0, 0, IPC_INFO, &info), SyscallSucceeds());\n+ EXPECT_GE(max_used_indexes.top(), max_index);\n+ max_used_indexes.pop();\n+ }\n+ ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceedsWithValue(0));\nEXPECT_EQ(info.semmap, 1024000000);\nEXPECT_EQ(info.semmni, 32000);\n" } ]
Go
Apache License 2.0
google/gvisor
Make semctl IPC_INFO cmd return the index of highest used entry. PiperOrigin-RevId: 346973338
259,858
11.12.2020 09:42:58
28,800
e0cde3fb87e8fd41437da7e2506664881544ef2b
Ensure individual steps timeout in case of infinite hang. Also, add a basic release test.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "_templates:\ncommon: &common\n+ timeout_in_minutes: 30\nretry:\nautomatic:\n- exit_status: -1\n@@ -22,6 +23,11 @@ steps:\n- git checkout go && git clean -f\n- go build ./...\n+ # Release workflow.\n+ - <<: *common\n+ label: \":ship: Release tests\"\n+ commands: make release\n+\n# Basic unit tests.\n- <<: *common\nlabel: \":test_tube: Unit tests\"\n" } ]
Go
Apache License 2.0
google/gvisor
Ensure individual steps timeout in case of infinite hang. Also, add a basic release test. PiperOrigin-RevId: 347016796
259,975
11.12.2020 11:24:22
28,800
3c673caf86c83070786a6baec0e92e109bfcbb54
Fix parser to include iterations.
[ { "change_type": "MODIFY", "old_path": "tools/bigquery/bigquery.go", "new_path": "tools/bigquery/bigquery.go", "diff": "@@ -21,6 +21,7 @@ package bigquery\nimport (\n\"context\"\n\"fmt\"\n+ \"strconv\"\n\"strings\"\n\"time\"\n@@ -109,6 +110,12 @@ func NewBenchmark(name string, iters int) *Benchmark {\nreturn &Benchmark{\nName: name,\nMetric: make([]*Metric, 0),\n+ Condition: []*Condition{\n+ {\n+ Name: \"iterations\",\n+ Value: strconv.Itoa(iters),\n+ },\n+ },\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "tools/parsers/go_parser_test.go", "new_path": "tools/parsers/go_parser_test.go", "diff": "@@ -33,6 +33,10 @@ func TestParseLine(t *testing.T) {\nwant: &bigquery.Benchmark{\nName: \"BenchmarkIperf\",\nCondition: []*bigquery.Condition{\n+ {\n+ Name: \"iterations\",\n+ Value: \"1\",\n+ },\n{\nName: \"GOMAXPROCS\",\nValue: \"6\",\n@@ -62,6 +66,10 @@ func TestParseLine(t *testing.T) {\nwant: &bigquery.Benchmark{\nName: \"BenchmarkRuby\",\nCondition: []*bigquery.Condition{\n+ {\n+ Name: \"iterations\",\n+ Value: \"1\",\n+ },\n{\nName: \"GOMAXPROCS\",\nValue: \"6\",\n@@ -100,12 +108,14 @@ func TestParseLine(t *testing.T) {\n}\nif !cmp.Equal(tc.want, got, nil) {\n- for _, c := range got.Condition {\n- t.Logf(\"Cond: %+v\", c)\n+ for i := range got.Condition {\n+ t.Logf(\"Metric: want: %+v got:%+v\", got.Condition[i], tc.want.Condition[i])\n}\n- for _, m := range got.Metric {\n- t.Logf(\"Metric: %+v\", m)\n+\n+ for i := range got.Metric {\n+ t.Logf(\"Metric: want: %+v got:%+v\", got.Metric[i], tc.want.Metric[i])\n}\n+\nt.Fatalf(\"Compare failed want: %+v got: %+v\", tc.want, got)\n}\n})\n@@ -131,7 +141,7 @@ func TestParseOutput(t *testing.T) {\n`,\nnumBenchmarks: 2,\nnumMetrics: 1,\n- numConditions: 1,\n+ numConditions: 2,\n},\n{\nname: \"Ruby\",\n@@ -142,7 +152,7 @@ BenchmarkRuby/server_threads.5\nBenchmarkRuby/server_threads.5-6 1 1416003331 ns/op 0.00950 average_latency.s 465 requests_per_second.QPS`,\nnumBenchmarks: 2,\nnumMetrics: 3,\n- numConditions: 2,\n+ numConditions: 3,\n},\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix parser to include iterations. PiperOrigin-RevId: 347038652
259,858
11.12.2020 11:50:08
28,800
76c2f21cecf6c690aaf3aba8eccbc593eb3a6305
Add local hooks for BuildKite.
[ { "change_type": "ADD", "old_path": null, "new_path": ".buildkite/hooks/post-command", "diff": "+# Upload test logs on failure, if there are any.\n+if [[ \"${BUILDKITE_COMMAND_EXIT_STATUS}\" -ne \"0\" ]]; then\n+ declare log_count=0\n+ for log in $(make testlogs 2>/dev/null | sort | uniq); do\n+ buildkite-agent artifact upload \"${log}\"\n+ log_count=$((${log_count}+1))\n+ # N.B. If *all* tests fail due to some common cause, then we will\n+ # end up spending way too much time uploading logs. Instead, we just\n+ # upload the first 100 and stop. That is hopefully enough to debug.\n+ if [[ \"${log_count}\" -ge 100 ]]; then\n+ echo \"Only uploaded first 100 failures; skipping the rest.\"\n+ break\n+ fi\n+ done\n+ # Attempt to clear the cache and shut down.\n+ make clean || echo \"make clean failed with code $?\"\n+ make bazel-shutdown || echo \"make bazel-shutdown failed with code $?\"\n+fi\n+\n+# Kill any running containers (clear state).\n+CONTAINERS=\"$(docker ps -q)\"\n+if ! [[ -z \"${CONTAINERS}\" ]]; then\n+ docker container kill ${CONTAINERS} 2>/dev/null || true\n+fi\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".buildkite/hooks/pre-command", "diff": "+# Setup for parallelization with PARTITION and TOTAL_PARTITIONS.\n+export PARTITION=${BUILDKITE_PARALLEL_JOB:-0}\n+PARTITION=$((${PARTITION}+1)) # 1-indexed, but PARALLEL_JOB is 0-indexed.\n+export TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\n+\n+# Ensure Docker has experimental enabled.\n+if ! grep experimental /etc/docker/daemon.json >/dev/null; then\n+ make sudo TARGETS=//runsc:runsc ARGS=\"install --experimental=true\"\n+ sudo systemctl reload docker\n+fi\n" } ]
Go
Apache License 2.0
google/gvisor
Add local hooks for BuildKite. PiperOrigin-RevId: 347044353
259,858
11.12.2020 13:23:27
28,800
5bdc167d174515eb51ba1bb0f4b4d1e484e8996c
Fix run and sudo targets. These are not passing arguments properly. This breaks the current pre-command for BuildKite.
[ { "change_type": "MODIFY", "old_path": ".buildkite/hooks/pre-command", "new_path": ".buildkite/hooks/pre-command", "diff": "@@ -4,7 +4,8 @@ PARTITION=$((${PARTITION}+1)) # 1-indexed, but PARALLEL_JOB is 0-indexed.\nexport TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\n# Ensure Docker has experimental enabled.\n-if ! grep experimental /etc/docker/daemon.json >/dev/null; then\n+EXPERIMENTAL=$(sudo docker version --format='{{.Server.Experimental}}')\n+if test \"${EXPERIMENTAL}\" != \"true\"; then\nmake sudo TARGETS=//runsc:runsc ARGS=\"install --experimental=true\"\n- sudo systemctl reload docker\n+ sudo systemctl restart docker\nfi\n" }, { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -67,11 +67,11 @@ copy: ## Copies the given $(TARGETS) to the given $(DESTINATION). E.g. make copy\n.PHONY: copy\nrun: ## Runs the given $(TARGETS), built with $(OPTIONS), using $(ARGS). E.g. make run TARGETS=runsc ARGS=-version\n- @$(call build,$(TARGETS) $(ARGS))\n+ @$(call run,$(TARGETS),$(ARGS))\n.PHONY: run\nsudo: ## Runs the given $(TARGETS) as per run, but using \"sudo -E\". E.g. make sudo TARGETS=test/root:root_test ARGS=-test.v\n- @$(call sudo,$(TARGETS) $(ARGS))\n+ @$(call sudo,$(TARGETS),$(ARGS))\n.PHONY: sudo\n# Load image helpers.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix run and sudo targets. These are not passing arguments properly. This breaks the current pre-command for BuildKite. PiperOrigin-RevId: 347062729
259,860
11.12.2020 15:41:44
28,800
1e92732eb19ac5cfa3df6ff01cc1ea71d80a9198
Make fixes to vfs2 leak checking.
[ { "change_type": "MODIFY", "old_path": "pkg/refsvfs2/BUILD", "new_path": "pkg/refsvfs2/BUILD", "diff": "@@ -9,7 +9,7 @@ go_template(\n\"refs_template.go\",\n],\nopt_consts = [\n- \"logTrace\",\n+ \"enableLogging\",\n],\ntypes = [\n\"T\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/refsvfs2/refs_template.go", "new_path": "pkg/refsvfs2/refs_template.go", "diff": "@@ -74,11 +74,6 @@ func (r *Refs) LogRefs() bool {\nreturn enableLogging\n}\n-// EnableLeakCheck enables reference leak checking on r.\n-func (r *Refs) EnableLeakCheck() {\n- refsvfs2.Register(r)\n-}\n-\n// ReadRefs returns the current number of references. The returned count is\n// inherently racy and is unsafe to use without external synchronization.\nfunc (r *Refs) ReadRefs() int64 {\n@@ -136,7 +131,7 @@ func (r *Refs) TryIncRef() bool {\nfunc (r *Refs) DecRef(destroy func()) {\nv := atomic.AddInt64(&r.refCount, -1)\nif enableLogging {\n- refsvfs2.LogDecRef(r, v+1)\n+ refsvfs2.LogDecRef(r, v)\n}\nswitch {\ncase v < 0:\n@@ -153,6 +148,6 @@ func (r *Refs) DecRef(destroy func()) {\nfunc (r *Refs) afterLoad() {\nif r.ReadRefs() > 0 {\n- r.EnableLeakCheck()\n+ refsvfs2.Register(r)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Make fixes to vfs2 leak checking. PiperOrigin-RevId: 347089828
259,975
11.12.2020 20:53:59
28,800
4b697aae55eacac75f5e9c76aacd40981720c3fd
Fix long running bazel build jobs. Skip the bazel clean command on the last run of the benchmark. Use --test.benchtime=1ns to force running the benchmark once (https://github.com/golang/go/issues/32051)
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/bazel_test.go", "new_path": "test/benchmarks/fs/bazel_test.go", "diff": "@@ -61,10 +61,10 @@ func runBuildBenchmark(b *testing.B, image, workdir, target string) {\nfor _, bm := range benchmarks {\npageCache := tools.Parameter{\nName: \"page_cache\",\n- Value: \"clean\",\n+ Value: \"dirty\",\n}\nif bm.clearCache {\n- pageCache.Value = \"dirty\"\n+ pageCache.Value = \"clean\"\n}\nfilesystem := tools.Parameter{\n@@ -129,13 +129,15 @@ func runBuildBenchmark(b *testing.B, image, workdir, target string) {\nif !strings.Contains(got, want) {\nb.Fatalf(\"string %s not in: %s\", want, got)\n}\n- // Clean bazel in case we use b.N.\n- _, err = container.Exec(ctx, dockerutil.ExecOpts{\n+\n+ // Clean bazel in the case we are doing another run.\n+ if i < b.N-1 {\n+ if _, err = container.Exec(ctx, dockerutil.ExecOpts{\nWorkDir: prefix + workdir,\n- }, \"bazel\", \"clean\")\n- if err != nil {\n+ }, \"bazel\", \"clean\"); err != nil {\nb.Fatalf(\"build failed with: %v\", err)\n}\n+ }\nb.StartTimer()\n}\n})\n" } ]
Go
Apache License 2.0
google/gvisor
Fix long running bazel build jobs. - Skip the bazel clean command on the last run of the benchmark. - Use --test.benchtime=1ns to force running the benchmark once (https://github.com/golang/go/issues/32051) PiperOrigin-RevId: 347124606
259,896
14.12.2020 10:20:49
28,800
ab593661efe4924369265a6b9f0dc719dcb371ab
Move SO_ERROR and SO_OOBINLINE option to socketops. SO_OOBINLINE option is set/get as boolean value, which is the same as linux. As we currently do not support disabling this option, we always return it as true.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -965,7 +965,7 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\n}\n// Get the last error and convert it.\n- err := ep.LastError()\n+ err := ep.SocketOptions().GetLastError()\nif err == nil {\noptP := primitive.Int32(0)\nreturn &optP, nil\n@@ -1127,13 +1127,8 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nreturn nil, syserr.ErrInvalidArgument\n}\n- var v tcpip.OutOfBandInlineOption\n- if err := ep.GetSockOpt(&v); err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n-\n- vP := primitive.Int32(v)\n- return &vP, nil\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetOutOfBandInline()))\n+ return &v, nil\ncase linux.SO_NO_CHECK:\nif outLen < sizeOfInt32 {\n@@ -1880,8 +1875,8 @@ func setSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, nam\nsocket.SetSockOptEmitUnimplementedEvent(t, name)\n}\n- opt := tcpip.OutOfBandInlineOption(v)\n- return syserr.TranslateNetstackError(ep.SetSockOpt(&opt))\n+ ep.SocketOptions().SetOutOfBandInline(v != 0)\n+ return nil\ncase linux.SO_NO_CHECK:\nif len(optVal) < sizeOfInt32 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -37,6 +37,9 @@ type SocketOptionsHandler interface {\n// OnCorkOptionSet is invoked when TCP_CORK is set for an endpoint.\nOnCorkOptionSet(v bool)\n+\n+ // LastError is invoked when SO_ERROR is read for an endpoint.\n+ LastError() *Error\n}\n// DefaultSocketOptionsHandler is an embeddable type that implements no-op\n@@ -60,6 +63,11 @@ func (*DefaultSocketOptionsHandler) OnDelayOptionSet(bool) {}\n// OnCorkOptionSet implements SocketOptionsHandler.OnCorkOptionSet.\nfunc (*DefaultSocketOptionsHandler) OnCorkOptionSet(bool) {}\n+// LastError implements SocketOptionsHandler.LastError.\n+func (*DefaultSocketOptionsHandler) LastError() *Error {\n+ return nil\n+}\n+\n// SocketOptions contains all the variables which store values for SOL_SOCKET,\n// SOL_IP, SOL_IPV6 and SOL_TCP level options.\n//\n@@ -316,3 +324,17 @@ func (so *SocketOptions) GetReceiveOriginalDstAddress() bool {\nfunc (so *SocketOptions) SetReceiveOriginalDstAddress(v bool) {\nstoreAtomicBool(&so.receiveOriginalDstAddress, v)\n}\n+\n+// GetLastError gets value for SO_ERROR option.\n+func (so *SocketOptions) GetLastError() *Error {\n+ return so.handler.LastError()\n+}\n+\n+// GetOutOfBandInline gets value for SO_OOBINLINE option.\n+func (*SocketOptions) GetOutOfBandInline() bool {\n+ return true\n+}\n+\n+// SetOutOfBandInline sets value for SO_OOBINLINE option. We currently do not\n+// support disabling this option.\n+func (*SocketOptions) SetOutOfBandInline(bool) {}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1096,14 +1096,6 @@ type RemoveMembershipOption MembershipOption\nfunc (*RemoveMembershipOption) isSettableSocketOption() {}\n-// OutOfBandInlineOption is used by SetSockOpt/GetSockOpt to specify whether\n-// TCP out-of-band data is delivered along with the normal in-band data.\n-type OutOfBandInlineOption int\n-\n-func (*OutOfBandInlineOption) isGettableSocketOption() {}\n-\n-func (*OutOfBandInlineOption) isSettableSocketOption() {}\n-\n// SocketDetachFilterOption is used by SetSockOpt to detach a previously attached\n// classic BPF filter on a given endpoint.\ntype SocketDetachFilterOption int\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1838,9 +1838,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\ne.keepalive.Unlock()\ne.notifyProtocolGoroutine(notifyKeepaliveChanged)\n- case *tcpip.OutOfBandInlineOption:\n- // We don't currently support disabling this option.\n-\ncase *tcpip.TCPUserTimeoutOption:\ne.LockUser()\ne.userTimeout = time.Duration(*v)\n@@ -2046,10 +2043,6 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n*o = tcpip.TCPUserTimeoutOption(e.userTimeout)\ne.UnlockUser()\n- case *tcpip.OutOfBandInlineOption:\n- // We don't currently support disabling this option.\n- *o = 1\n-\ncase *tcpip.CongestionControlOption:\ne.LockUser()\n*o = e.cc\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_generic.cc", "new_path": "test/syscalls/linux/socket_generic.cc", "diff": "@@ -853,5 +853,21 @@ TEST_P(AllSocketPairTest, SetAndGetBooleanSocketOptions) {\n}\n}\n+TEST_P(AllSocketPairTest, GetSocketOutOfBandInlineOption) {\n+ // We do not support disabling this option. It is always enabled.\n+ SKIP_IF(!IsRunningOnGvisor());\n+\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ int enable = -1;\n+ socklen_t enableLen = sizeof(enable);\n+\n+ int want = 1;\n+ ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_OOBINLINE, &enable,\n+ &enableLen),\n+ SyscallSucceeds());\n+ ASSERT_EQ(enableLen, sizeof(enable));\n+ EXPECT_EQ(enable, want);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Move SO_ERROR and SO_OOBINLINE option to socketops. SO_OOBINLINE option is set/get as boolean value, which is the same as linux. As we currently do not support disabling this option, we always return it as true. PiperOrigin-RevId: 347413905
259,860
14.12.2020 10:44:53
28,800
65e4ed8fbe15e3a8ebf96fdacf439d30d8a0e491
Do not check for reference leaks after saving. We should not assert that all resources are dropped after saving.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/control/state.go", "new_path": "pkg/sentry/control/state.go", "diff": "@@ -62,6 +62,7 @@ func (s *State) Save(o *SaveOpts, _ *struct{}) error {\nCallback: func(err error) {\nif err == nil {\nlog.Infof(\"Save succeeded: exiting...\")\n+ s.Kernel.SetSaveSuccess(false /* autosave */)\n} else {\nlog.Warningf(\"Save failed: exiting...\")\ns.Kernel.SetSaveError(err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -214,9 +214,11 @@ type Kernel struct {\n// netlinkPorts manages allocation of netlink socket port IDs.\nnetlinkPorts *port.Manager\n- // saveErr is the error causing the sandbox to exit during save, if\n- // any. It is protected by extMu.\n- saveErr error `state:\"nosave\"`\n+ // saveStatus is nil if the sandbox has not been saved, errSaved or\n+ // errAutoSaved if it has been saved successfully, or the error causing the\n+ // sandbox to exit during save.\n+ // It is protected by extMu.\n+ saveStatus error `state:\"nosave\"`\n// danglingEndpoints is used to save / restore tcpip.DanglingEndpoints.\ndanglingEndpoints struct{} `state:\".([]tcpip.Endpoint)\"`\n@@ -1481,12 +1483,42 @@ func (k *Kernel) NetlinkPorts() *port.Manager {\nreturn k.netlinkPorts\n}\n-// SaveError returns the sandbox error that caused the kernel to exit during\n-// save.\n-func (k *Kernel) SaveError() error {\n+var (\n+ errSaved = errors.New(\"sandbox has been successfully saved\")\n+ errAutoSaved = errors.New(\"sandbox has been successfully auto-saved\")\n+)\n+\n+// SaveStatus returns the sandbox save status. If it was saved successfully,\n+// autosaved indicates whether save was triggered by autosave. If it was not\n+// saved successfully, err indicates the sandbox error that caused the kernel to\n+// exit during save.\n+func (k *Kernel) SaveStatus() (saved, autosaved bool, err error) {\n+ k.extMu.Lock()\n+ defer k.extMu.Unlock()\n+ switch k.saveStatus {\n+ case nil:\n+ return false, false, nil\n+ case errSaved:\n+ return true, false, nil\n+ case errAutoSaved:\n+ return true, true, nil\n+ default:\n+ return false, false, k.saveStatus\n+ }\n+}\n+\n+// SetSaveSuccess sets the flag indicating that save completed successfully, if\n+// no status was already set.\n+func (k *Kernel) SetSaveSuccess(autosave bool) {\nk.extMu.Lock()\ndefer k.extMu.Unlock()\n- return k.saveErr\n+ if k.saveStatus == nil {\n+ if autosave {\n+ k.saveStatus = errAutoSaved\n+ } else {\n+ k.saveStatus = errSaved\n+ }\n+ }\n}\n// SetSaveError sets the sandbox error that caused the kernel to exit during\n@@ -1494,8 +1526,8 @@ func (k *Kernel) SaveError() error {\nfunc (k *Kernel) SetSaveError(err error) {\nk.extMu.Lock()\ndefer k.extMu.Unlock()\n- if k.saveErr == nil {\n- k.saveErr = err\n+ if k.saveStatus == nil {\n+ k.saveStatus = err\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/shm/BUILD", "new_path": "pkg/sentry/kernel/shm/BUILD", "diff": "@@ -6,6 +6,9 @@ package(licenses = [\"notice\"])\ngo_template_instance(\nname = \"shm_refs\",\nout = \"shm_refs.go\",\n+ consts = {\n+ \"enableLogging\": \"true\",\n+ },\npackage = \"shm\",\nprefix = \"Shm\",\ntemplate = \"//pkg/refsvfs2:refs_template\",\n" } ]
Go
Apache License 2.0
google/gvisor
Do not check for reference leaks after saving. We should not assert that all resources are dropped after saving. PiperOrigin-RevId: 347420131
259,896
14.12.2020 12:00:46
28,800
2e191cb3f72858c61943168a69b0aff0fda6ee45
Move SO_LINGER option to socketops.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -428,11 +428,7 @@ func (s *socketOpsCommon) Release(ctx context.Context) {\nreturn\n}\n- var v tcpip.LingerOption\n- if err := s.Endpoint.GetSockOpt(&v); err != nil {\n- return\n- }\n-\n+ v := s.Endpoint.SocketOptions().GetLinger()\n// The case for zero timeout is handled in tcp endpoint close function.\n// Close is blocked until either:\n// 1. The endpoint state is not in any of the states: FIN-WAIT1,\n@@ -1092,11 +1088,8 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nreturn nil, syserr.ErrInvalidArgument\n}\n- var v tcpip.LingerOption\nvar linger linux.Linger\n- if err := ep.GetSockOpt(&v); err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n+ v := ep.SocketOptions().GetLinger()\nif v.Enabled {\nlinger.OnOff = 1\n@@ -1899,10 +1892,11 @@ func setSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, nam\nsocket.SetSockOptEmitUnimplementedEvent(t, name)\n}\n- return syserr.TranslateNetstackError(\n- ep.SetSockOpt(&tcpip.LingerOption{\n+ ep.SocketOptions().SetLinger(tcpip.LingerOption{\nEnabled: v.OnOff != 0,\n- Timeout: time.Second * time.Duration(v.Linger)}))\n+ Timeout: time.Second * time.Duration(v.Linger),\n+ })\n+ return nil\ncase linux.SO_DETACH_FILTER:\n// optval is ignored.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/unix.go", "new_path": "pkg/sentry/socket/unix/transport/unix.go", "diff": "@@ -746,9 +746,6 @@ type baseEndpoint struct {\n// or may be used if the endpoint is connected.\npath string\n- // linger is used for SO_LINGER socket option.\n- linger tcpip.LingerOption\n-\n// ops is used to get socket level options.\nops tcpip.SocketOptions\n}\n@@ -840,12 +837,6 @@ func (e *baseEndpoint) SendMsg(ctx context.Context, data [][]byte, c ControlMess\n// SetSockOpt sets a socket option.\nfunc (e *baseEndpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch v := opt.(type) {\n- case *tcpip.LingerOption:\n- e.Lock()\n- e.linger = *v\n- e.Unlock()\n- }\nreturn nil\n}\n@@ -922,18 +913,9 @@ func (e *baseEndpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *baseEndpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n- switch o := opt.(type) {\n- case *tcpip.LingerOption:\n- e.Lock()\n- *o = e.linger\n- e.Unlock()\n- return nil\n-\n- default:\nlog.Warningf(\"Unsupported socket option: %T\", opt)\nreturn tcpip.ErrUnknownProtocolOption\n}\n-}\n// LastError implements Endpoint.LastError.\nfunc (*baseEndpoint) LastError() *tcpip.Error {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -16,6 +16,8 @@ package tcpip\nimport (\n\"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/sync\"\n)\n// SocketOptionsHandler holds methods that help define endpoint specific\n@@ -77,24 +79,24 @@ type SocketOptions struct {\n// These fields are accessed and modified using atomic operations.\n- // broadcastEnabled determines whether datagram sockets are allowed to send\n- // packets to a broadcast address.\n+ // broadcastEnabled determines whether datagram sockets are allowed to\n+ // send packets to a broadcast address.\nbroadcastEnabled uint32\n- // passCredEnabled determines whether SCM_CREDENTIALS socket control messages\n- // are enabled.\n+ // passCredEnabled determines whether SCM_CREDENTIALS socket control\n+ // messages are enabled.\npassCredEnabled uint32\n// noChecksumEnabled determines whether UDP checksum is disabled while\n// transmitting for this socket.\nnoChecksumEnabled uint32\n- // reuseAddressEnabled determines whether Bind() should allow reuse of local\n- // address.\n+ // reuseAddressEnabled determines whether Bind() should allow reuse of\n+ // local address.\nreuseAddressEnabled uint32\n- // reusePortEnabled determines whether to permit multiple sockets to be bound\n- // to an identical socket address.\n+ // reusePortEnabled determines whether to permit multiple sockets to be\n+ // bound to an identical socket address.\nreusePortEnabled uint32\n// keepAliveEnabled determines whether TCP keepalive is enabled for this\n@@ -142,6 +144,13 @@ type SocketOptions struct {\n// receiveOriginalDstAddress is used to specify if the original destination of\n// the incoming packet should be returned as an ancillary message.\nreceiveOriginalDstAddress uint32\n+\n+ // mu protects the access to the below fields.\n+ mu sync.Mutex `state:\"nosave\"`\n+\n+ // linger determines the amount of time the socket should linger before\n+ // close. We currently implement this option for TCP socket only.\n+ linger LingerOption\n}\n// InitHandler initializes the handler. This must be called before using the\n@@ -338,3 +347,18 @@ func (*SocketOptions) GetOutOfBandInline() bool {\n// SetOutOfBandInline sets value for SO_OOBINLINE option. We currently do not\n// support disabling this option.\nfunc (*SocketOptions) SetOutOfBandInline(bool) {}\n+\n+// GetLinger gets value for SO_LINGER option.\n+func (so *SocketOptions) GetLinger() LingerOption {\n+ so.mu.Lock()\n+ linger := so.linger\n+ so.mu.Unlock()\n+ return linger\n+}\n+\n+// SetLinger sets value for SO_LINGER option.\n+func (so *SocketOptions) SetLinger(linger LingerOption) {\n+ so.mu.Lock()\n+ so.linger = linger\n+ so.mu.Unlock()\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1145,10 +1145,6 @@ type LingerOption struct {\nTimeout time.Duration\n}\n-func (*LingerOption) isGettableSocketOption() {}\n-\n-func (*LingerOption) isSettableSocketOption() {}\n-\n// IPPacketInfo is the message structure for IP_PKTINFO.\n//\n// +stateify savable\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -75,8 +75,6 @@ type endpoint struct {\nroute *stack.Route `state:\"manual\"`\nttl uint8\nstats tcpip.TransportEndpointStats `state:\"nosave\"`\n- // linger is used for SO_LINGER socket option.\n- linger tcpip.LingerOption\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n@@ -338,15 +336,6 @@ func (e *endpoint) Peek([][]byte) (int64, *tcpip.Error) {\n// SetSockOpt sets a socket option.\nfunc (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch v := opt.(type) {\n- case *tcpip.SocketDetachFilterOption:\n- return nil\n-\n- case *tcpip.LingerOption:\n- e.mu.Lock()\n- e.linger = *v\n- e.mu.Unlock()\n- }\nreturn nil\n}\n@@ -399,17 +388,8 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n- switch o := opt.(type) {\n- case *tcpip.LingerOption:\n- e.mu.Lock()\n- *o = e.linger\n- e.mu.Unlock()\n- return nil\n-\n- default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n-}\nfunc send4(r *stack.Route, ident uint16, data buffer.View, ttl uint8, owner tcpip.PacketOwner) *tcpip.Error {\nif len(data) < header.ICMPv4MinimumSize {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint.go", "new_path": "pkg/tcpip/transport/packet/endpoint.go", "diff": "@@ -85,8 +85,6 @@ type endpoint struct {\nstats tcpip.TransportEndpointStats `state:\"nosave\"`\nbound bool\nboundNIC tcpip.NICID\n- // linger is used for SO_LINGER socket option.\n- linger tcpip.LingerOption\n// lastErrorMu protects lastError.\nlastErrorMu sync.Mutex `state:\"nosave\"`\n@@ -306,16 +304,10 @@ func (ep *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n// used with SetSockOpt, and this function always returns\n// tcpip.ErrNotSupported.\nfunc (ep *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch v := opt.(type) {\n+ switch opt.(type) {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n- case *tcpip.LingerOption:\n- ep.mu.Lock()\n- ep.linger = *v\n- ep.mu.Unlock()\n- return nil\n-\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -376,17 +368,8 @@ func (ep *endpoint) LastError() *tcpip.Error {\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (ep *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n- switch o := opt.(type) {\n- case *tcpip.LingerOption:\n- ep.mu.Lock()\n- *o = ep.linger\n- ep.mu.Unlock()\n- return nil\n-\n- default:\nreturn tcpip.ErrNotSupported\n}\n-}\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (ep *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -85,8 +85,6 @@ type endpoint struct {\n// Connect(), and is valid only when conneted is true.\nroute *stack.Route `state:\"manual\"`\nstats tcpip.TransportEndpointStats `state:\"nosave\"`\n- // linger is used for SO_LINGER socket option.\n- linger tcpip.LingerOption\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n@@ -532,16 +530,10 @@ func (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n// SetSockOpt implements tcpip.Endpoint.SetSockOpt.\nfunc (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch v := opt.(type) {\n+ switch opt.(type) {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n- case *tcpip.LingerOption:\n- e.mu.Lock()\n- e.linger = *v\n- e.mu.Unlock()\n- return nil\n-\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -593,17 +585,8 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n- switch o := opt.(type) {\n- case *tcpip.LingerOption:\n- e.mu.Lock()\n- *o = e.linger\n- e.mu.Unlock()\n- return nil\n-\n- default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n-}\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -674,9 +674,6 @@ type endpoint struct {\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n- // linger is used for SO_LINGER socket option.\n- linger tcpip.LingerOption\n-\n// ops is used to get socket level options.\nops tcpip.SocketOptions\n}\n@@ -1040,7 +1037,8 @@ func (e *endpoint) Close() {\nreturn\n}\n- if e.linger.Enabled && e.linger.Timeout == 0 {\n+ linger := e.SocketOptions().GetLinger()\n+ if linger.Enabled && linger.Timeout == 0 {\ns := e.EndpointState()\nisResetState := s == StateEstablished || s == StateCloseWait || s == StateFinWait1 || s == StateFinWait2 || s == StateSynRecv\nif isResetState {\n@@ -1906,11 +1904,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n- case *tcpip.LingerOption:\n- e.LockUser()\n- e.linger = *v\n- e.UnlockUser()\n-\ndefault:\nreturn nil\n}\n@@ -2071,11 +2064,6 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\nPort: port,\n}\n- case *tcpip.LingerOption:\n- e.LockUser()\n- *o = e.linger\n- e.UnlockUser()\n-\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -144,9 +144,6 @@ type endpoint struct {\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n- // linger is used for SO_LINGER socket option.\n- linger tcpip.LingerOption\n-\n// ops is used to get socket level options.\nops tcpip.SocketOptions\n}\n@@ -768,11 +765,6 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n-\n- case *tcpip.LingerOption:\n- e.mu.Lock()\n- e.linger = *v\n- e.mu.Unlock()\n}\nreturn nil\n}\n@@ -851,11 +843,6 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n*o = tcpip.BindToDeviceOption(e.bindToDevice)\ne.mu.RUnlock()\n- case *tcpip.LingerOption:\n- e.mu.RLock()\n- *o = e.linger\n- e.mu.RUnlock()\n-\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Move SO_LINGER option to socketops. PiperOrigin-RevId: 347437786
259,992
14.12.2020 21:15:49
28,800
b2a697334890705fa899fd81db52d7b11c03f785
Update containerd/cgroups
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -524,8 +524,8 @@ go_repository(\nname = \"com_github_containerd_cgroups\",\nbuild_file_proto_mode = \"disable\",\nimportpath = \"github.com/containerd/cgroups\",\n- sum = \"h1:5yg0k8gqOssNLsjjCtXIADoPbAtUtQZJfC8hQ4r2oFY=\",\n- version = \"v0.0.0-20181219155423-39b18af02c41\",\n+ sum = \"h1:7grrpcfCtbZLsjtB0DgMuzs1umsJmpzaHMZ6cO6iAWw=\",\n+ version = \"v0.0.0-20201119153540-4cbc285b3327\",\n)\ngo_repository(\n" }, { "change_type": "MODIFY", "old_path": "go.mod", "new_path": "go.mod", "diff": "@@ -10,7 +10,7 @@ require (\ngithub.com/Microsoft/hcsshim v0.8.6 // indirect\ngithub.com/cenkalti/backoff v1.1.1-0.20190506075156-2146c9339422 // indirect\ngithub.com/cilium/ebpf v0.0.0-20200110133405-4032b1d8aae3 // indirect\n- github.com/containerd/cgroups v0.0.0-20181219155423-39b18af02c41 // indirect\n+ github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327\ngithub.com/containerd/containerd v1.3.9 // indirect\ngithub.com/containerd/continuity v0.0.0-20200928162600-f2cc35102c2a // indirect\ngithub.com/containerd/fifo v0.0.0-20191213151349-ff969a566b00 // indirect\n" }, { "change_type": "MODIFY", "old_path": "go.sum", "new_path": "go.sum", "diff": "@@ -51,6 +51,8 @@ github.com/containerd/cgroups v0.0.0-20181219155423-39b18af02c41 h1:5yg0k8gqOssN\ngithub.com/containerd/cgroups v0.0.0-20181219155423-39b18af02c41/go.mod h1:X9rLEHIqSf/wfK8NsPqxJmeZgW4pcfzdXITDrUSJ6uI=\ngithub.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59 h1:qWj4qVYZ95vLWwqyNJCQg7rDsG5wPdze0UaPolH7DUk=\ngithub.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59/go.mod h1:pA0z1pT8KYB3TCXK/ocprsh7MAkoW8bZVzPdih9snmM=\n+github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327 h1:7grrpcfCtbZLsjtB0DgMuzs1umsJmpzaHMZ6cO6iAWw=\n+github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE=\ngithub.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw=\ngithub.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e h1:GdiIYd8ZDOrT++e1NjhSD4rGt9zaJukHm4rt5F4mRQc=\ngithub.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e/go.mod h1:8Pf4gM6VEbTNRIT26AyyU7hxdQU3MvAvxVI0sc00XBE=\n" }, { "change_type": "MODIFY", "old_path": "pkg/shim/v2/BUILD", "new_path": "pkg/shim/v2/BUILD", "diff": "@@ -22,6 +22,7 @@ go_library(\n\"//runsc/specutils\",\n\"@com_github_burntsushi_toml//:go_default_library\",\n\"@com_github_containerd_cgroups//:go_default_library\",\n+ \"@com_github_containerd_cgroups//stats/v1:go_default_library\",\n\"@com_github_containerd_console//:go_default_library\",\n\"@com_github_containerd_containerd//api/events:go_default_library\",\n\"@com_github_containerd_containerd//api/types/task:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/shim/v2/service.go", "new_path": "pkg/shim/v2/service.go", "diff": "@@ -28,6 +28,7 @@ import (\n\"github.com/BurntSushi/toml\"\n\"github.com/containerd/cgroups\"\n+ cgroupsstats \"github.com/containerd/cgroups/stats/v1\"\n\"github.com/containerd/console\"\n\"github.com/containerd/containerd/api/events\"\n\"github.com/containerd/containerd/api/types/task\"\n@@ -735,48 +736,48 @@ func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.\n// as runc.\n//\n// [0]: https://github.com/google/gvisor/blob/277a0d5a1fbe8272d4729c01ee4c6e374d047ebc/runsc/boot/events.go#L61-L81\n- metrics := &cgroups.Metrics{\n- CPU: &cgroups.CPUStat{\n- Usage: &cgroups.CPUUsage{\n+ metrics := &cgroupsstats.Metrics{\n+ CPU: &cgroupsstats.CPUStat{\n+ Usage: &cgroupsstats.CPUUsage{\nTotal: stats.Cpu.Usage.Total,\nKernel: stats.Cpu.Usage.Kernel,\nUser: stats.Cpu.Usage.User,\nPerCPU: stats.Cpu.Usage.Percpu,\n},\n- Throttling: &cgroups.Throttle{\n+ Throttling: &cgroupsstats.Throttle{\nPeriods: stats.Cpu.Throttling.Periods,\nThrottledPeriods: stats.Cpu.Throttling.ThrottledPeriods,\nThrottledTime: stats.Cpu.Throttling.ThrottledTime,\n},\n},\n- Memory: &cgroups.MemoryStat{\n+ Memory: &cgroupsstats.MemoryStat{\nCache: stats.Memory.Cache,\n- Usage: &cgroups.MemoryEntry{\n+ Usage: &cgroupsstats.MemoryEntry{\nLimit: stats.Memory.Usage.Limit,\nUsage: stats.Memory.Usage.Usage,\nMax: stats.Memory.Usage.Max,\nFailcnt: stats.Memory.Usage.Failcnt,\n},\n- Swap: &cgroups.MemoryEntry{\n+ Swap: &cgroupsstats.MemoryEntry{\nLimit: stats.Memory.Swap.Limit,\nUsage: stats.Memory.Swap.Usage,\nMax: stats.Memory.Swap.Max,\nFailcnt: stats.Memory.Swap.Failcnt,\n},\n- Kernel: &cgroups.MemoryEntry{\n+ Kernel: &cgroupsstats.MemoryEntry{\nLimit: stats.Memory.Kernel.Limit,\nUsage: stats.Memory.Kernel.Usage,\nMax: stats.Memory.Kernel.Max,\nFailcnt: stats.Memory.Kernel.Failcnt,\n},\n- KernelTCP: &cgroups.MemoryEntry{\n+ KernelTCP: &cgroupsstats.MemoryEntry{\nLimit: stats.Memory.KernelTCP.Limit,\nUsage: stats.Memory.KernelTCP.Usage,\nMax: stats.Memory.KernelTCP.Max,\nFailcnt: stats.Memory.KernelTCP.Failcnt,\n},\n},\n- Pids: &cgroups.PidsStat{\n+ Pids: &cgroupsstats.PidsStat{\nCurrent: stats.Pids.Current,\nLimit: stats.Pids.Limit,\n},\n" } ]
Go
Apache License 2.0
google/gvisor
Update containerd/cgroups PiperOrigin-RevId: 347532687
260,003
15.12.2020 09:53:20
28,800
25ebddbddfbc518a810c0aebde85a1b2e14bc7df
Fix a data race in packetEPs packetEPs may get into a state that `len < cap`, casuing append() modifying the original slice storage. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -54,9 +54,9 @@ type NIC struct {\nsync.RWMutex\nspoofing bool\npromiscuous bool\n- // packetEPs is protected by mu, but the contained PacketEndpoint\n- // values are not.\n- packetEPs map[tcpip.NetworkProtocolNumber][]PacketEndpoint\n+ // packetEPs is protected by mu, but the contained packetEndpointList are\n+ // not.\n+ packetEPs map[tcpip.NetworkProtocolNumber]*packetEndpointList\n}\n}\n@@ -82,6 +82,39 @@ type DirectionStats struct {\nBytes *tcpip.StatCounter\n}\n+type packetEndpointList struct {\n+ mu sync.RWMutex\n+\n+ // eps is protected by mu, but the contained PacketEndpoint values are not.\n+ eps []PacketEndpoint\n+}\n+\n+func (p *packetEndpointList) add(ep PacketEndpoint) {\n+ p.mu.Lock()\n+ defer p.mu.Unlock()\n+ p.eps = append(p.eps, ep)\n+}\n+\n+func (p *packetEndpointList) remove(ep PacketEndpoint) {\n+ p.mu.Lock()\n+ defer p.mu.Unlock()\n+ for i, epOther := range p.eps {\n+ if epOther == ep {\n+ p.eps = append(p.eps[:i], p.eps[i+1:]...)\n+ break\n+ }\n+ }\n+}\n+\n+// forEach calls fn with each endpoints in p while holding the read lock on p.\n+func (p *packetEndpointList) forEach(fn func(PacketEndpoint)) {\n+ p.mu.RLock()\n+ defer p.mu.RUnlock()\n+ for _, ep := range p.eps {\n+ fn(ep)\n+ }\n+}\n+\n// newNIC returns a new NIC using the default NDP configurations from stack.\nfunc newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICContext) *NIC {\n// TODO(b/141011931): Validate a LinkEndpoint (ep) is valid. For\n@@ -102,7 +135,7 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\nstats: makeNICStats(),\nnetworkEndpoints: make(map[tcpip.NetworkProtocolNumber]NetworkEndpoint),\n}\n- nic.mu.packetEPs = make(map[tcpip.NetworkProtocolNumber][]PacketEndpoint)\n+ nic.mu.packetEPs = make(map[tcpip.NetworkProtocolNumber]*packetEndpointList)\n// Check for Neighbor Unreachability Detection support.\nvar nud NUDHandler\n@@ -125,11 +158,11 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\n// Register supported packet and network endpoint protocols.\nfor _, netProto := range header.Ethertypes {\n- nic.mu.packetEPs[netProto] = []PacketEndpoint{}\n+ nic.mu.packetEPs[netProto] = new(packetEndpointList)\n}\nfor _, netProto := range stack.networkProtocols {\nnetNum := netProto.Number()\n- nic.mu.packetEPs[netNum] = nil\n+ nic.mu.packetEPs[netNum] = new(packetEndpointList)\nnic.networkEndpoints[netNum] = netProto.NewEndpoint(nic, stack, nud, nic)\n}\n@@ -638,15 +671,23 @@ func (n *NIC) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\npkt.RXTransportChecksumValidated = n.LinkEndpoint.Capabilities()&CapabilityRXChecksumOffload != 0\n// Are any packet type sockets listening for this network protocol?\n- packetEPs := n.mu.packetEPs[protocol]\n- // Add any other packet type sockets that may be listening for all protocols.\n- packetEPs = append(packetEPs, n.mu.packetEPs[header.EthernetProtocolAll]...)\n+ protoEPs := n.mu.packetEPs[protocol]\n+ // Other packet type sockets that are listening for all protocols.\n+ anyEPs := n.mu.packetEPs[header.EthernetProtocolAll]\nn.mu.RUnlock()\n- for _, ep := range packetEPs {\n+\n+ // Deliver to interested packet endpoints without holding NIC lock.\n+ deliverPacketEPs := func(ep PacketEndpoint) {\np := pkt.Clone()\np.PktType = tcpip.PacketHost\nep.HandlePacket(n.id, local, protocol, p)\n}\n+ if protoEPs != nil {\n+ protoEPs.forEach(deliverPacketEPs)\n+ }\n+ if anyEPs != nil {\n+ anyEPs.forEach(deliverPacketEPs)\n+ }\n// Parse headers.\nnetProto := n.stack.NetworkProtocolInstance(protocol)\n@@ -687,16 +728,17 @@ func (n *NIC) DeliverOutboundPacket(remote, local tcpip.LinkAddress, protocol tc\n// We do not deliver to protocol specific packet endpoints as on Linux\n// only ETH_P_ALL endpoints get outbound packets.\n// Add any other packet sockets that maybe listening for all protocols.\n- packetEPs := n.mu.packetEPs[header.EthernetProtocolAll]\n+ eps := n.mu.packetEPs[header.EthernetProtocolAll]\nn.mu.RUnlock()\n- for _, ep := range packetEPs {\n+\n+ eps.forEach(func(ep PacketEndpoint) {\np := pkt.Clone()\np.PktType = tcpip.PacketOutgoing\n// Add the link layer header as outgoing packets are intercepted\n// before the link layer header is created.\nn.LinkEndpoint.AddHeader(local, remote, protocol, p)\nep.HandlePacket(n.id, local, protocol, p)\n- }\n+ })\n}\n// DeliverTransportPacket delivers the packets to the appropriate transport\n@@ -849,7 +891,7 @@ func (n *NIC) registerPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep Pa\nif !ok {\nreturn tcpip.ErrNotSupported\n}\n- n.mu.packetEPs[netProto] = append(eps, ep)\n+ eps.add(ep)\nreturn nil\n}\n@@ -862,13 +904,7 @@ func (n *NIC) unregisterPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep\nif !ok {\nreturn\n}\n-\n- for i, epOther := range eps {\n- if epOther == ep {\n- n.mu.packetEPs[netProto] = append(eps[:i], eps[i+1:]...)\n- return\n- }\n- }\n+ eps.remove(ep)\n}\n// isValidForOutgoing returns true if the endpoint can be used to send out a\n" } ]
Go
Apache License 2.0
google/gvisor
Fix a data race in packetEPs packetEPs may get into a state that `len < cap`, casuing append() modifying the original slice storage. Reported-by: [email protected] PiperOrigin-RevId: 347634351
259,858
15.12.2020 10:02:55
28,800
4e963c99ce23ce6838b4bca351f767460601f34a
Cleanup GitHub actions workflows. Also, drop the pull_request template, since this has not proved to be helpful, and just results in a commit message the includes the list.
[ { "change_type": "DELETE", "old_path": ".github/pull_request_template.md", "new_path": null, "diff": "-* [ ] Have you followed the guidelines in [CONTRIBUTING.md](../blob/master/CONTRIBUTING.md)?\n-* [ ] Have you formatted and linted your code?\n-* [ ] Have you added relevant tests?\n-* [ ] Have you added appropriate Fixes & Updates references?\n-* [ ] If yes, please erase all these lines!\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "+# This workflow builds the source code, extracts nogo annotations and\n+# posts them to GitHub, if applicable. This leverages the fact that the\n+# workflow token has appropriate permissions to do so, and attempts to\n+# leverage the GitHub workflow caches.\n+#\n+# This workflow also generates the build badge that is referred to by\n+# the main README.\nname: \"Build\"\non:\npush:\nbranches:\n- master\n- - feature/**\npull_request:\nbranches:\n- - master\n- - feature/**\n+ - \"**\"\njobs:\ndefault:\n@@ -22,7 +27,7 @@ jobs:\n${{ runner.os }}-bazel-\n- run: make\n- run: make build OPTIONS=\"--build_tag_filters nogo\" TARGETS=\"//...\"\n- - run: make run TARGETS=\"//tools/github\" ARGS=\"-path=bazel-bin/ nogo\"\n+ - run: make run TARGETS=\"//tools/github\" ARGS=\"-path=bazel-bin/ -path=bazel-out/ nogo\"\nenv:\nGITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\nGITHUB_REPOSITORY: ${{ github.repository }}\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/go.yml", "new_path": ".github/workflows/go.yml", "diff": "+# This workflow generates the Go branch. Note that this does not test the Go\n+# branch, as this is rolled into the main continuous integration pipeline. This\n+# workflow simply generates and pushes the branch, as long as appropriate\n+# permissions are available.\nname: \"Go\"\non:\npush:\nbranches:\n- master\n- pull_request:\n- branches:\n- - master\n- - feature/**\njobs:\ngenerate:\n@@ -19,20 +19,13 @@ jobs:\nelse\necho ::set-output name=has_token::false\nfi\n- - run: |\n- jq -nc '{\"state\": \"pending\", \"context\": \"go tests\"}' | \\\n- curl -sL -X POST -d @- \\\n- -H \"Content-Type: application/json\" \\\n- -H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n- \"${{ github.event.pull_request.statuses_url }}\"\n- if: github.event_name == 'pull_request'\n- uses: actions/checkout@v2\n- if: github.event_name == 'push' && steps.setup.outputs.has_token == 'true'\n+ if: steps.setup.outputs.has_token == 'true'\nwith:\nfetch-depth: 0\ntoken: '${{ secrets.GO_TOKEN }}'\n- uses: actions/checkout@v2\n- if: github.event_name == 'pull_request' || steps.setup.outputs.has_token != 'true'\n+ if: steps.setup.outputs.has_token != 'true'\nwith:\nfetch-depth: 0\n- uses: actions/setup-go@v2\n@@ -50,32 +43,7 @@ jobs:\nkey: ${{ runner.os }}-bazel-${{ hashFiles('WORKSPACE') }}\nrestore-keys: |\n${{ runner.os }}-bazel-\n- # Create gopath to merge the changes. The first execution will create\n- # symlinks to the cache, e.g. bazel-bin. Once the cache is setup, delete\n- # old gopath files that may exist from previous runs (and could contain\n- # files that are now deleted). Then run gopath again for good.\n- - run: |\n- make build TARGETS=\"//:gopath\"\n- rm -rf bazel-bin/gopath\n- make build TARGETS=\"//:gopath\"\n- - run: tools/go_branch.sh\n- - run: git checkout go && git clean -f\n- - run: go build ./...\n- - if: github.event_name == 'push'\n+ - run: make go\nrun: |\ngit remote add upstream \"https://github.com/${{ github.repository }}\"\ngit push upstream go:go\n- - if: ${{ success() && github.event_name == 'pull_request' }}\n- run: |\n- jq -nc '{\"state\": \"success\", \"context\": \"go tests\"}' | \\\n- curl -sL -X POST -d @- \\\n- -H \"Content-Type: application/json\" \\\n- -H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n- \"${{ github.event.pull_request.statuses_url }}\"\n- - if: ${{ failure() && github.event_name == 'pull_request' }}\n- run: |\n- jq -nc '{\"state\": \"failure\", \"context\": \"go tests\"}' | \\\n- curl -sL -X POST -d @- \\\n- -H \"Content-Type: application/json\" \\\n- -H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n- \"${{ github.event.pull_request.statuses_url }}\"\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/issue_reviver.yml", "new_path": ".github/workflows/issue_reviver.yml", "diff": "+# This workflow revives issues that are still referenced in the code, and may\n+# have been accidentally closed or marked stale.\nname: \"Issue reviver\"\non:\nschedule:\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/labeler.yml", "new_path": ".github/workflows/labeler.yml", "diff": "+# Labeler labels incoming pull requests.\nname: \"Labeler\"\non:\n- pull_request\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/stale.yml", "new_path": ".github/workflows/stale.yml", "diff": "+# The stale workflow closes stale issues and pull requests, unless specific\n+# tags have been applied in order to keep them open.\nname: \"Close stale issues\"\non:\nschedule:\n" } ]
Go
Apache License 2.0
google/gvisor
Cleanup GitHub actions workflows. Also, drop the pull_request template, since this has not proved to be helpful, and just results in a commit message the includes the list. PiperOrigin-RevId: 347636507
259,896
15.12.2020 11:04:49
28,800
b15acae9a6e20a09a97b5fdfee5850469ff3b0ea
Fix error code for connect in raw sockets.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -404,7 +404,7 @@ func (*endpoint) Disconnect() *tcpip.Error {\nfunc (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n// Raw sockets do not support connecting to a IPv4 address on a IPv6 endpoint.\nif e.TransportEndpointInfo.NetProto == header.IPv6ProtocolNumber && len(addr.Addr) != header.IPv6AddressSize {\n- return tcpip.ErrInvalidOptionValue\n+ return tcpip.ErrAddressFamilyNotSupported\n}\ne.mu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/raw_socket.cc", "new_path": "test/syscalls/linux/raw_socket.cc", "diff": "@@ -894,7 +894,7 @@ TEST_P(RawSocketTest, ConnectOnIPv6Socket) {\nASSERT_THAT(connect(sock, reinterpret_cast<struct sockaddr*>(&addr),\nsizeof(sockaddr_in6)),\n- SyscallFailsWithErrno(EINVAL));\n+ SyscallFailsWithErrno(EAFNOSUPPORT));\n}\nINSTANTIATE_TEST_SUITE_P(\n" } ]
Go
Apache License 2.0
google/gvisor
Fix error code for connect in raw sockets. PiperOrigin-RevId: 347650354
260,001
15.12.2020 15:38:19
28,800
7aa674eb68e9b760ea72508dfb79a19dbf5b85ed
Change violation mode to an enum
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/filesystem.go", "new_path": "pkg/sentry/fsimpl/verity/filesystem.go", "diff": "@@ -163,7 +163,7 @@ afterSymlink:\n// verifyChildLocked verifies the hash of child against the already verified\n// hash of the parent to ensure the child is expected. verifyChild triggers a\n// sentry panic if unexpected modifications to the file system are detected. In\n-// noCrashOnVerificationFailure mode it returns a syserror instead.\n+// ErrorOnViolation mode it returns a syserror instead.\n//\n// Preconditions:\n// * fs.renameMu must be locked.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -92,10 +92,8 @@ const (\n)\nvar (\n- // noCrashOnVerificationFailure indicates whether the sandbox should panic\n- // whenever verification fails. If true, an error is returned instead of\n- // panicking. This should only be set for tests.\n- noCrashOnVerificationFailure bool\n+ // action specifies the action towards detected violation.\n+ action ViolationAction\n// verityMu synchronizes concurrent operations that enable verity and perform\n// verification checks.\n@@ -106,6 +104,18 @@ var (\n// content.\ntype HashAlgorithm int\n+// ViolationAction is a type specifying the action when an integrity violation\n+// is detected.\n+type ViolationAction int\n+\n+const (\n+ // PanicOnViolation terminates the sentry on detected violation.\n+ PanicOnViolation ViolationAction = 0\n+ // ErrorOnViolation returns an error from the violating system call on\n+ // detected violation.\n+ ErrorOnViolation = 1\n+)\n+\n// Currently supported hashing algorithms include SHA256 and SHA512.\nconst (\nSHA256 HashAlgorithm = iota\n@@ -200,10 +210,8 @@ type InternalFilesystemOptions struct {\n// system wrapped by verity file system.\nLowerGetFSOptions vfs.GetFilesystemOptions\n- // NoCrashOnVerificationFailure indicates whether the sandbox should\n- // panic whenever verification fails. If true, an error is returned\n- // instead of panicking. This should only be set for tests.\n- NoCrashOnVerificationFailure bool\n+ // Action specifies the action on an integrity violation.\n+ Action ViolationAction\n}\n// Name implements vfs.FilesystemType.Name.\n@@ -215,10 +223,10 @@ func (FilesystemType) Name() string {\nfunc (FilesystemType) Release(ctx context.Context) {}\n// alertIntegrityViolation alerts a violation of integrity, which usually means\n-// unexpected modification to the file system is detected. In\n-// noCrashOnVerificationFailure mode, it returns EIO, otherwise it panic.\n+// unexpected modification to the file system is detected. In ErrorOnViolation\n+// mode, it returns EIO, otherwise it panic.\nfunc alertIntegrityViolation(msg string) error {\n- if noCrashOnVerificationFailure {\n+ if action == ErrorOnViolation {\nreturn syserror.EIO\n}\npanic(msg)\n@@ -231,7 +239,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nctx.Warningf(\"verity.FilesystemType.GetFilesystem: missing verity configs\")\nreturn nil, nil, syserror.EINVAL\n}\n- noCrashOnVerificationFailure = iopts.NoCrashOnVerificationFailure\n+ action = iopts.Action\n// Mount the lower file system. The lower file system is wrapped inside\n// verity, and should not be exposed or connected.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity_test.go", "new_path": "pkg/sentry/fsimpl/verity/verity_test.go", "diff": "@@ -96,7 +96,7 @@ func newVerityRoot(t *testing.T, hashAlg HashAlgorithm) (*vfs.VirtualFilesystem,\nLowerName: \"tmpfs\",\nAlg: hashAlg,\nAllowRuntimeEnable: true,\n- NoCrashOnVerificationFailure: true,\n+ Action: ErrorOnViolation,\n},\n},\n})\n" } ]
Go
Apache License 2.0
google/gvisor
Change violation mode to an enum PiperOrigin-RevId: 347706953
259,875
15.12.2020 16:03:41
28,800
1e56a2f9a29ff72eada493bf024a4e3fd5a963b6
Implement command SEM_INFO and SEM_STAT for semctl.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/sem.go", "new_path": "pkg/abi/linux/sem.go", "diff": "@@ -43,10 +43,10 @@ const (\nSEMVMX = 32767\nSEMAEM = SEMVMX\n- // followings are unused in kernel\nSEMUME = SEMOPM\nSEMMNU = SEMMNS\nSEMMAP = SEMMNS\n+ SEMUSZ = 20\n)\nconst SEM_UNDO = 0x1000\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore.go", "diff": "@@ -193,12 +193,26 @@ func (r *Registry) IPCInfo() *linux.SemInfo {\nSemMsl: linux.SEMMSL,\nSemOpm: linux.SEMOPM,\nSemUme: linux.SEMUME,\n- SemUsz: 0, // SemUsz not supported.\n+ SemUsz: linux.SEMUSZ,\nSemVmx: linux.SEMVMX,\nSemAem: linux.SEMAEM,\n}\n}\n+// SemInfo returns a seminfo structure containing the same information as\n+// for IPC_INFO, except that SemUsz field returns the number of existing\n+// semaphore sets, and SemAem field returns the number of existing semaphores.\n+func (r *Registry) SemInfo() *linux.SemInfo {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+\n+ info := r.IPCInfo()\n+ info.SemUsz = uint32(len(r.semaphores))\n+ info.SemAem = uint32(r.totalSems())\n+\n+ return info\n+}\n+\n// HighestIndex returns the index of the highest used entry in\n// the kernel's array.\nfunc (r *Registry) HighestIndex() int32 {\n@@ -289,6 +303,18 @@ func (r *Registry) FindByID(id int32) *Set {\nreturn r.semaphores[id]\n}\n+// FindByIndex looks up a set given an index.\n+func (r *Registry) FindByIndex(index int32) *Set {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+\n+ id, present := r.indexes[index]\n+ if !present {\n+ return nil\n+ }\n+ return r.semaphores[id]\n+}\n+\nfunc (r *Registry) findByKey(key int32) *Set {\nfor _, v := range r.semaphores {\nif v.key == key {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64.go", "new_path": "pkg/sentry/syscalls/linux/linux64.go", "diff": "@@ -118,7 +118,7 @@ var AMD64 = &kernel.SyscallTable{\n63: syscalls.Supported(\"uname\", Uname),\n64: syscalls.Supported(\"semget\", Semget),\n65: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n- 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n+ 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_STAT_ANY not supported.\", nil),\n67: syscalls.Supported(\"shmdt\", Shmdt),\n68: syscalls.ErrorWithEvent(\"msgget\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n69: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n@@ -619,7 +619,7 @@ var ARM64 = &kernel.SyscallTable{\n188: syscalls.ErrorWithEvent(\"msgrcv\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n- 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n+ 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_STAT_ANY not supported.\", nil),\n192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_sem.go", "new_path": "pkg/sentry/syscalls/linux/sys_sem.go", "diff": "@@ -155,10 +155,28 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n}\nreturn uintptr(r.HighestIndex()), nil, nil\n- case linux.SEM_INFO,\n- linux.SEM_STAT,\n- linux.SEM_STAT_ANY:\n+ case linux.SEM_INFO:\n+ buf := args[3].Pointer()\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ info := r.SemInfo()\n+ if _, err := info.CopyOut(t, buf); err != nil {\n+ return 0, nil, err\n+ }\n+ return uintptr(r.HighestIndex()), nil, nil\n+\n+ case linux.SEM_STAT:\n+ arg := args[3].Pointer()\n+ // id is an index in SEM_STAT.\n+ semid, ds, err := semStat(t, id)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ if _, err := ds.CopyOut(t, arg); err != nil {\n+ return 0, nil, err\n+ }\n+ return uintptr(semid), nil, err\n+ case linux.SEM_STAT_ANY:\nt.Kernel().EmitUnimplementedEvent(t)\nfallthrough\n@@ -203,6 +221,17 @@ func ipcStat(t *kernel.Task, id int32) (*linux.SemidDS, error) {\nreturn set.GetStat(creds)\n}\n+func semStat(t *kernel.Task, index int32) (int32, *linux.SemidDS, error) {\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ set := r.FindByIndex(index)\n+ if set == nil {\n+ return 0, nil, syserror.EINVAL\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ ds, err := set.GetStat(creds)\n+ return set.ID, ds, err\n+}\n+\nfunc setVal(t *kernel.Task, id int32, num int32, val int16) error {\nr := t.IPCNamespace().SemaphoreRegistry()\nset := r.FindByID(id)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/semaphore.cc", "new_path": "test/syscalls/linux/semaphore.cc", "diff": "#include <atomic>\n#include <cerrno>\n#include <ctime>\n-#include <stack>\n+#include <set>\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n+using ::testing::Contains;\n+\nnamespace gvisor {\nnamespace testing {\nnamespace {\n+constexpr int kSemMap = 1024000000;\n+constexpr int kSemMni = 32000;\n+constexpr int kSemMns = 1024000000;\n+constexpr int kSemMnu = 1024000000;\n+constexpr int kSemMsl = 32000;\n+constexpr int kSemOpm = 500;\n+constexpr int kSemUme = 500;\n+constexpr int kSemUsz = 20;\n+constexpr int kSemVmx = 32767;\n+constexpr int kSemAem = 32767;\n+\nclass AutoSem {\npublic:\nexplicit AutoSem(int id) : id_(id) {}\n@@ -775,42 +788,151 @@ TEST(SemaphoreTest, SemopGetncntOnSignal_NoRandomSave) {\n}\nTEST(SemaphoreTest, IpcInfo) {\n- std::stack<int> sem_ids;\n- std::stack<int> max_used_indexes;\n+ constexpr int kLoops = 5;\n+ std::set<int> sem_ids;\nstruct seminfo info;\n- for (int i = 0; i < 3; i++) {\n- int sem_id = 0;\n- ASSERT_THAT(sem_id = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT),\n- SyscallSucceeds());\n- sem_ids.push(sem_id);\n+ // Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n+ ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceedsWithValue(0));\n+ for (int i = 0; i < kLoops; i++) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+ sem_ids.insert(sem.release());\n+ }\n+ ASSERT_EQ(sem_ids.size(), kLoops);\n+\nint max_used_index = 0;\nEXPECT_THAT(max_used_index = semctl(0, 0, IPC_INFO, &info),\nSyscallSucceeds());\n- if (!max_used_indexes.empty()) {\n- EXPECT_GT(max_used_index, max_used_indexes.top());\n+\n+ int index_count = 0;\n+ for (int i = 0; i <= max_used_index; i++) {\n+ struct semid_ds ds = {};\n+ int sem_id = semctl(i, 0, SEM_STAT, &ds);\n+ // Only if index i is used within the registry.\n+ if (sem_id != -1) {\n+ ASSERT_THAT(sem_ids, Contains(sem_id));\n+ struct semid_ds ipc_stat_ds;\n+ ASSERT_THAT(semctl(sem_id, 0, IPC_STAT, &ipc_stat_ds), SyscallSucceeds());\n+ EXPECT_EQ(ds.sem_perm.__key, ipc_stat_ds.sem_perm.__key);\n+ EXPECT_EQ(ds.sem_perm.uid, ipc_stat_ds.sem_perm.uid);\n+ EXPECT_EQ(ds.sem_perm.gid, ipc_stat_ds.sem_perm.gid);\n+ EXPECT_EQ(ds.sem_perm.cuid, ipc_stat_ds.sem_perm.cuid);\n+ EXPECT_EQ(ds.sem_perm.cgid, ipc_stat_ds.sem_perm.cgid);\n+ EXPECT_EQ(ds.sem_perm.mode, ipc_stat_ds.sem_perm.mode);\n+ EXPECT_EQ(ds.sem_otime, ipc_stat_ds.sem_otime);\n+ EXPECT_EQ(ds.sem_ctime, ipc_stat_ds.sem_ctime);\n+ EXPECT_EQ(ds.sem_nsems, ipc_stat_ds.sem_nsems);\n+\n+ // Remove the semaphore set's read permission.\n+ struct semid_ds ipc_set_ds;\n+ ipc_set_ds.sem_perm.uid = getuid();\n+ ipc_set_ds.sem_perm.gid = getgid();\n+ // Keep the semaphore set's write permission so that it could be removed.\n+ ipc_set_ds.sem_perm.mode = 0200;\n+ ASSERT_THAT(semctl(sem_id, 0, IPC_SET, &ipc_set_ds), SyscallSucceeds());\n+ ASSERT_THAT(semctl(i, 0, SEM_STAT, &ds), SyscallFailsWithErrno(EACCES));\n+\n+ index_count += 1;\n+ }\n+ }\n+ EXPECT_EQ(index_count, kLoops);\n+ ASSERT_THAT(semctl(0, 0, IPC_INFO, &info),\n+ SyscallSucceedsWithValue(max_used_index));\n+ for (const int sem_id : sem_ids) {\n+ ASSERT_THAT(semctl(sem_id, 0, IPC_RMID), SyscallSucceeds());\n}\n- max_used_indexes.push(max_used_index);\n+\n+ ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(info.semmap, kSemMap);\n+ EXPECT_EQ(info.semmni, kSemMni);\n+ EXPECT_EQ(info.semmns, kSemMns);\n+ EXPECT_EQ(info.semmnu, kSemMnu);\n+ EXPECT_EQ(info.semmsl, kSemMsl);\n+ EXPECT_EQ(info.semopm, kSemOpm);\n+ EXPECT_EQ(info.semume, kSemUme);\n+ EXPECT_EQ(info.semusz, kSemUsz);\n+ EXPECT_EQ(info.semvmx, kSemVmx);\n+ EXPECT_EQ(info.semaem, kSemAem);\n+}\n+\n+TEST(SemaphoreTest, SemInfo) {\n+ constexpr int kLoops = 5;\n+ constexpr int kSemSetSize = 3;\n+ std::set<int> sem_ids;\n+ struct seminfo info;\n+ // Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n+ ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceedsWithValue(0));\n+ for (int i = 0; i < kLoops; i++) {\n+ AutoSem sem(semget(IPC_PRIVATE, kSemSetSize, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+ sem_ids.insert(sem.release());\n}\n- while (!sem_ids.empty()) {\n- int sem_id = sem_ids.top();\n- sem_ids.pop();\n+ ASSERT_EQ(sem_ids.size(), kLoops);\n+ int max_used_index = 0;\n+ EXPECT_THAT(max_used_index = semctl(0, 0, SEM_INFO, &info),\n+ SyscallSucceeds());\n+ EXPECT_EQ(info.semmap, kSemMap);\n+ EXPECT_EQ(info.semmni, kSemMni);\n+ EXPECT_EQ(info.semmns, kSemMns);\n+ EXPECT_EQ(info.semmnu, kSemMnu);\n+ EXPECT_EQ(info.semmsl, kSemMsl);\n+ EXPECT_EQ(info.semopm, kSemOpm);\n+ EXPECT_EQ(info.semume, kSemUme);\n+ EXPECT_EQ(info.semusz, sem_ids.size());\n+ EXPECT_EQ(info.semvmx, kSemVmx);\n+ EXPECT_EQ(info.semaem, sem_ids.size() * kSemSetSize);\n+\n+ int index_count = 0;\n+ for (int i = 0; i <= max_used_index; i++) {\n+ struct semid_ds ds = {};\n+ int sem_id = semctl(i, 0, SEM_STAT, &ds);\n+ // Only if index i is used within the registry.\n+ if (sem_id != -1) {\n+ ASSERT_THAT(sem_ids, Contains(sem_id));\n+ struct semid_ds ipc_stat_ds;\n+ ASSERT_THAT(semctl(sem_id, 0, IPC_STAT, &ipc_stat_ds), SyscallSucceeds());\n+ EXPECT_EQ(ds.sem_perm.__key, ipc_stat_ds.sem_perm.__key);\n+ EXPECT_EQ(ds.sem_perm.uid, ipc_stat_ds.sem_perm.uid);\n+ EXPECT_EQ(ds.sem_perm.gid, ipc_stat_ds.sem_perm.gid);\n+ EXPECT_EQ(ds.sem_perm.cuid, ipc_stat_ds.sem_perm.cuid);\n+ EXPECT_EQ(ds.sem_perm.cgid, ipc_stat_ds.sem_perm.cgid);\n+ EXPECT_EQ(ds.sem_perm.mode, ipc_stat_ds.sem_perm.mode);\n+ EXPECT_EQ(ds.sem_otime, ipc_stat_ds.sem_otime);\n+ EXPECT_EQ(ds.sem_ctime, ipc_stat_ds.sem_ctime);\n+ EXPECT_EQ(ds.sem_nsems, ipc_stat_ds.sem_nsems);\n+\n+ // Remove the semaphore set's read permission.\n+ struct semid_ds ipc_set_ds;\n+ ipc_set_ds.sem_perm.uid = getuid();\n+ ipc_set_ds.sem_perm.gid = getgid();\n+ // Keep the semaphore set's write permission so that it could be removed.\n+ ipc_set_ds.sem_perm.mode = 0200;\n+ ASSERT_THAT(semctl(sem_id, 0, IPC_SET, &ipc_set_ds), SyscallSucceeds());\n+ ASSERT_THAT(semctl(i, 0, SEM_STAT, &ds), SyscallFailsWithErrno(EACCES));\n+\n+ index_count += 1;\n+ }\n+ }\n+ EXPECT_EQ(index_count, kLoops);\n+ ASSERT_THAT(semctl(0, 0, SEM_INFO, &info),\n+ SyscallSucceedsWithValue(max_used_index));\n+ for (const int sem_id : sem_ids) {\nASSERT_THAT(semctl(sem_id, 0, IPC_RMID), SyscallSucceeds());\n- int max_index = max_used_indexes.top();\n- EXPECT_THAT(max_index = semctl(0, 0, IPC_INFO, &info), SyscallSucceeds());\n- EXPECT_GE(max_used_indexes.top(), max_index);\n- max_used_indexes.pop();\n}\n- ASSERT_THAT(semctl(0, 0, IPC_INFO, &info), SyscallSucceedsWithValue(0));\n- EXPECT_EQ(info.semmap, 1024000000);\n- EXPECT_EQ(info.semmni, 32000);\n- EXPECT_EQ(info.semmns, 1024000000);\n- EXPECT_EQ(info.semmnu, 1024000000);\n- EXPECT_EQ(info.semmsl, 32000);\n- EXPECT_EQ(info.semopm, 500);\n- EXPECT_EQ(info.semume, 500);\n- EXPECT_EQ(info.semvmx, 32767);\n- EXPECT_EQ(info.semaem, 32767);\n+ ASSERT_THAT(semctl(0, 0, SEM_INFO, &info), SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(info.semmap, kSemMap);\n+ EXPECT_EQ(info.semmni, kSemMni);\n+ EXPECT_EQ(info.semmns, kSemMns);\n+ EXPECT_EQ(info.semmnu, kSemMnu);\n+ EXPECT_EQ(info.semmsl, kSemMsl);\n+ EXPECT_EQ(info.semopm, kSemOpm);\n+ EXPECT_EQ(info.semume, kSemUme);\n+ EXPECT_EQ(info.semusz, 0);\n+ EXPECT_EQ(info.semvmx, kSemVmx);\n+ EXPECT_EQ(info.semaem, 0);\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Implement command SEM_INFO and SEM_STAT for semctl. PiperOrigin-RevId: 347711998
260,004
15.12.2020 16:27:01
28,800
50c658a9f6df85998a08f51f680302366c2df240
Don't split enabled flag across multicast group state Startblock: has LGTM from asfez and then add reviewer brunodalbo
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "new_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "diff": "@@ -131,17 +131,6 @@ type multicastGroupState struct {\n// GenericMulticastProtocolOptions holds options for the generic multicast\n// protocol.\ntype GenericMulticastProtocolOptions struct {\n- // Enabled indicates whether the generic multicast protocol will be\n- // performed.\n- //\n- // When enabled, the protocol may transmit report and leave messages when\n- // joining and leaving multicast groups respectively, and handle incoming\n- // packets.\n- //\n- // When disabled, the protocol will still keep track of locally joined groups,\n- // it just won't transmit and handle packets, or update groups' state.\n- Enabled bool\n-\n// Rand is the source of random numbers.\nRand *rand.Rand\n@@ -170,6 +159,17 @@ type GenericMulticastProtocolOptions struct {\n// MulticastGroupProtocol is a multicast group protocol whose core state machine\n// can be represented by GenericMulticastProtocolState.\ntype MulticastGroupProtocol interface {\n+ // Enabled indicates whether the generic multicast protocol will be\n+ // performed.\n+ //\n+ // When enabled, the protocol may transmit report and leave messages when\n+ // joining and leaving multicast groups respectively, and handle incoming\n+ // packets.\n+ //\n+ // When disabled, the protocol will still keep track of locally joined groups,\n+ // it just won't transmit and handle packets, or update groups' state.\n+ Enabled() bool\n+\n// SendReport sends a multicast report for the specified group address.\n//\n// Returns false if the caller should queue the report to be sent later. Note,\n@@ -196,6 +196,9 @@ type MulticastGroupProtocol interface {\n//\n// GenericMulticastProtocolState.Init MUST be called before calling any of\n// the methods on GenericMulticastProtocolState.\n+//\n+// GenericMulticastProtocolState.MakeAllNonMemberLocked MUST be called when the\n+// multicast group protocol is disabled so that leave messages may be sent.\ntype GenericMulticastProtocolState struct {\n// Do not allow overwriting this state.\n_ sync.NoCopy\n@@ -235,9 +238,11 @@ func (g *GenericMulticastProtocolState) Init(protocolMU *sync.RWMutex, opts Gene\n//\n// The groups will still be considered joined locally.\n//\n+// MUST be called when the multicast group protocol is disabled.\n+//\n// Precondition: g.protocolMU must be locked.\nfunc (g *GenericMulticastProtocolState) MakeAllNonMemberLocked() {\n- if !g.opts.Enabled {\n+ if !g.opts.Protocol.Enabled() {\nreturn\n}\n@@ -255,7 +260,7 @@ func (g *GenericMulticastProtocolState) MakeAllNonMemberLocked() {\n//\n// Precondition: g.protocolMU must be locked.\nfunc (g *GenericMulticastProtocolState) InitializeGroupsLocked() {\n- if !g.opts.Enabled {\n+ if !g.opts.Protocol.Enabled() {\nreturn\n}\n@@ -290,12 +295,8 @@ func (g *GenericMulticastProtocolState) SendQueuedReportsLocked() {\n// JoinGroupLocked handles joining a new group.\n//\n-// If dontInitialize is true, the group will be not be initialized and will be\n-// left in the non-member state - no packets will be sent for it until it is\n-// initialized via InitializeGroups.\n-//\n// Precondition: g.protocolMU must be locked.\n-func (g *GenericMulticastProtocolState) JoinGroupLocked(groupAddress tcpip.Address, dontInitialize bool) {\n+func (g *GenericMulticastProtocolState) JoinGroupLocked(groupAddress tcpip.Address) {\nif info, ok := g.memberships[groupAddress]; ok {\n// The group has already been joined.\ninfo.joins++\n@@ -310,6 +311,10 @@ func (g *GenericMulticastProtocolState) JoinGroupLocked(groupAddress tcpip.Addre\nstate: nonMember,\nlastToSendReport: false,\ndelayedReportJob: tcpip.NewJob(g.opts.Clock, g.protocolMU, func() {\n+ if !g.opts.Protocol.Enabled() {\n+ panic(fmt.Sprintf(\"delayed report job fired for group %s while the multicast group protocol is disabled\", groupAddress))\n+ }\n+\ninfo, ok := g.memberships[groupAddress]\nif !ok {\npanic(fmt.Sprintf(\"expected to find group state for group = %s\", groupAddress))\n@@ -320,7 +325,7 @@ func (g *GenericMulticastProtocolState) JoinGroupLocked(groupAddress tcpip.Addre\n}),\n}\n- if !dontInitialize && g.opts.Enabled {\n+ if g.opts.Protocol.Enabled() {\ng.initializeNewMemberLocked(groupAddress, &info)\n}\n@@ -372,7 +377,7 @@ func (g *GenericMulticastProtocolState) LeaveGroupLocked(groupAddress tcpip.Addr\n//\n// Precondition: g.protocolMU must be locked.\nfunc (g *GenericMulticastProtocolState) HandleQueryLocked(groupAddress tcpip.Address, maxResponseTime time.Duration) {\n- if !g.opts.Enabled {\n+ if !g.opts.Protocol.Enabled() {\nreturn\n}\n@@ -406,7 +411,7 @@ func (g *GenericMulticastProtocolState) HandleQueryLocked(groupAddress tcpip.Add\n//\n// Precondition: g.protocolMU must be locked.\nfunc (g *GenericMulticastProtocolState) HandleReportLocked(groupAddress tcpip.Address) {\n- if !g.opts.Enabled {\n+ if !g.opts.Protocol.Enabled() {\nreturn\n}\n@@ -518,7 +523,7 @@ func (g *GenericMulticastProtocolState) maybeSendDelayedReportLocked(groupAddres\n// maybeSendLeave attempts to send a leave message.\nfunc (g *GenericMulticastProtocolState) maybeSendLeave(groupAddress tcpip.Address, lastToSendReport bool) {\n- if !g.opts.Enabled || !lastToSendReport {\n+ if !g.opts.Protocol.Enabled() || !lastToSendReport {\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip/generic_multicast_protocol_test.go", "new_path": "pkg/tcpip/network/ip/generic_multicast_protocol_test.go", "diff": "@@ -50,6 +50,9 @@ type mockMulticastGroupProtocol struct {\n// Must only be accessed with mu held.\nmakeQueuePackets bool\n+\n+ // Must only be accessed with mu held.\n+ disabled bool\n}\nfunc (m *mockMulticastGroupProtocol) init() {\n@@ -63,6 +66,22 @@ func (m *mockMulticastGroupProtocol) initLocked() {\nm.sendLeaveGroupAddrCount = make(map[tcpip.Address]int)\n}\n+func (m *mockMulticastGroupProtocol) setEnabled(v bool) {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.disabled = !v\n+}\n+\n+// Enabled implements ip.MulticastGroupProtocol.\n+//\n+// Precondition: m.mu must be read locked.\n+func (m *mockMulticastGroupProtocol) Enabled() bool {\n+ return !m.disabled\n+}\n+\n+// SendReport implements ip.MulticastGroupProtocol.\n+//\n+// Precondition: m.mu must be locked.\nfunc (m *mockMulticastGroupProtocol) SendReport(groupAddress tcpip.Address) (bool, *tcpip.Error) {\nif m.mu.TryLock() {\nm.mu.Unlock()\n@@ -77,6 +96,9 @@ func (m *mockMulticastGroupProtocol) SendReport(groupAddress tcpip.Address) (boo\nreturn !m.makeQueuePackets, nil\n}\n+// SendLeave implements ip.MulticastGroupProtocol.\n+//\n+// Precondition: m.mu must be locked.\nfunc (m *mockMulticastGroupProtocol) SendLeave(groupAddress tcpip.Address) *tcpip.Error {\nif m.mu.TryLock() {\nm.mu.Unlock()\n@@ -115,7 +137,11 @@ func (m *mockMulticastGroupProtocol) check(sendReportGroupAddresses []tcpip.Addr\n// ignore mockMulticastGroupProtocol.mu and mockMulticastGroupProtocol.t\ncmp.FilterPath(\nfunc(p cmp.Path) bool {\n- return p.Last().String() == \".mu\" || p.Last().String() == \".t\" || p.Last().String() == \".makeQueuePackets\"\n+ switch p.Last().String() {\n+ case \".mu\", \".t\", \".makeQueuePackets\", \".disabled\":\n+ return true\n+ }\n+ return false\n},\ncmp.Ignore(),\n),\n@@ -150,7 +176,6 @@ func TestJoinGroup(t *testing.T) {\nmgp.init()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(0)),\nClock: clock,\nProtocol: &mgp,\n@@ -161,7 +186,7 @@ func TestJoinGroup(t *testing.T) {\n// Joining a group should send a report immediately and another after\n// a random interval between 0 and the maximum unsolicited report delay.\nmgp.mu.Lock()\n- g.JoinGroupLocked(test.addr, false /* dontInitialize */)\n+ g.JoinGroupLocked(test.addr)\nmgp.mu.Unlock()\nif test.shouldSendReports {\nif diff := mgp.check([]tcpip.Address{test.addr} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n@@ -210,7 +235,6 @@ func TestLeaveGroup(t *testing.T) {\nmgp.init()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(1)),\nClock: clock,\nProtocol: &mgp,\n@@ -219,7 +243,7 @@ func TestLeaveGroup(t *testing.T) {\n})\nmgp.mu.Lock()\n- g.JoinGroupLocked(test.addr, false /* dontInitialize */)\n+ g.JoinGroupLocked(test.addr)\nmgp.mu.Unlock()\nif test.shouldSendMessages {\nif diff := mgp.check([]tcpip.Address{test.addr} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n@@ -295,7 +319,6 @@ func TestHandleReport(t *testing.T) {\nmgp.init()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(2)),\nClock: clock,\nProtocol: &mgp,\n@@ -304,19 +327,19 @@ func TestHandleReport(t *testing.T) {\n})\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr1, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr1)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr2, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr2)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr3, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr3)\nmgp.mu.Unlock()\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -391,7 +414,6 @@ func TestHandleQuery(t *testing.T) {\nmgp.init()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(3)),\nClock: clock,\nProtocol: &mgp,\n@@ -400,19 +422,19 @@ func TestHandleQuery(t *testing.T) {\n})\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr1, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr1)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr2, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr2)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr3, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr3)\nmgp.mu.Unlock()\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -451,7 +473,6 @@ func TestJoinCount(t *testing.T) {\nmgp.init()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(4)),\nClock: clock,\nProtocol: &mgp,\n@@ -461,7 +482,7 @@ func TestJoinCount(t *testing.T) {\n// Set the join count to 2 for a group.\n{\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr1, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr1)\nres := g.IsLocallyJoinedRLocked(addr1)\nmgp.mu.Unlock()\nif !res {\n@@ -474,7 +495,7 @@ func TestJoinCount(t *testing.T) {\n}\n{\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr1, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr1)\nres := g.IsLocallyJoinedRLocked(addr1)\nmgp.mu.Unlock()\nif !res {\n@@ -563,7 +584,6 @@ func TestMakeAllNonMemberAndInitialize(t *testing.T) {\nmgp.init()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(3)),\nClock: clock,\nProtocol: &mgp,\n@@ -572,19 +592,19 @@ func TestMakeAllNonMemberAndInitialize(t *testing.T) {\n})\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr1, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr1)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr2, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr2)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr3, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr3)\nmgp.mu.Unlock()\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -634,37 +654,13 @@ func TestMakeAllNonMemberAndInitialize(t *testing.T) {\n// TestGroupStateNonMember tests that groups do not send packets when in the\n// non-member state, but are still considered locally joined.\nfunc TestGroupStateNonMember(t *testing.T) {\n- tests := []struct {\n- name string\n- enabled bool\n- dontInitialize bool\n- }{\n- {\n- name: \"Disabled\",\n- enabled: false,\n- dontInitialize: false,\n- },\n- {\n- name: \"Keep non-member\",\n- enabled: true,\n- dontInitialize: true,\n- },\n- {\n- name: \"disabled and Keep non-member\",\n- enabled: false,\n- dontInitialize: true,\n- },\n- }\n-\n- for _, test := range tests {\n- t.Run(test.name, func(t *testing.T) {\nvar g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\nmgp.init()\n+ mgp.setEnabled(false)\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: test.enabled,\nRand: rand.New(rand.NewSource(3)),\nClock: clock,\nProtocol: &mgp,\n@@ -674,7 +670,7 @@ func TestGroupStateNonMember(t *testing.T) {\n// Joining groups should not send any reports.\n{\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr1, test.dontInitialize)\n+ g.JoinGroupLocked(addr1)\nres := g.IsLocallyJoinedRLocked(addr1)\nmgp.mu.Unlock()\nif !res {\n@@ -686,7 +682,7 @@ func TestGroupStateNonMember(t *testing.T) {\n}\n{\nmgp.mu.Lock()\n- g.JoinGroupLocked(addr2, test.dontInitialize)\n+ g.JoinGroupLocked(addr2)\nres := g.IsLocallyJoinedRLocked(addr2)\nmgp.mu.Unlock()\nif !res {\n@@ -732,8 +728,6 @@ func TestGroupStateNonMember(t *testing.T) {\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- })\n- }\n}\nfunc TestQueuedPackets(t *testing.T) {\n@@ -742,7 +736,6 @@ func TestQueuedPackets(t *testing.T) {\nmgp.init()\nclock := faketime.NewManualClock()\ng.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n- Enabled: true,\nRand: rand.New(rand.NewSource(4)),\nClock: clock,\nProtocol: &mgp,\n@@ -753,7 +746,7 @@ func TestQueuedPackets(t *testing.T) {\n// send the packet.\nmgp.mu.Lock()\nmgp.makeQueuePackets = true\n- g.JoinGroupLocked(addr1, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr1)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -845,7 +838,7 @@ func TestQueuedPackets(t *testing.T) {\n// not affect a newly joined group's reports from being sent.\nmgp.mu.Lock()\nmgp.makeQueuePackets = true\n- g.JoinGroupLocked(addr2, false /* dontInitialize */)\n+ g.JoinGroupLocked(addr2)\nmgp.mu.Unlock()\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/igmp.go", "new_path": "pkg/tcpip/network/ipv4/igmp.go", "diff": "@@ -72,8 +72,6 @@ type igmpState struct {\n// The IPv4 endpoint this igmpState is for.\nep *endpoint\n- enabled bool\n-\ngenericMulticastProtocol ip.GenericMulticastProtocolState\n// igmpV1Present is for maintaining compatibility with IGMPv1 Routers, from\n@@ -95,6 +93,13 @@ type igmpState struct {\nigmpV1Job *tcpip.Job\n}\n+// Enabled implements ip.MulticastGroupProtocol.\n+func (igmp *igmpState) Enabled() bool {\n+ // No need to perform IGMP on loopback interfaces since they don't have\n+ // neighbouring nodes.\n+ return igmp.ep.protocol.options.IGMP.Enabled && !igmp.ep.nic.IsLoopback() && igmp.ep.Enabled()\n+}\n+\n// SendReport implements ip.MulticastGroupProtocol.\n//\n// Precondition: igmp.ep.mu must be read locked.\n@@ -127,11 +132,7 @@ func (igmp *igmpState) SendLeave(groupAddress tcpip.Address) *tcpip.Error {\n// Must only be called once for the lifetime of igmp.\nfunc (igmp *igmpState) init(ep *endpoint) {\nigmp.ep = ep\n- // No need to perform IGMP on loopback interfaces since they don't have\n- // neighbouring nodes.\n- igmp.enabled = ep.protocol.options.IGMP.Enabled && !igmp.ep.nic.IsLoopback()\nigmp.genericMulticastProtocol.Init(&ep.mu.RWMutex, ip.GenericMulticastProtocolOptions{\n- Enabled: igmp.enabled,\nRand: ep.protocol.stack.Rand(),\nClock: ep.protocol.stack.Clock(),\nProtocol: igmp,\n@@ -223,7 +224,7 @@ func (igmp *igmpState) handleMembershipQuery(groupAddress tcpip.Address, maxResp\n// As per RFC 2236 Section 6, Page 10: If the maximum response time is zero\n// then change the state to note that an IGMPv1 router is present and\n// schedule the query received Job.\n- if igmp.enabled && maxRespTime == 0 {\n+ if maxRespTime == 0 && igmp.Enabled() {\nigmp.igmpV1Job.Cancel()\nigmp.igmpV1Job.Schedule(v1RouterPresentTimeout)\nigmp.setV1Present(true)\n@@ -296,7 +297,7 @@ func (igmp *igmpState) writePacket(destAddress tcpip.Address, groupAddress tcpip\n//\n// Precondition: igmp.ep.mu must be locked.\nfunc (igmp *igmpState) joinGroup(groupAddress tcpip.Address) {\n- igmp.genericMulticastProtocol.JoinGroupLocked(groupAddress, !igmp.ep.Enabled() /* dontInitialize */)\n+ igmp.genericMulticastProtocol.JoinGroupLocked(groupAddress)\n}\n// isInGroup returns true if the specified group has been joined locally.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/mld.go", "new_path": "pkg/tcpip/network/ipv6/mld.go", "diff": "@@ -58,6 +58,13 @@ type mldState struct {\ngenericMulticastProtocol ip.GenericMulticastProtocolState\n}\n+// Enabled implements ip.MulticastGroupProtocol.\n+func (mld *mldState) Enabled() bool {\n+ // No need to perform MLD on loopback interfaces since they don't have\n+ // neighbouring nodes.\n+ return mld.ep.protocol.options.MLD.Enabled && !mld.ep.nic.IsLoopback() && mld.ep.Enabled()\n+}\n+\n// SendReport implements ip.MulticastGroupProtocol.\n//\n// Precondition: mld.ep.mu must be read locked.\n@@ -80,9 +87,6 @@ func (mld *mldState) SendLeave(groupAddress tcpip.Address) *tcpip.Error {\nfunc (mld *mldState) init(ep *endpoint) {\nmld.ep = ep\nmld.genericMulticastProtocol.Init(&ep.mu.RWMutex, ip.GenericMulticastProtocolOptions{\n- // No need to perform MLD on loopback interfaces since they don't have\n- // neighbouring nodes.\n- Enabled: ep.protocol.options.MLD.Enabled && !mld.ep.nic.IsLoopback(),\nRand: ep.protocol.stack.Rand(),\nClock: ep.protocol.stack.Clock(),\nProtocol: mld,\n@@ -112,7 +116,7 @@ func (mld *mldState) handleMulticastListenerReport(mldHdr header.MLD) {\n//\n// Precondition: mld.ep.mu must be locked.\nfunc (mld *mldState) joinGroup(groupAddress tcpip.Address) {\n- mld.genericMulticastProtocol.JoinGroupLocked(groupAddress, !mld.ep.Enabled() /* dontInitialize */)\n+ mld.genericMulticastProtocol.JoinGroupLocked(groupAddress)\n}\n// isInGroup returns true if the specified group has been joined locally.\n" } ]
Go
Apache License 2.0
google/gvisor
Don't split enabled flag across multicast group state Startblock: has LGTM from asfez and then add reviewer brunodalbo PiperOrigin-RevId: 347716242
260,004
15.12.2020 17:43:38
28,800
c55e5bda4d4590c84c6210b78c4b44c849f4400a
Validate router alert's data length RFC 2711 specifies that the router alert's length field is always 2 so we should make sure only 2 bytes are read from a router alert option's data field. Test: header.TestIPv6OptionsExtHdrIterErr
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"bufio\"\n\"bytes\"\n\"encoding/binary\"\n+ \"errors\"\n\"fmt\"\n\"io\"\n\"math\"\n@@ -274,6 +275,10 @@ func ipv6UnknownActionFromIdentifier(id IPv6ExtHdrOptionIdentifier) IPv6OptionUn\nreturn IPv6OptionUnknownAction((id & ipv6UnknownExtHdrOptionActionMask) >> ipv6UnknownExtHdrOptionActionShift)\n}\n+// ErrMalformedIPv6ExtHdrOption indicates that an IPv6 extension header option\n+// is malformed.\n+var ErrMalformedIPv6ExtHdrOption = errors.New(\"malformed IPv6 extension header option\")\n+\n// IPv6UnknownExtHdrOption holds the identifier and data for an IPv6 extension\n// header option that is unknown by the parsing utilities.\ntype IPv6UnknownExtHdrOption struct {\n@@ -351,10 +356,15 @@ func (i *IPv6OptionsExtHdrOptionsIterator) Next() (IPv6ExtHdrOption, bool, error\ncontinue\ncase ipv6RouterAlertHopByHopOptionIdentifier:\nvar routerAlertValue [ipv6RouterAlertPayloadLength]byte\n- if n, err := i.reader.Read(routerAlertValue[:]); err != nil {\n- panic(fmt.Sprintf(\"error when reading RouterAlert option's data bytes: %s\", err))\n- } else if n != ipv6RouterAlertPayloadLength {\n- return nil, true, fmt.Errorf(\"read %d bytes for RouterAlert option, expected %d\", n, ipv6RouterAlertPayloadLength)\n+ if n, err := io.ReadFull(&i.reader, routerAlertValue[:]); err != nil {\n+ switch err {\n+ case io.EOF, io.ErrUnexpectedEOF:\n+ return nil, true, fmt.Errorf(\"got invalid length (%d) for router alert option (want = %d): %w\", length, ipv6RouterAlertPayloadLength, ErrMalformedIPv6ExtHdrOption)\n+ default:\n+ return nil, true, fmt.Errorf(\"read %d out of %d option data bytes for router alert option: %w\", n, ipv6RouterAlertPayloadLength, err)\n+ }\n+ } else if n != int(length) {\n+ return nil, true, fmt.Errorf(\"got invalid length (%d) for router alert option (want = %d): %w\", length, ipv6RouterAlertPayloadLength, ErrMalformedIPv6ExtHdrOption)\n}\nreturn &IPv6RouterAlertOption{Value: IPv6RouterAlertValue(binary.BigEndian.Uint16(routerAlertValue[:]))}, false, nil\ndefault:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers_test.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers_test.go", "diff": "@@ -212,6 +212,31 @@ func TestIPv6OptionsExtHdrIterErr(t *testing.T) {\nbytes: []byte{1, 3},\nerr: io.ErrUnexpectedEOF,\n},\n+ {\n+ name: \"Router alert without data\",\n+ bytes: []byte{byte(ipv6RouterAlertHopByHopOptionIdentifier), 0},\n+ err: ErrMalformedIPv6ExtHdrOption,\n+ },\n+ {\n+ name: \"Router alert with partial data\",\n+ bytes: []byte{byte(ipv6RouterAlertHopByHopOptionIdentifier), 1, 1},\n+ err: ErrMalformedIPv6ExtHdrOption,\n+ },\n+ {\n+ name: \"Router alert with partial data and Pad1\",\n+ bytes: []byte{byte(ipv6RouterAlertHopByHopOptionIdentifier), 1, 1, 0},\n+ err: ErrMalformedIPv6ExtHdrOption,\n+ },\n+ {\n+ name: \"Router alert with extra data\",\n+ bytes: []byte{byte(ipv6RouterAlertHopByHopOptionIdentifier), 3, 1, 2, 3},\n+ err: ErrMalformedIPv6ExtHdrOption,\n+ },\n+ {\n+ name: \"Router alert with missing data\",\n+ bytes: []byte{byte(ipv6RouterAlertHopByHopOptionIdentifier), 1},\n+ err: io.ErrUnexpectedEOF,\n+ },\n}\ncheck := func(t *testing.T, it IPv6OptionsExtHdrOptionsIterator, expectedErr error) {\n" } ]
Go
Apache License 2.0
google/gvisor
Validate router alert's data length RFC 2711 specifies that the router alert's length field is always 2 so we should make sure only 2 bytes are read from a router alert option's data field. Test: header.TestIPv6OptionsExtHdrIterErr PiperOrigin-RevId: 347727876
259,858
16.12.2020 11:42:58
28,800
7da25e6dc3095378ecaf292759ef84b656a306b8
Restore refresh target.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -132,6 +132,9 @@ configure = $(call configure_noreload,$(1),$(2)) && $(reload_docker)\ninstall_runtime = $(call configure,$(RUNTIME),$(1) --TESTONLY-test-name-env=RUNSC_TEST_NAME)\ntest_runtime = $(call test,--test_arg=--runtime=$(RUNTIME) $(PARTITIONS) $(1))\n+refresh: $(RUNTIME_BIN) ## Updates the runtime binary.\n+.PHONY: refresh\n+\ndev: $(RUNTIME_BIN) ## Installs a set of local runtimes. Requires sudo.\n@$(call configure_noreload,$(RUNTIME),--net-raw)\n@$(call configure_noreload,$(RUNTIME)-d,--net-raw --debug --strace --log-packets)\n" } ]
Go
Apache License 2.0
google/gvisor
Restore refresh target. PiperOrigin-RevId: 347864621
260,004
16.12.2020 17:23:40
28,800
c740865f86e3b5f1692194c9d0b0d4986218f294
Cleanup locking in multicast group protocol tests Startblock: has LGTM from asfez and then add reviewer tamird
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip/generic_multicast_protocol_test.go", "new_path": "pkg/tcpip/network/ip/generic_multicast_protocol_test.go", "diff": "@@ -37,46 +37,105 @@ const (\nvar _ ip.MulticastGroupProtocol = (*mockMulticastGroupProtocol)(nil)\n-type mockMulticastGroupProtocol struct {\n- t *testing.T\n-\n- mu sync.RWMutex\n+type mockMulticastGroupProtocolProtectedFields struct {\n+ sync.RWMutex\n- // Must only be accessed with mu held.\n+ genericMulticastGroup ip.GenericMulticastProtocolState\nsendReportGroupAddrCount map[tcpip.Address]int\n-\n- // Must only be accessed with mu held.\nsendLeaveGroupAddrCount map[tcpip.Address]int\n-\n- // Must only be accessed with mu held.\nmakeQueuePackets bool\n-\n- // Must only be accessed with mu held.\ndisabled bool\n}\n-func (m *mockMulticastGroupProtocol) init() {\n+type mockMulticastGroupProtocol struct {\n+ t *testing.T\n+\n+ mu mockMulticastGroupProtocolProtectedFields\n+}\n+\n+func (m *mockMulticastGroupProtocol) init(opts ip.GenericMulticastProtocolOptions) {\nm.mu.Lock()\ndefer m.mu.Unlock()\nm.initLocked()\n+ opts.Protocol = m\n+ m.mu.genericMulticastGroup.Init(&m.mu.RWMutex, opts)\n}\nfunc (m *mockMulticastGroupProtocol) initLocked() {\n- m.sendReportGroupAddrCount = make(map[tcpip.Address]int)\n- m.sendLeaveGroupAddrCount = make(map[tcpip.Address]int)\n+ m.mu.sendReportGroupAddrCount = make(map[tcpip.Address]int)\n+ m.mu.sendLeaveGroupAddrCount = make(map[tcpip.Address]int)\n}\nfunc (m *mockMulticastGroupProtocol) setEnabled(v bool) {\nm.mu.Lock()\ndefer m.mu.Unlock()\n- m.disabled = !v\n+ m.mu.disabled = !v\n+}\n+\n+func (m *mockMulticastGroupProtocol) setQueuePackets(v bool) {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.makeQueuePackets = v\n+}\n+\n+func (m *mockMulticastGroupProtocol) joinGroup(addr tcpip.Address) {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.genericMulticastGroup.JoinGroupLocked(addr)\n+}\n+\n+func (m *mockMulticastGroupProtocol) leaveGroup(addr tcpip.Address) bool {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ return m.mu.genericMulticastGroup.LeaveGroupLocked(addr)\n+}\n+\n+func (m *mockMulticastGroupProtocol) handleReport(addr tcpip.Address) {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.genericMulticastGroup.HandleReportLocked(addr)\n+}\n+\n+func (m *mockMulticastGroupProtocol) handleQuery(addr tcpip.Address, maxRespTime time.Duration) {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.genericMulticastGroup.HandleQueryLocked(addr, maxRespTime)\n+}\n+\n+func (m *mockMulticastGroupProtocol) isLocallyJoined(addr tcpip.Address) bool {\n+ m.mu.RLock()\n+ defer m.mu.RUnlock()\n+ return m.mu.genericMulticastGroup.IsLocallyJoinedRLocked(addr)\n+}\n+\n+func (m *mockMulticastGroupProtocol) makeAllNonMember() {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.genericMulticastGroup.MakeAllNonMemberLocked()\n+}\n+\n+func (m *mockMulticastGroupProtocol) initializeGroups() {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.genericMulticastGroup.InitializeGroupsLocked()\n+}\n+\n+func (m *mockMulticastGroupProtocol) sendQueuedReports() {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.mu.genericMulticastGroup.SendQueuedReportsLocked()\n}\n// Enabled implements ip.MulticastGroupProtocol.\n//\n// Precondition: m.mu must be read locked.\nfunc (m *mockMulticastGroupProtocol) Enabled() bool {\n- return !m.disabled\n+ if m.mu.TryLock() {\n+ m.mu.Unlock()\n+ m.t.Fatal(\"got write lock, expected to not take the lock; generic multicast protocol must take the read or write lock before calling Enabled\")\n+ }\n+\n+ return !m.mu.disabled\n}\n// SendReport implements ip.MulticastGroupProtocol.\n@@ -92,8 +151,8 @@ func (m *mockMulticastGroupProtocol) SendReport(groupAddress tcpip.Address) (boo\nm.t.Fatalf(\"got read lock, expected to not take the lock; generic multicast protocol must take the write lock before sending report for %s\", groupAddress)\n}\n- m.sendReportGroupAddrCount[groupAddress]++\n- return !m.makeQueuePackets, nil\n+ m.mu.sendReportGroupAddrCount[groupAddress]++\n+ return !m.mu.makeQueuePackets, nil\n}\n// SendLeave implements ip.MulticastGroupProtocol.\n@@ -109,7 +168,7 @@ func (m *mockMulticastGroupProtocol) SendLeave(groupAddress tcpip.Address) *tcpi\nm.t.Fatalf(\"got read lock, expected to not take the lock; generic multicast protocol must take the write lock before sending leave for %s\", groupAddress)\n}\n- m.sendLeaveGroupAddrCount[groupAddress]++\n+ m.mu.sendLeaveGroupAddrCount[groupAddress]++\nreturn nil\n}\n@@ -129,16 +188,19 @@ func (m *mockMulticastGroupProtocol) check(sendReportGroupAddresses []tcpip.Addr\ndiff := cmp.Diff(\n&mockMulticastGroupProtocol{\n+ mu: mockMulticastGroupProtocolProtectedFields{\nsendReportGroupAddrCount: sendReportGroupAddrCount,\nsendLeaveGroupAddrCount: sendLeaveGroupAddrCount,\n},\n+ },\nm,\ncmp.AllowUnexported(mockMulticastGroupProtocol{}),\n+ cmp.AllowUnexported(mockMulticastGroupProtocolProtectedFields{}),\n// ignore mockMulticastGroupProtocol.mu and mockMulticastGroupProtocol.t\ncmp.FilterPath(\nfunc(p cmp.Path) bool {\nswitch p.Last().String() {\n- case \".mu\", \".t\", \".makeQueuePackets\", \".disabled\":\n+ case \".RWMutex\", \".t\", \".makeQueuePackets\", \".disabled\", \".genericMulticastGroup\":\nreturn true\n}\nreturn false\n@@ -170,24 +232,19 @@ func TestJoinGroup(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(0)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\nAllNodesAddress: addr2,\n})\n// Joining a group should send a report immediately and another after\n// a random interval between 0 and the maximum unsolicited report delay.\n- mgp.mu.Lock()\n- g.JoinGroupLocked(test.addr)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(test.addr)\nif test.shouldSendReports {\nif diff := mgp.check([]tcpip.Address{test.addr} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -229,22 +286,17 @@ func TestLeaveGroup(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(1)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\nAllNodesAddress: addr2,\n})\n- mgp.mu.Lock()\n- g.JoinGroupLocked(test.addr)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(test.addr)\nif test.shouldSendMessages {\nif diff := mgp.check([]tcpip.Address{test.addr} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -254,11 +306,9 @@ func TestLeaveGroup(t *testing.T) {\n// Leaving a group should send a leave report immediately and cancel any\n// delayed reports.\n{\n- mgp.mu.Lock()\n- res := g.LeaveGroupLocked(test.addr)\n- mgp.mu.Unlock()\n- if !res {\n- t.Fatalf(\"got g.LeaveGroupLocked(%s) = false, want = true\", test.addr)\n+\n+ if !mgp.leaveGroup(test.addr) {\n+ t.Fatalf(\"got mgp.leaveGroup(%s) = false, want = true\", test.addr)\n}\n}\nif test.shouldSendMessages {\n@@ -313,43 +363,32 @@ func TestHandleReport(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(2)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\nAllNodesAddress: addr3,\n})\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr1)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr1)\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr2)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr2)\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr3)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr3)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Receiving a report for a group we have a timer scheduled for should\n// cancel our delayed report timer for the group.\n- mgp.mu.Lock()\n- g.HandleReportLocked(test.reportAddr)\n- mgp.mu.Unlock()\n+ mgp.handleReport(test.reportAddr)\nif len(test.expectReportsFor) != 0 {\n// Generic multicast protocol timers are expected to take the job mutex.\nclock.Advance(maxUnsolicitedReportDelay)\n@@ -408,34 +447,25 @@ func TestHandleQuery(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(3)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\nAllNodesAddress: addr3,\n})\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr1)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr1)\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr2)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr2)\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr3)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr3)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n@@ -447,9 +477,7 @@ func TestHandleQuery(t *testing.T) {\n// Receiving a query should make us schedule a new delayed report if it\n// is a query directed at us or a general query.\n- mgp.mu.Lock()\n- g.HandleQueryLocked(test.queryAddr, test.maxDelay)\n- mgp.mu.Unlock()\n+ mgp.handleQuery(test.queryAddr, test.maxDelay)\nif len(test.expectReportsFor) != 0 {\nclock.Advance(test.maxDelay)\nif diff := mgp.check(test.expectReportsFor /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n@@ -467,40 +495,27 @@ func TestHandleQuery(t *testing.T) {\n}\nfunc TestJoinCount(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(4)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: time.Second,\n})\n// Set the join count to 2 for a group.\n- {\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr1)\n- res := g.IsLocallyJoinedRLocked(addr1)\n- mgp.mu.Unlock()\n- if !res {\n- t.Fatalf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", addr1)\n- }\n+ mgp.joinGroup(addr1)\n+ if !mgp.isLocallyJoined(addr1) {\n+ t.Fatalf(\"got mgp.isLocallyJoined(%s) = false, want = true\", addr1)\n}\n// Only the first join should trigger a report to be sent.\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- {\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr1)\n- res := g.IsLocallyJoinedRLocked(addr1)\n- mgp.mu.Unlock()\n- if !res {\n- t.Errorf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", addr1)\n- }\n+ mgp.joinGroup(addr1)\n+ if !mgp.isLocallyJoined(addr1) {\n+ t.Errorf(\"got mgp.isLocallyJoined(%s) = false, want = true\", addr1)\n}\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -510,17 +525,11 @@ func TestJoinCount(t *testing.T) {\n}\n// Group should still be considered joined after leaving once.\n- {\n- mgp.mu.Lock()\n- leaveGroupRes := g.LeaveGroupLocked(addr1)\n- isLocallyJoined := g.IsLocallyJoinedRLocked(addr1)\n- mgp.mu.Unlock()\n- if !leaveGroupRes {\n- t.Errorf(\"got g.LeaveGroupLocked(%s) = false, want = true\", addr1)\n- }\n- if !isLocallyJoined {\n- t.Errorf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", addr1)\n+ if !mgp.leaveGroup(addr1) {\n+ t.Errorf(\"got mgp.leaveGroup(%s) = false, want = true\", addr1)\n}\n+ if !mgp.isLocallyJoined(addr1) {\n+ t.Errorf(\"got mgp.isLocallyJoined(%s) = false, want = true\", addr1)\n}\n// A leave report should only be sent once the join count reaches 0.\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n@@ -531,17 +540,11 @@ func TestJoinCount(t *testing.T) {\n}\n// Leaving once more should actually remove us from the group.\n- {\n- mgp.mu.Lock()\n- leaveGroupRes := g.LeaveGroupLocked(addr1)\n- isLocallyJoined := g.IsLocallyJoinedRLocked(addr1)\n- mgp.mu.Unlock()\n- if !leaveGroupRes {\n- t.Errorf(\"got g.LeaveGroupLocked(%s) = false, want = true\", addr1)\n- }\n- if isLocallyJoined {\n- t.Errorf(\"got g.IsLocallyJoinedRLocked(%s) = true, want = false\", addr1)\n+ if !mgp.leaveGroup(addr1) {\n+ t.Errorf(\"got mgp.leaveGroup(%s) = false, want = true\", addr1)\n}\n+ if mgp.isLocallyJoined(addr1) {\n+ t.Errorf(\"got mgp.isLocallyJoined(%s) = true, want = false\", addr1)\n}\nif diff := mgp.check(nil /* sendReportGroupAddresses */, []tcpip.Address{addr1} /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -552,17 +555,11 @@ func TestJoinCount(t *testing.T) {\n// Group should no longer be joined so we should not have anything to\n// leave.\n- {\n- mgp.mu.Lock()\n- leaveGroupRes := g.LeaveGroupLocked(addr1)\n- isLocallyJoined := g.IsLocallyJoinedRLocked(addr1)\n- mgp.mu.Unlock()\n- if leaveGroupRes {\n- t.Errorf(\"got g.LeaveGroupLocked(%s) = true, want = false\", addr1)\n- }\n- if isLocallyJoined {\n- t.Errorf(\"got g.IsLocallyJoinedRLocked(%s) = true, want = false\", addr1)\n+ if mgp.leaveGroup(addr1) {\n+ t.Errorf(\"got mgp.leaveGroup(%s) = true, want = false\", addr1)\n}\n+ if mgp.isLocallyJoined(addr1) {\n+ t.Errorf(\"got mgp.isLocallyJoined(%s) = true, want = false\", addr1)\n}\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -578,43 +575,32 @@ func TestJoinCount(t *testing.T) {\n}\nfunc TestMakeAllNonMemberAndInitialize(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(3)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\nAllNodesAddress: addr3,\n})\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr1)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr1)\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr2)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr2)\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr3)\n- mgp.mu.Unlock()\n+ mgp.joinGroup(addr3)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Should send the leave reports for each but still consider them locally\n// joined.\n- mgp.mu.Lock()\n- g.MakeAllNonMemberLocked()\n- mgp.mu.Unlock()\n+ mgp.makeAllNonMember()\nif diff := mgp.check(nil /* sendReportGroupAddresses */, []tcpip.Address{addr1, addr2} /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n@@ -624,18 +610,13 @@ func TestMakeAllNonMemberAndInitialize(t *testing.T) {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\nfor _, group := range []tcpip.Address{addr1, addr2, addr3} {\n- mgp.mu.RLock()\n- res := g.IsLocallyJoinedRLocked(group)\n- mgp.mu.RUnlock()\n- if !res {\n- t.Fatalf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", group)\n+ if !mgp.isLocallyJoined(group) {\n+ t.Fatalf(\"got mgp.isLocallyJoined(%s) = false, want = true\", group)\n}\n}\n// Should send the initial set of unsolcited reports.\n- mgp.mu.Lock()\n- g.InitializeGroupsLocked()\n- mgp.mu.Unlock()\n+ mgp.initializeGroups()\nif diff := mgp.check([]tcpip.Address{addr1, addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n@@ -654,49 +635,34 @@ func TestMakeAllNonMemberAndInitialize(t *testing.T) {\n// TestGroupStateNonMember tests that groups do not send packets when in the\n// non-member state, but are still considered locally joined.\nfunc TestGroupStateNonMember(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\nmgp := mockMulticastGroupProtocol{t: t}\nclock := faketime.NewManualClock()\n- mgp.init()\n- mgp.setEnabled(false)\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(3)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\n})\n+ mgp.setEnabled(false)\n// Joining groups should not send any reports.\n- {\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr1)\n- res := g.IsLocallyJoinedRLocked(addr1)\n- mgp.mu.Unlock()\n- if !res {\n- t.Fatalf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", addr1)\n- }\n+ mgp.joinGroup(addr1)\n+ if !mgp.isLocallyJoined(addr1) {\n+ t.Fatalf(\"got mgp.isLocallyJoined(%s) = false, want = true\", addr1)\n}\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- {\n- mgp.mu.Lock()\n- g.JoinGroupLocked(addr2)\n- res := g.IsLocallyJoinedRLocked(addr2)\n- mgp.mu.Unlock()\n- if !res {\n- t.Fatalf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", addr2)\n- }\n+ mgp.joinGroup(addr2)\n+ if !mgp.isLocallyJoined(addr1) {\n+ t.Fatalf(\"got mgp.isLocallyJoined(%s) = false, want = true\", addr2)\n}\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Receiving a query should not send any reports.\n- mgp.mu.Lock()\n- g.HandleQueryLocked(addr1, time.Nanosecond)\n- mgp.mu.Unlock()\n+ mgp.handleQuery(addr1, time.Nanosecond)\n// Generic multicast protocol timers are expected to take the job mutex.\nclock.Advance(time.Nanosecond)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n@@ -704,21 +670,11 @@ func TestGroupStateNonMember(t *testing.T) {\n}\n// Leaving groups should not send any leave messages.\n- {\n- mgp.mu.Lock()\n- addr2LeaveRes := g.LeaveGroupLocked(addr2)\n- addr1IsJoined := g.IsLocallyJoinedRLocked(addr1)\n- addr2IsJoined := g.IsLocallyJoinedRLocked(addr2)\n- mgp.mu.Unlock()\n- if !addr2LeaveRes {\n- t.Errorf(\"got g.LeaveGroupLocked(%s) = false, want = true\", addr2)\n- }\n- if !addr1IsJoined {\n- t.Errorf(\"got g.IsLocallyJoinedRLocked(%s) = false, want = true\", addr1)\n- }\n- if addr2IsJoined {\n- t.Errorf(\"got g.IsLocallyJoinedRLocked(%s) = true, want = false\", addr2)\n+ if !mgp.leaveGroup(addr1) {\n+ t.Errorf(\"got mgp.leaveGroup(%s) = false, want = true\", addr2)\n}\n+ if mgp.isLocallyJoined(addr1) {\n+ t.Errorf(\"got mgp.isLocallyJoined(%s) = true, want = false\", addr2)\n}\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -731,23 +687,18 @@ func TestGroupStateNonMember(t *testing.T) {\n}\nfunc TestQueuedPackets(t *testing.T) {\n- var g ip.GenericMulticastProtocolState\n- var mgp mockMulticastGroupProtocol\n- mgp.init()\nclock := faketime.NewManualClock()\n- g.Init(&mgp.mu, ip.GenericMulticastProtocolOptions{\n+ mgp := mockMulticastGroupProtocol{t: t}\n+ mgp.init(ip.GenericMulticastProtocolOptions{\nRand: rand.New(rand.NewSource(4)),\nClock: clock,\n- Protocol: &mgp,\nMaxUnsolicitedReportDelay: maxUnsolicitedReportDelay,\n})\n// Joining should trigger a SendReport, but mgp should report that we did not\n// send the packet.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = true\n- g.JoinGroupLocked(addr1)\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(true)\n+ mgp.joinGroup(addr1)\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n@@ -760,10 +711,8 @@ func TestQueuedPackets(t *testing.T) {\n}\n// Mock being able to successfully send the report.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = false\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(false)\n+ mgp.sendQueuedReports()\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n@@ -775,19 +724,15 @@ func TestQueuedPackets(t *testing.T) {\n}\n// Should not have anything else to send (we should be idle).\n- mgp.mu.Lock()\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.sendQueuedReports()\nclock.Advance(time.Hour)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Receive a query but mock being unable to send reports again.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = true\n- g.HandleQueryLocked(addr1, time.Nanosecond)\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(true)\n+ mgp.handleQuery(addr1, time.Nanosecond)\nclock.Advance(time.Nanosecond)\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -795,28 +740,22 @@ func TestQueuedPackets(t *testing.T) {\n// Mock being able to send reports again - we should have a packet queued to\n// send.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = false\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(false)\n+ mgp.sendQueuedReports()\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Should not have anything else to send.\n- mgp.mu.Lock()\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.sendQueuedReports()\nclock.Advance(time.Hour)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Receive a query again, but mock being unable to send reports.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = true\n- g.HandleQueryLocked(addr1, time.Nanosecond)\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(true)\n+ mgp.handleQuery(addr1, time.Nanosecond)\nclock.Advance(time.Nanosecond)\nif diff := mgp.check([]tcpip.Address{addr1} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -825,10 +764,8 @@ func TestQueuedPackets(t *testing.T) {\n// Receiving a report should should transition us into the idle member state,\n// even if we had a packet queued. We should no longer have any packets to\n// send.\n- mgp.mu.Lock()\n- g.HandleReportLocked(addr1)\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.handleReport(addr1)\n+ mgp.sendQueuedReports()\nclock.Advance(time.Hour)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n@@ -836,27 +773,21 @@ func TestQueuedPackets(t *testing.T) {\n// When we fail to send the initial set of reports, incoming reports should\n// not affect a newly joined group's reports from being sent.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = true\n- g.JoinGroupLocked(addr2)\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(true)\n+ mgp.joinGroup(addr2)\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- mgp.mu.Lock()\n- g.HandleReportLocked(addr2)\n+ mgp.handleReport(addr2)\n// Attempting to send queued reports while still unable to send reports should\n// not change the host state.\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.sendQueuedReports()\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Mock being able to successfully send the report.\n- mgp.mu.Lock()\n- mgp.makeQueuePackets = false\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.setQueuePackets(false)\n+ mgp.sendQueuedReports()\nif diff := mgp.check([]tcpip.Address{addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n@@ -867,9 +798,7 @@ func TestQueuedPackets(t *testing.T) {\n}\n// Should not have anything else to send.\n- mgp.mu.Lock()\n- g.SendQueuedReportsLocked()\n- mgp.mu.Unlock()\n+ mgp.sendQueuedReports()\nclock.Advance(time.Hour)\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n" } ]
Go
Apache License 2.0
google/gvisor
Cleanup locking in multicast group protocol tests Startblock: has LGTM from asfez and then add reviewer tamird PiperOrigin-RevId: 347928471